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:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+679
@@ -0,0 +1,679 @@
|
||||
// Package netimage shows pictures from the network, in any window of native UI:
|
||||
//
|
||||
// netimage.Image(c, "https://example.com/cat.jpg").Size(80, 80).Radius(8)
|
||||
//
|
||||
// It is what a feed, a chat or a shop needs of every picture: while it comes a
|
||||
// placeholder holds its place; once it came it fades in. Pictures stay in memory
|
||||
// as long as there is room, and on disk across runs, as their servers' caching
|
||||
// headers say, so a list scrolled back shows them at once and a phone offline
|
||||
// shows what it had. What's on screen downloads before what a fling left behind,
|
||||
// which doesn't download at all if it's gone by its turn.
|
||||
package netimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// Options say how a picture shows.
|
||||
type Options struct {
|
||||
// Placeholder fills its place until it shows; by default a muted color of
|
||||
// the theme.
|
||||
Placeholder ui.Color
|
||||
// Fit says how it fills what it's given; Cover by default.
|
||||
Fit ui.Fit
|
||||
// MaxSide bounds the longest side of the bitmap kept, in pixels; by
|
||||
// default 2048. Give about what it shows at, on a screen of 3 pixels per
|
||||
// DIP: a list of 80 DIP thumbnails holds 240, not a phone's 4000 pixel
|
||||
// photos.
|
||||
MaxSide int
|
||||
// NoFade shows it at once.
|
||||
NoFade bool
|
||||
}
|
||||
|
||||
// Image returns an element showing the picture at url: a placeholder, then the
|
||||
// picture. Give it a size, or it takes the picture's as it comes.
|
||||
func Image(c *ui.Context, url string, o ...Options) ui.Element {
|
||||
var opt Options
|
||||
if len(o) > 0 {
|
||||
opt = o[0]
|
||||
}
|
||||
src, age, _ := load(c, url, opt.MaxSide)
|
||||
fit := opt.Fit
|
||||
if fit == 0 {
|
||||
fit = ui.Cover
|
||||
}
|
||||
if src == nil {
|
||||
fill := opt.Placeholder
|
||||
if fill == (ui.Color{}) {
|
||||
fill = c.Theme().Border
|
||||
}
|
||||
return ui.Box(c).Background(fill).Role(ui.RoleImage)
|
||||
}
|
||||
e := ui.Image(c, src).Fit(fit).Role(ui.RoleImage)
|
||||
if !opt.NoFade && age >= 0 && age < fadeTime {
|
||||
e.Opacity(float32(age) / float32(fadeTime))
|
||||
c.AnimationFrame()
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// Load returns the picture at url, nil while it comes, to draw it in some other
|
||||
// way, as an ui.Avatar. The view is built again once it comes. err is what went
|
||||
// wrong the last time it was asked for: it's asked for again a while later, as
|
||||
// the view goes on asking.
|
||||
func Load(c *ui.Context, url string, o ...Options) (src ui.ImageSource, err error) {
|
||||
maxSide := 0
|
||||
if len(o) > 0 {
|
||||
maxSide = o[0].MaxSide
|
||||
}
|
||||
src, _, err = load(c, url, maxSide)
|
||||
return src, err
|
||||
}
|
||||
|
||||
// Preload downloads pictures to disk before they show, as the next page of a
|
||||
// list that's about to come.
|
||||
func Preload(urls ...string) {
|
||||
for _, u := range urls {
|
||||
shared.preload(u)
|
||||
}
|
||||
}
|
||||
|
||||
// Forget takes a picture out of memory and off the disk: its next showing
|
||||
// downloads it again.
|
||||
func Forget(url string) {
|
||||
shared.forget(url)
|
||||
}
|
||||
|
||||
// Clear empties the memory and the disk of pictures.
|
||||
func Clear() {
|
||||
shared.clear()
|
||||
}
|
||||
|
||||
// SetClient sets what downloads pictures, as one that signs requests in.
|
||||
func SetClient(c *http.Client) {
|
||||
shared.mu.Lock()
|
||||
defer shared.mu.Unlock()
|
||||
shared.client = c
|
||||
}
|
||||
|
||||
const (
|
||||
fadeTime = 180 * time.Millisecond
|
||||
defaultSide = 2048
|
||||
// memoryLimit bounds the pixels held, in bytes.
|
||||
memoryLimit = 128 << 20
|
||||
// diskLimit bounds the pictures on disk, in bytes.
|
||||
diskLimit = 256 << 20
|
||||
// workers download at a time.
|
||||
workers = 6
|
||||
// abandoned is how long after its last showing a picture still waiting
|
||||
// is given up: a fling went past it.
|
||||
abandoned = 2 * time.Second
|
||||
// onScreen is how long after its last showing a picture may still show.
|
||||
onScreen = 2 * time.Second
|
||||
// maxBytes and maxPixels bound what one picture may ask of the phone.
|
||||
maxBytes = 64 << 20
|
||||
maxPixels = 64 << 20
|
||||
// tooManyEntries sweeps what failed and what's no longer asked for.
|
||||
tooManyEntries = 2048
|
||||
// retryAfter waits before asking again for what failed.
|
||||
retryAfter = 10 * time.Second
|
||||
// defaultFresh is how long a picture is trusted whose server says nothing.
|
||||
defaultFresh = 7 * 24 * time.Hour
|
||||
)
|
||||
|
||||
func load(c *ui.Context, url string, maxSide int) (ui.ImageSource, time.Duration, error) {
|
||||
if maxSide <= 0 {
|
||||
maxSide = defaultSide
|
||||
}
|
||||
return shared.request(url, maxSide, c)
|
||||
}
|
||||
|
||||
// key names a picture at a size, in memory.
|
||||
type key struct {
|
||||
url string
|
||||
side int
|
||||
}
|
||||
|
||||
type entry struct {
|
||||
key key
|
||||
src ui.ImageSource
|
||||
size int64
|
||||
err error
|
||||
// used is its last showing, came when it came to memory, failed when it
|
||||
// last failed.
|
||||
used, came, failed time.Time
|
||||
// loading says a worker has it or it waits for one.
|
||||
loading bool
|
||||
// fresh says the disk's copy showed at once, not after a wait: no fade.
|
||||
fresh bool
|
||||
// preload goes to disk alone, and isn't given up; forgotten was let go of as
|
||||
// it downloads, and keeps nothing.
|
||||
preload, forgotten bool
|
||||
// waiters are the views to build again.
|
||||
waiters []*ui.Context
|
||||
}
|
||||
|
||||
type cache struct {
|
||||
mu sync.Mutex
|
||||
entries map[key]*entry
|
||||
queue []*entry
|
||||
running int
|
||||
held int64
|
||||
client *http.Client
|
||||
dir string
|
||||
pruned bool
|
||||
once sync.Once
|
||||
now func() time.Time
|
||||
// limit is memoryLimit, smaller in tests.
|
||||
limit int64
|
||||
}
|
||||
|
||||
var shared = newCache()
|
||||
|
||||
func newCache() *cache {
|
||||
return &cache{entries: map[key]*entry{}, now: time.Now, limit: memoryLimit}
|
||||
}
|
||||
|
||||
// request returns the picture, and starts bringing it if it's not there. c may
|
||||
// be nil for no view to tell. age is how long ago it came, or -1 for long enough
|
||||
// not to fade.
|
||||
func (m *cache) request(url string, side int, c *ui.Context) (ui.ImageSource, time.Duration, error) {
|
||||
m.once.Do(func() {
|
||||
// Short of memory, the system would rather end the app.
|
||||
mygo.App.OnMemoryWarning(m.dropMemory)
|
||||
})
|
||||
k := key{url, side}
|
||||
now := m.now()
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
e := m.entries[k]
|
||||
if e == nil {
|
||||
e = &entry{key: k}
|
||||
m.entries[k] = e
|
||||
}
|
||||
e.used = now
|
||||
if e.src != nil {
|
||||
age := now.Sub(e.came)
|
||||
if e.fresh {
|
||||
age = -1
|
||||
}
|
||||
return e.src, age, nil
|
||||
}
|
||||
if c != nil && !slices.Contains(e.waiters, c) {
|
||||
e.waiters = append(e.waiters, c)
|
||||
}
|
||||
if !e.loading && (e.err == nil || now.Sub(e.failed) >= retryAfter) {
|
||||
e.loading = true
|
||||
m.queue = append(m.queue, e)
|
||||
m.startLocked()
|
||||
}
|
||||
return nil, -1, e.err
|
||||
}
|
||||
|
||||
// preload downloads a picture to disk, unless it's there or on its way.
|
||||
func (m *cache) preload(url string) {
|
||||
k := key{url: url}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.entries[k] != nil {
|
||||
return
|
||||
}
|
||||
e := &entry{key: k, preload: true, loading: true, used: m.now()}
|
||||
m.entries[k] = e
|
||||
m.queue = append(m.queue, e)
|
||||
m.startLocked()
|
||||
}
|
||||
|
||||
// startLocked gives workers what waits, the last asked for first: what's on
|
||||
// screen now. What's gone by its turn leaves, and the views that asked build
|
||||
// again, to ask again if they still show it.
|
||||
func (m *cache) startLocked() {
|
||||
var told []*ui.Context
|
||||
for m.running < workers && len(m.queue) > 0 {
|
||||
e := m.queue[len(m.queue)-1]
|
||||
m.queue = m.queue[:len(m.queue)-1]
|
||||
if e.forgotten {
|
||||
told = append(told, e.waiters...)
|
||||
e.waiters = nil
|
||||
continue
|
||||
}
|
||||
if !e.preload && m.now().Sub(e.used) > abandoned {
|
||||
e.loading = false
|
||||
told = append(told, e.waiters...)
|
||||
e.waiters = nil
|
||||
delete(m.entries, e.key)
|
||||
continue
|
||||
}
|
||||
m.running++
|
||||
go m.bring(e)
|
||||
}
|
||||
if len(m.entries) > tooManyEntries {
|
||||
now := m.now()
|
||||
for k, e := range m.entries {
|
||||
if e.src == nil && !e.loading && now.Sub(e.failed) >= retryAfter {
|
||||
told = append(told, e.waiters...)
|
||||
delete(m.entries, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(told) > 0 {
|
||||
go func() {
|
||||
for _, c := range told {
|
||||
c.Invalidate()
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (m *cache) bring(e *entry) {
|
||||
r, err := m.fetch(e.key.url)
|
||||
var src ui.ImageSource
|
||||
size := int64(0)
|
||||
if err == nil && !e.preload {
|
||||
src, size, err = safeDecode(r.data, e.key.side)
|
||||
if err != nil && r.fallback != nil {
|
||||
// A 200 of what's no picture, as a captive portal's page: what it
|
||||
// had stands.
|
||||
src, size, err = safeDecode(r.fallback, e.key.side)
|
||||
r.store = nil
|
||||
} else if err != nil && r.fromDisk {
|
||||
// Spoiled: the next time asks the server.
|
||||
if body, meta := m.paths(e.key.url); body != "" {
|
||||
os.Remove(body)
|
||||
os.Remove(meta)
|
||||
}
|
||||
}
|
||||
} else if err == nil && r.store != nil && !isPicture(r.data) {
|
||||
r.store = nil
|
||||
}
|
||||
m.mu.Lock()
|
||||
gone := e.forgotten
|
||||
m.mu.Unlock()
|
||||
if err == nil && r.store != nil && !gone {
|
||||
r.store()
|
||||
}
|
||||
m.mu.Lock()
|
||||
e.loading = false
|
||||
now := m.now()
|
||||
switch {
|
||||
case gone || e.preload:
|
||||
if m.entries[e.key] == e {
|
||||
delete(m.entries, e.key)
|
||||
}
|
||||
case err != nil:
|
||||
e.err, e.failed = err, now
|
||||
default:
|
||||
e.src, e.err, e.size = src, nil, size
|
||||
e.came, e.fresh = now, r.fromDisk && now.Sub(e.used) < 50*time.Millisecond
|
||||
m.held += size
|
||||
m.evictLocked(e)
|
||||
}
|
||||
waiters := e.waiters
|
||||
e.waiters = nil
|
||||
m.running--
|
||||
m.startLocked()
|
||||
m.mu.Unlock()
|
||||
for _, c := range waiters {
|
||||
c.Invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
// isPicture reports whether data can be a picture, without decoding it all.
|
||||
func isPicture(data []byte) bool {
|
||||
if _, _, err := image.DecodeConfig(bytes.NewReader(data)); err == nil {
|
||||
return true
|
||||
}
|
||||
return bytes.Contains(data[:min(len(data), 4096)], []byte("<svg"))
|
||||
}
|
||||
|
||||
// safeDecode decodes what came from anywhere, which a decoder may panic on, and
|
||||
// which may say it's enormous: a small file can ask for gigabytes, which would
|
||||
// end the app.
|
||||
func safeDecode(data []byte, side int) (src ui.ImageSource, size int64, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = fmt.Errorf("netimage: decoding: %v", r)
|
||||
}
|
||||
}()
|
||||
if c, _, cerr := image.DecodeConfig(bytes.NewReader(data)); cerr == nil && int64(c.Width)*int64(c.Height) > maxPixels {
|
||||
return nil, 0, fmt.Errorf("netimage: %d×%d pixels is too many", c.Width, c.Height)
|
||||
}
|
||||
return decode(data, side)
|
||||
}
|
||||
|
||||
// decode makes the bitmap: on this goroutine, off the main thread.
|
||||
func decode(data []byte, side int) (ui.ImageSource, int64, error) {
|
||||
b, err := ui.DecodeBitmapScaled(data, side)
|
||||
if err != nil {
|
||||
// An SVG, which has no pixels to scale.
|
||||
s, serr := ui.DecodeImage(data)
|
||||
if serr != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return s, int64(len(data)), nil
|
||||
}
|
||||
w, h := b.Size()
|
||||
return b, int64(w) * int64(h) * 4, nil
|
||||
}
|
||||
|
||||
// evictLocked lets go of the pictures shown longest ago, down to the limit, but
|
||||
// keep, which just came, and what showed a moment ago: pictures on screen that
|
||||
// don't fit the limit go over it, rather than each pushing out the next for good.
|
||||
func (m *cache) evictLocked(keep *entry) {
|
||||
if m.held <= m.limit {
|
||||
return
|
||||
}
|
||||
now := m.now()
|
||||
for _, e := range m.heldOldestFirstLocked() {
|
||||
if m.held <= m.limit || now.Sub(e.used) < onScreen {
|
||||
return
|
||||
}
|
||||
if e != keep {
|
||||
m.held -= e.size
|
||||
delete(m.entries, e.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *cache) heldOldestFirstLocked() []*entry {
|
||||
var held []*entry
|
||||
for _, e := range m.entries {
|
||||
if e.src != nil {
|
||||
held = append(held, e)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(held, func(a, b *entry) int { return a.used.Compare(b.used) })
|
||||
return held
|
||||
}
|
||||
|
||||
// dropMemory lets go of the oldest three quarters. What's on screen is the last
|
||||
// to go: a window that hasn't built lately still shows it, and would flicker.
|
||||
func (m *cache) dropMemory() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
target := m.held / 4
|
||||
for _, e := range m.heldOldestFirstLocked() {
|
||||
if m.held <= target {
|
||||
return
|
||||
}
|
||||
m.held -= e.size
|
||||
delete(m.entries, e.key)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *cache) forget(url string) {
|
||||
m.dropLocked(func(k key) bool { return k.url == url })
|
||||
if body, meta := m.paths(url); body != "" {
|
||||
os.Remove(body)
|
||||
os.Remove(meta)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *cache) clear() {
|
||||
m.dropLocked(func(key) bool { return true })
|
||||
if dir := m.directory(); dir != "" {
|
||||
os.RemoveAll(dir)
|
||||
}
|
||||
}
|
||||
|
||||
// dropLocked lets go of the entries match says: those downloading finish for
|
||||
// nothing, keeping nothing, as after logging out.
|
||||
func (m *cache) dropLocked(match func(key) bool) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for k, e := range m.entries {
|
||||
if !match(k) {
|
||||
continue
|
||||
}
|
||||
e.forgotten = true
|
||||
m.held -= e.size
|
||||
e.size = 0
|
||||
delete(m.entries, k)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *cache) directory() string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.dir == "" {
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
m.dir = filepath.Join(cache, "mygo-netimage")
|
||||
}
|
||||
return m.dir
|
||||
}
|
||||
|
||||
func (m *cache) paths(url string) (body, meta string) {
|
||||
dir := m.directory()
|
||||
if dir == "" {
|
||||
return "", ""
|
||||
}
|
||||
sum := sha256.Sum256([]byte(url))
|
||||
name := hex.EncodeToString(sum[:])
|
||||
return filepath.Join(dir, name), filepath.Join(dir, name+".json")
|
||||
}
|
||||
|
||||
// metadata is what a picture's response said of its caching.
|
||||
type metadata struct {
|
||||
ETag string `json:"etag,omitempty"`
|
||||
LastModified string `json:"lastModified,omitempty"`
|
||||
FreshUntil time.Time `json:"freshUntil"`
|
||||
}
|
||||
|
||||
// fetched is what fetch found.
|
||||
type fetched struct {
|
||||
data []byte
|
||||
// fromDisk says it took no download; store writes it to disk, once it's
|
||||
// known to be a picture; fallback is the disk's copy, older, while data is
|
||||
// new.
|
||||
fromDisk bool
|
||||
store func()
|
||||
fallback []byte
|
||||
}
|
||||
|
||||
// fetch returns the picture's bytes, from disk while they're fresh, asking the
|
||||
// server whether they changed once they aren't. A phone offline shows what it
|
||||
// has, however old.
|
||||
func (m *cache) fetch(url string) (fetched, error) {
|
||||
body, metaPath := m.paths(url)
|
||||
var meta metadata
|
||||
var cached []byte
|
||||
if body != "" {
|
||||
if d, err := os.ReadFile(body); err == nil {
|
||||
cached = d
|
||||
if raw, err := os.ReadFile(metaPath); err == nil {
|
||||
json.Unmarshal(raw, &meta)
|
||||
}
|
||||
if m.now().Before(meta.FreshUntil) {
|
||||
return fetched{data: cached, fromDisk: true}, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
stale := fetched{data: cached, fromDisk: true}
|
||||
m.mu.Lock()
|
||||
client := m.client
|
||||
m.mu.Unlock()
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return fetched{}, err
|
||||
}
|
||||
if cached != nil {
|
||||
if meta.ETag != "" {
|
||||
req.Header.Set("If-None-Match", meta.ETag)
|
||||
}
|
||||
if meta.LastModified != "" {
|
||||
req.Header.Set("If-Modified-Since", meta.LastModified)
|
||||
}
|
||||
}
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
if cached != nil {
|
||||
return stale, nil
|
||||
}
|
||||
return fetched{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
switch {
|
||||
case res.StatusCode == http.StatusNotModified && cached != nil:
|
||||
next := m.metadataOf(res)
|
||||
if next.ETag == "" {
|
||||
next.ETag = meta.ETag
|
||||
}
|
||||
if next.LastModified == "" {
|
||||
next.LastModified = meta.LastModified
|
||||
}
|
||||
m.writeMeta(metaPath, next)
|
||||
return stale, nil
|
||||
case res.StatusCode != http.StatusOK:
|
||||
if cached != nil && res.StatusCode >= 500 {
|
||||
return stale, nil
|
||||
}
|
||||
return fetched{}, fmt.Errorf("netimage: %s: %s", url, res.Status)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(res.Body, maxBytes+1))
|
||||
if err == nil && len(data) > maxBytes {
|
||||
err = fmt.Errorf("netimage: %s is larger than %d bytes", url, maxBytes)
|
||||
}
|
||||
if err != nil {
|
||||
if cached != nil {
|
||||
return stale, nil
|
||||
}
|
||||
return fetched{}, err
|
||||
}
|
||||
r := fetched{data: data, fallback: cached}
|
||||
if body != "" && !noStore(res) {
|
||||
meta := m.metadataOf(res)
|
||||
r.store = func() { m.store(body, metaPath, data, meta) }
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func noStore(res *http.Response) bool {
|
||||
return strings.Contains(strings.ToLower(res.Header.Get("Cache-Control")), "no-store")
|
||||
}
|
||||
|
||||
// metadataOf reads Cache-Control's max-age and no-cache, then Expires.
|
||||
func (m *cache) metadataOf(res *http.Response) metadata {
|
||||
meta := metadata{ETag: res.Header.Get("ETag"), LastModified: res.Header.Get("Last-Modified")}
|
||||
now := m.now()
|
||||
fresh := defaultFresh
|
||||
found := false
|
||||
for part := range strings.SplitSeq(strings.ToLower(res.Header.Get("Cache-Control")), ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "no-cache" {
|
||||
fresh, found = 0, true
|
||||
break
|
||||
}
|
||||
if v, ok := strings.CutPrefix(part, "max-age="); ok {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
fresh, found = time.Duration(n)*time.Second, true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if t, err := http.ParseTime(res.Header.Get("Expires")); err == nil {
|
||||
fresh = t.Sub(now)
|
||||
}
|
||||
}
|
||||
meta.FreshUntil = now.Add(fresh)
|
||||
return meta
|
||||
}
|
||||
|
||||
// store writes the picture, whole or not at all, as other goroutines read it.
|
||||
func (m *cache) store(body, metaPath string, data []byte, meta metadata) {
|
||||
dir := filepath.Dir(body)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return
|
||||
}
|
||||
tmp, err := os.CreateTemp(dir, "tmp-")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = tmp.Write(data)
|
||||
if cerr := tmp.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(tmp.Name(), body)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(tmp.Name())
|
||||
return
|
||||
}
|
||||
m.writeMeta(metaPath, meta)
|
||||
m.mu.Lock()
|
||||
first := !m.pruned
|
||||
m.pruned = true
|
||||
m.mu.Unlock()
|
||||
if first {
|
||||
go m.prune(dir, diskLimit)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *cache) writeMeta(path string, meta metadata) {
|
||||
if raw, err := json.Marshal(meta); err == nil {
|
||||
os.WriteFile(path, raw, 0o644)
|
||||
}
|
||||
}
|
||||
|
||||
// prune removes what was written longest ago, once a run: a cache may not grow
|
||||
// without end on a phone.
|
||||
func (m *cache) prune(dir string, limit int64) {
|
||||
files, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
type file struct {
|
||||
path string
|
||||
size int64
|
||||
at time.Time
|
||||
}
|
||||
var all []file
|
||||
var total int64
|
||||
for _, f := range files {
|
||||
info, err := f.Info()
|
||||
if err != nil || strings.HasSuffix(f.Name(), ".json") {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(f.Name(), "tmp-") {
|
||||
os.Remove(filepath.Join(dir, f.Name())) // of a run that ended early
|
||||
continue
|
||||
}
|
||||
all = append(all, file{filepath.Join(dir, f.Name()), info.Size(), info.ModTime()})
|
||||
total += info.Size()
|
||||
}
|
||||
slices.SortFunc(all, func(a, b file) int { return a.at.Compare(b.at) })
|
||||
for _, f := range all {
|
||||
if total <= limit {
|
||||
return
|
||||
}
|
||||
os.Remove(f.path)
|
||||
os.Remove(f.path + ".json")
|
||||
total -= f.size
|
||||
}
|
||||
}
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
package netimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
func picture(t *testing.T, w, h int) []byte {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := range h {
|
||||
for x := range w {
|
||||
img.Set(x, y, color.RGBA{200, 100, 50, 255})
|
||||
}
|
||||
}
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// testCache is a cache of its own, on a clock of the test's.
|
||||
func testCache(t *testing.T) (*cache, *time.Time) {
|
||||
t.Helper()
|
||||
m := newCache()
|
||||
m.dir = t.TempDir()
|
||||
m.once.Do(func() {}) // no app to hear from
|
||||
clock := time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC)
|
||||
m.now = func() time.Time { return clock }
|
||||
t.Cleanup(func() { idle(t, m) }) // before its directory goes
|
||||
return m, &clock
|
||||
}
|
||||
|
||||
// get waits for the picture.
|
||||
func get(t *testing.T, m *cache, url string, side int) ui.ImageSource {
|
||||
t.Helper()
|
||||
var src ui.ImageSource
|
||||
wait.Until(t, "the picture to come", func() bool {
|
||||
s, _, err := m.request(url, side, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src = s
|
||||
return s != nil
|
||||
})
|
||||
return src
|
||||
}
|
||||
|
||||
// A picture downloads once: to memory, then to disk for the next run.
|
||||
func TestDownloadsOnce(t *testing.T) {
|
||||
data := picture(t, 8, 8)
|
||||
var hits atomic.Int32
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
w.Header().Set("Cache-Control", "max-age=3600")
|
||||
w.Write(data)
|
||||
}))
|
||||
defer s.Close()
|
||||
m, _ := testCache(t)
|
||||
get(t, m, s.URL, 100)
|
||||
get(t, m, s.URL, 100)
|
||||
if hits.Load() != 1 {
|
||||
t.Errorf("downloaded %d times", hits.Load())
|
||||
}
|
||||
// The next run: memory is gone, the disk stays.
|
||||
next, clock := testCache(t)
|
||||
next.dir = m.dir
|
||||
*clock = m.now()
|
||||
get(t, next, s.URL, 100)
|
||||
if hits.Load() != 1 {
|
||||
t.Errorf("after a restart, downloaded %d times", hits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// Past its freshness it asks, and the server may say it stays the same.
|
||||
func TestRevalidates(t *testing.T) {
|
||||
data := picture(t, 8, 8)
|
||||
var hits, same atomic.Int32
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
w.Header().Set("Cache-Control", "max-age=60")
|
||||
w.Header().Set("ETag", `"v1"`)
|
||||
if r.Header.Get("If-None-Match") == `"v1"` {
|
||||
same.Add(1)
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}))
|
||||
defer s.Close()
|
||||
m, clock := testCache(t)
|
||||
get(t, m, s.URL, 100)
|
||||
// Memory goes, an hour later: it asks.
|
||||
next, c2 := testCache(t)
|
||||
next.dir = m.dir
|
||||
*c2 = clock.Add(time.Hour)
|
||||
get(t, next, s.URL, 100)
|
||||
if hits.Load() != 2 || same.Load() != 1 {
|
||||
t.Errorf("%d requests, %d answered the same", hits.Load(), same.Load())
|
||||
}
|
||||
// It said fresh again: the one after doesn't ask.
|
||||
third, c3 := testCache(t)
|
||||
third.dir = m.dir
|
||||
*c3 = c2.Add(time.Second)
|
||||
get(t, third, s.URL, 100)
|
||||
if hits.Load() != 2 {
|
||||
t.Errorf("fresh again, it asked: %d requests", hits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// Offline, what it has shows, however old.
|
||||
func TestOffline(t *testing.T) {
|
||||
data := picture(t, 8, 8)
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "max-age=1")
|
||||
w.Write(data)
|
||||
}))
|
||||
m, clock := testCache(t)
|
||||
get(t, m, s.URL, 100)
|
||||
url := s.URL
|
||||
s.Close()
|
||||
next, c2 := testCache(t)
|
||||
next.dir = m.dir
|
||||
*c2 = clock.Add(24 * time.Hour)
|
||||
get(t, next, url, 100)
|
||||
}
|
||||
|
||||
// What fails says so, and is asked for again only a while later.
|
||||
func TestFailureWaits(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
data := picture(t, 8, 8)
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if hits.Add(1) == 1 {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}))
|
||||
defer s.Close()
|
||||
m, clock := testCache(t)
|
||||
wait.Until(t, "the failure", func() bool {
|
||||
_, _, err := m.request(s.URL, 100, nil)
|
||||
return err != nil
|
||||
})
|
||||
if _, _, err := m.request(s.URL, 100, nil); err == nil {
|
||||
t.Error("the failure went")
|
||||
}
|
||||
if hits.Load() != 1 {
|
||||
t.Errorf("asked again at once: %d", hits.Load())
|
||||
}
|
||||
*clock = clock.Add(retryAfter + time.Second)
|
||||
wait.Until(t, "it to come", func() bool {
|
||||
src, _, _ := m.request(s.URL, 100, nil)
|
||||
return src != nil
|
||||
})
|
||||
}
|
||||
|
||||
// A photo stays as big as what shows it.
|
||||
func TestScales(t *testing.T) {
|
||||
data := picture(t, 400, 200)
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(data) }))
|
||||
defer s.Close()
|
||||
m, _ := testCache(t)
|
||||
b := get(t, m, s.URL, 100).(*ui.Bitmap)
|
||||
if w, h := b.Size(); w != 100 || h != 50 {
|
||||
t.Errorf("scaled to %d×%d", w, h)
|
||||
}
|
||||
}
|
||||
|
||||
// Memory holds what was shown last, up to its limit.
|
||||
func TestEvicts(t *testing.T) {
|
||||
data := picture(t, 100, 100)
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(data) }))
|
||||
defer s.Close()
|
||||
m, clock := testCache(t)
|
||||
m.limit = 100 * 100 * 4 * 2 // two
|
||||
for i := range 4 {
|
||||
get(t, m, fmt.Sprintf("%s/%d", s.URL, i), 100)
|
||||
*clock = clock.Add(time.Second)
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.held > m.limit {
|
||||
t.Errorf("holds %d of %d", m.held, m.limit)
|
||||
}
|
||||
if m.entries[key{s.URL + "/0", 100}] != nil {
|
||||
t.Error("the first kept")
|
||||
}
|
||||
if m.entries[key{s.URL + "/3", 100}] == nil {
|
||||
t.Error("the last gone")
|
||||
}
|
||||
}
|
||||
|
||||
// The last asked for goes first, and what a fling left behind not at all.
|
||||
func TestLastFirst(t *testing.T) {
|
||||
data := picture(t, 8, 8)
|
||||
turn := make(chan struct{}, workers+3)
|
||||
arrived := make(chan string, workers+3)
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
arrived <- r.URL.Path
|
||||
<-turn
|
||||
w.Write(data)
|
||||
}))
|
||||
defer s.Close()
|
||||
m, clock := testCache(t)
|
||||
for i := range workers {
|
||||
m.request(fmt.Sprintf("%s/b%d", s.URL, i), 100, nil)
|
||||
}
|
||||
for range workers {
|
||||
wait.For(t, "the workers to be busy", arrived)
|
||||
}
|
||||
m.request(s.URL+"/gone", 100, nil)
|
||||
*clock = clock.Add(abandoned + time.Second)
|
||||
m.request(s.URL+"/older", 100, nil)
|
||||
m.request(s.URL+"/newest", 100, nil)
|
||||
// One worker at a time frees up, each taking the next.
|
||||
for _, want := range []string{"/newest", "/older"} {
|
||||
turn <- struct{}{}
|
||||
if got := wait.For(t, "a download", arrived); got != want {
|
||||
t.Errorf("downloading %s, want %s", got, want)
|
||||
}
|
||||
}
|
||||
for range workers + 2 {
|
||||
turn <- struct{}{}
|
||||
}
|
||||
idle(t, m)
|
||||
if len(arrived) != 0 {
|
||||
t.Errorf("what a fling left downloaded: %s", <-arrived)
|
||||
}
|
||||
}
|
||||
|
||||
// idle waits for the workers to finish.
|
||||
func idle(t *testing.T, m *cache) {
|
||||
t.Helper()
|
||||
wait.Until(t, "the workers to finish", func() bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.running == 0
|
||||
})
|
||||
}
|
||||
|
||||
// The disk keeps what was written last, without what a run left half written.
|
||||
func TestPrune(t *testing.T) {
|
||||
m, _ := testCache(t)
|
||||
old := filepath.Join(m.dir, "old")
|
||||
young := filepath.Join(m.dir, "young")
|
||||
tmp := filepath.Join(m.dir, "tmp-1")
|
||||
for _, f := range []string{old, young, tmp} {
|
||||
if err := os.WriteFile(f, make([]byte, 100), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
long := time.Now().Add(-time.Hour)
|
||||
if err := os.Chtimes(old, long, long); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.prune(m.dir, 100)
|
||||
if fileThere(old) || !fileThere(young) || fileThere(tmp) {
|
||||
t.Errorf("after pruning: old %v, young %v, tmp %v", fileThere(old), fileThere(young), fileThere(tmp))
|
||||
}
|
||||
}
|
||||
|
||||
func fileThere(p string) bool {
|
||||
_, err := os.Stat(p)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// A view shows the placeholder, and the picture once it comes, on its own.
|
||||
func TestImageInView(t *testing.T) {
|
||||
data := picture(t, 8, 8)
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(data) }))
|
||||
defer s.Close()
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CACHE_HOME", dir)
|
||||
t.Setenv("HOME", dir)
|
||||
var src ui.ImageSource
|
||||
tt := ui.NewTester(func(c *ui.Context) {
|
||||
Image(c, s.URL).Size(40, 40)
|
||||
src, _ = Load(c, s.URL)
|
||||
}, 100, 100)
|
||||
tt.Frame()
|
||||
wait.Until(t, "the picture to show", func() bool {
|
||||
tt.Frame()
|
||||
return src != nil
|
||||
})
|
||||
}
|
||||
|
||||
// A page that answers for the picture, as a captive portal's, leaves what the
|
||||
// disk has.
|
||||
func TestCaptivePortal(t *testing.T) {
|
||||
data := picture(t, 8, 8)
|
||||
var portal atomic.Bool
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "max-age=1")
|
||||
if portal.Load() {
|
||||
w.Write([]byte("<html>Sign in to the Wi-Fi</html>"))
|
||||
return
|
||||
}
|
||||
w.Write(data)
|
||||
}))
|
||||
defer s.Close()
|
||||
m, clock := testCache(t)
|
||||
get(t, m, s.URL, 100)
|
||||
portal.Store(true)
|
||||
next, c2 := testCache(t)
|
||||
next.dir = m.dir
|
||||
*c2 = clock.Add(time.Hour)
|
||||
get(t, next, s.URL, 100)
|
||||
idle(t, next)
|
||||
// And it's still there for the run after, the portal gone or not.
|
||||
body, _ := m.paths(s.URL)
|
||||
kept, err := os.ReadFile(body)
|
||||
if err != nil || !bytes.Equal(kept, data) {
|
||||
t.Errorf("the disk holds %d bytes, %v", len(kept), err)
|
||||
}
|
||||
}
|
||||
|
||||
// A small file that says it's enormous fails, rather than ending the app.
|
||||
func TestEnormousPicture(t *testing.T) {
|
||||
// A PNG's header says its size; what follows doesn't matter to the check.
|
||||
data := picture(t, 8, 8)
|
||||
data[16], data[17], data[18], data[19] = 0, 0, 0x75, 0x30 // 30000
|
||||
data[20], data[21], data[22], data[23] = 0, 0, 0x75, 0x30
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(data) }))
|
||||
defer s.Close()
|
||||
m, _ := testCache(t)
|
||||
wait.Until(t, "it to fail", func() bool {
|
||||
_, _, err := m.request(s.URL, 100, nil)
|
||||
return err != nil
|
||||
})
|
||||
}
|
||||
|
||||
// Pictures on screen that don't fit the limit stay, rather than each pushing out
|
||||
// the next for good.
|
||||
func TestOnScreenStays(t *testing.T) {
|
||||
data := picture(t, 100, 100)
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(data) }))
|
||||
defer s.Close()
|
||||
m, _ := testCache(t)
|
||||
m.limit = 100 * 100 * 4 // one
|
||||
for i := range 3 {
|
||||
get(t, m, fmt.Sprintf("%s/%d", s.URL, i), 100)
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if len(m.entries) != 3 {
|
||||
t.Errorf("%d of 3 on screen stay", len(m.entries))
|
||||
}
|
||||
}
|
||||
|
||||
// What's let go of as it downloads, as on logging out, stays off the disk.
|
||||
func TestForgetWhileDownloading(t *testing.T) {
|
||||
data := picture(t, 8, 8)
|
||||
arrived, finish := make(chan struct{}), make(chan struct{})
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
close(arrived)
|
||||
<-finish
|
||||
w.Write(data)
|
||||
}))
|
||||
defer s.Close()
|
||||
m, _ := testCache(t)
|
||||
m.request(s.URL, 100, nil)
|
||||
wait.For(t, "the download", arrived)
|
||||
m.clear()
|
||||
close(finish)
|
||||
idle(t, m)
|
||||
body, _ := m.paths(s.URL)
|
||||
if fileThere(body) {
|
||||
t.Error("it went to disk")
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if len(m.entries) != 0 || m.held != 0 {
|
||||
t.Errorf("%d entries, %d bytes", len(m.entries), m.held)
|
||||
}
|
||||
}
|
||||
|
||||
// Preloading fills the disk, not memory, and gives up on nothing however long it
|
||||
// waits for a worker.
|
||||
func TestPreload(t *testing.T) {
|
||||
data := picture(t, 8, 8)
|
||||
var hits atomic.Int32
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
w.Header().Set("Cache-Control", "max-age=3600")
|
||||
w.Write(data)
|
||||
}))
|
||||
defer s.Close()
|
||||
m, _ := testCache(t)
|
||||
m.preload(s.URL)
|
||||
idle(t, m)
|
||||
m.mu.Lock()
|
||||
held, n := m.held, len(m.entries)
|
||||
m.mu.Unlock()
|
||||
if held != 0 || n != 0 {
|
||||
t.Errorf("preloading holds %d bytes, %d entries", held, n)
|
||||
}
|
||||
get(t, m, s.URL, 100)
|
||||
if hits.Load() != 1 {
|
||||
t.Errorf("downloaded %d times", hits.Load())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user