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

+17
View File
@@ -0,0 +1,17 @@
# sfsymbols
Apple's [SF Symbols](https://developer.apple.com/sf-symbols/) for
[MyGo](https://github.com/egoist/mygo) apps of native UI on macOS: the
symbols the running system has, drawn by AppKit and handed over as an
image.
```go
import "github.com/egoist/mygo/plugins/sfsymbols"
sfsymbols.Symbol(c, "gearshape")
sfsymbols.Symbol(c, "trash").Size(20).Color(t.Accent).Weight(sfsymbols.Semibold).Fill()
```
See [the documentation](../../docs/plugins/sfsymbols.md), and
`examples/sf-symbols`. Nothing of
Apple's artwork is in the plugin: the symbols come from the system.
+47
View File
@@ -0,0 +1,47 @@
package sfsymbols
import "container/list"
// lru maps keys to values, holding at most limit of them: putting one more
// drops the least recently used. It is not safe for concurrent use.
type lru[K comparable, V any] struct {
limit int
order *list.List // of *entry[K, V], the most recently used first
items map[K]*list.Element
}
type entry[K comparable, V any] struct {
key K
val V
}
func newLRU[K comparable, V any](limit int) *lru[K, V] {
return &lru[K, V]{limit: limit, order: list.New(), items: map[K]*list.Element{}}
}
// get returns key's value, and marks it the most recently used.
func (c *lru[K, V]) get(key K) (V, bool) {
if e, ok := c.items[key]; ok {
c.order.MoveToFront(e)
return e.Value.(*entry[K, V]).val, true
}
var zero V
return zero, false
}
// put sets key's value, and drops the least recently used past the limit.
func (c *lru[K, V]) put(key K, val V) {
if e, ok := c.items[key]; ok {
e.Value.(*entry[K, V]).val = val
c.order.MoveToFront(e)
return
}
c.items[key] = c.order.PushFront(&entry[K, V]{key, val})
for c.order.Len() > c.limit {
last := c.order.Back()
c.order.Remove(last)
delete(c.items, last.Value.(*entry[K, V]).key)
}
}
func (c *lru[K, V]) len() int { return c.order.Len() }
+29
View File
@@ -0,0 +1,29 @@
package sfsymbols
import "testing"
// TestLRU checks that the cache holds no more than its limit, dropping the
// least recently used, and keeps what was used last.
func TestLRU(t *testing.T) {
c := newLRU[int, int](3)
for i := range 3 {
c.put(i, i*10)
}
c.get(0) // 1 is now the least recently used
c.put(3, 30)
if c.len() != 3 {
t.Fatalf("%d entries, want 3", c.len())
}
if _, ok := c.get(1); ok {
t.Error("1 kept, though the least recently used")
}
for _, k := range []int{0, 2, 3} {
if v, ok := c.get(k); !ok || v != k*10 {
t.Errorf("%d: %d, %v, want %d", k, v, ok, k*10)
}
}
c.put(2, 21)
if v, _ := c.get(2); v != 21 || c.len() != 3 {
t.Errorf("2 is %d with %d entries after an update, want 21 with 3", v, c.len())
}
}
+111
View File
@@ -0,0 +1,111 @@
//go:build darwin
package sfsymbols
import (
"sort"
"sync"
"unsafe"
"github.com/ebitengine/purego/objc"
)
// The system's catalog of its symbols, in CoreGlyphs, the bundle AppKit
// draws them from: their names in the order the SF Symbols app shows
// them, and, should that list be missing, every name with the release
// that added it.
const (
glyphs = "/System/Library/CoreServices/CoreGlyphs.bundle/Contents/Resources/"
orderList = glyphs + "symbol_order.plist"
availableList = glyphs + "name_availability.plist"
)
var names struct {
once sync.Once
list []string
}
// Names returns the names of the SF Symbols this macOS has, in the order
// the SF Symbols app shows them, as "0.circle" through "zzz", read from
// the system's own catalog; nil where there is none. The catalog is not
// public API: a macOS that moves it gives nil, while Image still draws the
// symbols it names.
func Names() []string {
names.once.Do(func() {
if !loadCG() {
return
}
withPool(func() {
names.list = readOrder()
if len(names.list) == 0 {
names.list = readAvailable()
}
})
})
return names.list
}
var (
selArrayFile = objc.RegisterName("arrayWithContentsOfFile:")
selDictFile = objc.RegisterName("dictionaryWithContentsOfFile:")
selObjectFor = objc.RegisterName("objectForKey:")
selAllKeys = objc.RegisterName("allKeys")
selCount = objc.RegisterName("count")
selObjectAt = objc.RegisterName("objectAtIndex:")
selUTF8 = objc.RegisterName("UTF8String")
selIsString = objc.RegisterName("isKindOfClass:")
)
func readOrder() []string {
path := nsString(orderList)
defer objc.Send[objc.ID](path, selRelease)
return strings(objc.Send[objc.ID](objc.ID(objc.GetClass("NSArray")), selArrayFile, path))
}
func readAvailable() []string {
path := nsString(availableList)
defer objc.Send[objc.ID](path, selRelease)
dict := objc.Send[objc.ID](objc.ID(objc.GetClass("NSDictionary")), selDictFile, path)
if dict == 0 {
return nil
}
key := nsString("symbols")
defer objc.Send[objc.ID](key, selRelease)
symbols := objc.Send[objc.ID](dict, selObjectFor, key)
if symbols == 0 {
return nil
}
list := strings(objc.Send[objc.ID](symbols, selAllKeys))
sort.Strings(list)
return list
}
// strings returns the NSStrings of the NSArray arr, skipping anything
// else.
func strings(arr objc.ID) []string {
if arr == 0 {
return nil
}
class := objc.ID(objc.GetClass("NSString"))
n := int(objc.Send[uint](arr, selCount))
out := make([]string, 0, n)
for i := range n {
s := objc.Send[objc.ID](arr, selObjectAt, uint(i))
if s == 0 || !objc.Send[bool](s, selIsString, class) {
continue
}
if p := objc.Send[unsafe.Pointer](s, selUTF8); p != nil {
out = append(out, goString(p))
}
}
return out
}
// goString copies the C string at p.
func goString(p unsafe.Pointer) string {
n := 0
for *(*byte)(unsafe.Add(p, n)) != 0 {
n++
}
return string(unsafe.Slice((*byte)(p), n))
}
+65
View File
@@ -0,0 +1,65 @@
// Package sfsymbols draws Apple's SF Symbols, as the running macOS has
// them, for native UI.
//
// sfsymbols.Symbol(c, "gearshape")
// sfsymbols.Symbol(c, "trash").Size(20).Color(t.Accent).Weight(sfsymbols.Semibold).Fill()
//
// Symbol shows one as SwiftUI's Image(systemName:) does; Image gives the
// bitmap, for drawing with a ui.Painter.
//
// The symbols are read from the system: AppKit draws each with its own
// design and weight, and the plugin copies the pixels. Nothing of Apple's
// artwork is in the app or its build. Where the system has no symbol of a
// name, and on every other OS, Image says so and Symbol draws its
// Fallback instead.
package sfsymbols
// Options of a symbol's drawing.
type Options struct {
// Natural draws the symbol at the size it has beside others of the
// same point size, rather than filling its box: a cross stays smaller
// than a wide rectangle, as SF Symbols balance them.
Natural bool
// Weight is the weight of the symbol's strokes, Regular by default.
Weight Weight
}
// Weight is the weight of a symbol's strokes, as a font's.
type Weight int
// The weights of SF Symbols, from the lightest to the heaviest, in that
// order; the zero Weight is Regular.
const (
UltraLight Weight = iota - 3
Thin
Light
Regular
Medium
Semibold
Bold
Heavy
Black
)
// fontWeight returns w as AppKit's NSFontWeight.
func (w Weight) fontWeight() float64 {
switch w {
case UltraLight:
return -0.8
case Thin:
return -0.6
case Light:
return -0.4
case Medium:
return 0.23
case Semibold:
return 0.3
case Bold:
return 0.4
case Heavy:
return 0.56
case Black:
return 0.62
}
return 0
}
+335
View File
@@ -0,0 +1,335 @@
//go:build darwin
package sfsymbols
import (
"image"
"math"
"runtime"
"structs"
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/ui"
)
var (
selSymbolImage = objc.RegisterName("imageWithSystemSymbolName:accessibilityDescription:")
selSymbolConfg = objc.RegisterName("configurationWithPointSize:weight:")
selSymbolApply = objc.RegisterName("imageWithSymbolConfiguration:")
selCGImage = objc.RegisterName("CGImageForProposedRect:context:hints:")
selSize = objc.RegisterName("size")
selAlloc = objc.RegisterName("alloc")
selInitBytes = objc.RegisterName("initWithBytes:length:encoding:")
selRelease = objc.RegisterName("release")
)
// cgRect is CGRect, which CGContextDrawImage takes by value.
type cgRect struct {
_ structs.HostLayout
X, Y, W, H float64
}
// cg holds the CoreGraphics functions the rasterizer calls, once resolved.
var cg struct {
once sync.Once
ok bool
space func() uintptr
releaseSpace func(space uintptr)
bitmap func(data unsafe.Pointer, width, height, bitsPerComponent, bytesPerRow, space uintptr, info uint32) uintptr
releaseCtx func(ctx uintptr)
draw func(ctx uintptr, rect cgRect, img uintptr)
width func(img uintptr) uintptr
height func(img uintptr) uintptr
// poolPush and poolPop are libobjc's autorelease pools; size sends a
// message that returns an NSSize.
poolPush, poolPop uintptr
size func(obj objc.ID, sel objc.SEL) nsSize
}
// nsSize is NSSize, which -[NSImage size] returns by value.
type nsSize struct {
_ structs.HostLayout
W, H float64
}
// cgPremultipliedLast and cgByteOrder32Big name the pixel format of the
// canvases: 8 bits of red, green, blue and alpha each, in that order.
const (
cgPremultipliedLast = 1
cgByteOrder32Big = 4 << 12
)
const nsUTF8StringEncoding = 4
// maxPx is the most pixels square Image draws a symbol.
const maxPx = 512
// naturalSpan is how many times its point size the ink of
// rectangle.on.rectangle, of the widest symbols, spans (its image, with
// its margins, spans 1.47).
const naturalSpan = 1.25
func loadCG() bool {
cg.once.Do(func() {
if _, err := purego.Dlopen("/System/Library/Frameworks/AppKit.framework/AppKit", purego.RTLD_NOW|purego.RTLD_GLOBAL); err != nil {
return
}
lib, err := purego.Dlopen("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
return
}
purego.RegisterLibFunc(&cg.space, lib, "CGColorSpaceCreateDeviceRGB")
purego.RegisterLibFunc(&cg.releaseSpace, lib, "CGColorSpaceRelease")
purego.RegisterLibFunc(&cg.bitmap, lib, "CGBitmapContextCreate")
purego.RegisterLibFunc(&cg.releaseCtx, lib, "CGContextRelease")
purego.RegisterLibFunc(&cg.draw, lib, "CGContextDrawImage")
purego.RegisterLibFunc(&cg.width, lib, "CGImageGetWidth")
purego.RegisterLibFunc(&cg.height, lib, "CGImageGetHeight")
libobjc, err := purego.Dlopen("/usr/lib/libobjc.A.dylib", purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
return
}
if cg.poolPush, err = purego.Dlsym(libobjc, "objc_autoreleasePoolPush"); err != nil {
return
}
if cg.poolPop, err = purego.Dlsym(libobjc, "objc_autoreleasePoolPop"); err != nil {
return
}
msgSend, err := purego.Dlsym(libobjc, "objc_msgSend")
if err != nil {
return
}
purego.RegisterFunc(&cg.size, msgSend)
cg.ok = true
})
return cg.ok
}
// Available reports whether this system draws SF Symbols at all: whether
// AppKit and CoreGraphics load here. A particular symbol may still be
// missing from an older macOS, and Image says so for it.
func Available() bool { return loadCG() }
// shapeKey names a symbol's shape: its name, its pixels square and its
// options. tintKey adds the color it is drawn in.
type shapeKey struct {
name string
px int
natural bool
weight Weight
}
type tintKey struct {
shapeKey
r, g, b, a uint8
}
// The caches hold the shapes AppKit drew and the bitmaps tinted from them,
// each up to a limit, past which the least recently used goes: an app
// that animates a symbol's color or size does not grow without end.
const (
shapeLimit = 256
tintLimit = 512
)
var (
mu sync.Mutex
shapes = newLRU[shapeKey, *image.RGBA](shapeLimit)
// missing holds the names this macOS has no symbol for, so that a
// Symbol trying a variant (Fill) does not ask AppKit every frame.
missing = newLRU[string, struct{}](shapeLimit)
tinted = newLRU[tintKey, *ui.Bitmap](tintLimit)
)
// Image returns the SF Symbol named name (as "gearshape"), drawn px pixels
// square in col, or false where the system has no such symbol: on another
// OS, or a macOS without it. px is limited to 8 through 512. The result is
// cached, and Image is safe to call from any goroutine.
func Image(name string, px int, col ui.Color, o Options) (ui.ImageSource, bool) {
if !loadCG() {
return nil, false
}
px = min(max(px, 8), maxPx)
sk := shapeKey{name: name, px: px, natural: o.Natural, weight: o.Weight}
tk := tintKey{shapeKey: sk, r: col.R, g: col.G, b: col.B, a: col.A}
mu.Lock()
b, ok := tinted.get(tk)
coverage, drawn := shapes.get(sk)
_, absent := missing.get(name)
mu.Unlock()
if ok {
return b, true
}
if absent {
return nil, false
}
if !drawn {
var absent bool
if coverage, drawn, absent = rasterize(name, px, o.Natural, o.Weight); !drawn {
// Only a name AppKit has no symbol for is remembered: another
// failure may not happen at another size or weight.
if absent {
mu.Lock()
missing.put(name, struct{}{})
mu.Unlock()
}
return nil, false
}
}
b = ui.NewBitmap(tint(coverage, col))
mu.Lock()
shapes.put(sk, coverage)
tinted.put(tk, b)
mu.Unlock()
return b, true
}
// canvas makes a bitmap context over pix, w by h pixels, and returns it
// with the function that releases it.
func canvas(pix []byte, w, h int) (uintptr, func()) {
space := cg.space()
ctx := cg.bitmap(unsafe.Pointer(&pix[0]), uintptr(w), uintptr(h), 8, uintptr(w*4), space, cgPremultipliedLast|cgByteOrder32Big)
cg.releaseSpace(space)
if ctx == 0 {
return 0, func() {}
}
return ctx, func() {
cg.releaseCtx(ctx)
runtime.KeepAlive(pix)
}
}
// rasterize draws the symbol's outline into a px×px canvas, centered and
// inset a little. With natural, every symbol takes one scale, as AppKit
// draws them at one point size: a cross stays smaller than a wide
// rectangle, rather than each filling the box.
func rasterize(name string, px int, natural bool, weight Weight) (out *image.RGBA, ok, absent bool) {
if !loadCG() {
return nil, false, false
}
withPool(func() { out, ok, absent = draw(name, px, natural, weight) })
return out, ok, absent
}
// withPool runs fn in an autorelease pool, for AppKit's temporary objects.
// A pool belongs to its thread: the goroutine stays on one until it pops.
func withPool(fn func()) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
p, _, _ := purego.SyscallN(cg.poolPush)
defer purego.SyscallN(cg.poolPop, p)
fn()
}
// draw is rasterize inside the pool. absent says AppKit has no symbol of
// the name; other failures leave it false.
func draw(name string, px int, natural bool, weight Weight) (out *image.RGBA, ok, absent bool) {
str := nsString(name)
defer objc.Send[objc.ID](str, selRelease)
img := objc.Send[objc.ID](objc.ID(objc.GetClass("NSImage")), selSymbolImage, str, objc.ID(0))
if img == 0 {
return nil, false, true
}
// A point size of px renders at the main screen's scale, 2× on a
// Retina screen: the canvas below scales it down, never up.
cfg := objc.Send[objc.ID](objc.ID(objc.GetClass("NSImageSymbolConfiguration")), selSymbolConfg, float64(px), weight.fontWeight())
img = objc.Send[objc.ID](img, selSymbolApply, cfg)
if img == 0 {
return nil, false, false
}
points := cg.size(img, selSize)
cgImage := objc.Send[objc.ID](img, selCGImage, uintptr(0), uintptr(0), uintptr(0))
if cgImage == 0 {
return nil, false, false
}
w, h := int(cg.width(uintptr(cgImage))), int(cg.height(uintptr(cgImage)))
if w <= 0 || h <= 0 || points.W <= 0 {
return nil, false, false
}
// pixelsPerPoint is the scale AppKit chose for the image.
pixelsPerPoint := float64(w) / points.W
// The glyph inside its alignment margins, in a canvas of its own size.
src := make([]byte, w*h*4)
ctx, done := canvas(src, w, h)
if ctx == 0 {
return nil, false, false
}
cg.draw(ctx, cgRect{W: float64(w), H: float64(h)}, uintptr(cgImage))
done()
minX, minY, maxX, maxY := w, h, -1, -1
for y := range h {
for x := range w {
if src[y*w*4+x*4+3] != 0 {
minX, maxX = min(minX, x), max(maxX, x)
minY, maxY = min(minY, y), max(maxY, y)
}
}
}
if maxX < 0 {
return nil, false, false
}
gw, gh := maxX-minX+1, maxY-minY+1
// The glyph, scaled into the box and centered.
dst := make([]byte, px*px*4)
dctx, ddone := canvas(dst, px, px)
if dctx == 0 {
return nil, false, false
}
const inset = 0.85
scale := math.Min(inset*float64(px)/float64(gw), inset*float64(px)/float64(gh))
if natural {
// Every symbol at one scale of points to pixels, whatever the
// screen's: rectangle.on.rectangle, of the widest, spans
// naturalSpan times the point size, and it, so every other, fits.
scale = math.Min(scale, 0.92/(naturalSpan*pixelsPerPoint))
}
dw, dh := float64(gw)*scale, float64(gh)*scale
// The image holds the glyph inside alignment margins: scale the whole
// image so that the glyph, and not the margins, fills the box.
cg.draw(dctx, cgRect{
X: (float64(px)-dw)/2 - float64(minX)*scale,
// CoreGraphics counts y up from the bottom, the rows down from the
// top: the margin below the glyph is the rows after maxY.
Y: (float64(px)-dh)/2 - float64(h-1-maxY)*scale,
W: float64(w) * scale,
H: float64(h) * scale,
}, uintptr(cgImage))
ddone()
out = image.NewRGBA(image.Rect(0, 0, px, px))
for i := range px * px {
a := dst[i*4+3]
out.Pix[i*4+0], out.Pix[i*4+1], out.Pix[i*4+2], out.Pix[i*4+3] = a, a, a, a
}
return out, true, false
}
// tint colors coverage, whose alpha holds the shape, in col.
func tint(coverage *image.RGBA, col ui.Color) *image.RGBA {
out := image.NewRGBA(coverage.Rect)
for i := range len(coverage.Pix) / 4 {
a := uint16(coverage.Pix[i*4+3]) * uint16(col.A) / 255
out.Pix[i*4+0] = uint8(uint16(col.R) * a / 255)
out.Pix[i*4+1] = uint8(uint16(col.G) * a / 255)
out.Pix[i*4+2] = uint8(uint16(col.B) * a / 255)
out.Pix[i*4+3] = uint8(a)
}
return out
}
// nsString makes an owned NSString for s, which the caller releases. It
// copies the bytes, which stay alive until the message returns.
func nsString(s string) objc.ID {
b := append([]byte(s), 0)
str := objc.Send[objc.ID](objc.Send[objc.ID](objc.ID(objc.GetClass("NSString")), selAlloc), selInitBytes,
unsafe.Pointer(&b[0]), uintptr(len(s)), uintptr(nsUTF8StringEncoding))
runtime.KeepAlive(b)
return str
}
@@ -0,0 +1,273 @@
//go:build darwin
package sfsymbols
import (
"image"
"testing"
"github.com/egoist/mygo/ui"
)
// TestImage checks that a symbol the app names draws, at the
// size asked and with the color asked, and that one this macOS has not
// says so rather than drawing nothing.
func TestImage(t *testing.T) {
for _, name := range []string{"xmark", "gearshape", "sidebar.leading", "terminal"} {
src, ok := Image(name, 48, ui.Hex("#ffffff"), Options{})
if !ok {
t.Fatalf("%s: the system draws no such symbol", name)
}
if w, h := src.(*ui.Bitmap).Size(); w != 48 || h != 48 {
t.Fatalf("%s: %dx%d pixels, want 48x48", name, w, h)
}
}
if _, ok := Image("no.symbol.of.that.name", 48, ui.Hex("#ffffff"), Options{}); ok {
t.Fatal("a name the system has not drew as a symbol")
}
}
// TestCoverage checks that a symbol covers some of its box and not
// all of it, and that tint keeps the premultiplied alpha of the shape.
func TestCoverage(t *testing.T) {
coverage, ok, _ := rasterize("xmark", 64, false, Regular)
if !ok {
t.Fatal("xmark drew nothing")
}
lit := 0
for i := range 64 * 64 {
if coverage.Pix[i*4+3] != 0 {
lit++
}
}
if lit == 0 || lit == 64*64 {
t.Fatalf("%d of %d pixels lit", lit, 64*64)
}
col := ui.RGBA(0xff, 0x40, 0x20, 0.5)
tinted := tint(coverage, col)
for i := range 64 * 64 {
a, r := tinted.Pix[i*4+3], tinted.Pix[i*4+0]
if r == 0 && a != 0 && coverage.Pix[i*4+3] != 0 {
t.Fatal("a lit pixel lost its color")
}
if r > a {
t.Fatalf("pixel %d: %d red over %d alpha, not premultiplied", i, r, a)
}
}
}
// TestFillsItsBox checks that a symbol's ink fills the box rather
// than the alignment margins of the image it comes in, and that it sits
// centered in it.
func TestFillsItsBox(t *testing.T) {
for _, name := range []string{"xmark", "gearshape", "rectangle.split.2x1", "chevron.down", "square.and.arrow.up"} {
coverage, ok, _ := rasterize(name, 48, false, Regular)
if !ok {
t.Fatalf("%s drew nothing", name)
}
b := inkOf(coverage)
if big := max(b.Dx(), b.Dy()); big < 40 || big > 44 {
t.Fatalf("%s: ink is %dx%d, want about 41x41 in a 48 box", name, b.Dx(), b.Dy())
}
cx, cy := (b.Min.X+b.Max.X)/2, (b.Min.Y+b.Max.Y)/2
// Margins on either side within a pixel: centered, not shifted by
// the image's uneven alignment margins.
if l, r, tp, bt := b.Min.X, 48-b.Max.X, b.Min.Y, 48-b.Max.Y; max(l-r, r-l) > 1 || max(tp-bt, bt-tp) > 1 {
t.Fatalf("%s: margins %d left, %d right, %d top, %d bottom: want even", name, l, r, tp, bt)
}
if max(cx-24, 24-cx) > 1 || max(cy-24, 24-cy) > 1 {
t.Fatalf("%s: ink centered at %d,%d, want 24,24", name, cx, cy)
}
}
}
// inkOf returns the box of the lit pixels of coverage.
func inkOf(coverage *image.RGBA) image.Rectangle {
w, h := coverage.Rect.Dx(), coverage.Rect.Dy()
minX, minY, maxX, maxY := w, h, -1, -1
for y := range h {
for x := range w {
if coverage.Pix[y*coverage.Stride+x*4+3] != 0 {
minX, maxX = min(minX, x), max(maxX, x)
minY, maxY = min(minY, y), max(maxY, y)
}
}
}
return image.Rect(minX, minY, maxX+1, maxY+1)
}
// TestNatural checks that a symbol drawn at its natural size is smaller
// than one that fills its box.
func TestNatural(t *testing.T) {
filled, ok, _ := rasterize("xmark", 64, false, Regular)
if !ok {
t.Fatal("xmark drew nothing")
}
natural, ok, _ := rasterize("xmark", 64, true, Regular)
if !ok {
t.Fatal("xmark drew nothing at its natural size")
}
if f, n := inkOf(filled), inkOf(natural); n.Dx() >= f.Dx() {
t.Fatalf("natural ink %d wide, filled %d: want smaller", n.Dx(), f.Dx())
}
}
// TestNaturalBalances checks that at their natural size a cross stays
// smaller than a wide rectangle, as SF Symbols balance them, while both
// fill their boxes alike otherwise.
func TestNaturalBalances(t *testing.T) {
width := func(name string, natural bool) int {
c, ok, _ := rasterize(name, 100, natural, Regular)
if !ok {
t.Fatalf("%s drew nothing", name)
}
return inkOf(c).Dx()
}
if x, r := width("xmark", true), width("rectangle.on.rectangle", true); x >= r*4/5 {
t.Errorf("natural xmark %d wide, rectangle.on.rectangle %d: want the cross well smaller", x, r)
}
if r := width("rectangle.on.rectangle", true); r > 92 || r < 80 {
t.Errorf("natural rectangle.on.rectangle %d wide in 100: want it to nearly fill", r)
}
}
// TestRasterizeAlone checks that rasterize loads what it needs, so that a
// test calling it runs alone.
func TestRasterizeAlone(t *testing.T) {
if _, ok, absent := rasterize("no.symbol.of.that.name", 32, false, Regular); ok || !absent {
t.Errorf("a missing name: ok %v, absent %v; want false, true", ok, absent)
}
}
// TestWeightOrder checks that the weights' order is their heaviness.
func TestWeightOrder(t *testing.T) {
ws := []Weight{UltraLight, Thin, Light, Regular, Medium, Semibold, Bold, Heavy, Black}
for i := 1; i < len(ws); i++ {
if ws[i] <= ws[i-1] || ws[i].fontWeight() <= ws[i-1].fontWeight() {
t.Errorf("%d after %d is not heavier", ws[i], ws[i-1])
}
}
var zero Weight
if zero != Regular {
t.Error("the zero Weight is not Regular")
}
}
// TestAvailable checks that Available agrees with Image.
func TestAvailable(t *testing.T) {
if !Available() {
t.Skip("no AppKit here")
}
if _, ok := Image("gearshape", 8, ui.Hex("#000000"), Options{}); !ok {
t.Fatal("gearshape not drawn though symbols are available")
}
}
// TestCacheBounded checks that a color animated over many frames keeps the
// caches at their limits, and draws the symbol's shape once.
func TestCacheBounded(t *testing.T) {
first, ok := Image("gearshape", 24, ui.RGB(0, 0, 0), Options{})
if !ok {
t.Fatal("gearshape drew nothing")
}
if again, _ := Image("gearshape", 24, ui.RGB(0, 0, 0), Options{}); again != first {
t.Error("the same symbol, size and color drew again")
}
for i := range tintLimit + 100 {
Image("gearshape", 24, ui.RGB(uint8(i), uint8(i>>8), 0), Options{})
}
mu.Lock()
n, s := tinted.len(), shapes.len()
_, drawn := shapes.get(shapeKey{name: "gearshape", px: 24})
mu.Unlock()
if n > tintLimit || s > shapeLimit {
t.Fatalf("%d tinted and %d shapes cached, past the limits %d and %d", n, s, tintLimit, shapeLimit)
}
if !drawn {
t.Error("gearshape's shape dropped while it was in use")
}
}
// TestWeight checks that a heavier weight draws more ink.
func TestWeight(t *testing.T) {
ink := func(w Weight) int {
coverage, ok, _ := rasterize("circle", 64, true, w)
if !ok {
t.Fatalf("circle at %d drew nothing", w)
}
n := 0
for i := range len(coverage.Pix) / 4 {
n += int(coverage.Pix[i*4+3])
}
return n
}
if light, black := ink(UltraLight), ink(Black); black <= light {
t.Errorf("black ink %d, ultralight %d: want more", black, light)
}
}
// TestFillVariant checks that a filled variant draws, and that a name
// missing once answers from the cache.
func TestFillVariant(t *testing.T) {
if _, ok := Image("trash.fill", 32, ui.RGB(0, 0, 0), Options{}); !ok {
t.Fatal("trash.fill drew nothing")
}
if _, ok := Image("gearshape.nope", 32, ui.RGB(0, 0, 0), Options{}); ok {
t.Fatal("a missing name drew")
}
mu.Lock()
_, absent := missing.get("gearshape.nope")
mu.Unlock()
if !absent {
t.Error("a missing name was not remembered")
}
}
// TestSymbolDraws checks that a Symbol paints the system's symbol in its
// color.
func TestSymbolDraws(t *testing.T) {
tt := ui.NewTester(func(c *ui.Context) {
ui.Column(c).Fill().Background(ui.RGB(255, 255, 255)).Children(func() {
Symbol(c, "square.fill").Size(30).Color(ui.RGB(0, 0, 255))
})
}, 40, 40)
tt.Frame()
img := tt.Image()
blue := 0
for i := 0; i < len(img.Pix); i += 4 {
if img.Pix[i+2] > 200 && img.Pix[i] < 60 {
blue++
}
}
if blue == 0 {
t.Error("square.fill painted no blue")
}
}
// TestNames checks that the system's catalog lists thousands of symbols,
// these among them, and that they draw.
func TestNames(t *testing.T) {
list := Names()
if len(list) < 1000 {
t.Fatalf("%d names, want thousands", len(list))
}
has := map[string]bool{}
for _, n := range list {
has[n] = true
}
for _, n := range []string{"gearshape", "xmark", "trash.fill", "rectangle.on.rectangle"} {
if !has[n] {
t.Errorf("%s not listed", n)
}
}
for _, n := range list[:50] {
if _, ok := Image(n, 16, ui.RGB(0, 0, 0), Options{}); !ok {
t.Errorf("listed %s does not draw", n)
}
}
var available []string
withPool(func() { available = readAvailable() })
if len(available) < len(list) {
t.Errorf("the availability list has %d names, fewer than the order's %d", len(available), len(list))
}
}
+19
View File
@@ -0,0 +1,19 @@
//go:build !darwin
package sfsymbols
import "github.com/egoist/mygo/ui"
// Image returns the SF Symbol named name, drawn px pixels square in col,
// or false where the system has no such symbol: on another OS, or a macOS
// without it. Here it never has one.
func Image(name string, px int, col ui.Color, o Options) (ui.ImageSource, bool) {
return nil, false
}
// Available reports whether this system draws SF Symbols at all. It does
// not.
func Available() bool { return false }
// Names returns the names of the SF Symbols this system has. It has none.
func Names() []string { return nil }
+126
View File
@@ -0,0 +1,126 @@
package sfsymbols
import (
"math"
"github.com/egoist/mygo/ui"
)
// SymbolElement is the element Symbol makes: a ui.Element, with the
// symbol's own modifiers. Each returns the element, so they chain as
// SwiftUI's do, and the ui.Element's own methods (Margin, Tooltip, ...)
// are there too.
type SymbolElement struct {
ui.Element
s *symbol
}
// symbol is what a SymbolElement draws, read when it paints.
type symbol struct {
name string
color ui.Color
weight Weight
fill bool
natural bool
fallback *ui.SVG
}
// Symbol shows the SF Symbol named name, as SwiftUI's
// Image(systemName:): at the theme's font size and in its text color,
// drawn sharp at the display's scale, and named for assistive technology.
//
// sfsymbols.Symbol(c, "gearshape")
// sfsymbols.Symbol(c, "trash").Size(20).Color(t.Accent).Weight(sfsymbols.Semibold).Fill()
// sfsymbols.Symbol(c, "sparkles").Fallback(sparkles) // an SVG where the system has none
//
// Where the system has no symbol of that name, on another OS or a macOS
// without it, it draws its Fallback, or nothing, at the same size.
func Symbol(c *ui.Context, name string) SymbolElement {
t := c.Theme()
s := &symbol{name: name, color: t.Text}
size := t.FontSize
if size <= 0 {
size = 13
}
e := ui.Box(c).Size(size, size).Shrink(0).Role(ui.RoleImage).Label(name)
e.Draw(s.paint)
return SymbolElement{Element: e, s: s}
}
// Size sets the symbol's box, size DIPs square.
func (e SymbolElement) Size(size float32) SymbolElement {
e.Element.Size(size, size)
return e
}
// Color draws the symbol in col rather than the theme's text color, as
// SwiftUI's foregroundStyle.
func (e SymbolElement) Color(col ui.Color) SymbolElement {
if e.s != nil {
e.s.color = col
}
return e
}
// Weight draws the symbol's strokes at w, as SwiftUI's fontWeight.
func (e SymbolElement) Weight(w Weight) SymbolElement {
if e.s != nil {
e.s.weight = w
}
return e
}
// Fill draws the symbol's filled variant where it has one ("trash.fill"
// for "trash"), and the symbol itself where it has none, as SwiftUI's
// symbolVariant(.fill).
func (e SymbolElement) Fill() SymbolElement {
if e.s != nil {
e.s.fill = true
}
return e
}
// Natural draws the symbol at the size it has beside others of the same
// point size, rather than filling its box: see Options.Natural.
func (e SymbolElement) Natural() SymbolElement {
if e.s != nil {
e.s.natural = true
}
return e
}
// Fallback draws svg, in the symbol's color, where the system has no such
// symbol.
func (e SymbolElement) Fallback(svg *ui.SVG) SymbolElement {
if e.s != nil {
e.s.fallback = svg
}
return e
}
func (s *symbol) paint(p *ui.Painter, r ui.Rect) {
side := min(r.W, r.H)
if side <= 0 {
return
}
box := ui.Rect{X: r.X + (r.W-side)/2, Y: r.Y + (r.H-side)/2, W: side, H: side}
scale := p.Scale()
if scale <= 0 {
scale = 1
}
px := int(math.Ceil(float64(side * scale)))
o := Options{Natural: s.natural, Weight: s.weight}
if s.fill {
if src, ok := Image(s.name+".fill", px, s.color, o); ok {
p.Image(src, box, ui.Contain)
return
}
}
if src, ok := Image(s.name, px, s.color, o); ok {
p.Image(src, box, ui.Contain)
return
}
if s.fallback != nil {
p.Icon(s.fallback, box, s.color)
}
}
+49
View File
@@ -0,0 +1,49 @@
package sfsymbols
import (
"testing"
"github.com/egoist/mygo/ui"
)
// box is an SVG square filling its view box, for a fallback that shows.
var box = ui.MustParseSVG([]byte(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10" fill="currentColor"/></svg>`))
// TestSymbolElement checks that a Symbol is named for assistive technology
// and sized as asked, at the theme's font size by default.
func TestSymbolElement(t *testing.T) {
tt := ui.NewTester(func(c *ui.Context) {
ui.Row(c).Children(func() {
Symbol(c, "gearshape")
Symbol(c, "trash").Size(32).Color(ui.RGB(255, 0, 0)).Weight(Bold).Fill()
})
}, 200, 100)
r, ok := tt.Find("gearshape")
if !ok || r.W != r.H || r.W <= 0 {
t.Errorf("gearshape: found %v at %v, want a square", ok, r)
}
if r, ok := tt.Find("trash"); !ok || r.W != 32 || r.H != 32 {
t.Errorf("trash: found %v at %v, want 32 square", ok, r)
}
}
// TestSymbolFallback checks that a name no system has draws the fallback,
// in the symbol's color.
func TestSymbolFallback(t *testing.T) {
tt := ui.NewTester(func(c *ui.Context) {
ui.Column(c).Fill().Background(ui.RGB(255, 255, 255)).Children(func() {
Symbol(c, "no.such.symbol").Size(20).Color(ui.RGB(255, 0, 0)).Fallback(box)
})
}, 40, 40)
tt.Frame()
r, ok := tt.Find("no.such.symbol")
if !ok {
t.Fatal("no.such.symbol not found")
}
img := tt.Image()
s := img.Rect.Dx() / 40
px := img.RGBAAt(int(r.X+r.W/2)*s, int(r.Y+r.H/2)*s)
if px.R < 200 || px.G > 60 || px.B > 60 {
t.Errorf("the fallback's middle is %v, want red", px)
}
}