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.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
package texture
import (
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
)
var iosurface struct {
once sync.Once
retain, release uintptr
lock, unlock, base, bytesPerRow, width, height uintptr
pixelFormat uintptr
incrementUse, decrementUse uintptr
}
func loadIOSurface() bool {
s := &iosurface
s.once.Do(func() {
cf, err := purego.Dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
return
}
io, err := purego.Dlopen("/System/Library/Frameworks/IOSurface.framework/IOSurface", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
return
}
for _, f := range []struct {
lib uintptr
name string
p *uintptr
}{
{cf, "CFRetain", &s.retain}, {cf, "CFRelease", &s.release},
{io, "IOSurfaceLock", &s.lock}, {io, "IOSurfaceUnlock", &s.unlock},
{io, "IOSurfaceGetBaseAddress", &s.base}, {io, "IOSurfaceGetBytesPerRow", &s.bytesPerRow},
{io, "IOSurfaceGetWidth", &s.width}, {io, "IOSurfaceGetHeight", &s.height},
{io, "IOSurfaceGetPixelFormat", &s.pixelFormat},
{io, "IOSurfaceIncrementUseCount", &s.incrementUse}, {io, "IOSurfaceDecrementUseCount", &s.decrementUse},
} {
if *f.p, err = purego.Dlsym(f.lib, f.name); err != nil {
*f.p = 0
}
}
})
return s.release != 0 && s.width != 0
}
// useSurface marks a surface whose reference the texture took as in use:
// a pool of pixel buffers gives it to the producer again only once native
// UI shows another, rather than have it drawn while on screen.
func useSurface(s uintptr) {
if s != 0 && loadIOSurface() && iosurface.incrementUse != 0 {
purego.SyscallN(iosurface.incrementUse, s)
}
}
// retainSurface takes another reference to a surface, in use.
func retainSurface(s uintptr) {
if s != 0 && loadIOSurface() {
purego.SyscallN(iosurface.retain, s)
useSurface(s)
}
}
// releaseSurface lets go of a reference retainSurface or useSurface took.
func releaseSurface(s uintptr) {
if s != 0 && loadIOSurface() {
if iosurface.decrementUse != 0 {
purego.SyscallN(iosurface.decrementUse, s)
}
purego.SyscallN(iosurface.release, s)
}
}
func surfaceSize(s uintptr) (int, int) {
if s == 0 || !loadIOSurface() {
return 0, 0
}
w, _, _ := purego.SyscallN(iosurface.width, s)
h, _, _ := purego.SyscallN(iosurface.height, s)
return int(w), int(h)
}
// pixelFormatBGRA is kCVPixelFormatType_32BGRA, 'BGRA'.
const pixelFormatBGRA = 0x42475241
// readSurface copies the pixels of a 32-bit BGRA surface as premultiplied
// RGBA rows, for the CPU renderer.
func readSurface(s uintptr) []byte {
if s == 0 || !loadIOSurface() {
return nil
}
w, h := surfaceSize(s)
if f, _, _ := purego.SyscallN(iosurface.pixelFormat, s); f != pixelFormatBGRA || w == 0 || h == 0 {
return make([]byte, 4*w*h)
}
const readOnly = 1
purego.SyscallN(iosurface.lock, s, readOnly, 0)
defer purego.SyscallN(iosurface.unlock, s, readOnly, 0)
base, _, _ := purego.SyscallN(iosurface.base, s)
stride, _, _ := purego.SyscallN(iosurface.bytesPerRow, s)
if base == 0 {
return make([]byte, 4*w*h)
}
src := unsafe.Slice(*(**byte)(unsafe.Pointer(&base)), int(stride)*h)
out := make([]byte, 4*w*h)
for y := range h {
row, dst := src[y*int(stride):], out[4*w*y:]
for x := range w {
dst[4*x], dst[4*x+1], dst[4*x+2], dst[4*x+3] = row[4*x+2], row[4*x+1], row[4*x], row[4*x+3]
}
}
return out
}
var (
selDescriptor = objc.RegisterName("texture2DDescriptorWithPixelFormat:width:height:mipmapped:")
selSetUsage = objc.RegisterName("setUsage:")
selNewTexture = objc.RegisterName("newTextureWithDescriptor:iosurface:plane:")
)
// metalTexture returns a new texture of the Metal device showing the
// 32-bit BGRA surface s, w×h, which it retains while frames draw it.
func metalTexture(device, s uintptr, w, h int) uintptr {
if device == 0 || s == 0 {
return 0
}
const pixelFormatBGRA8Unorm, usageShaderRead = 80, 1
desc := objc.ID(objc.GetClass("MTLTextureDescriptor")).Send(selDescriptor, pixelFormatBGRA8Unorm, w, h, false)
if desc == 0 {
return 0
}
desc.Send(selSetUsage, usageShaderRead)
return uintptr(objc.ID(device).Send(selNewTexture, desc, s, 0))
}
+10
View File
@@ -0,0 +1,10 @@
//go:build !darwin
package texture
func useSurface(uintptr) {}
func retainSurface(uintptr) {}
func releaseSurface(uintptr) {}
func surfaceSize(uintptr) (int, int) { return 0, 0 }
func readSurface(uintptr) []byte { return nil }
func metalTexture(device, s uintptr, w, h int) uintptr { return 0 }
+182
View File
@@ -0,0 +1,182 @@
// Package texture is native.Texture: an image on the GPU that a native
// module's implementation draws into, as IOSurfaces on macOS, and that
// native UI shows as any image, with no copy through the CPU but for the
// CPU renderer's.
package texture
import (
"runtime"
"sync"
"sync/atomic"
"weak"
"github.com/egoist/mygo/internal/imagesrc"
"github.com/egoist/mygo/internal/scene"
)
type mark = imagesrc.Mark
// Texture is an image a native module presents frames into.
type Texture struct {
mark
id uint64
s *state
}
// state is what a texture's cleanup releases: the surfaces it holds.
type state struct {
mu sync.Mutex
// pending is the surface presented last, retained, which the next
// frame shows; seq counts presents.
pending uintptr
seq uint64
w, h int
// watch asks the windows that show the texture for a frame, by their
// key.
watch map[any]*watcher
// Main thread only: the image frames draw, and the surface it shows,
// retained.
img *scene.Image
shown uintptr
shownSeq uint64
// past are the surfaces frames showed before, held, in use, while
// frames in flight on the GPU may still read them.
past [inFlight]uintptr
}
// inFlight bounds the frames a renderer has in flight that may still read
// a surface the texture no longer shows (the Metal renderer's ring of two,
// and one more).
const inFlight = 3
// watcher is a window that drew the texture: invalidate asks it for a
// frame, and seen is the present it drew last.
type watcher struct {
invalidate func()
seen uint64
}
// staleAfter is how many presents a window may let pass without drawing
// the texture before it no longer counts as showing it. It draws it again
// as it shows it again, which watches it again.
const staleAfter = 128
var (
lastID atomic.Uint64
textures sync.Map // uint64 → weak.Pointer[Texture]
)
// New makes a texture, which shows nothing until a frame is presented.
func New() *Texture {
t := &Texture{id: lastID.Add(1), s: &state{watch: map[any]*watcher{}}}
textures.Store(t.id, weak.Make(t))
runtime.AddCleanup(t, func(s *state) { s.release() }, t.s)
return t
}
// Lookup returns the texture of id, or nil once it is gone.
func Lookup(id uint64) *Texture {
if p, ok := textures.Load(id); ok {
return p.(weak.Pointer[Texture]).Value()
}
return nil
}
// ID identifies the texture for the platform.
func (t *Texture) ID() uint64 { return t.id }
// Present shows surface, an IOSurfaceRef whose reference it takes, in the
// next frame of the windows showing the texture, from any thread.
func (t *Texture) Present(surface uintptr) {
if surface == 0 {
return
}
// In use while the texture holds it: a pool of pixel buffers gives it
// to the producer again only once native UI shows another.
useSurface(surface)
w, h := surfaceSize(surface)
s := t.s
s.mu.Lock()
old := s.pending
s.pending, s.w, s.h = surface, w, h
s.seq++
watch := make([]func(), 0, len(s.watch))
for key, w := range s.watch {
if s.seq-w.seen > staleAfter {
// Its window stopped drawing it, or is gone.
delete(s.watch, key)
continue
}
watch = append(watch, w.invalidate)
}
s.mu.Unlock()
releaseSurface(old)
for _, f := range watch {
f()
}
}
// Size returns the size of the frames presented last, in pixels, which
// Image lays the texture out at, as DIPs.
func (t *Texture) Size() (w, h float32) {
t.s.mu.Lock()
defer t.s.mu.Unlock()
return float32(t.s.w), float32(t.s.h)
}
// Frame returns the image a frame draws, showing the surface presented
// last, or nil before any. invalidate asks the window of key for a frame,
// which the next present calls. Main thread only.
func (t *Texture) Frame(key any, invalidate func()) *scene.Image {
s := t.s
s.mu.Lock()
if w := s.watch[key]; w != nil {
w.invalidate, w.seen = invalidate, s.seq
} else {
s.watch[key] = &watcher{invalidate: invalidate, seen: s.seq}
}
surface, seq, w, h := s.pending, s.seq, s.w, s.h
if surface != 0 && seq != s.shownSeq {
retainSurface(surface)
}
s.mu.Unlock()
if surface == 0 {
return nil
}
if s.img == nil {
s.img = scene.NewImageRGBA(w, h, nil)
// The CPU renderer reads the surface's pixels; GPU renderers wrap
// it, where they can (GPUTexture).
s.img.Restore = func() []byte { return readSurface(s.shown) }
s.img.GPU = s
}
if seq != s.shownSeq {
releaseSurface(s.past[0])
copy(s.past[:], s.past[1:])
s.past[inFlight-1] = s.shown
s.shown, s.shownSeq = surface, seq
s.img.W, s.img.H = w, h
s.img.Pix = nil
s.img.Changed()
}
return s.img
}
// GPUTexture wraps the surface shown in a texture of the renderer, with no
// copy: Metal's, on macOS. Main thread only.
func (s *state) GPUTexture(api scene.GPUAPI, device uintptr) uintptr {
if api != scene.Metal || s.img == nil {
return 0
}
return metalTexture(device, s.shown, s.img.W, s.img.H)
}
func (s *state) release() {
releaseSurface(s.pending)
releaseSurface(s.shown)
for _, p := range s.past {
releaseSurface(p)
}
}
+144
View File
@@ -0,0 +1,144 @@
package texture
import (
"runtime"
"testing"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/scene"
)
// newSurface makes a w×h 32-bit BGRA IOSurface filled with b, g, r, a.
func newSurface(t *testing.T, w, h int, bgra [4]byte) uintptr {
t.Helper()
cf, err := purego.Dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
t.Fatal(err)
}
io, err := purego.Dlopen("/System/Library/Frameworks/IOSurface.framework/IOSurface", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
t.Fatal(err)
}
sym := func(lib uintptr, name string) uintptr {
p, err := purego.Dlsym(lib, name)
if err != nil {
t.Fatal(err)
}
return p
}
const kCFNumberSInt32Type = 3
number := func(v int32) uintptr {
n, _, _ := purego.SyscallN(sym(cf, "CFNumberCreate"), 0, kCFNumberSInt32Type, uintptr(unsafe.Pointer(&v)))
return n
}
key := func(name string) uintptr {
p := sym(io, name) // the address of a global CFStringRef
return **(**uintptr)(unsafe.Pointer(&p))
}
keys := []uintptr{key("kIOSurfaceWidth"), key("kIOSurfaceHeight"), key("kIOSurfaceBytesPerElement"), key("kIOSurfacePixelFormat")}
values := []uintptr{number(int32(w)), number(int32(h)), number(4), number(pixelFormatBGRA)}
dict, _, _ := purego.SyscallN(sym(cf, "CFDictionaryCreate"), 0, uintptr(unsafe.Pointer(&keys[0])), uintptr(unsafe.Pointer(&values[0])), uintptr(len(keys)),
sym(cf, "kCFTypeDictionaryKeyCallBacks"), sym(cf, "kCFTypeDictionaryValueCallBacks"))
runtime.KeepAlive(keys)
runtime.KeepAlive(values)
s, _, _ := purego.SyscallN(sym(io, "IOSurfaceCreate"), dict)
if s == 0 {
t.Fatal("IOSurfaceCreate failed")
}
purego.SyscallN(iosurfaceLock(), s, 0, 0)
base, _, _ := purego.SyscallN(iosurface.base, s)
stride, _, _ := purego.SyscallN(iosurface.bytesPerRow, s)
pix := unsafe.Slice(*(**byte)(unsafe.Pointer(&base)), int(stride)*h)
for y := range h {
for x := range w {
copy(pix[y*int(stride)+4*x:], bgra[:])
}
}
purego.SyscallN(iosurface.unlock, s, 0, 0)
return s
}
func iosurfaceLock() uintptr {
loadIOSurface()
return iosurface.lock
}
func useCount(t *testing.T, s uintptr) int {
io, _ := purego.Dlopen("/System/Library/Frameworks/IOSurface.framework/IOSurface", purego.RTLD_NOW|purego.RTLD_GLOBAL)
f, err := purego.Dlsym(io, "IOSurfaceGetUseCount")
if err != nil {
t.Fatal(err)
}
n, _, _ := purego.SyscallN(f, s)
return int(int32(n))
}
func TestPresentAndFrame(t *testing.T) {
tex := New()
key := new(int)
if img := tex.Frame(key, func() {}); img != nil {
t.Fatal("a frame before any present")
}
asked := 0
tex.Frame(key, func() { asked++ })
// Each present takes a reference, which the producer gives it.
red := newSurface(t, 3, 2, [4]byte{0, 0, 255, 255})
purego.SyscallN(iosurface.retain, red) // ours, to read its use count after
tex.Present(red)
if asked != 1 {
t.Fatalf("the present asked for %d frames", asked)
}
if w, h := tex.Size(); w != 3 || h != 2 {
t.Fatalf("Size = %v×%v", w, h)
}
img := tex.Frame(key, func() { asked++ })
if img == nil || img.W != 3 || img.H != 2 || img.GPU == nil {
t.Fatalf("frame %+v", img)
}
if mtl, err := purego.Dlopen("/System/Library/Frameworks/Metal.framework/Metal", purego.RTLD_NOW|purego.RTLD_GLOBAL); err == nil {
if create, err := purego.Dlsym(mtl, "MTLCreateSystemDefaultDevice"); err == nil {
if device, _, _ := purego.SyscallN(create); device != 0 {
tex := objc.ID(img.GPU.GPUTexture(scene.Metal, device))
if tex == 0 || tex.Send(objc.RegisterName("width")) != 3 || tex.Send(objc.RegisterName("iosurface")) != objc.ID(red) {
t.Errorf("the Metal texture %x does not show the surface", tex)
}
tex.Send(objc.RegisterName("release"))
}
}
}
if px := img.Pixels(); len(px) != 24 || px[0] != 255 || px[1] != 0 || px[2] != 0 || px[3] != 255 {
t.Fatalf("the CPU's pixels %v, want red RGBA", px)
}
v := img.Version()
blue := newSurface(t, 3, 2, [4]byte{255, 0, 0, 255})
tex.Present(blue)
if useCount(t, red) == 0 {
t.Error("the surface shown went back to its producer while frames may still draw it")
}
if img := tex.Frame(key, func() {}); img.Version() == v || img.Pixels()[2] != 255 {
t.Fatalf("the next frame: version %d (was %d), pixels %v", img.Version(), v, img.Pixels())
}
// Frames in flight past, the red surface goes back.
for range inFlight {
tex.Present(newSurface(t, 3, 2, [4]byte{}))
tex.Frame(key, func() {})
}
if n := useCount(t, red); n != 0 {
t.Errorf("the red surface is still in use %d times", n)
}
// A window that stops drawing the texture stops being asked to.
asked = 0
for range 2 * staleAfter {
tex.Present(newSurface(t, 1, 1, [4]byte{}))
}
if asked > staleAfter || len(tex.s.watch) != 0 {
t.Errorf("a window that no longer draws the texture was asked %d times, and %d windows watch it", asked, len(tex.s.watch))
}
purego.SyscallN(iosurface.release, red)
}