Andee lives on your phone or Mac and uses any app like you do—no integrations, no root, any model; memory and passwords never leave your device | Andee 住进你的手机或 Mac,像你一样操作任何 App——无需集成、无需 Root、支持任意模型,记忆和密码绝不离开设备。
feat(android): the phone gets who it is — self, cares, diary, people, wiki — and the same 小本本
booboosui201439097c3b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 956d7c2..50789b6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -42,6 +42,7 @@ Toolchain notes that bite:- `gradle.properties` **does not pin the Gradle JDK** — it used to hardcode a machine-specific `org.gradle.java.home`, which made the build fail instantly on every other machine. The build needs a **JDK in the 17–20 range**: AGP 8.3.1 requires 17+, and the Gradle 8.4 wrapper cannot run on 21+ (Android Studio's bundled JBR 25 dies with `Unsupported class file major version 69`). Set `JAVA_HOME`, or put `org.gradle.java.home=<path to JDK 17–20>` in **`~/.gradle/gradle.properties`** — never in the repo's copy. In Android Studio, set *Settings → Build Tools → Gradle → Gradle JDK* to a 17–20 JDK.- `settings.gradle` puts **Aliyun mirrors first** for both plugin and dependency resolution. Keep them first when editing; they're there because the project is developed behind the GFW.+- **The root `build.gradle` pins R8 on the buildscript classpath** (`com.android.tools:r8`). AGP 8.3's bundled R8 reads Kotlin metadata only up to 2.0, and the move to Kotlin 2.1 made `minifyReleaseWithR8` fail outright ("Provided Metadata instance has version 2.1.0") — so `assembleRelease` was broken while `assembleDebug` was fine. Bump the pin whenever Kotlin moves.- `minSdk 30` is load-bearing, not arbitrary: `ACTION_IME_ENTER` and `AccessibilityService.takeScreenshot` are both API 30+.- Deliberately **no Jetpack Compose, no Hilt/Dagger, no coroutines.** Overlays can't host Compose, so all UI is hand-written `View` code; there's exactly one service, so dependencies are constructor-injected by hand; concurrency is `Handler` + dedicated `Executor`s. Match this style rather than introducing the modern stack.@@ -611,6 +612,17 @@ Bubbles alone felt random — "no overall idea, no soul" was the user's verdict- **`PlanMind` thinks about the plan without being asked, in two no-tool calls** (the triage pattern): `morning` once a day when the user first shows up (writes today's plan from directions, yesterday's outcomes, the draft, today's todos and the notebook — this is also what gives an unreviewed device a plan), and `muse` every ≥ 40 min while they are present, only for today's loose-time items, picking at most one. Timing state lives in the plan section's `meta`. Triggers: phone `USER_PRESENT` + a 10-min tick (`BodyCoreService.planTick`), Mac a 5-min tick with recent HID input (`PlanTicks`). Both fail closed — no key or a bad answer changes nothing. There is deliberately **no** "prepare while they are away" turn.- **`TurnGuards` refuses `note.directions` / `note.day_plan` on untrusted turns** — a planned bubble's tap is a trusted turn, so a stranger's words in the plan would be laundered.+### Who it is: self, cares, diary, people, wiki (`config/Selfhood.kt`, `config/People.kt`, `wiki/`)++The first cut of `docs/design/inner-drive.zh-CN.md`. Its self-description, the things it cares about (each with an interval; the device, not the model, works out how overdue one is), a diary, the people it has met, and a wiki of articles it wrote or knows of. All of it except the article bodies lives in the notebook blob (`NotebookBook.selfhood` / `people` / `wiki`), so wipe and export cover it; the bodies are `.md` files in a folder (`LocalWikiStore`) — `filesDir/wiki` on the phone (private: an article can be marked secret, and these files are not encrypted), `~/Library/Application Support/Andee/wiki` on the Mac. The phone's `Notebook.wipe` deletes that folder too, since the index pointing at it is gone.++- **One handler, `LifeTools`, for both bodies.** Each routes `LifeTools.METHODS` to it (`CommandDispatcher` on the phone, `DesktopNotebook.dispatchCall` on the Mac) and does nothing else, so the two cannot answer in different shapes. Every method is `note.*`, so the nightly review can write the diary.+- **`BrainHost.dispatch` carries the tool-call id**, set into `Notebook.callBeingRun` / `DesktopNotebook.callBeingRun` before the call, so an article records which call wrote it (`Meta.madeBy`). A test that fakes `BrainHost` with a `Proxy` must answer the new default methods (`selfIndex`, `wikiIndex`) with `""` — a proxy intercepts defaults too, and a null there kills the turn.+- **A stranger cannot change who it is.** `TurnGuards` refuses the writing half (`note.self`, `note.cares`, `note.diary`, `note.person`, `note.wiki_*` writes) on an untrusted turn; reading stays open. `GuestHost` does not allow any `note.*`.+- **`selfIndex` / `wikiIndex` ride on the user message**, one line each, beside the plan line — same reason as every other index there.+- **`TurnKind.WORK` and `LocalBrain.work()` exist but nothing calls them yet** on either body: a turn it starts itself on a care that came due, quiet (no voice, no card), with the tools a territory names (`BrainHost.workTools`). The driver is the next step of the design, not a missing wire.+- **The 小本本 card has the same eight tabs on both bodies**, in the same order: 自己 · 在意 · 日记 · 打算 · 人 · 维基 · 记忆 · 待办. A wiki entry opens to its article, read from the file at that moment; a memory unfolds to its content. What the model wrote is drawn as Markdown by **one parser in core (`text/Md`)** and two renderers (`desktop/Markdown.kt`, `ui/MarkdownView.kt`), so a table cannot be a table on one body and a wall of pipes on the other. Only http(s) links open; on the phone opening one hides the card first, because the overlay sits above the browser.+### Scenes: ways of working it learned with this person (local brain only)A scene (「陪我练英语」「帮我接管微信」「比价购物」) is a goal + voice + rules + routine that the model steps into for a while. It is **only a prompt** — no tool scoping, no scheduler of its own — and it is **learned, not shipped**: the model proposes one after the same kind of session has recurred, the user says yes, *then* `save_scene` writes it. `LocalPrompt` §11 is the whole teaching; the nightly review (`REVIEW_RULES` item 6) only leaves itself a `remember(type=feedback)` to propose one next time, because there is nobody to ask while it reviews.diff --git a/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt b/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.ktindex 87f403d..10cda93 100644--- a/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt+++ b/app/src/main/java/net/kuafuai/andee/brain/AndroidBrainHost.kt@@ -85,6 +85,10 @@ class AndroidBrainHost(override fun topicsIndex(): String = ChatHistory.topicsForPrompt()+ override fun selfIndex(): String = Notebook.selfhood(ctx).indexForPrompt()++ override fun wikiIndex(): String = Notebook.wiki(ctx).indexForPrompt()+override fun foldTopic(title: String, summary: String, rows: List<ScrollRow>, text: String): FoldedTopic? {val entries = rows.map { it.handle as ChatHistory.Entry }val t = ChatHistory.foldTopic(title = title, summary = summary, rows = entries, text = text, parentId = null)@@ -111,7 +115,8 @@ class AndroidBrainHost(?: toolName.takeIf { market.hasMethod(it) }?: net.kuafuai.andee.peer.PeerTasks.methodOf(toolName)- override fun dispatch(method: String, params: JSONObject, silent: Boolean, untrusted: Boolean): Any? {+ override fun dispatch(method: String, params: JSONObject, callId: String, silent: Boolean, untrusted: Boolean): Any? {+ Notebook.callBeingRun = callId// Not the dispatcher's: the link to the other devices is not part of this body, and the hub must never// see it. The turn guard still runs first — it is what keeps a stranger's notification from handing work on.if (method.startsWith("peer.")) {diff --git a/app/src/main/java/net/kuafuai/andee/config/Notebook.kt b/app/src/main/java/net/kuafuai/andee/config/Notebook.ktindex bd15092..0a12d85 100644--- a/app/src/main/java/net/kuafuai/andee/config/Notebook.kt+++ b/app/src/main/java/net/kuafuai/andee/config/Notebook.kt@@ -96,7 +96,9 @@ object Notebook {override fun wipe() {prefs(app).edit().clear().commit()}- }).also { book = it }+ }).apply {+ localWikiStore = net.kuafuai.andee.wiki.LocalWikiStore(wikiDir(app))+ }.also { book = it }}}@@ -110,6 +112,28 @@ object Notebook {fun plans(context: Context): net.kuafuai.andee.config.Plans =plans ?: synchronized(this) { plans ?: net.kuafuai.andee.config.Plans(book(context)).also { plans = it } }+ /**+ * Where wiki articles live: app-private storage, not shared. Unlike the notebook blob these are plain files, and+ * an article can be marked secret, so they stay where no other app can read them.+ */+ private fun wikiDir(context: Context): java.io.File = java.io.File(context.applicationContext.filesDir, "wiki")++ fun selfhood(context: Context): net.kuafuai.andee.config.Selfhood = book(context).selfhood+ fun people(context: Context): net.kuafuai.andee.config.People = book(context).people+ fun wiki(context: Context): net.kuafuai.andee.wiki.WikiBook = book(context).wiki++ /** The tool-call id of the [LifeTools] call being answered; set by the brain host just before it dispatches. */+ @Volatile var callBeingRun: String = ""++ @Volatile+ private var life: net.kuafuai.andee.config.LifeTools? = null++ /** `self_note`, `cares`, `diary`, `person`, `people`, `wiki_*` — the same handler the Mac uses. */+ fun life(context: Context): net.kuafuai.andee.config.LifeTools = life ?: synchronized(this) {+ life ?: net.kuafuai.andee.config.LifeTools(selfhood(context), people(context), wiki(context), callId = { callBeingRun })+ .also { life = it }+ }+/** The gear shelf (what is installed, what it is for), kept inside the notebook's own file. */fun gear(context: Context): net.kuafuai.andee.config.Gear = net.kuafuai.andee.config.Gear(book(context))@@ -135,6 +159,10 @@ object Notebook {fun wipe(context: Context) {book(context).wipe()metaPrefs(context).edit().clear().commit()+ // The wiki's index lived in the blob just wiped; its articles would be files nothing points at any more.+ wikiDir(context).listFiles()?.forEach { it.deleteRecursively() }+ // The live store writes into .history/ and archive/ without creating them; its constructor is what does.+ net.kuafuai.andee.wiki.LocalWikiStore(wikiDir(context))}fun indexForPrompt(context: Context, max: Int = 10): String = book(context).indexForPrompt(max)diff --git a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.ktindex 5b97f75..3c72acf 100644--- a/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt+++ b/app/src/main/java/net/kuafuai/andee/net/CommandDispatcher.kt@@ -1531,6 +1531,10 @@ class CommandDispatcher()}+ // Andee's inner life (`LifeTools`): shared logic in core, the same handler as the Mac's, and nothing+ // for the phone to arm. The tool-call id it records is set by the brain host before the call.+ in net.kuafuai.andee.config.LifeTools.METHODS -> Notebook.life(appContext).handle(method, params)+// The plan (`Plans`): shared logic in core; here only the alarms it asks for."note.directions", "note.day_plan" -> {val r = Notebook.plans(appContext).handle(diff --git a/app/src/main/java/net/kuafuai/andee/ui/MarkdownView.kt b/app/src/main/java/net/kuafuai/andee/ui/MarkdownView.ktnew file mode 100644index 0000000..39e0f17--- /dev/null+++ b/app/src/main/java/net/kuafuai/andee/ui/MarkdownView.kt@@ -0,0 +1,169 @@+package net.kuafuai.andee.ui++import android.content.Context+import android.graphics.Color+import android.graphics.Typeface+import android.text.SpannableStringBuilder+import android.text.Spanned+import android.text.TextPaint+import android.text.method.LinkMovementMethod+import android.text.style.BackgroundColorSpan+import android.text.style.ClickableSpan+import android.text.style.ForegroundColorSpan+import android.text.style.StrikethroughSpan+import android.text.style.StyleSpan+import android.text.style.TypefaceSpan+import android.view.View+import android.widget.HorizontalScrollView+import android.widget.LinearLayout+import android.widget.TextView+import net.kuafuai.andee.text.Md++/**+ * The phone's renderer for [Md]: what the model writes in the notebook and the wiki, drawn as Views in the+ * cards' palette instead of a page of asterisks and pipes. The parsing is shared with the Mac (`Markdown.kt`+ * there), so the two bodies show one article the same way.+ *+ * [onLink] receives an http(s) URL when one is tapped. The caller opens it — and folds its card first, because+ * an overlay sits above the browser it would open.+ */+object MarkdownView {++ fun build(+ context: Context,+ text: String,+ color: String = Glass.LABEL,+ size: Float = Glass.Type.BODY,+ onLink: (String) -> Unit = {},+ ): View {+ val col = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }+ Md.blocks(text).forEachIndexed { i, b ->+ val v = block(context, b, color, size, onLink)+ // A rule is an empty View: WRAP would let it take whatever height its parent offers.+ col.addView(v, LinearLayout.LayoutParams(MATCH, if (b is Md.Block.Rule) dp(context, 1) else WRAP).apply {+ if (i > 0) topMargin = dp(context, if (b is Md.Block.Heading) 14 else 8)+ })+ }+ return col+ }++ private fun block(c: Context, b: Md.Block, color: String, size: Float, onLink: (String) -> Unit): View = when (b) {+ is Md.Block.Heading -> text(c, b.text, Glass.TITLE, size + when (b.level) { 1 -> 5f; 2 -> 3f; 3 -> 1f; else -> 0f }, onLink).apply {+ setTypeface(typeface, if (b.level <= 3) Typeface.BOLD else Typeface.NORMAL)+ }+ is Md.Block.Para -> text(c, b.text, color, size, onLink)+ is Md.Block.Item -> LinearLayout(c).apply {+ orientation = LinearLayout.HORIZONTAL+ setPadding(dp(c, b.depth * 16), 0, 0, 0)+ addView(TextView(c).apply {+ this.text = b.marker+ textSize = size+ setTextColor(Color.parseColor(Glass.SECONDARY))+ minWidth = dp(c, 18)+ setLineSpacing(0f, LINE)+ }, LinearLayout.LayoutParams(WRAP, WRAP))+ addView(text(c, b.text, color, size, onLink), LinearLayout.LayoutParams(0, WRAP, 1f))+ }+ is Md.Block.Quote -> LinearLayout(c).apply {+ orientation = LinearLayout.HORIZONTAL+ addView(View(c).apply { setBackgroundColor(Color.parseColor(Glass.HAIRLINE)) },+ LinearLayout.LayoutParams(dp(c, 3), LinearLayout.LayoutParams.MATCH_PARENT).apply { rightMargin = dp(c, 10) })+ val inner = LinearLayout(c).apply { orientation = LinearLayout.VERTICAL }+ b.inner.forEachIndexed { i, ib ->+ inner.addView(block(c, ib, Glass.SECONDARY, size, onLink), LinearLayout.LayoutParams(MATCH, if (ib is Md.Block.Rule) dp(c, 1) else WRAP).apply {+ if (i > 0) topMargin = dp(c, 6)+ })+ }+ addView(inner, LinearLayout.LayoutParams(0, WRAP, 1f))+ }+ is Md.Block.Code -> HorizontalScrollView(c).apply {+ background = Glass.well(c, dp(c, 8))+ setPadding(dp(c, 10), dp(c, 8), dp(c, 10), dp(c, 8))+ isHorizontalScrollBarEnabled = false+ addView(TextView(c).apply {+ this.text = b.text+ textSize = size - 1f+ typeface = Typeface.MONOSPACE+ setTextColor(Color.parseColor(color))+ setLineSpacing(0f, LINE)+ setHorizontallyScrolling(true)+ })+ }+ is Md.Block.Table -> table(c, b, color, size, onLink)+ Md.Block.Rule -> View(c).apply { setBackgroundColor(Color.parseColor(Glass.HAIRLINE)) }+ }++ /** Columns share the width equally and wrap within it; a phone is too narrow for a table that scrolls sideways. */+ private fun table(c: Context, t: Md.Block.Table, color: String, size: Float, onLink: (String) -> Unit): View {+ val cols = maxOf(t.header.size, t.rows.maxOfOrNull { it.size } ?: 0)+ val s = size - 1f+ val box = LinearLayout(c).apply {+ orientation = LinearLayout.VERTICAL+ background = Glass.well(c, dp(c, 8))+ setPadding(dp(c, 10), dp(c, 4), dp(c, 10), dp(c, 4))+ }+ fun row(cells: List<String>, head: Boolean) {+ val r = LinearLayout(c).apply { orientation = LinearLayout.HORIZONTAL; setPadding(0, dp(c, 6), 0, dp(c, 6)) }+ for (k in 0 until cols) {+ r.addView(text(c, cells.getOrElse(k) { "" }, if (head) Glass.TITLE else color, s, onLink).apply {+ if (head) setTypeface(typeface, Typeface.BOLD)+ setPadding(0, 0, dp(c, 8), 0)+ }, LinearLayout.LayoutParams(0, WRAP, 1f))+ }+ box.addView(r, LinearLayout.LayoutParams(MATCH, WRAP))+ }+ fun line() = box.addView(View(c).apply { setBackgroundColor(Color.parseColor(Glass.HAIRLINE)) }, LinearLayout.LayoutParams(MATCH, dp(c, 1)))+ row(t.header, true)+ line()+ t.rows.forEachIndexed { i, r -> if (i > 0) line(); row(r, false) }+ return box+ }++ private fun text(c: Context, md: String, color: String, size: Float, onLink: (String) -> Unit): TextView = TextView(c).apply {+ val (spanned, links) = inline(md, onLink)+ text = spanned+ textSize = size+ setTextColor(Color.parseColor(color))+ setLineSpacing(0f, LINE)+ // Only where there is something to tap: LinkMovementMethod also takes over the view's touch handling.+ if (links) movementMethod = LinkMovementMethod.getInstance()+ }++ /** [Md.runs] as spans. Returns whether any of them can be tapped. */+ private fun inline(md: String, onLink: (String) -> Unit): Pair<CharSequence, Boolean> {+ val sb = SpannableStringBuilder()+ var links = false+ for (r in Md.runs(md)) {+ val start = sb.length+ sb.append(r.text)+ val end = sb.length+ fun span(o: Any) = sb.setSpan(o, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ when {+ r.bold && r.italic -> span(StyleSpan(Typeface.BOLD_ITALIC))+ r.bold -> span(StyleSpan(Typeface.BOLD))+ r.italic -> span(StyleSpan(Typeface.ITALIC))+ }+ if (r.code) { span(TypefaceSpan("monospace")); span(BackgroundColorSpan(Color.parseColor(Glass.WELL))) }+ if (r.strike) span(StrikethroughSpan())+ if (r.link) span(ForegroundColorSpan(Color.parseColor(Glass.ACCENT)))+ val url = r.url+ if (url != null) {+ links = true+ span(object : ClickableSpan() {+ override fun onClick(widget: View) = onLink(url)+ override fun updateDrawState(ds: TextPaint) {+ ds.color = Color.parseColor(Glass.ACCENT)+ ds.isUnderlineText = true+ }+ })+ }+ }+ return sb to links+ }++ private fun dp(c: Context, v: Int): Int = (v * c.resources.displayMetrics.density).toInt()++ private const val LINE = 1.35f+ private const val MATCH = LinearLayout.LayoutParams.MATCH_PARENT+ private const val WRAP = LinearLayout.LayoutParams.WRAP_CONTENT+}diff --git a/app/src/main/java/net/kuafuai/andee/ui/NotebookUi.kt b/app/src/main/java/net/kuafuai/andee/ui/NotebookUi.ktindex 113dacb..f1c553f 100644--- a/app/src/main/java/net/kuafuai/andee/ui/NotebookUi.kt+++ b/app/src/main/java/net/kuafuai/andee/ui/NotebookUi.kt@@ -27,13 +27,18 @@ import java.util.Locale* export-shaped. That is the only route to the raw text; the rows here answer* a different question: "what is it allowed to remember about me".*- * **记忆** groups [net.kuafuai.andee.config.Memory] by type, most important first within each.- * **待办** lists active and paused [net.kuafuai.andee.config.Todo]s, soonest first.+ * Eight tabs, the same eight and in the same order as the Mac's 小本本:+ * **自己** (its self-description), **在意** (its cares, most overdue first),+ * **日记** (the last week of diary pages), **打算** (today's plan), **人** (who it+ * knows), **维基** (its articles — tap one to read it from the file, now),+ * **记忆** ([net.kuafuai.andee.config.Memory] by type, tap to read the content),+ * **待办** (active and paused [net.kuafuai.andee.config.Todo]s, soonest first).+ * What the model wrote is Markdown and is drawn as such ([MarkdownView]).*- * No editing: the brain writes these, not the person. Delete is the only- * mutation, and it is **destructive** — gone from the encrypted blob, not- * archived — because a delete that merely hides something does not answer the- * question this page exists for.+ * No editing: the brain writes these, not the person. Delete (memories and+ * todos) is the only mutation, and it is **destructive** — gone from the+ * encrypted blob, not archived — because a delete that merely hides something+ * does not answer the question this page exists for.** Same window shape as [VaultUi], its sibling on top of the settings card:* focusable, hidden from accessibility, counted by [OwnCard] — a focused@@ -49,9 +54,18 @@ class NotebookUi(private var root: View? = null- /** 0 = memories, 1 = todos. */+ /** Index into [TABS]. */private var tab = 0+ /** The wiki article being read in the 维基 tab, or null for the list. */+ private var wikiOpen: String? = null++ /** What reading [wikiOpen] came back with; null while it is still being read. */+ private var wikiArticle: Result<net.kuafuai.andee.wiki.Article>? = null++ /** Memories whose content is unfolded. */+ private val expanded = mutableSetOf<String>()+/** Whether the compositor agreed to blur. See [Glass.frost]. */private var frosted = false@@ -137,7 +151,16 @@ class NotebookUi(orientation = LinearLayout.VERTICALsetPadding(dp(20), dp(16), dp(20), dp(16))}- if (tab == 0) buildMemories(body) else buildTodos(body)+ when (TABS[tab]) {+ Tab.SELF -> buildSelf(body)+ Tab.CARES -> buildCares(body)+ Tab.DIARY -> buildDiary(body)+ Tab.PLAN -> buildPlan(body)+ Tab.PEOPLE -> buildPeople(body)+ Tab.WIKI -> if (wikiOpen != null) buildArticle(body) else buildWiki(body)+ Tab.MEMORIES -> buildMemories(body)+ Tab.TODOS -> buildTodos(body)+ }scroll.addView(body, matchWrap())card.addView(scroll, LinearLayout.LayoutParams(MATCH, 0, 1f))@@ -204,17 +227,20 @@ class NotebookUi(layoutParams = LinearLayout.LayoutParams(dp(32), dp(32))}- private fun tabBar(): LinearLayout {+ /** Eight tabs do not fit a phone's width at a readable size, so the row scrolls sideways. */+ private fun tabBar(): View {val bar = LinearLayout(context).apply {orientation = LinearLayout.HORIZONTALsetPadding(dp(8), dp(8), dp(8), dp(8))}- bar.addView(tabButton(0, lctx.getString(R.string.notebook_tab_memories)))- bar.addView(View(context).apply {- layoutParams = LinearLayout.LayoutParams(dp(8), 1)- })- bar.addView(tabButton(1, lctx.getString(R.string.notebook_tab_todos)))- return bar+ TABS.forEachIndexed { i, t ->+ if (i > 0) bar.addView(View(context), LinearLayout.LayoutParams(dp(4), 1))+ bar.addView(tabButton(i, lctx.getString(t.label)))+ }+ return android.widget.HorizontalScrollView(context).apply {+ isHorizontalScrollBarEnabled = false+ addView(bar)+ }}private fun tabButton(index: Int, label: String): TextView =@@ -222,7 +248,7 @@ class NotebookUi(text = labeltextSize = Glass.Type.BODYgravity = Gravity.CENTER- setPadding(dp(16), dp(10), dp(16), dp(10))+ setPadding(dp(14), dp(10), dp(14), dp(10))val active = tab == indexsetTextColor(Color.parseColor(if (active) Glass.TITLE else Glass.SECONDARY),@@ -235,10 +261,216 @@ class NotebookUi(isClickable = !activeif (!active) {Glass.pressable(this)- setOnClickListener { tab = index; rebuild() }+ setOnClickListener { tab = index; wikiOpen = null; rebuild() }+ }+ layoutParams = LinearLayout.LayoutParams(WRAP, WRAP)+ }++ // ---- 自己 · 在意 · 日记 · 打算 · 人 · 维基 ----++ private fun md(text: String, color: String = Glass.LABEL, size: Float = Glass.Type.BODY): View =+ MarkdownView.build(context, text, color, size, onLink = ::openLink)++ /** A link opens in the browser, which an overlay would sit on top of — so the card goes first. */+ private fun openLink(url: String) {+ runCatching {+ context.startActivity(+ android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))+ .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK),+ )+ hide()+ }+ }++ private fun stamp(ms: Long): String = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US).format(ms)++ private fun panel(): LinearLayout = LinearLayout(context).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(dp(14), dp(12), dp(14), dp(12))+ background = Glass.panel(context, dp(14))+ }++ private fun label(text: String, size: Float, color: String, bold: Boolean = false, top: Int = 0): TextView =+ TextView(context).apply {+ this.text = text+ textSize = size+ setTextColor(Color.parseColor(color))+ if (bold) setTypeface(typeface, android.graphics.Typeface.BOLD)+ setPadding(0, dp(top), 0, 0)+ }++ private fun addRow(body: LinearLayout, v: View) = body.addView(v, matchWrap().apply { bottomMargin = dp(10) })++ private fun buildSelf(body: LinearLayout) {+ val n = Notebook.selfhood(context).narrative()+ if (n == null) {+ body.addView(emptyState(lctx.getString(R.string.notebook_empty_self), lctx.getString(R.string.notebook_empty_self_hint)))+ return+ }+ val p = panel()+ p.addView(label(lctx.getString(R.string.notebook_self_heading), Glass.Type.TITLE, Glass.TITLE, bold = true), matchWrap())+ p.addView(md(n.text, Glass.PHOTO_INK), matchWrap().apply { topMargin = dp(10) })+ p.addView(label(lctx.getString(R.string.notebook_updated_at, stamp(n.updatedAt)), Glass.Type.MICRO, Glass.MUTED, top = 8), matchWrap())+ addRow(body, p)+ }++ private fun buildCares(body: LinearLayout) {+ val self = Notebook.selfhood(context)+ val cares = self.cares().filter { it.status == "active" }.sortedByDescending { self.overdue(it) }+ if (cares.isEmpty()) {+ body.addView(emptyState(lctx.getString(R.string.notebook_empty_cares), lctx.getString(R.string.notebook_empty_cares_hint)))+ return+ }+ for (c in cares) {+ val p = panel()+ p.addView(label(c.what, Glass.Type.BODY, Glass.TITLE, bold = true), matchWrap())+ if (c.why.isNotBlank()) p.addView(md(c.why, Glass.PHOTO_INK, Glass.Type.CAPTION), matchWrap().apply { topMargin = dp(4) })+ if (c.note.isNotBlank()) p.addView(label(c.note, Glass.Type.CAPTION, Glass.SECONDARY, top = 6), matchWrap())+ val foot = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; setPadding(0, dp(8), 0, 0) }+ foot.addView(label(c.kind, Glass.Type.MICRO, Glass.MUTED), LinearLayout.LayoutParams(0, WRAP, 1f))+ if (self.overdue(c) > 0.5) foot.addView(label(lctx.getString(R.string.notebook_care_attention), Glass.Type.MICRO, Glass.ACCENT))+ p.addView(foot, matchWrap())+ addRow(body, p)+ }+ }++ private fun buildDiary(body: LinearLayout) {+ val pages = Notebook.selfhood(context).diary(7)+ if (pages.isEmpty()) {+ body.addView(emptyState(lctx.getString(R.string.notebook_empty_diary), lctx.getString(R.string.notebook_empty_diary_hint)))+ return+ }+ for (page in pages) {+ val p = panel()+ p.addView(label(page.date, Glass.Type.CAPTION, Glass.SECONDARY), matchWrap())+ p.addView(md(page.text), matchWrap().apply { topMargin = dp(10) })+ addRow(body, p)+ }+ }++ private fun buildPlan(body: LinearLayout) {+ val plans = Notebook.plans(context)+ val plan = plans.day(plans.today())+ if (plan == null) {+ body.addView(emptyState(lctx.getString(R.string.notebook_empty_plan), lctx.getString(R.string.notebook_empty_plan_hint)))+ return+ }+ val p = panel()+ p.addView(label(lctx.getString(R.string.notebook_plan_today), Glass.Type.TITLE, Glass.TITLE, bold = true), matchWrap())+ if (plan.intent.isNotBlank()) p.addView(md(plan.intent, Glass.SECONDARY, Glass.Type.CAPTION), matchWrap().apply { topMargin = dp(4) })+ val items = plan.items.filter { it.status == "planned" }+ if (items.isNotEmpty()) p.addView(View(context), LinearLayout.LayoutParams(1, dp(10)))+ for (item in items) {+ p.addView(label("• " + item.what, Glass.Type.BODY, Glass.LABEL, top = 6), matchWrap())+ val whenTxt = item.time.ifEmpty { item.slot }+ if (whenTxt.isNotEmpty()) p.addView(label(" $whenTxt", Glass.Type.CAPTION, Glass.SECONDARY), matchWrap())+ }+ addRow(body, p)+ }++ private fun buildPeople(body: LinearLayout) {+ val people = Notebook.people(context).all().filter { it.status == "active" }+ if (people.isEmpty()) {+ body.addView(emptyState(lctx.getString(R.string.notebook_empty_people), lctx.getString(R.string.notebook_empty_people_hint)))+ return+ }+ for (person in people) {+ val p = panel()+ p.addView(label(person.name, Glass.Type.TITLE, Glass.TITLE, bold = true), matchWrap())+ if (person.relation.isNotBlank()) p.addView(label(person.relation, Glass.Type.CAPTION, Glass.SECONDARY, top = 4), matchWrap())+ person.impressions.firstOrNull()?.let {+ p.addView(md(it.text, Glass.PHOTO_INK, Glass.Type.CAPTION), matchWrap().apply { topMargin = dp(8) })+ }+ addRow(body, p)+ }+ }++ private fun wikiLine(m: net.kuafuai.andee.wiki.Meta): String =+ listOf(m.kind, "v${m.version}", m.status.key, stamp(m.updated)).joinToString(" · ")++ private fun buildWiki(body: LinearLayout) {+ val entries = Notebook.wiki(context).all().sortedByDescending { it.updated }+ if (entries.isEmpty()) {+ body.addView(emptyState(lctx.getString(R.string.notebook_empty_wiki), lctx.getString(R.string.notebook_empty_wiki_hint)))+ return+ }+ for (m in entries) {+ val p = panel().apply {+ isClickable = true+ Glass.pressable(this)+ setOnClickListener { openArticle(m.id) }+ }+ val top = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }+ top.addView(label(m.title, Glass.Type.BODY, Glass.TITLE, bold = true), LinearLayout.LayoutParams(0, WRAP, 1f))+ top.addView(label(lctx.getString(R.string.notebook_wiki_open), Glass.Type.CAPTION, Glass.ACCENT))+ p.addView(top, matchWrap())+ p.addView(label(wikiLine(m), Glass.Type.MICRO, Glass.MUTED, top = 4), matchWrap())+ if (m.summary.isNotBlank()) {+ p.addView(label(m.summary, Glass.Type.CAPTION, Glass.PHOTO_INK, top = 6).apply {+ maxLines = 2+ ellipsize = android.text.TextUtils.TruncateAt.END+ }, matchWrap())+ }+ addRow(body, p)+ }+ }++ /** Reads the article from its file — off the main thread, since a backend other than the folder may be remote. */+ private fun openArticle(id: String) {+ wikiOpen = id+ wikiArticle = null+ rebuild()+ Thread({+ val r = Notebook.wiki(context).read(id)+ root?.post {+ if (wikiOpen != id) return@post+ wikiArticle = r+ rebuild()+ }+ }, "WikiRead").start()+ }++ private fun buildArticle(body: LinearLayout) {+ val bar = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }+ bar.addView(label(lctx.getString(R.string.notebook_wiki_back), Glass.Type.BODY, Glass.ACCENT).apply {+ setPadding(dp(2), dp(6), dp(12), dp(6))+ isClickable = true+ Glass.pressable(this)+ setOnClickListener { wikiOpen = null; wikiArticle = null; rebuild() }+ })+ bar.addView(View(context), LinearLayout.LayoutParams(0, 1, 1f))+ val article = wikiArticle?.getOrNull()+ if (article != null) {+ bar.addView(label(lctx.getString(R.string.notebook_wiki_copy), Glass.Type.CAPTION, Glass.ACCENT).apply {+ setPadding(dp(12), dp(6), dp(2), dp(6))+ isClickable = true+ Glass.pressable(this)+ setOnClickListener {+ val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ if (runCatching { cm.setPrimaryClip(ClipData.newPlainText(article.meta.title, article.body)) }.isSuccess) {+ text = lctx.getString(R.string.notebook_copied)+ }+ }+ })+ }+ body.addView(bar, matchWrap().apply { bottomMargin = dp(10) })+ val r = wikiArticle+ when {+ r == null -> body.addView(label(lctx.getString(R.string.notebook_wiki_reading), Glass.Type.BODY, Glass.SECONDARY), matchWrap())+ r.isFailure -> body.addView(label(r.exceptionOrNull()?.message.orEmpty(), Glass.Type.BODY, Glass.DANGER), matchWrap())+ else -> {+ val a = r.getOrThrow()+ val p = panel().apply { setPadding(dp(16), dp(14), dp(16), dp(16)) }+ p.addView(label(a.meta.title, Glass.Type.TITLE, Glass.TITLE, bold = true), matchWrap())+ p.addView(label(wikiLine(a.meta), Glass.Type.MICRO, Glass.MUTED, top = 4), matchWrap())+ if (a.meta.source.isNotBlank()) {+ p.addView(label(lctx.getString(R.string.notebook_wiki_source, a.meta.source), Glass.Type.MICRO, Glass.MUTED, top = 2), matchWrap())+ }+ p.addView(md(a.body), matchWrap().apply { topMargin = dp(14) })+ addRow(body, p)}- layoutParams = LinearLayout.LayoutParams(0, WRAP, 1f)}+ }@SuppressLint("SetTextI18n")private fun buildMemories(body: LinearLayout) {@@ -302,6 +534,16 @@ class NotebookUi(})row.addView(title, matchWrap())+ // Tap to read what it actually wrote down; the description is only the line it recalls it by.+ if (m.content.isNotBlank()) {+ row.isClickable = true+ Glass.pressable(row)+ row.setOnClickListener {+ if (!expanded.remove(m.name)) expanded += m.name+ rebuild()+ }+ }+if (m.description.isNotBlank()) {row.addView(TextView(context).apply {@@ -314,6 +556,10 @@ class NotebookUi()}+ if (m.name in expanded && m.content.isNotBlank()) {+ row.addView(md(m.content, Glass.PHOTO_INK, Glass.Type.CAPTION), matchWrap().apply { topMargin = dp(8) })+ }+val meta = buildString {val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US).format(m.updatedAt)append(stamp)@@ -415,8 +661,8 @@ class NotebookUi(layoutParams = matchWrap()}- private fun emptyState(msg: String): TextView = TextView(context).apply {- text = msg+ private fun emptyState(msg: String, hint: String? = null): TextView = TextView(context).apply {+ text = if (hint == null) msg else "$msg\n$hint"textSize = Glass.Type.BODYsetTextColor(Color.parseColor(Glass.MUTED))gravity = Gravity.CENTER@@ -448,7 +694,14 @@ class NotebookUi(private fun matchWrap() = LinearLayout.LayoutParams(MATCH, WRAP)+ private enum class Tab(@androidx.annotation.StringRes val label: Int) {+ SELF(R.string.notebook_tab_self), CARES(R.string.notebook_tab_cares), DIARY(R.string.notebook_tab_diary),+ PLAN(R.string.notebook_tab_plan), PEOPLE(R.string.notebook_tab_people), WIKI(R.string.notebook_tab_wiki),+ MEMORIES(R.string.notebook_tab_memories), TODOS(R.string.notebook_tab_todos),+ }+private companion object {+ val TABS = Tab.values()const val MATCH = LinearLayout.LayoutParams.MATCH_PARENTconst val WRAP = LinearLayout.LayoutParams.WRAP_CONTENT}diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xmlindex 02420a0..b10d80b 100644--- a/app/src/main/res/values-en/strings.xml+++ b/app/src/main/res/values-en/strings.xml@@ -477,6 +477,33 @@<string name="notebook_copied">Copied</string><string name="notebook_tab_memories">Memories</string><string name="notebook_tab_todos">Todos</string>+ <string name="notebook_tab_self">Self</string>+ <string name="notebook_tab_cares">Cares</string>+ <string name="notebook_tab_diary">Diary</string>+ <string name="notebook_tab_plan">Plan</string>+ <string name="notebook_tab_people">People</string>+ <string name="notebook_tab_wiki">Wiki</string>+ <string name="notebook_empty_self">No self-description yet</string>+ <string name="notebook_empty_self_hint">Andee will develop self-awareness as you talk</string>+ <string name="notebook_empty_cares">No cares yet</string>+ <string name="notebook_empty_cares_hint">Tell Andee what you care about</string>+ <string name="notebook_empty_diary">No diary yet</string>+ <string name="notebook_empty_diary_hint">Andee will write at the end of the day</string>+ <string name="notebook_empty_plan">No plan for today</string>+ <string name="notebook_empty_plan_hint">Andee will think about today in the morning</string>+ <string name="notebook_empty_people">No people yet</string>+ <string name="notebook_empty_people_hint">Andee will remember important people you mention</string>+ <string name="notebook_empty_wiki">Wiki is empty</string>+ <string name="notebook_empty_wiki_hint">Ask Andee knowledge questions</string>+ <string name="notebook_self_heading">Who I am</string>+ <string name="notebook_updated_at">Updated %1$s</string>+ <string name="notebook_care_attention">Needs attention</string>+ <string name="notebook_plan_today">Today\'s plan</string>+ <string name="notebook_wiki_open">Open ›</string>+ <string name="notebook_wiki_back">‹ Wiki</string>+ <string name="notebook_wiki_reading">Reading…</string>+ <string name="notebook_wiki_source">Source: %1$s</string>+ <string name="notebook_wiki_copy">Copy all</string><string name="notebook_empty_memories">Nothing written down yet</string><string name="notebook_empty_todos">Nothing queued up</string><string name="notebook_type_user">About you</string>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex a1c6a48..7d392f9 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -501,6 +501,33 @@<string name="notebook_copied">已复制</string><string name="notebook_tab_memories">记忆</string><string name="notebook_tab_todos">待办</string>+ <string name="notebook_tab_self">自己</string>+ <string name="notebook_tab_cares">在意</string>+ <string name="notebook_tab_diary">日记</string>+ <string name="notebook_tab_plan">打算</string>+ <string name="notebook_tab_people">人</string>+ <string name="notebook_tab_wiki">维基</string>+ <string name="notebook_empty_self">还没有自我描述</string>+ <string name="notebook_empty_self_hint">跟 Andee 对话时,它会逐渐形成自我认知</string>+ <string name="notebook_empty_cares">还没有在意的事</string>+ <string name="notebook_empty_cares_hint">告诉 Andee 你在意什么,它会帮你留意</string>+ <string name="notebook_empty_diary">还没有日记</string>+ <string name="notebook_empty_diary_hint">Andee 会在一天结束时自动记录</string>+ <string name="notebook_empty_plan">今天还没有打算</string>+ <string name="notebook_empty_plan_hint">Andee 会在早上思考今天的打算</string>+ <string name="notebook_empty_people">还没有记录的人</string>+ <string name="notebook_empty_people_hint">Andee 会记住你提到的重要的人</string>+ <string name="notebook_empty_wiki">维基还是空的</string>+ <string name="notebook_empty_wiki_hint">问 Andee 知识性的问题,它会保存到维基</string>+ <string name="notebook_self_heading">我是谁</string>+ <string name="notebook_updated_at">更新于 %1$s</string>+ <string name="notebook_care_attention">需要关注</string>+ <string name="notebook_plan_today">今天的打算</string>+ <string name="notebook_wiki_open">打开 ›</string>+ <string name="notebook_wiki_back">‹ 维基</string>+ <string name="notebook_wiki_reading">正在读取…</string>+ <string name="notebook_wiki_source">来源:%1$s</string>+ <string name="notebook_wiki_copy">复制全文</string><string name="notebook_empty_memories">还没记下什么</string><string name="notebook_empty_todos">没有排着的待办</string><string name="notebook_type_user">关于你</string>diff --git a/build.gradle b/build.gradleindex fe92dd6..b92c5af 100644--- a/build.gradle+++ b/build.gradle@@ -1,4 +1,18 @@// Top-level build file where you can add configuration options common to all sub-projects/modules.++// AGP 8.3's bundled R8 reads Kotlin metadata only up to 2.0, and Kotlin 2.1 (below) writes 2.1 — so+// `minifyReleaseWithR8` failed outright ("Provided Metadata instance has version 2.1.0"). A newer R8 on the+// buildscript classpath replaces the bundled one. Move it with the Kotlin version.+buildscript {+ repositories {+ maven { url 'https://maven.aliyun.com/repository/google' }+ google()+ }+ dependencies {+ classpath 'com.android.tools:r8:8.7.18'+ }+}+plugins {alias(libs.plugins.androidApplication) apply falseid 'org.jetbrains.kotlin.android' version '2.1.21' apply falsediff --git a/core/src/main/kotlin/net/kuafuai/andee/text/MarkdownBlocks.kt b/core/src/main/kotlin/net/kuafuai/andee/text/MarkdownBlocks.ktnew file mode 100644index 0000000..440862f--- /dev/null+++ b/core/src/main/kotlin/net/kuafuai/andee/text/MarkdownBlocks.kt@@ -0,0 +1,165 @@+package net.kuafuai.andee.text++/**+ * Markdown the model writes — diary pages, its self-description, wiki articles — parsed into blocks and styled runs+ * that each body draws with its own widgets (Compose on the Mac, Views on the phone). One parser, so a page cannot+ * render as a table on one body and a wall of pipes on the other.+ *+ * It is the subset the model actually writes: headings, lists, quotes, tables, fences, rules, and bold / italic /+ * code / strike / links inline. Anything it does not recognise falls through as an ordinary paragraph, so nothing+ * the model wrote is ever hidden. A leading `---` front-matter block (the wiki file's header) is dropped.+ *+ * `_italic_` only matches with no word character on either side, for the reason [stripMarkdown] gives: snake_case+ * tool names are everywhere in what this device writes, and `tap_screen_element` must not lose its underscores.+ */+object Md {+ sealed class Block {+ data class Heading(val level: Int, val text: String) : Block()+ data class Para(val text: String) : Block()+ /** [marker] is `•` or `3.`; [depth] counts nesting levels from 0. */+ data class Item(val marker: String, val depth: Int, val text: String) : Block()+ data class Quote(val inner: List<Block>) : Block()+ data class Code(val text: String) : Block()+ data class Table(val header: List<String>, val rows: List<List<String>>) : Block()+ object Rule : Block() { override fun toString() = "Rule" }+ }++ /** A stretch of inline text with one style. [link] marks any link; [url] is set only when it may be opened. */+ data class Run(+ val text: String,+ val bold: Boolean = false,+ val italic: Boolean = false,+ val code: Boolean = false,+ val strike: Boolean = false,+ val link: Boolean = false,+ val url: String? = null,+ )++ private val HEADING = Regex("""^(#{1,6})\s+(.*?)\s*#*\s*$""")+ private val ITEM = Regex("""^(\s*)([-*+]|\d+[.)])\s+(.*)$""")+ private val RULE = Regex("""^\s*([-*_])(\s*\1){2,}\s*$""")+ private val TABLE_SEP = Regex("""^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$""")++ fun stripFrontMatter(text: String): String {+ val t = text.trimStart()+ if (!t.startsWith("---\n")) return text+ val end = t.indexOf("\n---", 4)+ return if (end < 0) text else t.substring(end + 4).trimStart('\n')+ }++ fun blocks(raw: String): List<Block> = parse(stripFrontMatter(raw).replace("\r\n", "\n").lines())++ private fun parse(lines: List<String>): List<Block> {+ val out = mutableListOf<Block>()+ val para = mutableListOf<String>()+ fun flush() { if (para.isNotEmpty()) { out += Block.Para(joinLines(para)); para.clear() } }+ var i = 0+ while (i < lines.size) {+ val line = lines[i]+ val trimmed = line.trim()+ when {+ trimmed.isEmpty() -> { flush(); i++ }+ trimmed.startsWith("```") || trimmed.startsWith("~~~") -> {+ flush()+ val fence = trimmed.take(3)+ val body = mutableListOf<String>()+ i+++ while (i < lines.size && !lines[i].trim().startsWith(fence)) { body += lines[i]; i++ }+ i++ // the closing fence (or the end)+ out += Block.Code(body.joinToString("\n"))+ }+ HEADING.matches(trimmed) -> {+ flush()+ val m = HEADING.find(trimmed)!!+ out += Block.Heading(m.groupValues[1].length, m.groupValues[2])+ i+++ }+ RULE.matches(line) -> { flush(); out += Block.Rule; i++ }+ trimmed.startsWith(">") -> {+ flush()+ val inner = mutableListOf<String>()+ while (i < lines.size && lines[i].trim().startsWith(">")) {+ inner += lines[i].trim().removePrefix(">").removePrefix(" ")+ i+++ }+ out += Block.Quote(parse(inner))+ }+ trimmed.contains('|') && i + 1 < lines.size && TABLE_SEP.matches(lines[i + 1]) -> {+ flush()+ val header = cells(trimmed)+ i += 2+ val rows = mutableListOf<List<String>>()+ while (i < lines.size && lines[i].isNotBlank() && lines[i].contains('|')) { rows += cells(lines[i].trim()); i++ }+ out += Block.Table(header, rows)+ }+ ITEM.matches(line) -> {+ flush()+ val m = ITEM.find(line)!!+ val depth = m.groupValues[1].replace("\t", " ").length / 2+ val text = StringBuilder(m.groupValues[3])+ i+++ // A lazy continuation line belongs to the item, not to a new paragraph.+ while (i < lines.size && lines[i].isNotBlank() && lines[i].startsWith(" ") && !ITEM.matches(lines[i])) {+ text.append(' ').append(lines[i].trim()); i+++ }+ val marker = m.groupValues[2].let { if (it[0].isDigit()) it.trimEnd(')').trimEnd('.') + "." else "•" }+ out += Block.Item(marker, depth.coerceAtMost(4), text.toString())+ }+ else -> { para += trimmed; i++ }+ }+ }+ flush()+ return out+ }++ private fun cells(row: String): List<String> =+ row.trim().removePrefix("|").removeSuffix("|").split(Regex("""(?<!\\)\|""")).map { it.trim().replace("\\|", "|") }++ /** Soft line breaks: a space between Latin words, nothing between Chinese characters; two trailing spaces break. */+ private fun joinLines(lines: List<String>): String = buildString {+ for ((k, l) in lines.withIndex()) {+ if (k > 0) {+ val prev = lines[k - 1]+ if (prev.endsWith("\\")) { setLength(length - 1); append('\n') }+ else if (!(isCjk(last()) && isCjk(l.first()))) append(' ')+ }+ append(l)+ }+ }++ private fun isCjk(c: Char): Boolean = c.code in 0x2E80..0x9FFF || c.code in 0xFF00..0xFFEF || c.code in 0x3000..0x303F++ private val INLINE = Regex(+ """`([^`]+)`""" + // 1 code+ """|\*\*(.+?)\*\*|__(.+?)__""" + // 2,3 bold+ """|~~(.+?)~~""" + // 4 strike+ """|\[([^\]]+)]\(([^)\s]+)[^)]*\)""" + // 5,6 link+ """|(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?!\*)""" + // 7 italic+ """|(?<!\w)_(?!\s)(.+?)(?<!\s)_(?!\w)""" + // 8 italic+ """|<(https?://[^>\s]+)>""", // 9 autolink+ )++ /** Inline runs of [text], styles nesting (bold inside a link, italic inside bold). Only http(s) links carry a [Run.url]. */+ fun runs(text: String): List<Run> = mutableListOf<Run>().also { runs(text, Run(""), it) }.filter { it.text.isNotEmpty() }++ private fun runs(text: String, style: Run, out: MutableList<Run>) {+ var at = 0+ for (m in INLINE.findAll(text)) {+ out += style.copy(text = text.substring(at, m.range.first))+ val g = m.groupValues+ when {+ g[1].isNotEmpty() -> out += style.copy(text = g[1], code = true)+ g[2].isNotEmpty() || g[3].isNotEmpty() -> runs(g[2].ifEmpty { g[3] }, style.copy(bold = true), out)+ g[4].isNotEmpty() -> runs(g[4], style.copy(strike = true), out)+ g[5].isNotEmpty() -> runs(g[5], style.copy(link = true, url = g[6].takeIf(::web) ?: style.url), out)+ g[7].isNotEmpty() || g[8].isNotEmpty() -> runs(g[7].ifEmpty { g[8] }, style.copy(italic = true), out)+ g[9].isNotEmpty() -> out += style.copy(text = g[9], link = true, url = g[9])+ }+ at = m.range.last + 1+ }+ out += style.copy(text = text.substring(at))+ }++ /** A relative path from the model is shown, never followed. */+ private fun web(url: String) = url.startsWith("http://") || url.startsWith("https://")+}diff --git a/core/src/test/kotlin/net/kuafuai/andee/text/MarkdownBlocksTest.kt b/core/src/test/kotlin/net/kuafuai/andee/text/MarkdownBlocksTest.ktnew file mode 100644index 0000000..68c9f3e--- /dev/null+++ b/core/src/test/kotlin/net/kuafuai/andee/text/MarkdownBlocksTest.kt@@ -0,0 +1,68 @@+package net.kuafuai.andee.text++import net.kuafuai.andee.text.Md.Block+import net.kuafuai.andee.text.Md.Run+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class MarkdownBlocksTest {+ private val page = """+ ---+ title: 运营规划+ kind: plan+ ---++ # 运营规划(草稿 v1)++ > 本页是**基于公开数据**搭的初版。++ ---++ ## 一、现状++ | 项 | 值 | 来源 |+ |---|---|---|+ | 仓库 | `github.com/kuafuai/andee` | GitHub API |+ | 版本 | **v0.7.1** | Releases |++ - 留言区打开后,+ 拟了两条+ 1. 第一+ 中文换行+ 接着写+ """.trimIndent()++ @Test fun parsesWhatTheWikiActuallyHolds() {+ val b = Md.blocks(page)+ assertEquals(Block.Heading(1, "运营规划(草稿 v1)"), b[0])+ assertEquals(Block.Quote(listOf(Block.Para("本页是**基于公开数据**搭的初版。"))), b[1])+ assertEquals(Block.Rule, b[2])+ assertEquals(Block.Heading(2, "一、现状"), b[3])+ val t = b[4] as Block.Table+ assertEquals(listOf("项", "值", "来源"), t.header)+ assertEquals(2, t.rows.size)+ assertEquals(Block.Item("•", 0, "留言区打开后, 拟了两条"), b[5])+ assertEquals(Block.Item("1.", 0, "第一"), b[6])+ assertEquals(Block.Para("中文换行接着写"), b[7])+ }++ @Test fun inlineStylesNestAndTheMarkersAreGone() {+ val r = Md.runs("先**粗*斜*粗**后`码`再[链接](https://x.y)和[本地](notes/a.md)")+ assertEquals("先粗斜粗后码再链接和本地", r.joinToString("") { it.text })+ assertEquals(Run("斜", bold = true, italic = true), r[2])+ assertEquals(Run("码", code = true), r[5])+ assertEquals(Run("链接", link = true, url = "https://x.y"), r[7])+ // A relative path is shown as a link, never followed.+ assertEquals(Run("本地", link = true, url = null), r[9])+ }++ @Test fun snakeCaseKeepsItsUnderscores() {+ assertEquals(listOf(Run("call tap_screen_element then get_screen_element")), Md.runs("call tap_screen_element then get_screen_element"))+ }++ @Test fun noFrontMatterIsLeftAlone() {+ assertEquals(Block.Para("hello"), Md.blocks("hello").single())+ assertTrue(Md.blocks("").isEmpty())+ }+}diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.ktindex b5b5f4d..5fd1796 100644--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/DesktopBrainHost.kt@@ -82,6 +82,10 @@ class DesktopBrainHost(override fun planIndex(): String = DesktopNotebook.plans.indexForPrompt()+ override fun selfIndex(): String = DesktopNotebook.book.selfhood.indexForPrompt()++ override fun wikiIndex(): String = DesktopNotebook.book.wiki.indexForPrompt()+override fun friendsIndex(): String = Peers.tasks.indexForPrompt()override fun foldTopic(title: String, summary: String, rows: List<ScrollRow>, text: String): FoldedTopic? {diff --git a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Markdown.kt b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Markdown.ktindex 532637f..b566d6d 100644--- a/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Markdown.kt+++ b/desktop/src/main/kotlin/net/kuafuai/andee/desktop/Markdown.kt@@ -35,194 +35,63 @@ import androidx.compose.ui.text.withStyleimport androidx.compose.ui.unit.TextUnitimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.sp+import net.kuafuai.andee.text.Md/*** What the model writes in the notebook and the wiki is Markdown, and shown as plain text it reads as a- * page of asterisks and pipes. This is the subset it actually uses — headings, lists, quotes, tables,- * fences, rules, and bold / italic / code / links inline — drawn with the card's own palette. Anything it- * does not recognise falls through as an ordinary paragraph, so nothing the model wrote is ever hidden.- *- * A leading `---` front-matter block is dropped: it is the wiki file's header, which the card shows as- * its own line rather than as text.+ * page of asterisks and pipes. The parsing is [Md] in core, shared with the phone's renderer; this only+ * draws its blocks with the card's own palette.*/@Composablefun Markdown(text: String, modifier: Modifier = Modifier, color: Color = Palette.label, size: TextUnit = 14.sp) {- val blocks = remember(text) { MdParse.blocks(text) }+ val blocks = remember(text) { Md.blocks(text) }SelectionContainer(modifier) {Column {blocks.forEachIndexed { i, b ->- if (i > 0) Spacer(Modifier.height(if (b is MdBlock.Heading) 14.dp else 8.dp))+ if (i > 0) Spacer(Modifier.height(if (b is Md.Block.Heading) 14.dp else 8.dp))MdBlockView(b, color, size)}}}}-sealed class MdBlock {- data class Heading(val level: Int, val text: String) : MdBlock()- data class Para(val text: String) : MdBlock()- data class Item(val marker: String, val depth: Int, val text: String) : MdBlock()- data class Quote(val inner: List<MdBlock>) : MdBlock()- data class Code(val text: String) : MdBlock()- data class Table(val header: List<String>, val rows: List<List<String>>) : MdBlock()- object Rule : MdBlock()-}--object MdParse {- private val HEADING = Regex("""^(#{1,6})\s+(.*?)\s*#*\s*$""")- private val ITEM = Regex("""^(\s*)([-*+]|\d+[.)])\s+(.*)$""")- private val RULE = Regex("""^\s*([-*_])(\s*\1){2,}\s*$""")- private val TABLE_SEP = Regex("""^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$""")-- fun stripFrontMatter(text: String): String {- val t = text.trimStart()- if (!t.startsWith("---\n")) return text- val end = t.indexOf("\n---", 4)- return if (end < 0) text else t.substring(end + 4).trimStart('\n')- }-- fun blocks(raw: String): List<MdBlock> = parse(stripFrontMatter(raw).replace("\r\n", "\n").lines())-- private fun parse(lines: List<String>): List<MdBlock> {- val out = mutableListOf<MdBlock>()- val para = mutableListOf<String>()- fun flush() { if (para.isNotEmpty()) { out += MdBlock.Para(joinLines(para)); para.clear() } }- var i = 0- while (i < lines.size) {- val line = lines[i]- val trimmed = line.trim()- when {- trimmed.isEmpty() -> { flush(); i++ }- trimmed.startsWith("```") || trimmed.startsWith("~~~") -> {- flush()- val fence = trimmed.take(3)- val body = mutableListOf<String>()- i++- while (i < lines.size && !lines[i].trim().startsWith(fence)) { body += lines[i]; i++ }- i++ // the closing fence (or the end)- out += MdBlock.Code(body.joinToString("\n"))- }- HEADING.matches(trimmed) -> {- flush()- val m = HEADING.find(trimmed)!!- out += MdBlock.Heading(m.groupValues[1].length, m.groupValues[2])- i++- }- RULE.matches(line) -> { flush(); out += MdBlock.Rule; i++ }- trimmed.startsWith(">") -> {- flush()- val inner = mutableListOf<String>()- while (i < lines.size && lines[i].trim().startsWith(">")) {- inner += lines[i].trim().removePrefix(">").removePrefix(" ")- i++- }- out += MdBlock.Quote(parse(inner))- }- trimmed.contains('|') && i + 1 < lines.size && TABLE_SEP.matches(lines[i + 1]) -> {- flush()- val header = cells(trimmed)- i += 2- val rows = mutableListOf<List<String>>()- while (i < lines.size && lines[i].trim().contains('|') && lines[i].isNotBlank()) {- rows += cells(lines[i].trim()); i++- }- out += MdBlock.Table(header, rows)- }- ITEM.matches(line) -> {- flush()- val m = ITEM.find(line)!!- val depth = m.groupValues[1].replace("\t", " ").length / 2- val text = StringBuilder(m.groupValues[3])- i++- // A lazy continuation line belongs to the item, not to a new paragraph.- while (i < lines.size && lines[i].isNotBlank() && lines[i].startsWith(" ") && !ITEM.matches(lines[i])) {- text.append(' ').append(lines[i].trim()); i++- }- val marker = m.groupValues[2].let { if (it[0].isDigit()) it.trimEnd(')').trimEnd('.') + "." else "•" }- out += MdBlock.Item(marker, depth.coerceAtMost(4), text.toString())- }- else -> { para += trimmed; i++ }- }- }- flush()- return out- }-- private fun cells(row: String): List<String> =- row.trim().removePrefix("|").removeSuffix("|").split(Regex("""(?<!\\)\|""")).map { it.trim().replace("\\|", "|") }-- /** Soft line breaks: a space between Latin words, nothing between Chinese characters. */- private fun joinLines(lines: List<String>): String = buildString {- for ((k, l) in lines.withIndex()) {- if (k > 0) {- val hardBreak = lines[k - 1].endsWith(" ") || lines[k - 1].endsWith("\\")- if (hardBreak) { if (endsWith("\\")) setLength(length - 1); append('\n') }- else if (!(isCjk(last()) && isCjk(l.first()))) append(' ')- }- append(l)- }- }-- private fun isCjk(c: Char): Boolean = c.code in 0x2E80..0x9FFF || c.code in 0xFF00..0xFFEF || c.code in 0x3000..0x303F-- private val INLINE = Regex(- """`([^`]+)`""" + // 1 code- """|\*\*(.+?)\*\*|__(.+?)__""" + // 2,3 bold- """|~~(.+?)~~""" + // 4 strike- """|\[([^\]]+)]\(([^)\s]+)[^)]*\)""" + // 5,6 link- """|(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?!\*)|(?<!\w)_(?!\s)(.+?)(?<!\s)_(?!\w)""" + // 7,8 italic- """|<(https?://[^>\s]+)>""", // 9 autolink- )-- fun inline(text: String, accent: Color, codeBg: Color): AnnotatedString = buildAnnotatedString { appendInline(text, accent, codeBg) }-- private fun AnnotatedString.Builder.appendInline(text: String, accent: Color, codeBg: Color) {- var at = 0- for (m in INLINE.findAll(text)) {- append(text.substring(at, m.range.first))- val g = m.groupValues- when {- g[1].isNotEmpty() -> withStyle(SpanStyle(fontFamily = FontFamily.Monospace, background = codeBg, fontSize = 0.92.em())) { append(g[1]) }- g[2].isNotEmpty() || g[3].isNotEmpty() -> withStyle(SpanStyle(fontWeight = FontWeight.SemiBold)) { appendInline(g[2].ifEmpty { g[3] }, accent, codeBg) }- g[4].isNotEmpty() -> withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) { appendInline(g[4], accent, codeBg) }- g[5].isNotEmpty() -> link(g[5], g[6], accent)- g[7].isNotEmpty() || g[8].isNotEmpty() -> withStyle(SpanStyle(fontStyle = FontStyle.Italic)) { appendInline(g[7].ifEmpty { g[8] }, accent, codeBg) }- g[9].isNotEmpty() -> link(g[9], g[9], accent)- }- at = m.range.last + 1- }- append(text.substring(at))- }-- private fun AnnotatedString.Builder.link(label: String, url: String, accent: Color) {- // Only web links open; a relative path from the model is shown, not followed.- if (url.startsWith("http://") || url.startsWith("https://")) {- withLink(LinkAnnotation.Url(url, TextLinkStyles(SpanStyle(color = accent, textDecoration = TextDecoration.Underline)))) { append(label) }+/** [Md.runs] drawn as an [AnnotatedString] in the card's palette. */+private fun inline(text: String, accent: Color, codeBg: Color): AnnotatedString = buildAnnotatedString {+ for (r in Md.runs(text)) {+ val style = SpanStyle(+ fontWeight = if (r.bold) FontWeight.SemiBold else null,+ fontStyle = if (r.italic) FontStyle.Italic else null,+ fontFamily = if (r.code) FontFamily.Monospace else null,+ background = if (r.code) codeBg else Color.Unspecified,+ textDecoration = if (r.strike) TextDecoration.LineThrough else null,+ color = if (r.link) accent else Color.Unspecified,+ )+ val url = r.url+ if (url != null) {+ withLink(LinkAnnotation.Url(url, TextLinkStyles(style.copy(textDecoration = TextDecoration.Underline)))) { append(r.text) }} else {- withStyle(SpanStyle(color = accent)) { append(label) }+ withStyle(style) { append(r.text) }}}-- private fun Double.em() = androidx.compose.ui.unit.TextUnit(this.toFloat(), androidx.compose.ui.unit.TextUnitType.Em)}@Composable-private fun MdBlockView(b: MdBlock, color: Color, size: TextUnit) {+private fun MdBlockView(b: Md.Block, color: Color, size: TextUnit) {val accent = Palette.accentval codeBg = Palette.glassval line = (size.value * 1.6f).spwhen (b) {- is MdBlock.Heading -> {+ is Md.Block.Heading -> {val s = when (b.level) { 1 -> size.value + 6; 2 -> size.value + 3; 3 -> size.value + 1; else -> size.value }.sp- Text(MdParse.inline(b.text, accent, codeBg), color = Palette.title, fontSize = s, lineHeight = (s.value * 1.4f).sp,+ Text(inline(b.text, accent, codeBg), color = Palette.title, fontSize = s, lineHeight = (s.value * 1.4f).sp,fontWeight = if (b.level <= 2) FontWeight.SemiBold else FontWeight.Medium)}- is MdBlock.Para -> Text(MdParse.inline(b.text, accent, codeBg), color = color, fontSize = size, lineHeight = line)- is MdBlock.Item -> Row(Modifier.padding(start = (b.depth * 18).dp)) {+ is Md.Block.Para -> Text(inline(b.text, accent, codeBg), color = color, fontSize = size, lineHeight = line)+ is Md.Block.Item -> Row(Modifier.padding(start = (b.depth * 18).dp)) {Text(b.marker, color = Palette.secondary, fontSize = size, lineHeight = line, modifier = Modifier.widthIn(min = 18.dp))- Text(MdParse.inline(b.text, accent, codeBg), color = color, fontSize = size, lineHeight = line)+ Text(inline(b.text, accent, codeBg), color = color, fontSize = size, lineHeight = line)}- is MdBlock.Quote -> Row(Modifier.height(IntrinsicSize.Min)) {+ is Md.Block.Quote -> Row(Modifier.height(IntrinsicSize.Min)) {Box(Modifier.width(3.dp).fillMaxHeight().background(Palette.hairline, RoundedCornerShape(2.dp)))Spacer(Modifier.width(10.dp))Column {@@ -232,16 +101,16 @@ private fun MdBlockView(b: MdBlock, color: Color, size: TextUnit) {}}}- is MdBlock.Code -> Box(Modifier.fillMaxWidth().background(codeBg, RoundedCornerShape(8.dp)).horizontalScroll(rememberScrollState()).padding(10.dp)) {+ is Md.Block.Code -> Box(Modifier.fillMaxWidth().background(codeBg, RoundedCornerShape(8.dp)).horizontalScroll(rememberScrollState()).padding(10.dp)) {Text(b.text, color = color, fontSize = (size.value - 1).sp, fontFamily = FontFamily.Monospace, lineHeight = line, softWrap = false)}- is MdBlock.Table -> MdTable(b, color, size, accent, codeBg)- MdBlock.Rule -> Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(Palette.hairline))+ is Md.Block.Table -> MdTable(b, color, size, accent, codeBg)+ Md.Block.Rule -> Box(Modifier.fillMaxWidth().padding(vertical = 4.dp).height(1.dp).background(Palette.hairline))}}@Composable-private fun MdTable(t: MdBlock.Table, color: Color, size: TextUnit, accent: Color, codeBg: Color) {+private fun MdTable(t: Md.Block.Table, color: Color, size: TextUnit, accent: Color, codeBg: Color) {val cols = maxOf(t.header.size, t.rows.maxOfOrNull { it.size } ?: 0)val s = (size.value - 1).spColumn(Modifier.fillMaxWidth().background(codeBg, RoundedCornerShape(8.dp)).padding(vertical = 2.dp)) {@@ -249,7 +118,7 @@ private fun MdTable(t: MdBlock.Table, color: Color, size: TextUnit, accent: Colofun row(cells: List<String>, head: Boolean) {Row(Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 6.dp)) {for (c in 0 until cols) {- Text(MdParse.inline(cells.getOrElse(c) { "" }, accent, codeBg), color = if (head) Palette.title else color,+ Text(inline(cells.getOrElse(c) { "" }, accent, codeBg), color = if (head) Palette.title else color,fontSize = s, lineHeight = (s.value * 1.5f).sp, fontWeight = if (head) FontWeight.Medium else null,modifier = Modifier.weight(1f).padding(end = 10.dp))}diff --git a/desktop/src/test/kotlin/net/kuafuai/andee/desktop/MarkdownTest.kt b/desktop/src/test/kotlin/net/kuafuai/andee/desktop/MarkdownTest.ktdeleted file mode 100644index 3db0afe..0000000--- a/desktop/src/test/kotlin/net/kuafuai/andee/desktop/MarkdownTest.kt+++ /dev/null@@ -1,57 +0,0 @@-package net.kuafuai.andee.desktop--import androidx.compose.ui.graphics.Color-import org.junit.Assert.assertEquals-import org.junit.Assert.assertTrue-import org.junit.Test--class MarkdownTest {- private val page = """- ---- title: 运营规划- kind: plan- ----- # 运营规划(草稿 v1)-- > 本页是**基于公开数据**搭的初版。-- ----- ## 一、现状-- | 项 | 值 | 来源 |- |---|---|---|- | 仓库 | `github.com/kuafuai/andee` | GitHub API |- | 版本 | **v0.7.1** | Releases |-- - 留言区打开后,- 拟了两条- 1. 第一- 中文换行- 接着写- """.trimIndent()-- @Test fun parsesWhatTheWikiActuallyHolds() {- val b = MdParse.blocks(page)- assertEquals(MdBlock.Heading(1, "运营规划(草稿 v1)"), b[0])- assertTrue(b[1] is MdBlock.Quote)- assertEquals(MdBlock.Rule, b[2])- assertEquals(MdBlock.Heading(2, "一、现状"), b[3])- val t = b[4] as MdBlock.Table- assertEquals(listOf("项", "值", "来源"), t.header)- assertEquals(2, t.rows.size)- assertEquals(MdBlock.Item("•", 0, "留言区打开后, 拟了两条"), b[5])- assertEquals(MdBlock.Item("1.", 0, "第一"), b[6])- assertEquals(MdBlock.Para("中文换行接着写"), b[7])- }-- @Test fun inlineMarkersAreRemovedFromTheText() {- val s = MdParse.inline("先**粗**后`码`再[链接](https://x.y)和*斜*", Color.Blue, Color.Gray)- assertEquals("先粗后码再链接和斜", s.text)- }-- @Test fun noFrontMatterIsLeftAlone() {- assertEquals(MdBlock.Para("hello"), MdParse.blocks("hello").single())- }-}