Files
openchamber-android-native/third_party/mygo/internal/mobile/wire/gen/main.go
T
OpenChamber 6c0ee61750 feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
2026-11-18 13:22:59 +08:00

469 lines
16 KiB
Go

// Command gen writes the messages of spec.go for the three sides: Go
// (../msgs.go), Swift (the iOS host's Wire.swift) and Kotlin (the Android
// host's Wire.kt).
package main
import (
"bytes"
"fmt"
"go/format"
"log"
"os"
"path/filepath"
"strings"
"unicode"
)
// Paths from internal/mobile/wire, where go generate runs.
const (
goOut = "msgs.go"
swiftOut = "../ios/Sources/MyGoHost/Wire.swift"
kotlinOut = "../android/mygo/src/main/java/dev/mygo/Wire.kt"
)
func main() {
out := map[string][]byte{goOut: goSource(), swiftOut: swiftSource(), kotlinOut: kotlinSource()}
for path, b := range out {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
log.Fatal(err)
}
if err := os.WriteFile(path, b, 0o644); err != nil {
log.Fatal(err)
}
}
}
// lower makes a Go name the Swift and Kotlin one: ID → id, URLs → urls,
// SafeTop → safeTop, HTMLText → htmlText, BaseURL → baseURL.
func lower(s string) string {
r := []rune(s)
i := 0
for i < len(r) && unicode.IsUpper(r[i]) {
i++
}
switch {
case i == len(r) || string(r[i:]) == "s":
return strings.ToLower(s)
case i > 1:
i-- // the last capital starts the next word
}
return strings.ToLower(string(r[:i])) + string(r[i:])
}
const header = "Code generated by internal/mobile/wire/gen from spec.go; DO NOT EDIT."
// ---- Go
var goTypes = map[string]string{"int": "int", "float": "float64", "bool": "bool", "string": "string", "bytes": "[]byte", "strings": "[]string", "floats": "[]float64"}
var goRW = map[string]string{"int": "Int", "float": "Float", "bool": "Bool", "string": "String", "bytes": "Bytes", "strings": "Strings", "floats": "Floats"}
func goSource() []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "// %s\n\npackage wire\n\n", header)
b.WriteString("// Numbers of calls.\nconst (\n")
for i, m := range calls {
fmt.Fprintf(&b, "\tCall%s = %d\n", m.name, i+1)
}
b.WriteString(")\n\n// Numbers of events.\nconst (\n")
for i, m := range events {
fmt.Fprintf(&b, "\tEvent%s = %d\n", m.name, i+1)
}
b.WriteString(")\n\n")
goStruct := func(name, doc string, fs []field) {
if doc != "" {
fmt.Fprintf(&b, "// %s is %s.\n", name, doc)
}
fmt.Fprintf(&b, "type %s struct {\n", name)
for _, f := range fs {
fmt.Fprintf(&b, "\t%s %s\n", f.name, goTypes[f.typ])
}
b.WriteString("}\n\n")
}
enc := func(recv string, op string, fs []field) {
fmt.Fprintf(&b, "func (m *%s) Encode(w *Writer) {\n", recv)
if op != "" {
fmt.Fprintf(&b, "\tw.Uvarint(%s)\n", op)
}
for _, f := range fs {
fmt.Fprintf(&b, "\tw.%s(m.%s)\n", goRW[f.typ], f.name)
}
b.WriteString("}\n\n")
}
dec := func(recv string, fs []field) {
fmt.Fprintf(&b, "func (m *%s) Decode(r *Reader) {\n", recv)
for _, f := range fs {
fmt.Fprintf(&b, "\tm.%s = r.%s()\n", f.name, goRW[f.typ])
}
b.WriteString("}\n\n")
}
for _, m := range calls {
goStruct(m.name, m.doc, m.args)
enc(m.name, "Call"+m.name, m.args)
fmt.Fprintf(&b, "// Wait reports whether the caller waits for the host to run it.\nfunc (*%s) Wait() bool { return %v }\n\n", m.name, m.wait)
if m.wait {
goStruct(m.name+"Reply", "", m.reply)
dec(m.name+"Reply", m.reply)
}
}
for _, m := range events {
goStruct(m.name+"Event", m.doc, m.args)
dec(m.name+"Event", m.args)
if m.wait {
goStruct(m.name+"Reply", "", m.reply)
enc(m.name+"Reply", "", m.reply)
}
}
b.WriteString("// EventWaits reports whether the host waits for the reply of event op.\nfunc EventWaits(op uint64) bool {\n\tswitch op {\n\tcase ")
var waits []string
for _, m := range events {
if m.wait {
waits = append(waits, "Event"+m.name)
}
}
b.WriteString(strings.Join(waits, ", "))
b.WriteString(":\n\t\treturn true\n\t}\n\treturn false\n}\n")
src, err := format.Source(b.Bytes())
if err != nil {
log.Fatalf("%v\n%s", err, b.Bytes())
}
return src
}
// ---- Swift
var swiftTypes = map[string]string{"int": "Int", "float": "Double", "bool": "Bool", "string": "String", "bytes": "[UInt8]", "strings": "[String]", "floats": "[Double]"}
var swiftZero = map[string]string{"int": "0", "float": "0", "bool": "false", "string": `""`, "bytes": "[]", "strings": "[]", "floats": "[]"}
const swiftCodec = `
/// Writes the values of a message, as package wire encodes them.
public struct WireWriter {
public var buf: [UInt8] = []
public init() {}
mutating func uvarint(_ v: UInt64) {
var v = v
while v >= 0x80 { buf.append(UInt8(v & 0x7f) | 0x80); v >>= 7 }
buf.append(UInt8(v))
}
mutating func int(_ v: Int) { uvarint(UInt64(bitPattern: Int64((v << 1) ^ (v >> 63)))) }
mutating func bool(_ v: Bool) { buf.append(v ? 1 : 0) }
mutating func float(_ v: Double) { withUnsafeBytes(of: v.bitPattern.littleEndian) { buf.append(contentsOf: $0) } }
mutating func string(_ v: String) { let u = Array(v.utf8); uvarint(UInt64(u.count)); buf.append(contentsOf: u) }
mutating func bytes(_ v: [UInt8]) { uvarint(UInt64(v.count)); buf.append(contentsOf: v) }
mutating func strings(_ v: [String]) { uvarint(UInt64(v.count)); for s in v { string(s) } }
mutating func floats(_ v: [Double]) { uvarint(UInt64(v.count)); for f in v { float(f) } }
}
/// Reads the values of a message; past its end they read as zero.
public struct WireReader {
let buf: UnsafeRawBufferPointer
var at = 0
public init(_ buf: UnsafeRawBufferPointer) { self.buf = buf }
mutating func uvarint() -> UInt64 {
var v: UInt64 = 0, shift: UInt64 = 0
while at < buf.count {
let c = buf[at]; at += 1
v |= UInt64(c & 0x7f) << shift
if c < 0x80 { return v }
shift += 7
}
return 0
}
mutating func int() -> Int { let u = uvarint(); return Int(Int64(bitPattern: (u >> 1) ^ (0 &- (u & 1)))) }
mutating func bool() -> Bool { guard at < buf.count else { return false }; at += 1; return buf[at - 1] != 0 }
mutating func float() -> Double {
guard at + 8 <= buf.count else { at = buf.count; return 0 }
var bits: UInt64 = 0
for i in 0..<8 { bits |= UInt64(buf[at + i]) << (8 * UInt64(i)) }
at += 8
return Double(bitPattern: bits)
}
mutating func bytes() -> [UInt8] {
let n = Int(uvarint())
guard n >= 0, at + n <= buf.count else { at = buf.count; return [] }
defer { at += n }
return Array(buf[at..<at + n])
}
mutating func string() -> String { String(decoding: bytes(), as: UTF8.self) }
mutating func strings() -> [String] {
let n = Int(uvarint())
var s: [String] = []
for _ in 0..<min(n, buf.count - at) { s.append(string()) }
return s
}
mutating func floats() -> [Double] {
let n = Int(uvarint())
var f: [Double] = []
for _ in 0..<min(n, (buf.count - at) / 8) { f.append(float()) }
return f
}
}
`
func swiftSource() []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "// %s\n\n// swiftlint:disable all\n", header)
b.WriteString(swiftCodec)
str := func(name string, fs []field, decode, encode bool) {
fmt.Fprintf(&b, "\npublic struct %s {\n", name)
for _, f := range fs {
fmt.Fprintf(&b, " public var %s: %s = %s\n", lower(f.name), swiftTypes[f.typ], swiftZero[f.typ])
}
b.WriteString(" public init() {}\n")
if decode {
b.WriteString(" init(_ r: inout WireReader) {\n")
for _, f := range fs {
fmt.Fprintf(&b, " %s = r.%s()\n", lower(f.name), f.typ)
}
b.WriteString(" }\n")
}
if encode {
b.WriteString(" func encode(_ w: inout WireWriter) {\n")
for _, f := range fs {
fmt.Fprintf(&b, " w.%s(%s)\n", f.typ, lower(f.name))
}
b.WriteString(" }\n")
}
b.WriteString("}\n")
}
// Calls: the host decodes them and encodes their replies.
for _, m := range calls {
if len(m.args) > 0 {
str(m.name+"Call", m.args, true, false)
}
if m.wait {
str(m.name+"Reply", m.reply, false, true)
}
}
b.WriteString("\n/// The calls Go makes of the host, on the main thread.\npublic protocol HostCalls: AnyObject {\n")
for _, m := range calls {
sig := "func " + lower(m.name) + "("
if len(m.args) > 0 {
sig += "_ c: " + m.name + "Call"
}
sig += ")"
if m.wait {
sig += " -> " + m.name + "Reply"
}
if m.doc != "" {
fmt.Fprintf(&b, " /// %s\n", m.doc)
}
fmt.Fprintf(&b, " %s\n", sig)
}
b.WriteString("}\n\n/// Runs a call on h and encodes its reply, nil for a call not waited for.\npublic func dispatchCall(_ h: HostCalls, _ buf: UnsafeRawBufferPointer) -> [UInt8]? {\n var r = WireReader(buf)\n var w = WireWriter()\n switch r.uvarint() {\n")
for i, m := range calls {
fmt.Fprintf(&b, " case %d:\n", i+1)
arg := ""
if len(m.args) > 0 {
arg = m.name + "Call(&r)"
}
if m.wait {
fmt.Fprintf(&b, " h.%s(%s).encode(&w)\n return w.buf\n", lower(m.name), arg)
} else {
fmt.Fprintf(&b, " h.%s(%s)\n return nil\n", lower(m.name), arg)
}
}
b.WriteString(" default:\n return nil\n }\n}\n")
// Events: the host encodes them and decodes their replies.
b.WriteString("\n/// Encodes the events the host sends Go.\npublic enum Event {\n")
for i, m := range events {
if m.doc != "" {
fmt.Fprintf(&b, " /// %s\n", m.doc)
}
var params []string
for _, f := range m.args {
params = append(params, lower(f.name)+": "+swiftTypes[f.typ])
}
fmt.Fprintf(&b, " public static func %s(%s) -> [UInt8] {\n var w = WireWriter()\n w.uvarint(%d)\n", lower(m.name), strings.Join(params, ", "), i+1)
for _, f := range m.args {
fmt.Fprintf(&b, " w.%s(%s)\n", f.typ, lower(f.name))
}
b.WriteString(" return w.buf\n }\n")
}
b.WriteString("}\n")
for _, m := range events {
if m.wait {
str(m.name+"Reply", m.reply, true, false)
}
}
return b.Bytes()
}
// ---- Kotlin
var kotlinTypes = map[string]string{"int": "Long", "float": "Double", "bool": "Boolean", "string": "String", "bytes": "ByteArray", "strings": "List<String>", "floats": "DoubleArray"}
var kotlinZero = map[string]string{"int": "0L", "float": "0.0", "bool": "false", "string": `""`, "bytes": "ByteArray(0)", "strings": "emptyList()", "floats": "DoubleArray(0)"}
const kotlinCodec = `
/** Writes the values of a message, as package wire encodes them. */
class WireWriter {
private var buf = ByteArray(64)
var size = 0
private set
private fun room(n: Int) {
if (size + n > buf.size) buf = buf.copyOf(maxOf(buf.size * 2, size + n))
}
fun uvarint(v: Long) {
room(10)
var x = v
while (x and 0x7fL.inv() != 0L) {
buf[size++] = ((x and 0x7f) or 0x80).toByte()
x = x ushr 7
}
buf[size++] = x.toByte()
}
fun int(v: Long) = uvarint((v shl 1) xor (v shr 63))
fun bool(v: Boolean) { room(1); buf[size++] = if (v) 1 else 0 }
fun float(v: Double) {
room(8)
val bits = java.lang.Double.doubleToRawLongBits(v)
for (i in 0 until 8) buf[size++] = (bits ushr (8 * i)).toByte()
}
fun bytes(v: ByteArray) { uvarint(v.size.toLong()); room(v.size); v.copyInto(buf, size); size += v.size }
fun string(v: String) = bytes(v.toByteArray(Charsets.UTF_8))
fun strings(v: List<String>) { uvarint(v.size.toLong()); for (s in v) string(s) }
fun floats(v: DoubleArray) { uvarint(v.size.toLong()); for (f in v) float(f) }
fun toByteArray(): ByteArray = buf.copyOf(size)
}
/** Reads the values of a message; past its end they read as zero. */
class WireReader(private val buf: ByteArray) {
private var at = 0
/** Whether all of the message was read. */
fun done() = at >= buf.size
fun uvarint(): Long {
var v = 0L
var shift = 0
while (at < buf.size) {
val c = buf[at++].toInt() and 0xff
v = v or ((c and 0x7f).toLong() shl shift)
if (c < 0x80) return v
shift += 7
}
return 0
}
fun int(): Long { val u = uvarint(); return (u ushr 1) xor -(u and 1) }
fun bool(): Boolean = if (at < buf.size) buf[at++].toInt() != 0 else false
fun float(): Double {
if (at + 8 > buf.size) { at = buf.size; return 0.0 }
var bits = 0L
for (i in 0 until 8) bits = bits or ((buf[at + i].toLong() and 0xff) shl (8 * i))
at += 8
return java.lang.Double.longBitsToDouble(bits)
}
fun bytes(): ByteArray {
val n = uvarint().toInt()
if (n < 0 || at + n > buf.size) { at = buf.size; return ByteArray(0) }
val b = buf.copyOfRange(at, at + n)
at += n
return b
}
fun string(): String = String(bytes(), Charsets.UTF_8)
fun strings(): List<String> {
val n = uvarint().toInt()
val s = ArrayList<String>(minOf(n, buf.size - at).coerceAtLeast(0))
for (i in 0 until minOf(n, buf.size - at)) s.add(string())
return s
}
fun floats(): DoubleArray {
val n = minOf(uvarint().toInt(), (buf.size - at) / 8).coerceAtLeast(0)
return DoubleArray(n) { float() }
}
}
`
func kotlinSource() []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "// %s\n\n@file:Suppress(\"unused\", \"MemberVisibilityCanBePrivate\")\n\npackage dev.mygo\n", header)
b.WriteString(kotlinCodec)
class := func(name string, fs []field, decode, encode bool) {
fmt.Fprintf(&b, "\nclass %s(", name)
var ps []string
for _, f := range fs {
ps = append(ps, fmt.Sprintf("\n @JvmField var %s: %s = %s", lower(f.name), kotlinTypes[f.typ], kotlinZero[f.typ]))
}
b.WriteString(strings.Join(ps, ","))
if len(fs) > 0 {
b.WriteString(",\n")
}
b.WriteString(") {\n")
if decode {
b.WriteString(" constructor(r: WireReader) : this() {\n")
for _, f := range fs {
fmt.Fprintf(&b, " %s = r.%s()\n", lower(f.name), f.typ)
}
b.WriteString(" }\n")
}
if encode {
b.WriteString(" fun encode(w: WireWriter) {\n")
for _, f := range fs {
fmt.Fprintf(&b, " w.%s(%s)\n", f.typ, lower(f.name))
}
b.WriteString(" }\n")
}
b.WriteString("}\n")
}
for _, m := range calls {
if len(m.args) > 0 {
class(m.name+"Call", m.args, true, false)
}
if m.wait {
class(m.name+"Reply", m.reply, false, true)
}
}
b.WriteString("\n/** The calls Go makes of the host, on the UI thread. */\ninterface HostCalls {\n")
for _, m := range calls {
sig := "fun " + lower(m.name) + "("
if len(m.args) > 0 {
sig += "c: " + m.name + "Call"
}
sig += ")"
if m.wait {
sig += ": " + m.name + "Reply"
}
if m.doc != "" {
fmt.Fprintf(&b, " /** %s */\n", m.doc)
}
fmt.Fprintf(&b, " %s\n", sig)
}
b.WriteString("}\n\n/** Runs a call on h and encodes its reply, null for a call not waited for. */\nfun dispatchCall(h: HostCalls, buf: ByteArray): ByteArray? {\n val r = WireReader(buf)\n val w = WireWriter()\n when (r.uvarint().toInt()) {\n")
for i, m := range calls {
arg := ""
if len(m.args) > 0 {
arg = m.name + "Call(r)"
}
if m.wait {
fmt.Fprintf(&b, " %d -> { h.%s(%s).encode(w); return w.toByteArray() }\n", i+1, lower(m.name), arg)
} else {
fmt.Fprintf(&b, " %d -> h.%s(%s)\n", i+1, lower(m.name), arg)
}
}
b.WriteString(" }\n return null\n}\n\n/** Encodes the events the host sends Go. */\nobject Event {\n")
for i, m := range events {
if m.doc != "" {
fmt.Fprintf(&b, " /** %s */\n", m.doc)
}
var ps []string
for _, f := range m.args {
ps = append(ps, lower(f.name)+": "+kotlinTypes[f.typ])
}
fmt.Fprintf(&b, " @JvmStatic fun %s(%s): ByteArray {\n val w = WireWriter()\n w.uvarint(%d)\n", lower(m.name), strings.Join(ps, ", "), i+1)
for _, f := range m.args {
fmt.Fprintf(&b, " w.%s(%s)\n", f.typ, lower(f.name))
}
b.WriteString(" return w.toByteArray()\n }\n")
}
b.WriteString("}\n")
for _, m := range events {
if m.wait {
class(m.name+"Reply", m.reply, true, false)
}
}
return b.Bytes()
}