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

+314
View File
@@ -0,0 +1,314 @@
// Package transfer describes data exchanged through the clipboard and native
// drag and drop. Values contain explicit representations, never Go object
// references. The immutable model is shared by both integrations.
package transfer
import (
"bytes"
"errors"
"fmt"
"net/url"
"path/filepath"
"slices"
"strings"
"sync"
)
// Format names a representation. Use a MIME type for custom serialized data.
type Format string
const (
Text Format = "text/plain"
HTML Format = "text/html"
URIList Format = "text/uri-list"
// FileList is a URI list known to contain local files. Backends expose
// it as the system's file-list format as well as text/uri-list.
FileList Format = "application/x-mygo-file-list"
PNG Format = "image/png"
// Markdown is Markdown's text (RFC 7763), net.daringfireball.markdown
// on macOS.
Markdown Format = "text/markdown"
)
// ErrFormat means the requested item or representation is not available.
var ErrFormat = errors.New("transfer: representation unavailable")
// ErrProviderPanic means a lazy provider panicked. The panic is contained at
// the data boundary, rather than escaping through a native callback.
var ErrProviderPanic = errors.New("transfer: provider panicked")
type value struct {
once sync.Once
provider func() ([]byte, error)
bytes []byte
err error
}
// Representation is one format of an item, made with Bytes or Lazy.
type Representation struct {
format Format
value *value
}
// Bytes makes a representation, copying b. Empty data is valid.
func Bytes(format Format, b []byte) Representation {
validateFormat(format)
return Representation{format: format, value: &value{bytes: bytes.Clone(b)}}
}
// Lazy advertises a format without producing its bytes. The provider runs
// at most once per snapshot, when a destination requests this format;
// failures are cached too. Native integrations call it on the main thread.
// It must return promptly and must not wait for another main-thread action.
// Prepare expensive data on a goroutine before offering it.
func Lazy(format Format, provider func() ([]byte, error)) Representation {
validateFormat(format)
if provider == nil {
panic("transfer: nil provider")
}
return Representation{format: format, value: &value{provider: provider}}
}
func validateFormat(f Format) {
if f == "" || strings.ContainsAny(string(f), "\x00\r\n") {
panic("transfer: invalid format")
}
}
// Item is a value with alternative representations, in preference order.
// For example, one item can offer HTML and plain text of the same content.
type Item struct{ reps []Representation }
// NewItem makes an item. Duplicate formats and zero representations panic.
func NewItem(reps ...Representation) Item {
seen := map[Format]bool{}
for _, r := range reps {
if r.value == nil || seen[r.format] {
panic("transfer: invalid or duplicate representation")
}
seen[r.format] = true
}
return Item{reps: slices.Clone(reps)}
}
// Formats lists the item's advertised formats without invoking providers.
func (i Item) Formats() []Format {
f := make([]Format, len(i.reps))
for n, r := range i.reps {
f[n] = r.format
}
return f
}
// Read returns a copy of the requested bytes. It is safe from any goroutine.
func (i Item) Read(format Format) ([]byte, error) {
for _, r := range i.reps {
if r.format != format {
continue
}
v := r.value
v.once.Do(func() {
defer func() {
if p := recover(); p != nil {
v.bytes, v.err = nil, fmt.Errorf("%w: %v", ErrProviderPanic, p)
}
}()
if v.provider != nil {
v.bytes, v.err = v.provider()
if v.err != nil {
v.bytes = nil
}
v.bytes = bytes.Clone(v.bytes)
}
})
return bytes.Clone(v.bytes), v.err
}
return nil, ErrFormat
}
// Data is an immutable collection of items. Its zero value is empty.
type Data struct{ items []Item }
// New makes data from items, preserving their order.
func New(items ...Item) Data { return Data{items: slices.Clone(items)} }
// Items returns the items. Modifying the returned slice does not change Data.
func (d Data) Items() []Item { return slices.Clone(d.items) }
// Formats lists all formats, in item order, without invoking providers.
func (d Data) Formats() []Format {
var formats []Format
for _, i := range d.items {
for _, f := range i.Formats() {
if !slices.Contains(formats, f) {
formats = append(formats, f)
}
}
}
return formats
}
// Preferred chooses the first preferred format advertised by the data,
// without invoking any provider. The caller supplies its own preference
// order (for example, custom JSON before HTML before plain text).
func (d Data) Preferred(formats ...Format) (Format, bool) {
return PreferredFormat(d.Formats(), formats...)
}
// PreferredFormat negotiates formats from a clipboard or drag offer without
// requesting data. Receiver preference order wins over source item order.
func PreferredFormat(offered []Format, preferred ...Format) (Format, bool) {
for _, f := range preferred {
if slices.Contains(offered, f) {
return f, true
}
}
return "", false
}
// Snapshot starts a new provider cache, as each clipboard write or drag does.
func (d Data) Snapshot() Data {
items := make([]Item, len(d.items))
for n, i := range d.items {
for _, r := range i.reps {
v := &value{provider: r.value.provider}
if v.provider == nil {
v.bytes = bytes.Clone(r.value.bytes)
}
items[n].reps = append(items[n].reps, Representation{r.format, v})
}
}
return New(items...)
}
// Read reads a format for platforms with a single selection/data object.
// Text items are joined with newlines and URI lists with CRLF. Other
// formats use the first item offering them; macOS preserves separate items.
func (d Data) Read(format Format) ([]byte, error) {
var parts [][]byte
for _, i := range d.items {
if !slices.Contains(i.Formats(), format) {
continue
}
b, err := i.Read(format)
if err != nil {
return nil, err
}
parts = append(parts, b)
if format != Text && format != URIList && format != FileList {
break
}
}
if len(parts) == 0 {
return nil, ErrFormat
}
if format == URIList || format == FileList {
return bytes.Join(parts, []byte("\r\n")), nil
}
return bytes.Join(parts, []byte("\n")), nil
}
// Materialize copies matching representations into data with no providers.
// A failed representation rejects the transfer; an empty match is ErrFormat.
func (d Data) Materialize(formats []Format) (Data, error) {
var items []Item
for _, i := range d.items {
var reps []Representation
for _, f := range i.Formats() {
if !slices.Contains(formats, f) {
continue
}
b, err := i.Read(f)
if err != nil {
return Data{}, err
}
reps = append(reps, Bytes(f, b))
}
if len(reps) > 0 {
items = append(items, NewItem(reps...))
}
}
if len(items) == 0 {
return Data{}, ErrFormat
}
return New(items...), nil
}
// TextData offers a plain text item.
func TextData(text string) Data { return New(NewItem(Bytes(Text, []byte(text)))) }
// URLData offers a URL as a URI list and as plain text.
func URLData(raw string) (Data, error) {
u, err := url.Parse(raw)
if err != nil || u.Scheme == "" || strings.ContainsAny(raw, "\r\n\x00") {
return Data{}, fmt.Errorf("transfer: invalid URL %q", raw)
}
return New(NewItem(Bytes(URIList, []byte(raw)), Bytes(Text, []byte(raw)))), nil
}
// FileData offers existing file paths as file URLs, one item per path.
// Paths must be absolute. It neither reads nor deletes the files.
func FileData(paths ...string) (Data, error) {
items := make([]Item, 0, len(paths))
for _, path := range paths {
if !filepath.IsAbs(path) || strings.ContainsRune(path, 0) {
return Data{}, fmt.Errorf("transfer: file path must be absolute: %q", path)
}
p := filepath.ToSlash(path)
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
u := (&url.URL{Scheme: "file", Path: p}).String()
items = append(items, NewItem(Bytes(FileList, []byte(u)), Bytes(URIList, []byte(u))))
}
return New(items...), nil
}
// URLs returns the URLs of all URI-list items, ignoring comments and blanks.
func (d Data) URLs() ([]string, error) {
b, err := d.Read(URIList)
if err != nil {
return nil, err
}
var out []string
for _, line := range strings.Split(strings.ReplaceAll(string(b), "\r\n", "\n"), "\n") {
line = strings.TrimSpace(line)
if line != "" && !strings.HasPrefix(line, "#") {
out = append(out, line)
}
}
return out, nil
}
// Files returns local file paths only. Remote file authorities and other
// URL schemes are ignored, so a network URL never becomes a filesystem path.
func (d Data) Files() ([]string, error) {
var urls []string
var err error
if b, e := d.Read(FileList); e == nil {
urls = strings.Split(strings.ReplaceAll(string(b), "\r\n", "\n"), "\n")
} else if errors.Is(e, ErrFormat) {
urls, err = d.URLs()
} else {
err = e
}
if err != nil {
return nil, err
}
var paths []string
for _, raw := range urls {
u, err := url.Parse(raw)
if err != nil || u.Scheme != "file" || (u.Host != "" && u.Host != "localhost") || strings.ContainsRune(u.Path, 0) {
continue
}
p := u.Path
if len(p) > 3 && p[0] == '/' && p[2] == ':' {
p = p[1:]
}
p = filepath.FromSlash(p)
if filepath.IsAbs(p) {
paths = append(paths, p)
}
}
return paths, nil
}
+161
View File
@@ -0,0 +1,161 @@
package transfer
import (
"bytes"
"errors"
"path/filepath"
"slices"
"sync"
"sync/atomic"
"testing"
)
func TestRepresentationsAndSnapshots(t *testing.T) {
var calls atomic.Int32
input := []byte("plain")
d := New(NewItem(Bytes(Text, input), Lazy(HTML, func() ([]byte, error) {
calls.Add(1)
return []byte("<b>plain</b>"), nil
})))
input[0] = 'x'
if got := d.Formats(); !slices.Equal(got, []Format{Text, HTML}) || calls.Load() != 0 {
t.Fatalf("formats %v, calls %d", got, calls.Load())
}
b, _ := d.Read(Text)
if string(b) != "plain" {
t.Fatalf("stored input changed: %q", b)
}
b[0] = 'x'
b, _ = d.Read(Text)
if string(b) != "plain" {
t.Fatal("read exposed mutable storage")
}
snapshot := d.Snapshot()
var wg sync.WaitGroup
for range 16 {
wg.Go(func() {
b, err := snapshot.Read(HTML)
if err != nil || string(b) != "<b>plain</b>" {
t.Errorf("read %q: %v", b, err)
}
})
}
wg.Wait()
if calls.Load() != 1 {
t.Fatalf("provider called %d times", calls.Load())
}
d.Snapshot().Read(HTML)
if calls.Load() != 2 {
t.Fatal("a new session reused the old provider cache")
}
}
func TestMaterializeAndProviderFailure(t *testing.T) {
boom := errors.New("encode failed")
n := 0
d := New(NewItem(Bytes(Text, []byte("ok")), Lazy(HTML, func() ([]byte, error) { n++; return nil, boom })))
m, err := d.Materialize([]Format{Text})
if err != nil || n != 0 || !slices.Equal(m.Formats(), []Format{Text}) {
t.Fatalf("materialize %v: %v, calls %d", m.Formats(), err, n)
}
for range 2 {
if _, err := d.Materialize([]Format{HTML}); !errors.Is(err, boom) {
t.Fatalf("failed format: %v", err)
}
}
if n != 1 {
t.Fatal("provider failures were not cached")
}
if _, err := d.Materialize([]Format{PNG}); !errors.Is(err, ErrFormat) {
t.Fatalf("empty match: %v", err)
}
empty := New(NewItem(Bytes(Text, nil)))
if b, err := empty.Read(Text); err != nil || len(b) != 0 {
t.Fatalf("empty data: %q, %v", b, err)
}
}
func TestFileAndURLRepresentations(t *testing.T) {
paths := []string{filepath.Join(t.TempDir(), "a #%.txt"), filepath.Join(t.TempDir(), "日本語.txt")}
d, err := FileData(paths...)
if err != nil {
t.Fatal(err)
}
if got, err := d.Files(); err != nil || !slices.Equal(got, paths) {
t.Fatalf("files %q: %v", got, err)
}
if len(d.Items()) != 2 {
t.Fatal("file item boundaries lost")
}
urls, _ := d.URLs()
if !bytes.Contains([]byte(urls[0]), []byte("%23")) {
t.Fatal("file path was not URL escaped")
}
other, _ := URLData("https://example.com/a#b")
if files, err := other.Files(); err != nil || len(files) != 0 {
t.Fatalf("web URL became a file: %q, %v", files, err)
}
remote := New(NewItem(Bytes(URIList, []byte("# comment\r\nfile://remote/tmp/a\r\nhttps://example.com\r\n"))))
if files, _ := remote.Files(); len(files) != 0 {
t.Fatalf("remote paths %q", files)
}
if _, err := FileData("relative"); err == nil {
t.Fatal("relative file accepted")
}
if _, err := URLData("no-scheme"); err == nil {
t.Fatal("relative URL accepted")
}
}
func TestMultipleItemsCoalesceAndKeepAlternatives(t *testing.T) {
custom := Format("application/vnd.mygo.test")
d := New(NewItem(Bytes(Text, []byte("a")), Bytes(custom, []byte{0, 1})), NewItem(Bytes(Text, []byte("b")), Bytes(custom, []byte{2, 3})))
b, _ := d.Read(Text)
if string(b) != "a\nb" {
t.Fatalf("text %q", b)
}
b, _ = d.Read(custom)
if !bytes.Equal(b, []byte{0, 1}) {
t.Fatalf("custom bytes %v", b)
}
m, err := d.Materialize([]Format{custom})
if err != nil || len(m.Items()) != 2 {
t.Fatalf("materialized items: %d, %v", len(m.Items()), err)
}
}
func TestOperationNegotiation(t *testing.T) {
for _, tt := range []struct{ source, destination, suggested, want Operation }{
{Copy | Move, 0, Move, Copy}, {Copy | Move, Copy | Move, Move, Move},
{Move, Copy, Move, None}, {Copy, Move, Copy, None},
{Copy | Move, Copy | Move, None, Copy}, {Move, Move, Copy, Move},
{None, Copy | Move, Copy, None},
} {
if got := Negotiate(tt.source, tt.destination, tt.suggested); got != tt.want {
t.Errorf("%v & %v suggested %v: %v, want %v", tt.source, tt.destination, tt.suggested, got, tt.want)
}
}
}
func TestProviderPanicIsCachedAndNegotiationIsLazy(t *testing.T) {
var calls atomic.Int32
d := New(NewItem(Lazy(HTML, func() ([]byte, error) { calls.Add(1); panic("codec failed") }), Bytes(Text, []byte("fallback"))))
if f, ok := d.Preferred(PNG, Text, HTML); !ok || f != Text || calls.Load() != 0 {
t.Fatal("negotiation read a provider")
}
if _, ok := d.Preferred(PNG); ok {
t.Fatal("unavailable preference matched")
}
for range 2 {
b, err := d.Read(HTML)
if !errors.Is(err, ErrProviderPanic) || len(b) != 0 {
t.Fatalf("panic result %q: %v", b, err)
}
}
if calls.Load() != 1 {
t.Fatal("panicking provider retried")
}
if b, err := d.Read(Text); err != nil || string(b) != "fallback" {
t.Fatal("panic lost the alternative")
}
}
+93
View File
@@ -0,0 +1,93 @@
package transfer
import "image"
// Operation is a native drag effect, or a bitmask of allowed effects.
type Operation uint8
const (
None Operation = 0
Copy Operation = 1
Move Operation = 2
)
// Allowed supplies the safe default (copy) and removes unsupported effects.
func (o Operation) Allowed() Operation {
if o == None {
return Copy
}
return o & (Copy | Move)
}
// Negotiate chooses one effect shared by source and destination. A source's
// modifier-key suggestion wins when allowed; otherwise copy precedes move.
func Negotiate(source, destination, suggested Operation) Operation {
allowed := source & destination.Allowed()
if suggested == Copy || suggested == Move {
if allowed&suggested != 0 {
return suggested
}
}
if allowed&Copy != 0 {
return Copy
}
if allowed&Move != 0 {
return Move
}
return None
}
// DragOptions configures a native source. The default operation is copy.
type DragOptions struct {
Operations Operation
// Preview is copied at drag start. Hotspot is in image pixels; the
// preview is displayed in DIPs (one pixel per DIP).
Preview image.Image
Hotspot image.Point
// Done runs on the main thread exactly once, including cancellation,
// startup failure and source-window destruction. Delete or remove the
// original only after a successful Move; MyGo never deletes files.
Done func(Result)
}
// Result reports the destination's final effect. None means no drop.
type Result struct {
Operation Operation
// Canceled reports that the drag ended without a drop: let go over
// no target, or canceled.
Canceled bool
// Escaped reports that a canceled drag was given up (Escape,
// Window.CancelDataDrag, or the source window closing), rather than
// let go over no target.
Escaped bool
// Point is where the drag ended, in screen coordinates, as
// Screen.CursorScreenPoint reports them.
Point image.Point
Err error
}
// Offer describes a drag during hover, without reading its bytes.
type Offer struct {
Formats []Format
Operations Operation
Suggested Operation
}
// Preferred selects a format without requesting any representation bytes.
func (o Offer) Preferred(formats ...Format) (Format, bool) {
return PreferredFormat(o.Formats, formats...)
}
// DropOptions describes a destination. At least one offered format must
// match Formats. Empty Formats accepts none; zero Operations permits copy.
type DropOptions struct {
Formats []Format
Operations Operation
}
// Drop is a completed transfer. Its data is independent of the native
// session and can be read later, from any goroutine.
type Drop struct {
Data Data
Operation Operation
}