From 68363bf20d274956d56917d94cd2cf1dbaf21bec Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:13:38 +0000 Subject: [PATCH 01/43] Update README to reflect current project plans Removed outdated features from planned expansions section. --- README.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/README.md b/README.md index 3bcbc7d1..927ded5c 100644 --- a/README.md +++ b/README.md @@ -134,11 +134,8 @@ asyncao -debug # pprof on localhost:6060 Planned, not yet built but future expansions: - **Eventual mobile support** — native Android / iOS binaries. -- Eventual Legacy AO2 demo file converter to MP4/Video, for Archival. THIS IS MOSTLY DONE. PROBABLY NEEDS SOME IMPROVEMENTS BUT THIS IS A GOOD STATE. - Dedicated built in theme builder so people can easily make AsyncAO themes by importing images, fonts, colours and exporting them for later. Encourages people to stop relying on QT based themes, while making the proccess streamlined and easy for anyone. -- Lua plugin system so people can add lua plugins and make modifications to the client behaviour or features. -- Migrate to SDL3 -- + ## Credits All credit to the original Attorney Online developers — AsyncAO exists because From e4e0ae32afbea19079ff31cf20e7b83e1aebb04e Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:43:12 +0100 Subject: [PATCH 02/43] assets: a one-frame animated WebP decodes to its frame A WebP with the animation flag and a single frame produced no texture at all. Decode drops frame 0 when the first-frame decode says the file isn't animated (so a GIF or APNG that turns out static isn't uploaded twice), but the file still went down the streaming path, which appends only frames after frame 0 and then closes a page that was never made. The speaker's sprite then never arrived: strict sequencing held every message using it for the full 10 s, and each re-ask decoded the file again for nothing. Seen with Patty Thompson's "(a)/embarrassed" on miku.pizza. The stream now runs only when frame 0 went out as its first chunk; otherwise the file decodes as a still. Co-Authored-By: Claude Opus 5.5 --- internal/assets/decoder.go | 8 +++- internal/assets/webp_cgo_test.go | 71 ++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) diff --git a/internal/assets/decoder.go b/internal/assets/decoder.go index 3d95290f..1b16361a 100644 --- a/internal/assets/decoder.go +++ b/internal/assets/decoder.go @@ -659,6 +659,8 @@ func (p *DecoderPool) runJob(req DecodeRequest) { defer p.animGate.release() } + // established is whether frame 0 went out as a stream's first chunk; the stream appends only frames after it. + established := false if animated { if first, err := DecodeImage(req.Data, false); err == nil { // GIF/APNG can sniff "maybe" but decode static, and a static would upload the same texture twice. @@ -673,6 +675,7 @@ func (p *DecoderPool) runJob(req DecodeRequest) { if streamable { // Streaming pages grow frame by frame; frame 0 is the first chunk. first.Stream = true + established = true } req.OnDone(req.URL, first, nil) } else { @@ -681,8 +684,9 @@ func (p *DecoderPool) runJob(req DecodeRequest) { } } - // The definitely-animated CGO formats stream: frames land one at a time and the page plays what has arrived. - if streamable { + // The definitely-animated CGO formats stream: frames land one at a time and the page plays what has arrived. A file + // with the animation flag and one frame decodes as a still, as no stream ever sends its frame 0. + if streamable && established { p.streamAnimated(req) return } diff --git a/internal/assets/webp_cgo_test.go b/internal/assets/webp_cgo_test.go index 128ea4d1..ec817ddd 100644 --- a/internal/assets/webp_cgo_test.go +++ b/internal/assets/webp_cgo_test.go @@ -3,6 +3,7 @@ package assets import ( + "encoding/binary" "os" "path/filepath" "testing" @@ -213,3 +214,73 @@ func BenchmarkDecodeWebPAnim_256x192_3f(b *testing.B) { d.Release() } } + +// oneFrameAnimatedWebP wraps a still lossy WebP in the animation chunks, as encoders that keep the ANIM flag for a single +// frame write it; webpmux and img2webp both collapse one frame to a still, so the fixture is built here. +func oneFrameAnimatedWebP(t *testing.T, still []byte, w, h int) []byte { + t.Helper() + const ( + riffHeader = 12 + vp8xAnimFlag = 0x02 + frameMs = 150 + ) + if string(still[riffHeader:riffHeader+4]) != "VP8 " { + t.Fatalf("fixture chunk %q, want a lossy VP8 still", still[riffHeader:riffHeader+4]) + } + frame := still[riffHeader:] // the VP8 chunk, header and padding included + u24 := func(b []byte, v int) []byte { return append(b, byte(v), byte(v>>8), byte(v>>16)) } + chunk := func(b []byte, kind string, body []byte) []byte { + b = append(b, kind...) + b = binary.LittleEndian.AppendUint32(b, uint32(len(body))) + b = append(b, body...) + if len(body)%2 == 1 { + b = append(b, 0) + } + return b + } + vp8x := u24(u24([]byte{vp8xAnimFlag, 0, 0, 0}, w-1), h-1) + anim := []byte{0, 0, 0, 0, 0, 0} // background colour, loop forever + anmf := u24(u24(u24(u24(u24(nil, 0), 0), w-1), h-1), frameMs) + anmf = append(append(anmf, 0), frame...) + body := chunk(chunk(chunk([]byte("WEBP"), "VP8X", vp8x), "ANIM", anim), "ANMF", anmf) + out := binary.LittleEndian.AppendUint32([]byte("RIFF"), uint32(len(body))) + return append(out, body...) +} + +func TestAOneFrameAnimationDecodesToItsFrame(t *testing.T) { + const w, h = 256, 192 + data := oneFrameAnimatedWebP(t, fixture(t, "sprite_256x192.webp"), w, h) + if Sniff(data) != FormatWebPAnim { + t.Fatalf("built %v, want an animated webp", Sniff(data)) + } + const wait = 5 * time.Second + pool := NewDecoderPool(1) + defer pool.Close() + got := make(chan *Decoded, 4) + pool.Submit(DecodeRequest{ + URL: "x", Data: data, Type: AssetTypeCharSprite, PlayAnimations: true, + OnDone: func(_ string, d *Decoded, err error) { + if err != nil { + t.Errorf("decode: %v", err) + d = &Decoded{} + } + got <- d + }, + }) + var frames int + var final *Decoded + for final == nil { + select { + case d := <-got: + frames += len(d.Frames) + if !d.Partial { + final = d + } + case <-time.After(wait): + t.Fatalf("no final page after %d frames", frames) + } + } + if final == nil || frames != 1 || final.Width != w || final.Height != h { + t.Fatalf("delivered %d frames, final %+v; want one %dx%d frame and a final page", frames, final, w, h) + } +} From 6f0d1b8aef0efb2de63c80fd0378e8999cbb8a7c Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:59:29 +0100 Subject: [PATCH 03/43] wardrobe: a setting to wear a character with one click Settings > General > Wardrobe gets "Click: Selects / Wears". With Wears, one click on a character does what double-click does: switch to it when its slot is free, else wear it as an iniswap. Only the first click of a same-spot streak wears, so a double-click out of habit doesn't wear the character a second time, which would turn the switch into an iniswap. The hint shown with nothing selected follows the setting. Off by default; stored as wardrobeSingleClick. Co-Authored-By: Claude Opus 5.5 --- internal/config/settings.go | 2 ++ internal/config/settings_clone.go | 3 ++ internal/ui/settingswardrobe.go | 28 ++++++++++++++++++ internal/ui/wardrobedraw.go | 16 ++++++++-- internal/ui/wardrobewin_test.go | 49 +++++++++++++++++++++++++++++++ 5 files changed, 95 insertions(+), 3 deletions(-) diff --git a/internal/config/settings.go b/internal/config/settings.go index 1a2b1786..2294e06c 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -261,6 +261,8 @@ type Settings struct { WardrobeIconPxVal int `json:"wardrobeIconPx,omitempty"` // WardrobeNameAbove puts a grid card's name above its icon instead of below. WardrobeNameAbove bool `json:"wardrobeNameAbove,omitempty"` + // WardrobeSingleClick makes one click on a character wear it, as double-click does. + WardrobeSingleClick bool `json:"wardrobeSingleClick,omitempty"` // WardrobeAccentVal is the Wardrobe's highlight colour, packed 0xRRGGBB; 0 is the default blue. WardrobeAccentVal int `json:"wardrobeAccent,omitempty"` CustomChromeHex [7]string `json:"customChrome"` diff --git a/internal/config/settings_clone.go b/internal/config/settings_clone.go index 6a395d8e..b8ba2bb5 100644 --- a/internal/config/settings_clone.go +++ b/internal/config/settings_clone.go @@ -1230,6 +1230,9 @@ func (s *Settings) equal(o *Settings) bool { if s.WardrobeNameAbove != o.WardrobeNameAbove { return false } + if s.WardrobeSingleClick != o.WardrobeSingleClick { + return false + } if s.WardrobeAccentVal != o.WardrobeAccentVal { return false } diff --git a/internal/ui/settingswardrobe.go b/internal/ui/settingswardrobe.go index 600a06ed..0f445b0d 100644 --- a/internal/ui/settingswardrobe.go +++ b/internal/ui/settingswardrobe.go @@ -87,6 +87,7 @@ func (a *App) drawWardrobeSettings(y, w int32) int32 { "Character icons are 40 × 40; the larger sizes double or triple them. The List view keeps them at 40.") y += btnH + wardSetRowGap y = a.drawWardrobeNamePlacement(y) + y = a.drawWardrobeClick(y) return a.drawWardrobeAccentPicker(y) } @@ -117,6 +118,33 @@ func (a *App) drawWardrobeNamePlacement(y int32) int32 { return y + btnH + wardSetRowGap } +// drawWardrobeClick picks whether one click on a character selects it or wears it. +func (a *App) drawWardrobeClick(y int32) int32 { + c := a.ctx + pad := a.formX + c.Label(pad, y+wardSetLabelY, "Click", ColText) + single := a.d.Prefs.Load().WardrobeSingleClick + x := pad + panelFontLabelW + for _, ch := range [...]struct { + single bool + label string + }{{false, "Selects"}, {true, "Wears"}} { + r := sdl.Rect{X: x, Y: y, W: wardSetChoiceW, H: btnH} + bg, fg := ColPanel, ColText + if ch.single == single { + bg, fg = ColAccent, ColBackground + } + if c.ButtonCol(r, ch.label, bg, ColPanelHi, ColAccent, fg) && ch.single != single { + next := ch.single + a.d.Prefs.Update(func(sn *config.Settings) { sn.WardrobeSingleClick = next }) + } + x += wardSetChoiceW + wardSetGap + } + c.Tooltip(sdl.Rect{X: pad + panelFontLabelW, Y: y, W: x - pad - panelFontLabelW, H: btnH}, + "What one click on a character does. Wears: it switches to the character, or wears it as an iniswap when its slot is taken, as double-click does.") + return y + btnH + wardSetRowGap +} + // drawWardrobeAccentPicker is the Wardrobe's highlight colour: selections, the active buttons, focused fields and // drop outlines. It reuses the log highlight's wheel, slider and hex field. func (a *App) drawWardrobeAccentPicker(y int32) int32 { diff --git a/internal/ui/wardrobedraw.go b/internal/ui/wardrobedraw.go index 3c329e5c..73823e95 100644 --- a/internal/ui/wardrobedraw.go +++ b/internal/ui/wardrobedraw.go @@ -1150,7 +1150,7 @@ func (a *App) drawWardrobeItem(idx int, it wardrobe.Item, r sdl.Rect) { a.wardrobeItemInput(it, r) } -// wardrobeItemInput selects on click, uses on double-click, and arms a drag on press. +// wardrobeItemInput selects on click, uses on double-click (or on click with single click on), and arms a drag on press. func (a *App) wardrobeItemInput(it wardrobe.Item, r sdl.Rect) { c := a.ctx ward := &a.ward @@ -1173,14 +1173,20 @@ func (a *App) wardrobeItemInput(it wardrobe.Item, r sdl.Rect) { if c.mouseDown && !c.prevMouseDown && ward.source == wardrobe.SourceUser { a.startWardrobeDrag(wardDragChar, it.Char) } + single := a.d.Prefs.Load().WardrobeSingleClick switch { - case c.dblClick: + case c.dblClick && !single: c.dblClick = false a.wardrobeUse(it.Char) case c.ClickedIn(r): if ward.sel != it.Char { ward.sel, ward.confirmRemove, ward.nickOpen, ward.moveMenu = it.Char, false, false, false } + // Only a streak's first click wears: the second click of a double-click would wear it again, or as an iniswap. + if single && c.clickStreak == 1 { + a.wardrobeUse(it.Char) + } + c.dblClick = false } } @@ -1309,7 +1315,11 @@ func (a *App) drawWardrobeBar(r sdl.Rect) { right := r.X + r.W - 2*wardPanelPad ward.moreN = 0 if !ok { - c.LabelClipped(x, r.Y+(r.H-lh)/2, r.W-4*wardPanelPad, "Select a character to see what you can do with it. Double-click wears it.", wcDim) + hint := "Select a character to see what you can do with it. Double-click wears it." + if a.d.Prefs.Load().WardrobeSingleClick { + hint = "Click a character to wear it; what else you can do with it shows here." + } + c.LabelClipped(x, r.Y+(r.H-lh)/2, r.W-4*wardPanelPad, hint, wcDim) return } switch { diff --git a/internal/ui/wardrobewin_test.go b/internal/ui/wardrobewin_test.go index 9004bc0f..ff96d409 100644 --- a/internal/ui/wardrobewin_test.go +++ b/internal/ui/wardrobewin_test.go @@ -9,6 +9,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/render" + "github.com/SyntaxNyah/AsyncAO/internal/sdl" "github.com/SyntaxNyah/AsyncAO/internal/ui/wardrobe" ) @@ -237,3 +238,51 @@ func TestWardrobeWearWithEveryCharacterTakenWearsNothing(t *testing.T) { t.Fatalf("no free slot: wore anyway or said nothing (queued %q, warning %q)", a.ward.wearAfter, a.warnLine) } } + +// wardrobeClickTestApp is a rehearsal App whose pointer rests on a Wardrobe card; slot 1 (Maya) is free. +func wardrobeClickTestApp(t *testing.T, single bool) (*App, sdl.Rect) { + t.Helper() + const charINILoads = 2 + a := emotePreviewFollowTestApp(t) // switching enters the courtroom, which fetches the char.ini + a.iniChar = "" + a.sess = courtroom.NewRehearsalSession("", []string{"Phoenix", "Maya"}) + a.d.Viewport = render.NewViewport(nil, false) + a.charINIres = make(chan charINIFetch, charINILoads) + a.room, a.screen = nil, ScreenCharSelect + a.d.Prefs.Update(func(sn *config.Settings) { sn.WardrobeSingleClick = single }) + const side = 100 + card := sdl.Rect{W: side, H: side} + a.ctx.mouseX, a.ctx.mouseY = side/2, side/2 + a.ctx.downX, a.ctx.downY = side/2, side/2 + return a, card +} + +// click releases the button on the card as the streak's nth same-spot click. +func wardrobeClickOn(a *App, card sdl.Rect, nth int) { + const double = 2 + a.ctx.clicked, a.ctx.clickStreak, a.ctx.dblClick = true, nth, nth == double + a.wardrobeItemInput(wardrobe.Item{Char: "Maya"}, card) + a.ctx.clicked, a.ctx.dblClick = false, false +} + +func TestWardrobeSingleClickWearsOnce(t *testing.T) { + const maya = 1 + a, card := wardrobeClickTestApp(t, true) + wardrobeClickOn(a, card, 1) + if a.sess.MyCharID != maya { + t.Fatalf("one click left slot %d, want Maya's slot %d", a.sess.MyCharID, maya) + } + wardrobeClickOn(a, card, 2) // the second click of a double-click + if a.iniChar != "" { + t.Fatalf("a double-click wore Maya again as an iniswap (%q)", a.iniChar) + } +} + +func TestWardrobeClickOnlySelectsByDefault(t *testing.T) { + a, card := wardrobeClickTestApp(t, false) + before := a.sess.MyCharID + wardrobeClickOn(a, card, 1) + if a.sess.MyCharID != before || a.ward.sel != "Maya" { + t.Fatalf("a click switched to slot %d or didn't select (sel %q)", a.sess.MyCharID, a.ward.sel) + } +} From a52a5cf4f7db3dc7fc70f6bb767cb4706c27301e Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:22:50 +0100 Subject: [PATCH 04/43] courtroom: a held message asks again for what it waits on The wait gate asked for a message's needs when it armed and again only once its current blocker settled. A missing warning dropped on the way (the warning hand-off drops when full) left that blocker unsettled, so nothing asked again and the message waited out the whole limit, 10 s under strict sequencing. The hold now builds a fresh list and asks again once a second; asking for something already known missing sends its warning again, which settles it. A held tick stays allocation-free in between. Co-Authored-By: Claude Opus 5.5 --- internal/courtroom/courtroom.go | 19 ++++++++---- internal/courtroom/messageneeds_test.go | 39 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/internal/courtroom/courtroom.go b/internal/courtroom/courtroom.go index 7a749e28..62eba6f8 100644 --- a/internal/courtroom/courtroom.go +++ b/internal/courtroom/courtroom.go @@ -30,7 +30,10 @@ const ( // missingSpritesCap bounds the 404'd base set (hard rule 4); past it SpriteWaitTimeout bounds any unrecorded miss. // sequentialWaitLimit releases a strict-sequencing hold: a transient error or dropped warning never settles an asset. sequentialWaitLimit = 10 * time.Second - missingSpritesCap = 512 + // waitReaskInterval is how often a hold asks again for what it still waits on: an answer lost on the way, such as a + // dropped missing warning, would otherwise keep the message until the limit. + waitReaskInterval = time.Second + missingSpritesCap = 512 // missingDesksCap bounds the 404'd desk set (hard rule 4); past it the render-side release covers the layer. missingDesksCap = 512 // blipVolumeFull is the unattenuated blip scale, used with no BlipVolumeFor callback. @@ -324,9 +327,11 @@ type Courtroom struct { // CatchUpLinger holds each fast-forwarded message before the next; default zero drains one per frame. CatchUpLinger time.Duration - // waitLeft counts down an armed hold; waitFor is its message by pointer, so a new head re-arms. - waitLeft time.Duration - waitFor *protocol.ChatMessage + // waitLeft counts down an armed hold, and waitAskLeft to its next ask; waitFor is its message by pointer, so a new + // head re-arms. + waitLeft time.Duration + waitAskLeft time.Duration + waitFor *protocol.ChatMessage // waitBlocker is the need holding the message, needs messageNeeds' reused list. waitBlocker messageNeed needs []messageNeed @@ -591,7 +596,10 @@ func (c *Courtroom) waitHolds(msg *protocol.ChatMessage, behind int, dt time.Dur // This runs every frame of a hold: the need that stopped the last check is one lookup, the full list 174 allocations. // A release is always decided on a fresh list. armed := c.waitFor == msg - if !armed || c.needSettled(c.waitBlocker) { + if armed { + c.waitAskLeft -= dt + } + if !armed || c.needSettled(c.waitBlocker) || c.waitAskLeft <= 0 { needs := c.messageNeeds(msg) blocker, blocked := c.firstUnsettled(needs) if !blocked { @@ -609,6 +617,7 @@ func (c *Courtroom) waitHolds(msg *protocol.ChatMessage, behind int, dt time.Dur // Every fresh list, not only the first: a need that joins once char.ini lands (chat skin, blip) has no other // requester until begin, which runs only after the gate releases. c.requestNeeds(needs) + c.waitAskLeft = waitReaskInterval } c.waitLeft -= dt if c.waitLeft <= 0 { diff --git a/internal/courtroom/messageneeds_test.go b/internal/courtroom/messageneeds_test.go index 8106f45a..fcec839e 100644 --- a/internal/courtroom/messageneeds_test.go +++ b/internal/courtroom/messageneeds_test.go @@ -210,3 +210,42 @@ func TestHeldNeedCoversTheHeldMessageOnly(t *testing.T) { t.Error("a released message still counts as held") } } + +// TestWaitGateAsksAgainWhileItHolds: a missing warning that never reaches the gate (a full hand-off drops it) leaves the +// blocker unsettled, so the hold asks again, which re-sends the warning, instead of waiting out the limit. +func TestWaitGateAsksAgainWhileItHolds(t *testing.T) { + const ( + tick = 16 * time.Millisecond + wait = 5 * time.Second + ) + room, _ := recordingRoom(t) + room.SequentialWait = true + room.Assets = assetFake{sprite: func(string) bool { return false }} + idle := room.urls.Emote("Phoenix", "normal", EmoteIdle) + warnedFor := func() bool { + deadline := time.After(wait) + for { + select { + case w := <-room.mgr.Warnings(): + if w.Base == idle { + return true + } + case <-deadline: + return false + } + } + } + + room.HandleEvent(Event{Kind: EventMessage, Message: waitMsg("Phoenix", "normal", "hi")}) + room.Update(tick) + if !warnedFor() { + t.Fatal("the first ask never reported the sprite missing") + } + room.Update(waitReaskInterval) // the warning was lost: nothing settled the sprite + if room.QueueLen() != 1 { + t.Fatal("the message stopped waiting before the limit") + } + if !warnedFor() { + t.Fatal("the hold never asked again, so the lost warning was never sent again") + } +} From 7c52206ec092e11e29e99b3b363335d7c685513e Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:58:08 +0100 Subject: [PATCH 05/43] ui: the theme fit preview shows its drag hint only with a design (#153) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A theme without courtroom_design.ini drew "Drag to pan · scroll to zoom" over its own "no courtroom_design.ini" notice, four pixels apart. With no design there is nothing to pan, so the notice now shows alone. Fixes #153 Co-Authored-By: Claude Opus 5.5 --- internal/ui/settingstabs.go | 12 +++++++++-- internal/ui/themefitpreview_test.go | 33 +++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 internal/ui/themefitpreview_test.go diff --git a/internal/ui/settingstabs.go b/internal/ui/settingstabs.go index 4637198a..2203446e 100644 --- a/internal/ui/settingstabs.go +++ b/internal/ui/settingstabs.go @@ -754,6 +754,11 @@ func (a *App) drawSettingsStageFX(y int32) int32 { return y } +const ( + themeFitPreviewHint = "Drag to pan · scroll to zoom" + themeFitNoDesignText = "This theme has no courtroom_design.ini — the fit modes don't apply to it." +) + // drawThemeFitPreview draws the Custom theme fit preview; drag pans, scroll zooms, both write prefs and re-fit live. func (a *App) drawThemeFitPreview(box sdl.Rect) { c := a.ctx @@ -782,10 +787,13 @@ func (a *App) drawThemeFitPreview(box sdl.Rect) { } c.popClip(clipPrev, clipHad) } else { - c.LabelClipped(box.X+8, box.Y+8, box.W-16, "This theme has no courtroom_design.ini — the fit modes don't apply to it.", ColTextDim) + c.LabelClipped(box.X+8, box.Y+8, box.W-16, themeFitNoDesignText, ColTextDim) } c.Border(box, ColAccent) - c.Label(box.X+6, box.Y+4, "Drag to pan · scroll to zoom", ColTextDim) + // Without a design there is nothing to pan, and the hint would sit on the line above. + if ok { + c.Label(box.X+6, box.Y+4, themeFitPreviewHint, ColTextDim) + } // Wheel zooms and drag pans via the setters, then invalidate the geometry cache. if c.hovering(box) && c.wheelY != 0 { diff --git a/internal/ui/themefitpreview_test.go b/internal/ui/themefitpreview_test.go new file mode 100644 index 00000000..d0f36134 --- /dev/null +++ b/internal/ui/themefitpreview_test.go @@ -0,0 +1,33 @@ +package ui + +import ( + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/sdl" +) + +// TestThemeFitPreviewHintOnlyWithADesign: a theme without courtroom_design.ini shows its notice alone, not the +// drag-to-pan hint on top of it (#153). +func TestThemeFitPreviewHintOnlyWithADesign(t *testing.T) { + const boxW, boxH = 560, 340 + a, cleanup := stageThemedCourtroom(t) + defer cleanup() + box := sdl.Rect{W: boxW, H: boxH} + + delete(a.themeRects, ao2CanvasKey) + a.ctx.purgeTextCache() + a.drawThemeFitPreview(box) + if !textCacheHasLabel(a.ctx, themeFitNoDesignText) { + t.Fatal("no notice for a theme without a design") + } + if textCacheHasLabel(a.ctx, themeFitPreviewHint) { + t.Error("the drag-to-pan hint is drawn over the no-design notice") + } + + a.themeRects[ao2CanvasKey] = a.themeRectsOrig[ao2CanvasKey] + a.ctx.purgeTextCache() + a.drawThemeFitPreview(box) + if !textCacheHasLabel(a.ctx, themeFitPreviewHint) { + t.Error("the drag-to-pan hint is missing for a theme with a design") + } +} From 633742bfd33ddb8159b69f75c55264dc0670b555 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:00:11 +0100 Subject: [PATCH 06/43] ui, render: effect dropdown icons keep their shape (#77) The effects dropdown copied each icon into its whole row cell, so square art came out stretched to the cell's 23x28. AO2's QIcon keeps the aspect ratio. The icon is now fitted inside the cell and centred, through the preview window's fit helper, which takes a box and is exported for it. Fixes #77 Co-Authored-By: Claude Opus 5.5 --- internal/render/previewwindow.go | 22 +++++++++++----------- internal/render/previewwindow_test.go | 26 ++++++++++++++++++-------- internal/ui/effectspicker.go | 6 ++++-- 3 files changed, 33 insertions(+), 21 deletions(-) diff --git a/internal/render/previewwindow.go b/internal/render/previewwindow.go index 175f6cac..f95c947b 100644 --- a/internal/render/previewwindow.go +++ b/internal/render/previewwindow.go @@ -303,27 +303,27 @@ func (p *PreviewWindow) Present() { _ = p.ren.Clear() if p.tex != nil { winW, winH := p.win.GetSize() - dst := previewFitRect(winW, winH, p.texW, p.texH) + dst := FitRect(sdl.Rect{W: winW, H: winH}, p.texW, p.texH) _ = p.ren.Copy(p.tex, nil, &dst) } _ = p.ren.Present() // the preview has its own renderer; a failed present only drops a preview frame } -// previewFitRect fits src in win on both axes, centred, as the window can be narrower than the art. -func previewFitRect(winW, winH, srcW, srcH int32) sdl.Rect { - if winW <= 0 || winH <= 0 || srcW <= 0 || srcH <= 0 { - return sdl.Rect{W: winW, H: winH} +// FitRect fits src in box on both axes, centred, keeping its aspect; a source with no size fills the box. +func FitRect(box sdl.Rect, srcW, srcH int32) sdl.Rect { + if box.W <= 0 || box.H <= 0 || srcW <= 0 || srcH <= 0 { + return box } // Cross-multiply to compare the ratios using only integer math. var w, h int32 - if int64(winW)*int64(srcH) <= int64(winH)*int64(srcW) { - w = winW - h = int32((int64(srcH)*int64(winW) + int64(srcW)/2) / int64(srcW)) // rounded, not truncated + if int64(box.W)*int64(srcH) <= int64(box.H)*int64(srcW) { + w = box.W + h = int32((int64(srcH)*int64(box.W) + int64(srcW)/2) / int64(srcW)) // rounded, not truncated } else { - h = winH - w = int32((int64(srcW)*int64(winH) + int64(srcH)/2) / int64(srcH)) + h = box.H + w = int32((int64(srcW)*int64(box.H) + int64(srcH)/2) / int64(srcH)) } - return sdl.Rect{X: (winW - w) / 2, Y: (winH - h) / 2, W: w, H: h} + return sdl.Rect{X: box.X + (box.W-w)/2, Y: box.Y + (box.H-h)/2, W: w, H: h} } // HandleEvent handles this window's events; the caller routes by window id, so no id check is needed. diff --git a/internal/render/previewwindow_test.go b/internal/render/previewwindow_test.go index 71db7152..02bce32b 100644 --- a/internal/render/previewwindow_test.go +++ b/internal/render/previewwindow_test.go @@ -571,9 +571,9 @@ func TestClampPositionToDisplaysRecentresAnUnreachablePosition(t *testing.T) { } } -// --- previewFitRect (aspect-preserving, non-stretch Present) ----------------- +// --- FitRect (aspect-preserving, non-stretch Present) ----------------- -func TestPreviewFitRectPreservesAspectAndCentres(t *testing.T) { +func TestFitRectPreservesAspectAndCentres(t *testing.T) { cases := []struct { name string winW, winH, srcW, srcH int32 @@ -586,9 +586,9 @@ func TestPreviewFitRectPreservesAspectAndCentres(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - got := previewFitRect(c.winW, c.winH, c.srcW, c.srcH) + got := FitRect(sdl.Rect{W: c.winW, H: c.winH}, c.srcW, c.srcH) if got.W != c.wantW || got.H != c.wantH { - t.Fatalf("previewFitRect(%d,%d,%d,%d) size = %dx%d, want %dx%d", + t.Fatalf("FitRect(%d,%d,%d,%d) size = %dx%d, want %dx%d", c.winW, c.winH, c.srcW, c.srcH, got.W, got.H, c.wantW, c.wantH) } // Centred on both axes. @@ -602,18 +602,28 @@ func TestPreviewFitRectPreservesAspectAndCentres(t *testing.T) { } } -// TestPreviewFitRectDegenerateInputsFillTheWindow pins the fallback: a +// TestFitRectDegenerateInputsFillTheWindow pins the fallback: a // source with no usable size must not divide by zero or return a // zero-area rect nobody can see — it fills the window instead. -func TestPreviewFitRectDegenerateInputsFillTheWindow(t *testing.T) { +func TestFitRectDegenerateInputsFillTheWindow(t *testing.T) { for _, c := range []struct{ srcW, srcH int32 }{{0, 100}, {100, 0}, {-5, 100}} { - got := previewFitRect(320, 240, c.srcW, c.srcH) + got := FitRect(sdl.Rect{W: 320, H: 240}, c.srcW, c.srcH) if got.W != 320 || got.H != 240 { - t.Errorf("previewFitRect(320,240,%d,%d) = %+v, want the whole 320x240 window", c.srcW, c.srcH, got) + t.Errorf("FitRect(320,240,%d,%d) = %+v, want the whole 320x240 window", c.srcW, c.srcH, got) } } } +// TestFitRectKeepsTheBoxOffset: a square icon in the effects dropdown's 23x28 cell keeps its shape, inside the cell (#77). +func TestFitRectKeepsTheBoxOffset(t *testing.T) { + const cellX, cellY, cellW, cellH, iconSide = 40, 60, 23, 28, 64 + got := FitRect(sdl.Rect{X: cellX, Y: cellY, W: cellW, H: cellH}, iconSide, iconSide) + want := sdl.Rect{X: cellX, Y: cellY + (cellH-cellW)/2, W: cellW, H: cellW} + if got != want { + t.Errorf("FitRect = %+v, want %+v", got, want) + } +} + func TestPreviewWindowOpenFailureStaysClosed(t *testing.T) { want := errors.New("no window") pw := NewPreviewWindow(func(string, int32, int32) (*sdl.Window, *sdl.Renderer, error) { return nil, nil, want }) diff --git a/internal/ui/effectspicker.go b/internal/ui/effectspicker.go index 30dedca3..d8fa6492 100644 --- a/internal/ui/effectspicker.go +++ b/internal/ui/effectspicker.go @@ -13,6 +13,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" "github.com/SyntaxNyah/AsyncAO/internal/theme" ) @@ -522,8 +523,9 @@ func (a *App) overlayIconDraw(i int, tr sdl.Rect) { a.overlayDemandTheme(path, base) } if page, ok := a.cachedPage(&a.overlayIconPages, &a.overlayIconGen, n, i, base); ok && len(page.Frames) > 0 { - // Through the shared cgo scratch, never &tr: a parameter's address heap-escapes on every cgo call. - c.cgoRect = tr + // Kept to its aspect like AO2's QIcon. Through the shared cgo scratch, never &tr: a parameter's address + // heap-escapes on every cgo call. + c.cgoRect = render.FitRect(tr, page.W, page.H) c.copy(page.Frames[0], nil, &c.cgoRect) } else { c.Fill(tr, overlayIconChipColor) From 96ec55bb72d559b9ffc78a1dad6aebdb4322ad27 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:03:43 +0100 Subject: [PATCH 07/43] ui, render: the sprite preview uses the character's scaling (#88) The preview drew a sprite with whatever filter its texture had: the default until the sprite had been on stage, where the courtroom sets the char.ini filter. A pixel-art character previewed smooth until it was sent. The preview now applies the courtroom's rule for the previewed character (user setting, then char.ini scaling, then point-sampled when enlarged), so emote and portrait previews match the stage from the first frame. Effect and background previews keep the filter they have. Fixes #88 Co-Authored-By: Claude Opus 5.5 --- internal/render/prescale.go | 2 +- internal/render/scalemode.go | 10 +++---- internal/render/scenery.go | 2 +- internal/render/spritescale_test.go | 20 +++++-------- internal/render/streaming_test.go | 2 +- internal/render/textures.go | 2 +- internal/render/viewport.go | 6 ++-- internal/ui/app.go | 2 ++ internal/ui/app_room.go | 1 + internal/ui/previewscaling_test.go | 45 +++++++++++++++++++++++++++++ internal/ui/screensemote.go | 2 ++ internal/ui/screenslobby.go | 33 +++++++++++++++++++++ 12 files changed, 103 insertions(+), 24 deletions(-) create mode 100644 internal/ui/previewscaling_test.go diff --git a/internal/render/prescale.go b/internal/render/prescale.go index 4d87283d..2de7b7ce 100644 --- a/internal/render/prescale.go +++ b/internal/render/prescale.go @@ -115,7 +115,7 @@ func scaledPixels(n int32, s float32) int32 { // drawScaled copies frame of page to dst through sf, a pre-scaled copy, and reports whether it drew; false leaves the // draw to the caller (not SDL's software renderer, or too big to keep). src carries the colour mod to bake in, and -// page's applyScaleMode must have run, as its remembered filter is the one baked in. alpha fades the copy. +// page's ApplyScaleMode must have run, as its remembered filter is the one baked in. alpha fades the copy. func (v *Viewport) drawScaled(ren *sdl.Renderer, sf *scaledFrame, page *TexturePage, frame int, src *sdl.Texture, dst sdl.Rect, flip sdl.RendererFlip, modR, modG, modB, alpha uint8) bool { if !v.prescale { diff --git a/internal/render/scalemode.go b/internal/render/scalemode.go index 39afc552..247730de 100644 --- a/internal/render/scalemode.go +++ b/internal/render/scalemode.go @@ -12,9 +12,9 @@ func setTextureScaleMode(tex *sdl.Texture, mode sdl.ScaleMode) bool { return tex != nil && tex.SetScaleMode(mode) == nil } -// spriteScaleMode applies AO2's rule (animationlayer.cpp:229-273): smooth, but point-sampled when enlarged. -func (v *Viewport) spriteScaleMode(layer *courtroom.SpriteLayer, nativeH, targetH int32) sdl.ScaleMode { - switch courtroom.ResolveScalingMode(v.fx.UserScaling, layer.Scaling) { +// SpriteScaleMode applies AO2's rule (animationlayer.cpp:229-273): smooth, but point-sampled when enlarged. +func SpriteScaleMode(user, char courtroom.ScalingMode, nativeH, targetH int32) sdl.ScaleMode { + switch courtroom.ResolveScalingMode(user, char) { case courtroom.ScalingPixel: return sdl.ScaleModeNearest case courtroom.ScalingSmooth: @@ -26,8 +26,8 @@ func (v *Viewport) spriteScaleMode(layer *courtroom.SpriteLayer, nativeH, target return sdl.ScaleModeLinear } -// applyScaleMode sets every frame's filter, memoised so the steady state does no cgo; render thread only. -func (p *TexturePage) applyScaleMode(ren *sdl.Renderer, mode sdl.ScaleMode) { +// ApplyScaleMode sets every frame's filter, memoised so the steady state does no cgo; render thread only. +func (p *TexturePage) ApplyScaleMode(ren *sdl.Renderer, mode sdl.ScaleMode) { if p == nil || ren == nil { return } diff --git a/internal/render/scenery.go b/internal/render/scenery.go index 35472ad1..26a3ece4 100644 --- a/internal/render/scenery.go +++ b/internal/render/scenery.go @@ -46,7 +46,7 @@ func (v *Viewport) drawScenery(ren *sdl.Renderer, scene *courtroom.Scene, base s return } v.fillRect = sceneryRect(vp, page.W, page.H, scene.SceneryStretch, v.panorama, v.origin) - page.applyScaleMode(ren, sceneryScaleMode(v.fx.UserScaling, scene.SceneryScaling, scene.SceneryStretch, page.H, v.fillRect.H)) + page.ApplyScaleMode(ren, sceneryScaleMode(v.fx.UserScaling, scene.SceneryScaling, scene.SceneryStretch, page.H, v.fillRect.H)) tex := page.Frames[frame] d := uint8(channelMax) if dimPct < percentMax { diff --git a/internal/render/spritescale_test.go b/internal/render/spritescale_test.go index 149444af..239e4d40 100644 --- a/internal/render/spritescale_test.go +++ b/internal/render/spritescale_test.go @@ -8,7 +8,7 @@ import ( ) // TestSpriteNativeHLatchesToTheIdle pins that one character keeps ONE native -// height while its bases swap under it. spriteScaleMode decides the filter from +// height while its bases swap under it. SpriteScaleMode decides the filter from // this height, and re-reading it from whichever page was drawing let a // talk/preanim page that decoded at a different size flip the filter // mid-animation — the reported "swaps to smooth scaling for animations". @@ -89,9 +89,7 @@ func TestSpriteScaleModeFollowsAO2(t *testing.T) { {"unknown native height", courtroom.ScalingAuto, courtroom.ScalingAuto, 0, sdl.ScaleModeLinear}, } { t.Run(tc.name, func(t *testing.T) { - v := &Viewport{fx: SpriteFX{UserScaling: tc.user}} - layer := &courtroom.SpriteLayer{Scaling: tc.char} - if got := v.spriteScaleMode(layer, tc.nativeH, stageH); got != tc.want { + if got := SpriteScaleMode(tc.user, tc.char, tc.nativeH, stageH); got != tc.want { t.Errorf("got %d, want %d", got, tc.want) } }) @@ -101,7 +99,7 @@ func TestSpriteScaleModeFollowsAO2(t *testing.T) { // TestApplyScaleModeIsMemoised guards the cost, not the correctness. The apply // runs on the render loop for every sprite of every frame, and each real change // forces a renderer flush (mandatory under HINT_RENDER_BATCHING — see -// applyScaleMode). Without the memo a stable stage would flush twice per frame +// ApplyScaleMode). Without the memo a stable stage would flush twice per frame // forever, quietly undoing the batching the client turns on at startup. func TestApplyScaleModeIsMemoised(t *testing.T) { ren, cleanup := newHeadlessRenderer(t) @@ -122,7 +120,7 @@ func TestApplyScaleModeIsMemoised(t *testing.T) { if page.scaleModeSet { t.Error("a fresh page must start unlatched — otherwise the first apply is skipped") } - page.applyScaleMode(ren, sdl.ScaleModeNearest) + page.ApplyScaleMode(ren, sdl.ScaleModeNearest) if !page.scaleModeSet || page.scaleMode != sdl.ScaleModeNearest { t.Fatalf("first apply did not latch: set=%v mode=%d", page.scaleModeSet, page.scaleMode) } @@ -142,14 +140,14 @@ func TestApplyScaleModeIsMemoised(t *testing.T) { // memo's back, then ask for the memoised mode. If the memo works nothing runs // and the sabotage survives; if it were removed the loop would overwrite it. setTextureScaleMode(page.Frames[0], sdl.ScaleModeLinear) - page.applyScaleMode(ren, sdl.ScaleModeNearest) + page.ApplyScaleMode(ren, sdl.ScaleModeNearest) if got, _ := textureScaleMode(page.Frames[0]); got != sdl.ScaleModeLinear { t.Error("re-applying the memoised mode did real work (cgo + a mandatory renderer flush) " + "— that runs per sprite per frame and defeats HINT_RENDER_BATCHING") } // A genuine change still takes. - page.applyScaleMode(ren, sdl.ScaleModeLinear) + page.ApplyScaleMode(ren, sdl.ScaleModeLinear) if page.scaleMode != sdl.ScaleModeLinear { t.Errorf("a changed mode must re-apply, got %d", page.scaleMode) } @@ -163,11 +161,9 @@ func TestApplyScaleModeIsMemoised(t *testing.T) { // TestSpriteScaleModeZeroAlloc keeps the resolver honest against the // zero-allocation render loop (CLAUDE.md hard rule). It runs per sprite per frame. func TestSpriteScaleModeZeroAlloc(t *testing.T) { - v := &Viewport{} - layer := &courtroom.SpriteLayer{Scaling: courtroom.ScalingAuto} if n := testing.AllocsPerRun(200, func() { - _ = v.spriteScaleMode(layer, 256, 1080) + _ = SpriteScaleMode(courtroom.ScalingAuto, courtroom.ScalingAuto, 256, 1080) }); n != 0 { - t.Errorf("spriteScaleMode allocates %v/op, want 0", n) + t.Errorf("SpriteScaleMode allocates %v/op, want 0", n) } } diff --git a/internal/render/streaming_test.go b/internal/render/streaming_test.go index 70856fa1..95a6c457 100644 --- a/internal/render/streaming_test.go +++ b/internal/render/streaming_test.go @@ -99,7 +99,7 @@ func TestAppendStreamKeepsLatchedScaleMode(t *testing.T) { t.Fatal("establish: page must be resident") } // A draw latches the filter exactly the way viewport.go does. - page.applyScaleMode(ren, sdl.ScaleModeNearest) + page.ApplyScaleMode(ren, sdl.ScaleModeNearest) if err := store.AppendStream(base, streamChunk(1, true, 3)); err != nil { t.Fatalf("append: %v", err) diff --git a/internal/render/textures.go b/internal/render/textures.go index 8e4597a4..f8ecb986 100644 --- a/internal/render/textures.go +++ b/internal/render/textures.go @@ -713,7 +713,7 @@ func (s *TextureStore) AppendStream(base string, d *assets.Decoded) error { if err != nil { return err } - // applyScaleMode skips a page already set, so appended frames must inherit its filter or stay bilinear. + // ApplyScaleMode skips a page already set, so appended frames must inherit its filter or stay bilinear. // No Flush is needed: new textures have no queued copies. if page.scaleModeSet { for _, t := range frames { diff --git a/internal/render/viewport.go b/internal/render/viewport.go index be4ffe1c..3575dc50 100644 --- a/internal/render/viewport.go +++ b/internal/render/viewport.go @@ -986,7 +986,7 @@ func (v *Viewport) drawOverlay(ren *sdl.Renderer, scene *courtroom.Scene, vp sdl } tex := page.Frames[clampFrame(v.overlayAnim.frame, len(page.Frames))] dst := overlayDstRect(o, vp, page.W, page.H) - page.applyScaleMode(ren, v.overlayScaleMode(o, page.H, dst.H)) + page.ApplyScaleMode(ren, v.overlayScaleMode(o, page.H, dst.H)) v.ovRect = dst if o.Flip { _ = v.copies.CopyFlip(ren, tex, nil, &v.ovRect, sdl.FLIP_HORIZONTAL) @@ -1148,7 +1148,7 @@ func (v *Viewport) drawBackgroundDoF(ren *sdl.Renderer, scene *courtroom.Scene, } tex := page.Frames[frame] dst := sceneryRect(vp, page.W, page.H, scene.SceneryStretch, v.panorama, v.origin) - page.applyScaleMode(ren, sceneryScaleMode(v.fx.UserScaling, scene.SceneryScaling, scene.SceneryStretch, page.H, dst.H)) + page.ApplyScaleMode(ren, sceneryScaleMode(v.fx.UserScaling, scene.SceneryScaling, scene.SceneryStretch, page.H, dst.H)) r := vp.H / dofBlurDivisor if r < dofBlurMin { r = dofBlurMin @@ -1306,7 +1306,7 @@ func (v *Viewport) drawSprite(ren *sdl.Renderer, layer *courtroom.SpriteLayer, a } // AO2 filters per sprite, from frame height against the widget height (calculateFrameGeometry, courtroom.cpp:778). // Must be vp.H, not v.dstRect.H: dstRect grows with a transmitted scale or zoom, changing the filter. - drawPage.applyScaleMode(ren, v.spriteScaleMode(layer, anim.spriteNativeH(layer, page), vp.H)) + drawPage.ApplyScaleMode(ren, SpriteScaleMode(v.fx.UserScaling, layer.Scaling, anim.spriteNativeH(layer, page), vp.H)) // A transmitted style takes precedence over the viewer's local wash for this layer. var ( diff --git a/internal/ui/app.go b/internal/ui/app.go index 19d40751..d07f102d 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -260,6 +260,8 @@ type App struct { // previewBase, so every other previewBase setter invalidates the caption automatically. previewName string previewNameFor string + // previewScaling is the char.ini filter of the character the preview shows, so it draws as the courtroom would. + previewScaling previewScaling previewFor string // base the preview clock was started for previewAt time.Time // loop anchor — animated previews play, not freeze previewZoom int // magnifier factor (1 = fit; >1 shows a cursor-panned window) diff --git a/internal/ui/app_room.go b/internal/ui/app_room.go index 5867d36b..04051ff5 100644 --- a/internal/ui/app_room.go +++ b/internal/ui/app_room.go @@ -1494,6 +1494,7 @@ func (a *App) previewPortraitAnim(name string) string { func (a *App) setCharPortraitPreview(name string) { anim := a.previewPortraitAnim(name) a.previewBase = a.urls.Emote(name, anim, courtroom.EmoteIdle) + a.notePreviewChar(name) a.d.Manager.PrefetchChain(a.previewBase, a.urls.EmoteAlts(name, anim, courtroom.EmoteIdle), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (preview) } diff --git a/internal/ui/previewscaling_test.go b/internal/ui/previewscaling_test.go new file mode 100644 index 00000000..48b3451a --- /dev/null +++ b/internal/ui/previewscaling_test.go @@ -0,0 +1,45 @@ +package ui + +import ( + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/courtroom" + "github.com/SyntaxNyah/AsyncAO/internal/sdl" +) + +// TestSpritePreviewUsesTheCharactersScaling: the preview draws a character's sprite with its char.ini filter before +// the sprite has ever been on stage (#88). +func TestSpritePreviewUsesTheCharactersScaling(t *testing.T) { + const winW, winH = 800, 600 + for _, tc := range []struct { + name string + scaling courtroom.ScalingMode + before sdl.ScaleMode + want sdl.ScaleMode + }{ + {"pixel", courtroom.ScalingPixel, sdl.ScaleModeLinear, sdl.ScaleModeNearest}, + {"smooth", courtroom.ScalingSmooth, sdl.ScaleModeNearest, sdl.ScaleModeLinear}, + } { + t.Run(tc.name, func(t *testing.T) { + a := newPreviewFeedApp(t) + a.urls = courtroom.NewURLBuilder("http://test.example/base/") + a.charMetaCache = map[string]charMeta{a.charINIURL(tc.name): {done: true, scaling: tc.scaling}} + page, ok := a.d.Store.Get(previewFeedFixtureBase) + if !ok { + t.Fatal("fixture page missing") + } + page.ApplyScaleMode(a.ctx.Ren, tc.before) + + a.notePreviewChar(tc.name) + a.drawSpritePreview(winW, winH, "") + + got, err := page.Frames[0].GetScaleMode() + if err != nil { + t.Skipf("scale mode unreadable: %v", err) + } + if got != tc.want { + t.Errorf("preview filter = %d, want %d", got, tc.want) + } + }) + } +} diff --git a/internal/ui/screensemote.go b/internal/ui/screensemote.go index aa41b1f6..1fbe2649 100644 --- a/internal/ui/screensemote.go +++ b/internal/ui/screensemote.go @@ -29,11 +29,13 @@ func (a *App) previewEmote(char string, e *courtroom.Emote) { if e.Preanim != "" && e.Preanim != "-" { // "-" / "" = no preanim (AO convention) a.previewBase = a.urls.Emote(char, e.Preanim, courtroom.EmotePreanim) a.previewName, a.previewNameFor = name, a.previewBase + a.notePreviewChar(char) a.d.Manager.Prefetch(a.previewBase, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (preanim preview) return } a.previewBase = a.urls.Emote(char, e.Anim, courtroom.EmoteTalk) a.previewName, a.previewNameFor = name, a.previewBase + a.notePreviewChar(char) a.d.Manager.PrefetchChain(a.previewBase, a.urls.EmoteAlts(char, e.Anim, courtroom.EmoteTalk), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (preview) } diff --git a/internal/ui/screenslobby.go b/internal/ui/screenslobby.go index 74ebba65..e27e57b3 100644 --- a/internal/ui/screenslobby.go +++ b/internal/ui/screenslobby.go @@ -12,6 +12,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/helper/value" "github.com/SyntaxNyah/AsyncAO/internal/network" "github.com/SyntaxNyah/AsyncAO/internal/protocol" + "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" ) @@ -931,6 +932,7 @@ func (a *App) drawSpritePreview(w, h int32, name string) { if zh < 1 { zh = 1 } + a.applyPreviewScaleMode(page, zh, dst.H) relX := float64(c.mouseX-dst.X) / float64(dst.W) relY := float64(c.mouseY-dst.Y) / float64(dst.H) relX = value.Clamp(relX, 0, 1) @@ -938,6 +940,7 @@ func (a *App) drawSpritePreview(w, h int32, name string) { src := sdl.Rect{X: value.Clamp(int32(relX*float64(page.W))-zw/2, 0, page.W-zw), Y: value.Clamp(int32(relY*float64(page.H))-zh/2, 0, page.H-zh), W: zw, H: zh} c.copy(tex, &src, &dst) } else { + a.applyPreviewScaleMode(page, page.H, dst.H) c.copy(tex, nil, &dst) } a.drawPreviewZoom(frame, page.W, page.H, dst.H) @@ -980,6 +983,36 @@ func (a *App) drawSpritePreview(w, h int32, name string) { c.Tooltip(closeB, "Close the preview") } +// previewScaling is the char.ini filter of the character behind one preview base; settled once its char.ini answered. +type previewScaling struct { + base, char string + mode courtroom.ScalingMode + settled bool +} + +// notePreviewChar records whose sprite the preview now shows; idempotent, as the portrait preview is set every frame. +func (a *App) notePreviewChar(char string) { + if a.previewScaling.base == a.previewBase && a.previewScaling.char == char { + return + } + a.previewScaling = previewScaling{base: a.previewBase, char: char} +} + +// applyPreviewScaleMode gives a character preview the courtroom's filter, which the page otherwise only gets once the +// sprite is on stage (#88). Other previews keep the filter they have. +func (a *App) applyPreviewScaleMode(page *render.TexturePage, nativeH, targetH int32) { + ps := &a.previewScaling + if ps.base != a.previewBase { + return + } + if !ps.settled { + m := a.charMetaFor(ps.char) + ps.mode, ps.settled = m.scaling, m.done + } + user := courtroom.ScalingMode(a.d.Prefs.SpriteScalingMode()) + page.ApplyScaleMode(a.ctx.Ren, render.SpriteScaleMode(user, ps.mode, nativeH, targetH)) +} + // previewGripRect is the resize grip's hit rect, shared by the draw and the input handler. func previewGripRect(frame sdl.Rect) sdl.Rect { return sdl.Rect{X: frame.X + frame.W - 16, Y: frame.Y + frame.H - previewCaptionH - 16, W: 16, H: 16} From dfd2e8bd6abd51f55aa90838910b925d9117e8e2 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:05:04 +0100 Subject: [PATCH 08/43] ui: the SFX Browser opens in front of the Extras box (#32) The SFX Browser takes the screen like the Wardrobe, Jukebox and Background picker, but it was missing from the popups that hide the Extras box, so the box opened over the browser it had just launched. It is now in that set: the box hides while the browser is open and returns when it closes, as with the other three. Fixes #32 Co-Authored-By: Claude Opus 5.5 --- internal/ui/floatbox.go | 6 +++--- internal/ui/overlayfence_test.go | 7 ++----- internal/ui/screens.go | 3 +-- internal/ui/sfxbrowserfront_test.go | 25 +++++++++++++++++++++++++ 4 files changed, 31 insertions(+), 10 deletions(-) create mode 100644 internal/ui/sfxbrowserfront_test.go diff --git a/internal/ui/floatbox.go b/internal/ui/floatbox.go index c37caa83..71f615cb 100644 --- a/internal/ui/floatbox.go +++ b/internal/ui/floatbox.go @@ -179,9 +179,9 @@ func (a *App) extrasPalette() extrasPalette { func (a *App) blockingCourtPopup() bool { // Floating panels (pair, mod, CM, evidence, ban box, timer, login, pair popup, pinned pieces) stay out: they fence // by footprint, and adding one would make extrasSurfaceLive false and disable its own fence. - // Not courtroomModalUp's set: this adds classicEdit and omits showSfxBrowser, which would hide the panels too. - // Ask courtroomModalUp whether drawCourtroomModals will take the screen. - return a.ward.show || a.showJukebox || a.bgPick.show || + // Not courtroomModalUp's set: this adds classicEdit. Ask courtroomModalUp whether drawCourtroomModals will take the + // screen. + return a.ward.show || a.showJukebox || a.bgPick.show || a.showSfxBrowser || a.classicEdit } diff --git a/internal/ui/overlayfence_test.go b/internal/ui/overlayfence_test.go index acbd682f..a5b2b204 100644 --- a/internal/ui/overlayfence_test.go +++ b/internal/ui/overlayfence_test.go @@ -435,15 +435,12 @@ func TestCourtroomModalUpMatchesDraw(t *testing.T) { } } // blockingCourtPopup is a DIFFERENT question and must not be mistaken for this - // one: it omits the SFX browser and adds classicEdit. Pinned so a future "just - // reuse it" refactor has to confront that. + // one: it adds classicEdit. Pinned so a future "just reuse it" refactor has to + // confront that. a.showSfxBrowser = true if !a.courtroomModalUp() { t.Error("the SFX browser IS in the return-to-top modal set (drawCourtroomModals draws it)") } - if a.blockingCourtPopup() { - t.Error("blockingCourtPopup deliberately does NOT list the SFX browser — do not reuse it as the modal predicate") - } a.showSfxBrowser = false a.classicEdit = true if a.courtroomModalUp() { diff --git a/internal/ui/screens.go b/internal/ui/screens.go index a4e3ebc7..8a19dfb9 100644 --- a/internal/ui/screens.go +++ b/internal/ui/screens.go @@ -473,8 +473,7 @@ func (a *App) modalReturnSkippedWhileEditing() bool { return a.layoutEditorArmed // courtroomModalUp reports whether drawCourtroomModals will take the screen, for decisions made before the pass reaches // it. -// Not blockingCourtPopup (floatbox.go): that set omits showSfxBrowser and adds classicEdit, so it would answer wrongly -// here. +// Not blockingCourtPopup (floatbox.go): that set adds classicEdit, so it would answer wrongly here. func (a *App) courtroomModalUp() bool { for i := range courtroomModals { if courtroomModals[i].open(a) { diff --git a/internal/ui/sfxbrowserfront_test.go b/internal/ui/sfxbrowserfront_test.go new file mode 100644 index 00000000..31afda59 --- /dev/null +++ b/internal/ui/sfxbrowserfront_test.go @@ -0,0 +1,25 @@ +package ui + +import ( + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/courtroom" +) + +// TestSfxBrowserHidesTheExtrasBox: opened from the Extras box, the SFX Browser shows in front, as the Wardrobe and +// Jukebox do; the box comes back when it closes (#32). +func TestSfxBrowserHidesTheExtrasBox(t *testing.T) { + a := testTabApp(t) + a.sess = courtroom.NewRehearsalSession("", nil) + a.room = &courtroom.Courtroom{} + a.showWidgets = true + + a.toggleSfxBrowser() + if a.extrasSurfaceLive() { + t.Error("the Extras box still draws over the open SFX Browser") + } + a.toggleSfxBrowser() + if !a.extrasSurfaceLive() { + t.Error("the Extras box did not come back after the SFX Browser closed") + } +} From ca655a6d979949733b283e741e96cbea878e6f11 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:08:01 +0100 Subject: [PATCH 09/43] =?UTF-8?q?ui:=20each=20list's=20=E2=8B=AE=20menu=20?= =?UTF-8?q?shows=20only=20its=20own=20options=20(#85)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Music view, the Areas view and the player list open one shared menu, and the music and roster blocks showed in all three: the player list offered fade-in and loop, the music list offered roster refresh and follow. The menu now remembers which view opened it and shows only that view's block, and a divider no longer opens the menu. Fixes #85 Co-Authored-By: Claude Opus 5.5 --- internal/ui/apptypes.go | 1 + internal/ui/areamenu.go | 2 +- internal/ui/areamenu_test.go | 130 +++++++++++++++----------------- internal/ui/musicheader.go | 57 ++++++++++---- internal/ui/musicheader_test.go | 4 +- internal/ui/playerlist.go | 4 +- internal/ui/screensmusic.go | 4 +- 7 files changed, 112 insertions(+), 90 deletions(-) diff --git a/internal/ui/apptypes.go b/internal/ui/apptypes.go index 9c5d29aa..500ea591 100644 --- a/internal/ui/apptypes.go +++ b/internal/ui/apptypes.go @@ -702,6 +702,7 @@ type sessionState struct { musicMenuAt sdl.Point // preferred top-left (clamped at draw) musicMenuTab int // tab the menu opened on — auto-close on switch musicMenuThemed bool // the panel drew inside a theme canvas when it opened (gates the volume-view row) + musicMenuFrom musicMenuSource liveDetailsArea string // area of the last auto /getarea pull; re-pull on area change suppressAreaEchoUntil time.Time // keep /gas/getarea reply lines out of OOC until this time — the WHOLE reply burst (a multi-area /gas spans several messages), not just the first // Follow-a-player: followUID is the player we trail across areas ("" = off); we auto-jump to their area on each diff --git a/internal/ui/areamenu.go b/internal/ui/areamenu.go index b6210b6c..63891dd7 100644 --- a/internal/ui/areamenu.go +++ b/internal/ui/areamenu.go @@ -162,6 +162,6 @@ func splitAreaHeaderRow(row sdl.Rect) areaHeaderLayout { // click-away closes it on the frame it opened (musicheader.go). func (a *App) drawAreaMenuButton(btn sdl.Rect, themed bool) { if a.musicIconButton(btn, iconKebab, "Area options — background, refresh the list, per-area chat log, CM controls") { - a.openMusicMenuFromButton(sdl.Point{X: btn.X, Y: btn.Y + btn.H}, themed) + a.openMusicMenuFromButton(sdl.Point{X: btn.X, Y: btn.Y + btn.H}, themed, musicMenuFromAreas) } } diff --git a/internal/ui/areamenu_test.go b/internal/ui/areamenu_test.go index c14cd9f5..cf4e8411 100644 --- a/internal/ui/areamenu_test.go +++ b/internal/ui/areamenu_test.go @@ -125,82 +125,72 @@ func TestAreaMenuButtonTakesRoomFromItsOwnRow(t *testing.T) { } } -// TestMusicViewMenuCarriesNoAreaRow is the gate the shared pane demands back in -// exchange for hosting the block. Three triggers open ONE popup — the Music -// header's ⋮, the roster toolbar's ⋮ and now the Areas view's — so a block that -// forgets to gate itself is not a dead row, it is five rows appearing in a menu -// about a list the user is not looking at. That is exactly how the first cut of -// this kit shipped. -// -// It drives musicMenuRowDrawn (the pane's own row filter) rather than re-deciding -// liveness, and asserts BOTH directions: nothing of the block on the Music view, -// all of it — divider included — on the Areas view. The divider matters on its own, -// because it carries the shared musicMenuSeparator kind and so is invisible to -// every per-kind predicate: gate the four rows and forget the fifth and the music -// menu ends in a rule under its last row with nothing beneath it. -func TestMusicViewMenuCarriesNoAreaRow(t *testing.T) { +// TestEachListMenuHoldsOnlyItsOwnRows: the Music, Areas and player-list views open one shared popup, and each sees only +// its own block (#85), with no divider at either end. +func TestEachListMenuHoldsOnlyItsOwnRows(t *testing.T) { const themed = false // the classic panel; the volume row's answer is not what's under test - drawn := func(a *App) (areaRows int, height int32) { - for i, row := range musicMenuRows { - if !a.musicMenuRowDrawn(i, themed) { - continue + blockOf := func(k musicMenuKind) musicMenuSource { + switch { + case isAreaMenuKind(k): + return musicMenuFromAreas + case isRosterMenuKind(k): + return musicMenuFromRoster + } + return musicMenuFromMusic + } + for _, tc := range []struct { + name string + tab int + from musicMenuSource + torn bool + }{ + {"music", logTabMusic, musicMenuFromMusic, false}, + {"areas", logTabAreas, musicMenuFromAreas, false}, + {"roster", logTabPlayers, musicMenuFromRoster, false}, + // A torn Areas panel draws whatever logTab says and carries its own ⋮ (torntabs.go). + {"torn areas", logTabMusic, musicMenuFromAreas, true}, + } { + t.Run(tc.name, func(t *testing.T) { + a := &App{} + a.logTab = tc.tab + if tc.torn { + a.classicOv = map[string][4]float64{tornKeyFor(logTabAreas): {}} } - if isAreaMenuKind(row.kind) { - areaRows++ + a.musicMenuFrom = tc.from + first, last := -1, -1 + for i, row := range musicMenuRows { + drawn := a.musicMenuRowDrawn(i, themed) + if drawn { + if first < 0 { + first = i + } + last = i + } + if row.kind == musicMenuSeparator { + continue + } + if own := blockOf(row.kind) == tc.from; drawn != own { + t.Errorf("%q drawn = %v, want %v", row.label, drawn, own) + } } - } - return areaRows, a.musicMenuHeight(themed) - } - - // logTab lives on the EMBEDDED sessionState (app.go), so it cannot be set by name - // in an App literal — onView builds the whole view state one way for all five - // cases below. - onView := func(tab int) *App { - a := &App{} - a.logTab = tab - return a - } - - music := onView(logTabMusic) - if n, _ := drawn(music); n != 0 { - t.Errorf("the Music view's ⋮ offers %d area row(s) — they act on a list it is not showing", n) - } - if n, _ := drawn(onView(logTabPlayers)); n != 0 { - t.Errorf("the roster toolbar's ⋮ offers %d area row(s)", n) - } - - areas := onView(logTabAreas) - wantRows := 0 - for _, row := range areaMenuRows { - if isAreaMenuKind(row.kind) { - wantRows++ - } - } - gotRows, areasH := drawn(areas) - if gotRows != wantRows { - t.Fatalf("the Areas view's own ⋮ offers %d of its %d rows — the gate is too tight to be useful", gotRows, wantRows) - } - // The block's divider must go dark WITH the block: the height difference is the - // four rows AND one separator, never the rows alone. - _, musicH := drawn(music) - if want := int32(wantRows)*musicMenuItemH + musicMenuSepH; areasH-musicH != want { - t.Errorf("the AREA block costs %d px on the Areas view and 0 on the Music view, want %d px "+ - "(%d rows + its divider) — a divider left behind draws a rule under the last roster row", - areasH-musicH, want, wantRows) + if first < 0 { + t.Fatal("the menu is empty") + } + if musicMenuRows[first].kind == musicMenuSeparator || musicMenuRows[last].kind == musicMenuSeparator { + t.Error("the menu starts or ends with a divider") + } + }) } - // A TORN Areas panel draws whatever logTab says and carries its own ⋮ - // (torntabs.go), so the rows have to be live there too or that button is inert. - torn := onView(logTabMusic) - torn.classicOv = map[string][4]float64{tornKeyFor(logTabAreas): {}} - if n, _ := drawn(torn); n != wantRows { - t.Errorf("a torn-off Areas panel offers %d of its %d rows — its ⋮ opens a menu with nothing in it", n, wantRows) - } - // …and a fully hidden Areas tab draws in none of the three places, torn or not. - hidden := onView(logTabAreas) + // A fully hidden Areas tab draws in none of the three places, torn or not. + hidden := &App{} + hidden.logTab = logTabAreas + hidden.musicMenuFrom = musicMenuFromAreas hidden.hidden = map[string]bool{panelTabAreas: true} - if n, _ := drawn(hidden); n != 0 { - t.Errorf("a hidden Areas tab still offers %d area row(s)", n) + for i := range musicMenuRows { + if hidden.musicMenuRowDrawn(i, themed) { + t.Errorf("a hidden Areas tab still draws %q", musicMenuRows[i].label) + } } } diff --git a/internal/ui/musicheader.go b/internal/ui/musicheader.go index 24492621..3341c80c 100644 --- a/internal/ui/musicheader.go +++ b/internal/ui/musicheader.go @@ -204,20 +204,40 @@ var musicMenuRows = append([]musicMenuRow{ {musicMenuFollow, "Follow players"}, }, areaMenuRows[:]...) -// musicMenuRowLive reports whether a row is offered this frame. The volume view isn't offered in a theme's canvas, -// whose slider rects win. Roster rows are live everywhere; area rows only from the Areas view (areamenu.go). +// musicMenuSource is the list view whose ⋮ or right-click opened the shared menu. +type musicMenuSource uint8 + +const ( + musicMenuFromMusic musicMenuSource = iota + musicMenuFromAreas + musicMenuFromRoster +) + +// isRosterMenuKind reports whether k belongs to the roster block. +func isRosterMenuKind(k musicMenuKind) bool { + return k >= musicMenuRosterRefresh && k <= musicMenuFollow +} + +// musicMenuRowLive reports whether a row is offered this frame: each view's menu holds only its own block (#85). The +// volume view isn't offered in a theme's canvas, whose slider rects win. func (a *App) musicMenuRowLive(k musicMenuKind, themed bool) bool { - if isAreaMenuKind(k) { - return a.areaMenuRowLive(k) // areamenu.go owns the AREA block - } - if k == musicMenuVolumeView { + switch { + case k == musicMenuSeparator: + return true + case isAreaMenuKind(k): + return a.musicMenuFrom == musicMenuFromAreas && a.areaMenuRowLive(k) // areamenu.go owns the AREA block + case isRosterMenuKind(k): + return a.musicMenuFrom == musicMenuFromRoster + case a.musicMenuFrom != musicMenuFromMusic: + return false + case k == musicMenuVolumeView: return !themed } return true } -// musicMenuRowDrawn reports whether row i paints: it is live and, if a separator, some live item follows. A separator -// has no kind of its own, so this takes a block's divider down with the block. +// musicMenuRowDrawn reports whether row i paints: it is live and, if a separator, live items lie on both sides of it. +// A separator has no kind of its own, so this takes a block's divider down with the block. func (a *App) musicMenuRowDrawn(i int, themed bool) bool { row := musicMenuRows[i] if !a.musicMenuRowLive(row.kind, themed) { @@ -226,6 +246,16 @@ func (a *App) musicMenuRowDrawn(i int, themed bool) bool { if row.kind != musicMenuSeparator { return true } + itemAbove := false + for _, prev := range musicMenuRows[:i] { + if prev.kind != musicMenuSeparator && a.musicMenuRowLive(prev.kind, themed) { + itemAbove = true + break + } + } + if !itemAbove { + return false // a divider never opens the menu + } for _, next := range musicMenuRows[i+1:] { if next.kind == musicMenuSeparator { return false // the run to this divider's right is empty; the next one owns it @@ -301,19 +331,20 @@ func (a *App) musicEffectsSupported() bool { return a.sess != nil && a.sess.Features.Has(protocol.FeatureEffects) } -// openMusicMenu opens the menu at `at` (the draw clamps it). The tab is stored so a popup can't survive a tab switch, -// and themed because the menu paints after the panel has returned. -func (a *App) openMusicMenu(at sdl.Point, themed bool) { +// openMusicMenu opens from's menu at `at` (the draw clamps it). The tab is stored so a popup can't survive a tab +// switch, and themed because the menu paints after the panel has returned. +func (a *App) openMusicMenu(at sdl.Point, themed bool, from musicMenuSource) { a.musicMenuAt = at a.musicMenuTab = a.activeTab a.musicMenuThemed = themed + a.musicMenuFrom = from a.musicMenuOpen = true } // openMusicMenuFromButton opens the menu and consumes the press: musicIconButton never clears c.clicked, and the panel // anchors below the button, so drawMusicMenu's click-away would close it the frame it opened. -func (a *App) openMusicMenuFromButton(at sdl.Point, themed bool) { - a.openMusicMenu(at, themed) +func (a *App) openMusicMenuFromButton(at sdl.Point, themed bool, from musicMenuSource) { + a.openMusicMenu(at, themed, from) a.ctx.clicked = false // the opening click is the menu's, not the click-away's } diff --git a/internal/ui/musicheader_test.go b/internal/ui/musicheader_test.go index 59395573..a986e84b 100644 --- a/internal/ui/musicheader_test.go +++ b/internal/ui/musicheader_test.go @@ -215,7 +215,7 @@ func TestMusicKebabSurvivesItsOwnOpeningClick(t *testing.T) { return a } - if a := frame(func(a *App, at sdl.Point) { a.openMusicMenuFromButton(at, false) }); !a.musicMenuOpen { + if a := frame(func(a *App, at sdl.Point) { a.openMusicMenuFromButton(at, false, musicMenuFromMusic) }); !a.musicMenuOpen { t.Error("the ⋮ menu closed on the frame it opened — every row it hosts (volume " + "view, the four MC playback flags, stop, random) is then reachable only by " + "right-clicking the track list") @@ -224,7 +224,7 @@ func TestMusicKebabSurvivesItsOwnOpeningClick(t *testing.T) { // the assertion above is load-bearing rather than vacuously true. If this one // goes red, the click-away rule changed — re-derive whether the consumption is // still what keeps the button alive. - if a := frame(func(a *App, at sdl.Point) { a.openMusicMenu(at, false) }); a.musicMenuOpen { + if a := frame(func(a *App, at sdl.Point) { a.openMusicMenu(at, false, musicMenuFromMusic) }); a.musicMenuOpen { t.Error("an unconsumed opening click no longer closes the menu, so this test can " + "no longer prove openMusicMenuFromButton's consumption is what fixes the ⋮") } diff --git a/internal/ui/playerlist.go b/internal/ui/playerlist.go index b9df163a..25983cb1 100644 --- a/internal/ui/playerlist.go +++ b/internal/ui/playerlist.go @@ -197,8 +197,8 @@ func (a *App) drawPlayerList(r sdl.Rect) { case plItemMenu: // Same helper as the Music header, click consumption included, or click-away closes the menu at once. // themed is derived: inside the theme's music_list, drawMusicList discards the Volume-sliders row. - if a.musicIconButton(it.r, iconKebab, "Roster & playback options — refresh details, legacy snapshot, pair status, follow") { - a.openMusicMenuFromButton(sdl.Point{X: it.r.X, Y: it.r.Y + it.r.H}, a.rosterMenuThemed()) + if a.musicIconButton(it.r, iconKebab, "Roster options — refresh details, legacy snapshot, pair status, follow") { + a.openMusicMenuFromButton(sdl.Point{X: it.r.X, Y: it.r.Y + it.r.H}, a.rosterMenuThemed(), musicMenuFromRoster) } } } diff --git a/internal/ui/screensmusic.go b/internal/ui/screensmusic.go index a89ca3bd..16c7602b 100644 --- a/internal/ui/screensmusic.go +++ b/internal/ui/screensmusic.go @@ -259,7 +259,7 @@ func (a *App) drawMusicList(r sdl.Rect, themed, searchExternal, nowPlayingExtern if br, ok := plan.rect(musicItemMenu); ok { if a.musicIconButton(br, iconKebab, "More: playback options, volume sliders (right-click the list opens this too)") { // FromButton: the press must be consumed or drawMusicMenu's click-away closes the menu the frame it opened. - a.openMusicMenuFromButton(sdl.Point{X: br.X, Y: br.Y + br.H}, themed) + a.openMusicMenuFromButton(sdl.Point{X: br.X, Y: br.Y + br.H}, themed, musicMenuFromMusic) } } // "music_name" is AO2's id for this line (courtroom.cpp:1201). elemLabelFont keeps the chrome face when the theme @@ -370,7 +370,7 @@ func (a *App) drawMusicList(r sdl.Rect, themed, searchExternal, nowPlayingExtern // Right-click opens the same menu as the ⋮ button; AO2's entry point is on_music_list_context_menu_requested // (courtroom.cpp:5821). if c.rightClicked && c.hovering(r) { - a.openMusicMenu(sdl.Point{X: c.mouseX, Y: c.mouseY}, themed) + a.openMusicMenu(sdl.Point{X: c.mouseX, Y: c.mouseY}, themed, musicMenuFromMusic) c.rightClicked = false } } From 08e2c0e53b7c78d83a84e5d15354318502d1efc4 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:52:13 +0000 Subject: [PATCH 10/43] ui: fold repeated blankposts in the IC log AO2 suppresses a blankpost when it repeats the previous blankpost from the same speaker. Match that in both the active and parked-tab IC logs while still delivering every blankpost to the courtroom for its emote change. The folded entry carries the queue weight so ghost text stays paired with the play queue. Refs #64 --- internal/ui/app_connect.go | 37 +++++++++++++++++---------------- internal/ui/app_ic.go | 42 ++++++++++++++++++++++++++++++++++++-- internal/ui/ghosttext.go | 5 ++++- internal/ui/tabs.go | 12 ++++++----- 4 files changed, 70 insertions(+), 26 deletions(-) diff --git a/internal/ui/app_connect.go b/internal/ui/app_connect.go index a52a128c..e9ba75fb 100644 --- a/internal/ui/app_connect.go +++ b/internal/ui/app_connect.go @@ -734,24 +734,25 @@ func (a *App) handleSessionEvents(events []courtroom.Event) { force := a.d.Prefs.Load().ForceCharNames // The log's name resolves through the same char.ini rung as the plate (remoteIniShownameFor). line, speaker, bodyRuneStart, styles := icLogEntry(ev.Message, force, a.friendNick(ev.Message), a.remoteIniShownameFor) - a.pushICStyled(line, ev.Message.TextColor, fr, fc, speaker, styles, bodyRuneStart) - // Store the speaker's position (wire Side) per entry for the advanced pos filter. - a.icLog[len(a.icLog)-1].pos = icPos(ev.Message) - // This line has a message in the play queue behind it: the log is written on arrival, the courtroom - // speaks it later, and ghost text (ghosttext.go) pairs the two by counting. Stamped only here because - // the EventMessage branch is the only push that enqueues. - a.icLog[len(a.icLog)-1].speech = true - // Reactions: stamp the entry with its content-stable ref, computed from the raw wire fields (CharName + - // marker-free text), not the display line, which bakes in client-local showname, nick and timestamp and - // wouldn't match a peer's ref. A speaker line becomes a reaction target and the "last message"; float - // any reaction this message carries. - if speaker != "" { - ref := courtroom.MakeReactionRef(ev.Message.CharName, courtroom.StripSpriteStyle(ev.Message.Message)) - a.icLog[len(a.icLog)-1].ref = ref - a.lastReactRef, a.lastReactName = ref, speaker - } - if r, ok := courtroom.DecodeReactionMarker(ev.Message.Message); ok { - a.onIncomingReaction(r) + if a.pushICStyled(line, ev.Message.TextColor, fr, fc, speaker, styles, bodyRuneStart) { + // Store the speaker's position (wire Side) per entry for the advanced pos filter. + a.icLog[len(a.icLog)-1].pos = icPos(ev.Message) + // This line has a message in the play queue behind it: the log is written on arrival, the courtroom + // speaks it later, and ghost text (ghosttext.go) pairs the two by counting. Stamped only here because + // the EventMessage branch is the only push that enqueues. + a.icLog[len(a.icLog)-1].speech = true + // Reactions: stamp the entry with its content-stable ref, computed from the raw wire fields (CharName + + // marker-free text), not the display line, which bakes in client-local showname, nick and timestamp and + // wouldn't match a peer's ref. A speaker line becomes a reaction target and the "last message"; float + // any reaction this message carries. + if speaker != "" { + ref := courtroom.MakeReactionRef(ev.Message.CharName, courtroom.StripSpriteStyle(ev.Message.Message)) + a.icLog[len(a.icLog)-1].ref = ref + a.lastReactRef, a.lastReactName = ref, speaker + } + if r, ok := courtroom.DecodeReactionMarker(ev.Message.Message); ok { + a.onIncomingReaction(r) + } } a.noteShowname(ev.Message.CharName, ev.Message.Showname) // live-roster name cache a.notePairPartner(ev.Message) // #20: track each player's current pair diff --git a/internal/ui/app_ic.go b/internal/ui/app_ic.go index b37de789..29238294 100644 --- a/internal/ui/app_ic.go +++ b/internal/ui/app_ic.go @@ -7,6 +7,7 @@ import ( "sort" "strings" "time" + "unicode" "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/config" @@ -837,6 +838,9 @@ type icEntry struct { ref uint32 // content-stable reaction ref (#2): MakeReactionRef(CharName, clean text); 0 = system line // speech marks a line from an IC message, which has a counterpart in the play queue (see ghosttext.go). speech bool + // speechExtra counts additional queued messages folded into this entry's repeated blankposts, so ghost + // text still pairs one log row with every message the log collapsed. + speechExtra int // styles holds inline-colour runs over the body; bodyRuneStart is the rune offset of the body within text. styles []courtroom.StyleRun bodyRuneStart int @@ -1064,8 +1068,39 @@ func (a *App) pushIC(line string, color int, friend bool, friendColor int32, spe a.pushICStyled(line, color, friend, friendColor, speaker, nil, 0) } +// icBodyBlank reports whether the body at bodyRuneStart has no visible text. The head before it is the +// speaker prefix; a blank body is a blankpost. +func icBodyBlank(line string, bodyRuneStart int) bool { + if bodyRuneStart <= 0 { + return false + } + n := 0 + for _, r := range line { + if n >= bodyRuneStart && !unicode.IsSpace(r) { + return false + } + n++ + } + return n >= bodyRuneStart +} + +// appendICEntry appends e, folding a repeated blankpost from the same speaker into the previous entry. +// It returns false when folded; the previous entry then represents one more queued message. +func appendICEntry(log *[]icEntry, e icEntry) bool { + if n := len(*log); n > 0 { + last := &(*log)[n-1] + if e.speaker == last.speaker && icBodyBlank(e.text, e.bodyRuneStart) && icBodyBlank(last.text, last.bodyRuneStart) { + last.speechExtra++ + return false + } + } + *log = append(*log, e) + return true +} + // pushICStyled is pushIC plus the inline-colour runs and the body's rune offset within the line. -func (a *App) pushICStyled(line string, color int, friend bool, friendColor int32, speaker string, styles []courtroom.StyleRun, bodyRuneStart int) { +// It returns false when a repeated blankpost was folded into the previous entry. +func (a *App) pushICStyled(line string, color int, friend bool, friendColor int32, speaker string, styles []courtroom.StyleRun, bodyRuneStart int) bool { // Cap first: everything else describes the stored text. extractURLs splits on Fields and no codec rune is // whitespace, // so a trailing marker would fuse onto a link, @@ -1075,12 +1110,15 @@ func (a *App) pushICStyled(line string, color int, friend bool, friendColor int3 if urls := extractURLs(line, 1); len(urls) > 0 { url = urls[0] } - a.icLog = append(a.icLog, icEntry{text: line, color: color, url: url, friend: friend, friendColor: friendColor, speaker: speaker, stamp: a.icStamp(), styles: styles, bodyRuneStart: bodyRuneStart}) + if !appendICEntry(&a.icLog, icEntry{text: line, color: color, url: url, friend: friend, friendColor: friendColor, speaker: speaker, stamp: a.icStamp(), styles: styles, bodyRuneStart: bodyRuneStart}) { + return false + } if cap := a.icLogCapFor(); cap > 0 && len(a.icLog) > cap { copy(a.icLog, a.icLog[len(a.icLog)-cap:]) a.icLog = a.icLog[:cap] } a.icLogSeq++ // invalidate the filter cache (len alone lies at the cap) + return true } // icLogCapFor returns the live IC scrollback cap, 0 for no cap; diff --git a/internal/ui/ghosttext.go b/internal/ui/ghosttext.go index 0010fcc2..f2b9eef1 100644 --- a/internal/ui/ghosttext.go +++ b/internal/ui/ghosttext.go @@ -42,6 +42,7 @@ func queuedCount(queued int) int { } // firstQueuedEntry returns the index of the oldest of the n most recent speech lines, skipping system lines. +// A folded blankpost entry stands for its whole run, so its weight is 1 + speechExtra. // Returns len(log) when n is 0 or the log holds too few: it can under-hide, never hide a line already said. func firstQueuedEntry(log []icEntry, n int) int { if n <= 0 { @@ -51,9 +52,11 @@ func firstQueuedEntry(log []icEntry, n int) int { if !log[i].speech { continue } - if n--; n == 0 { + weight := 1 + log[i].speechExtra + if n <= weight { return i } + n -= weight } return len(log) } diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index 7754f820..8dcc08e0 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -426,12 +426,14 @@ func (a *App) routeBackgroundEvent(t *courtTab, ev courtroom.Event) { // One name for both the entry's speaker and capLogLine's head marker, so the two can't drift. speaker := icSpeakerName(ev.Message, force, nil) line, _, bodyRuneStart, styles := icLogEntry(ev.Message, force, "", nil) - s.icLog = append(s.icLog, icEntry{text: capLogLine(line, speaker), color: ev.Message.TextColor, friend: fr, friendColor: fc, speaker: speaker, pos: icPos(ev.Message), stamp: a.icStamp(), styles: styles, bodyRuneStart: bodyRuneStart}) - if cap := a.icLogCapFor(); cap > 0 && len(s.icLog) > cap { - copy(s.icLog, s.icLog[len(s.icLog)-cap:]) - s.icLog = s.icLog[:cap] + entry := icEntry{text: capLogLine(line, speaker), color: ev.Message.TextColor, friend: fr, friendColor: fc, speaker: speaker, pos: icPos(ev.Message), stamp: a.icStamp(), styles: styles, bodyRuneStart: bodyRuneStart} + if appendICEntry(&s.icLog, entry) { + if cap := a.icLogCapFor(); cap > 0 && len(s.icLog) > cap { + copy(s.icLog, s.icLog[len(s.icLog)-cap:]) + s.icLog = s.icLog[:cap] + } + s.icLogSeq++ } - s.icLogSeq++ t.unread++ if fr { a.signalFriend(s.serverName, ev.Message) // alert even from a backgrounded server From 09d88104c3f017b432eb9247efc07b6fc2ad6e86 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:05:19 +0000 Subject: [PATCH 11/43] deps: bump aolib to v2.6.5 Picks up the aolib fix that serializes jsonschema.Compiler, preventing concurrent map read/write fatals when multiple sessions validate their first JSON packets. --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 9e5d5b48..e09deb2f 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( require github.com/coder/websocket v1.8.12 -require github.com/AO-Underground/aolib/go/v2 v2.6.1 +require github.com/AO-Underground/aolib/go/v2 v2.6.5 require ( github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect diff --git a/go.sum b/go.sum index 2118f5a7..c1209344 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -github.com/AO-Underground/aolib/go/v2 v2.6.1 h1:Pn/BZ5desmvnCS21iZdVpuX6HpLSUhTva9To1YXJl8o= -github.com/AO-Underground/aolib/go/v2 v2.6.1/go.mod h1:8zK2xBlP1VOw+YZNhyv+slbFv7OP6B8AnDGRuFq7q3A= +github.com/AO-Underground/aolib/go/v2 v2.6.5 h1:1iUlL9LzDNkAo+4tgtqQQARKbJj6/FzHNl7X8d1x2so= +github.com/AO-Underground/aolib/go/v2 v2.6.5/go.mod h1:8zK2xBlP1VOw+YZNhyv+slbFv7OP6B8AnDGRuFq7q3A= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo= From 207a6c879c881abe33b99fccac87e4a2ab6a2a57 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:37:07 +0100 Subject: [PATCH 12/43] changelog: v2.1.1-rc.1 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The test build's notes list the bug fixes on v2.1.1-devel: the one-frame animated WebP, the held message that asks again, folded blankposts, the sprite preview's scaling (#88), effect icon shape (#77), the SFX Browser in front of the Extras box (#32), each list's own ⋮ menu (#85), the theme fit preview's hint (#153), the aolib crash fix and the one-click Wardrobe setting. The shipped-changelog test now pins the newest entry and allows a pre-release header. Co-Authored-By: Claude Opus 5.5 --- internal/ui/assets/CHANGELOG.md | 24 ++++++++++++++++++++++++ internal/ui/markdown_test.go | 18 +++++++----------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/internal/ui/assets/CHANGELOG.md b/internal/ui/assets/CHANGELOG.md index 4c39fdb1..21e8c058 100644 --- a/internal/ui/assets/CHANGELOG.md +++ b/internal/ui/assets/CHANGELOG.md @@ -4,6 +4,30 @@ What changed, newest first. The "What's New" screen renders this embedded file, so every build ships its own history offline. The version you're running is tagged "installed" below. +## v2.1.1-rc.1 - 2026-11-18 + +A test build of a bug-fix release for v2.1.0. Only players with +**Include pre-releases** switched on get this update. + +- A sprite saved as an animated WebP with a single frame shows again. Before, + it never appeared, and with strict sequencing every message using it waited + 10 seconds. +- A message waiting on a missing file no longer sits out the whole 10 seconds + when the missing-file notice gets lost; it asks again every second. +- Repeated blankposts from the same speaker show once in the IC log, as in AO2. +- The sprite preview uses the character's own scaling from the first frame, so + pixel-art characters no longer preview blurry until they speak. +- Effect icons in the effects dropdown keep their shape instead of stretching. +- The SFX Browser opens in front of the Extras box instead of behind it. +- Each list's ⋮ menu shows only its own options: the player list no longer + offers music fade and loop, and the music list no longer offers roster + options. +- A theme without `courtroom_design.ini` no longer draws the drag hint over + its notice in the theme fit preview. +- Fixed a crash when several servers sent their first packets at once. +- New Wardrobe setting in Settings ▸ General: **Click: Selects / Wears**. With + Wears, one click wears a character. Off by default. + ## v2.1.0 - 2026-11-14 AsyncAO moves from SDL2 to SDL3. It draws with Direct3D 11 on Windows and diff --git a/internal/ui/markdown_test.go b/internal/ui/markdown_test.go index 64c5c05e..72710223 100644 --- a/internal/ui/markdown_test.go +++ b/internal/ui/markdown_test.go @@ -79,26 +79,22 @@ func TestParseMarkdownBlocks(t *testing.T) { } } -// TestShippedChangelog pins what the What's New screen shows: v2.1.0 is the first entry, no pre-release entry is left, -// and no heading keeps markdown markup. +// TestShippedChangelog pins what the What's New screen shows: the newest release is the first entry, and no heading +// keeps markdown markup. func TestShippedChangelog(t *testing.T) { + const newest = "v2.1.1-rc.1 " blocks := parseMarkdownBlocks(changelogMD) first := "" for _, b := range blocks { - if b.level == markdownSection { - if first == "" { - first = b.text - } - if strings.Contains(b.text, "-rc.") { - t.Errorf("pre-release entry %q is still in the changelog", b.text) - } + if b.level == markdownSection && first == "" { + first = b.text } if b.level > 0 && strings.ContainsAny(b.text, "*`") { t.Errorf("heading %q keeps markup", b.text) } } - if !strings.HasPrefix(first, "v2.1.0 ") { - t.Errorf("first entry %q, want v2.1.0", first) + if !strings.HasPrefix(first, newest) { + t.Errorf("first entry %q, want %s", first, newest) } } From 53589ad1e460f9b55d06927f2ed37b59ae238372 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:50:56 +0100 Subject: [PATCH 13/43] ui: make server description links clickable where they appear (#134) The expanded lobby description drew its links as plain text and then listed them again underneath. The OOC log's link walker now has no font of its own (wrappedLinkSpans), so the lobby uses it too: links show in the accent colour in place, underline on hover and open on click. A link the wrap ends with an ellipsis still opens the whole address. Co-Authored-By: Claude Opus 5.5 --- internal/ui/app.go | 6 +-- internal/ui/court_extras.go | 2 +- internal/ui/lobbydesclinks_test.go | 48 +++++++++++++++++++++++ internal/ui/logwrap_test.go | 2 +- internal/ui/ooclinks_test.go | 2 +- internal/ui/qol.go | 35 +++++++++-------- internal/ui/screenslobby.go | 61 +++++++++++++++++++++++------- 7 files changed, 121 insertions(+), 35 deletions(-) create mode 100644 internal/ui/lobbydesclinks_test.go diff --git a/internal/ui/app.go b/internal/ui/app.go index d07f102d..365b8f3f 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -210,8 +210,8 @@ type App struct { // First click opens the full description under the row; a second click on the same row joins. selServer int descLines []string - descLinks []string // clickable URLs found in the description - helpScroll int32 // ScreenServerHelp scroll position + descLinks []linkSpan // clickable URLs in descLines + helpScroll int32 // ScreenServerHelp scroll position // --- the active server session (every per-server field) --- // sessionState is embedded so the whole session parks and restores as one struct move on tab switch. @@ -308,7 +308,7 @@ type App struct { oocWrapSrc []int // parallel to oocWrap: the source oocLog entry index of each display line (mirrors icWrapLine.entry) // Every URL in a paragraph is separately hoverable. oocWrapLink is the flat table in row order; // oocWrapLinkAt has len(rows)+1 entries, so row r's spans are oocWrapLink[oocWrapLinkAt[r]:oocWrapLinkAt[r+1]]. - oocWrapLink []oocLinkSpan + oocWrapLink []linkSpan oocWrapLinkAt []int32 oocWrapSeq uint64 oocWrapEpoch uint64 diff --git a/internal/ui/court_extras.go b/internal/ui/court_extras.go index 87f2f0d3..6ea9e446 100644 --- a/internal/ui/court_extras.go +++ b/internal/ui/court_extras.go @@ -1392,7 +1392,7 @@ func (a *App) drawEvidenceCompare(rect sdl.Rect) { // drawEvidenceDescriptionLine draws one wrapped description line, rendering URLs as clickable links like the OOC log. func (a *App) drawEvidenceDescriptionLine(x, y, maxW int32, line string) { c := a.ctx - links := extractURLs(line, oocLinksPerParagraphMax) + links := extractURLs(line, linksPerParagraphMax) if len(links) == 0 { c.LabelClipped(x, y, maxW, line, ColText) return diff --git a/internal/ui/lobbydesclinks_test.go b/internal/ui/lobbydesclinks_test.go new file mode 100644 index 00000000..b914dfba --- /dev/null +++ b/internal/ui/lobbydesclinks_test.go @@ -0,0 +1,48 @@ +package ui + +import ( + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +// Issue #134: links in a server description are clickable where they appear, not repeated under the text. +func TestServerDescriptionLinksAreInline(t *testing.T) { + const ( + site = "https://github.com/SyntaxNyah/Nyathena" + webao = "webao.miku.pizza/client.html" + listW = 1000 + wantLn = 2 + ) + a := testTabApp(t) + a.servers = []network.ServerEntry{{Name: "Skrapegropen", Description: "Fork: " + site + ". Web: www." + webao}} + a.selectServerRow(0, listW) + + if len(a.descLinks) != wantLn { + t.Fatalf("got %d links, want %d: %+v", len(a.descLinks), wantLn, a.descLinks) + } + for i, want := range []string{site, "www." + webao} { + s := a.descLinks[i] + if s.url != want { + t.Errorf("link %d opens %q, want %q", i, s.url, want) + } + if got := a.descLines[s.row][s.lo:s.hi]; got != want { + t.Errorf("link %d covers %q, want %q", i, got, want) + } + } + for _, line := range a.descLines { + if line == site { + t.Errorf("link repeated as its own row: %q", a.descLines) + } + } +} + +// A link cut by the wrap's ellipsis still opens the whole address. +func TestWrappedLinkSpansEllipsisOpensFullURL(t *testing.T) { + const url = "https://example.com/long/path" + rows := []string{"see https://example.com/lo…"} + spans, _ := wrappedLinkSpans(nil, rows, 0, "see "+url+" more words", rows[0], 0) + if len(spans) != 1 || spans[0].url != url { + t.Fatalf("spans = %+v, want one opening %q", spans, url) + } +} diff --git a/internal/ui/logwrap_test.go b/internal/ui/logwrap_test.go index 1a3b4ff2..b780507f 100644 --- a/internal/ui/logwrap_test.go +++ b/internal/ui/logwrap_test.go @@ -83,7 +83,7 @@ func TestLogHangingIndent(t *testing.T) { // wrapped-across-rows case), row 5 holds two distinct links side by side. func TestOOCHoverSpan(t *testing.T) { a := testTabApp(t) - a.oocWrapLink = []oocLinkSpan{ + a.oocWrapLink = []linkSpan{ {row: 1, x0: 0, x1: 100, link: 0, url: "u1"}, {row: 2, x0: 0, x1: 100, link: 0, url: "u1"}, {row: 3, x0: 0, x1: 40, link: 0, url: "u1"}, diff --git a/internal/ui/ooclinks_test.go b/internal/ui/ooclinks_test.go index e170a625..eee35da5 100644 --- a/internal/ui/ooclinks_test.go +++ b/internal/ui/ooclinks_test.go @@ -17,7 +17,7 @@ import ( // spanText is the drawn text a span covers — the assertion that matters most, // since a span's whole job is to point at the characters the user sees. -func spanText(a *App, s oocLinkSpan) string { +func spanText(a *App, s linkSpan) string { if int(s.row) >= len(a.oocWrap) { return "" } diff --git a/internal/ui/qol.go b/internal/ui/qol.go index 89e3decf..410a56eb 100644 --- a/internal/ui/qol.go +++ b/internal/ui/qol.go @@ -1107,30 +1107,31 @@ const oocWrapMinCharsPerRow = 4 // Derived from oocLineCap so a legitimate entry is never clipped; the "…" marker needs a synthetic width. const oocWrapMaxLinesPerEntry = oocLineCap / oocWrapMinCharsPerRow -// oocLinkSpan is one clickable link on one wrapped OOC row: its byte range in the displayed text, pixel range and URL. +// linkSpan is one clickable link on one wrapped row: its byte range in the displayed text, pixel range and URL. // A link the wrap hard-split contributes one span per row sharing an id, so the highlight covers the whole link. -type oocLinkSpan struct { - row int32 // display-row index into a.oocWrap - lo, hi int32 // byte range inside a.oocWrap[row] (the drawn text) +type linkSpan struct { + row int32 // display-row index into the wrapped rows + lo, hi int32 // byte range inside the row (the drawn text) x0, x1 int32 // pixel range relative to the row's TEXT origin (hanging indent NOT included) link int32 // link id; the pieces of one wrapped link share it and are contiguous in the table url string // what a click opens — read from the UNMASKED paragraph (streamer mode masks display only) } -// oocLinksPerParagraphMax bounds the clickable links of one paragraph (hard rule 4); links past it still display. -const oocLinksPerParagraphMax = 64 +// linksPerParagraphMax bounds the clickable links of one paragraph (hard rule 4); links past it still display. +const linksPerParagraphMax = 64 -// appendLinkSpans records the link regions of one wrapped paragraph; only inside oocWrapped's cached rebuild. -// Positions come from masked, the drawn text, since streamer mode shifts offsets; the URL to open comes from raw. -func (a *App) appendLinkSpans(dst []oocLinkSpan, rows []string, rowBase int, raw, masked string, nextID int32) ([]oocLinkSpan, int32) { - rawLinks := extractURLs(raw, oocLinksPerParagraphMax) +// wrappedLinkSpans records the byte ranges of the links in one wrapped paragraph; callers measure x0/x1 in their face. +// Positions come from drawn, the text the rows hold, since streamer mode and ellipses shift offsets; the URL to open +// comes from raw. +func wrappedLinkSpans(dst []linkSpan, rows []string, rowBase int, raw, drawn string, nextID int32) ([]linkSpan, int32) { + rawLinks := extractURLs(raw, linksPerParagraphMax) if len(rawLinks) == 0 || len(rows) == 0 { return dst, nextID // the overwhelming common case: no link in this paragraph, no work } start, startID := len(dst), nextID rawAt := 0 // cursor into rawLinks rowIdx, pos := 0, 0 // walk position: row, byte offset within it - for _, tok := range strings.Fields(masked) { + for _, tok := range strings.Fields(drawn) { // Masking can eat or rewrite a link, so pair by exact match scanning forward from the cursor, // falling back to the next unconsumed raw link when the drawn text no longer matches. tlo, thi := urlTokenRange(tok) @@ -1179,7 +1180,7 @@ func (a *App) appendLinkSpans(dst []oocLinkSpan, rows []string, rowBase int, raw // Intersect with the link's trimmed range; brackets and a sentence period are not part of it. ovLo, ovHi := max(consumed, tlo), min(consumed+n, thi) if ovHi > ovLo { - dst = append(dst, oocLinkSpan{ + dst = append(dst, linkSpan{ row: int32(rowBase + rowIdx), lo: int32(pos + ovLo - consumed), hi: int32(pos + ovHi - consumed), @@ -1194,12 +1195,12 @@ func (a *App) appendLinkSpans(dst []oocLinkSpan, rows []string, rowBase int, raw nextID++ } } - return a.measureLinkSpans(dst, start, rows, rowBase), nextID + return dst, nextID } // measureLinkSpans fills the pixel range of dst[start:] in the face each row draws in, so tint and hit test match. // A row the per-glyph raster draws has no advance to trust here, so its first link covers the whole row. -func (a *App) measureLinkSpans(dst []oocLinkSpan, start int, rows []string, rowBase int) []oocLinkSpan { +func (a *App) measureLinkSpans(dst []linkSpan, start int, rows []string, rowBase int) []linkSpan { w := start for k := start; k < len(dst); k++ { s := dst[k] @@ -1222,7 +1223,7 @@ func (a *App) measureLinkSpans(dst []oocLinkSpan, start int, rows []string, rowB } // oocRowLinks returns row li's link spans, a view into the flat table with no allocation. -func (a *App) oocRowLinks(li int) []oocLinkSpan { +func (a *App) oocRowLinks(li int) []linkSpan { if li < 0 || li+1 >= len(a.oocWrapLinkAt) { return nil } @@ -1309,7 +1310,9 @@ func (a *App) oocWrapped(width int32) []string { } } // Each URL on the line gets its own span, positioned on the drawn rows but opening the link as it arrived. - links, nextLinkID = a.appendLinkSpans(links, lines, rowBase, rawPara, trimmed, nextLinkID) + linkStart := len(links) + links, nextLinkID = wrappedLinkSpans(links, lines, rowBase, rawPara, trimmed, nextLinkID) + links = a.measureLinkSpans(links, linkStart, lines, rowBase) remaining -= len(lines) if truncated { break // clipped this paragraph — no point wrapping later ones diff --git a/internal/ui/screenslobby.go b/internal/ui/screenslobby.go index e27e57b3..55d78ee7 100644 --- a/internal/ui/screenslobby.go +++ b/internal/ui/screenslobby.go @@ -297,19 +297,14 @@ func (a *App) drawLobby(w, h int32) { } y += rowH if i == a.selServer && len(a.descLines) > 0 { - boxH := int32(len(a.descLines)+len(a.descLinks))*lineH + btnH + 16 + boxH := int32(len(a.descLines))*lineH + btnH + 16 if y > listTop-boxH && y < h { box := sdl.Rect{X: pad + 16, Y: y, W: w - 2*pad - 16, H: boxH - 4} c.Fill(box, ColPanelHi) c.Border(box, ColAccent) ly := y + 3 - for _, line := range a.descLines { - c.LabelClipped(box.X+6, ly, box.W-12, line, ColText) - ly += lineH - } - // URLs from the description: clickable, opens the browser. - for _, link := range a.descLinks { - a.linkLabel(box.X+6, ly, box.W-12, link) + for row, line := range a.descLines { + a.drawDescRow(box.X+6, ly, box.W-12, lineH, row, line) ly += lineH } // Rehearse: offline browse of the cached roster. Read the snapshot: a ★ removal this frame may have @@ -478,9 +473,6 @@ func (a *App) drawServerRow(e *network.ServerEntry, idx int, y, w int32) { } } -// maxDescLinks bounds the clickable-link rows under a description. -const maxDescLinks = 4 - // lobbyWarnStripH is the strip behind a notice at the lobby's bottom; lobbyWarnTextDY places its text up from the edge. const ( lobbyWarnStripH int32 = 30 @@ -497,8 +489,51 @@ func (a *App) selectServerRow(idx int, w int32) { if desc == "" { desc = "(no description)" } - a.descLines = a.ctx.WrapText(desc, w-2*pad-40, maxDescLines) - a.descLinks = extractURLs(desc, maxDescLinks) + c := a.ctx + a.descLines = c.WrapText(desc, w-2*pad-40, maxDescLines) + // Positions come from the rows joined, as the wrap may end the last row with an ellipsis desc doesn't have. + a.descLinks, _ = wrappedLinkSpans(a.descLinks[:0], a.descLines, 0, desc, strings.Join(a.descLines, " "), 0) + for k := range a.descLinks { + s := &a.descLinks[k] + row := a.descLines[s.row] + s.x0, s.x1 = c.TextWidth(row[:s.lo]), c.TextWidth(row[:s.hi]) + } +} + +// drawDescRow draws one description row with its links in the accent colour; hovering underlines one, a click opens it. +func (a *App) drawDescRow(x, y, maxW, lineH int32, row int, line string) { + c := a.ctx + drawn := int32(0) + for _, s := range a.descLinks { + if int(s.row) != row || s.x0 >= maxW { + continue + } + x1 := min(s.x1, maxW) + a.drawDescSegment(x, y, maxW, lineH, drawn, s.x0, line, ColText) + a.drawDescSegment(x, y, maxW, lineH, s.x0, x1, line, ColAccent) + if c.hovering(sdl.Rect{X: x + s.x0, Y: y, W: x1 - s.x0, H: lineH}) { + c.Fill(sdl.Rect{X: x + s.x0, Y: y + lineH - descUnderlineRise, W: x1 - s.x0, H: 1}, ColAccent) + if c.clicked { + a.openBrowser(schemeForOpen(s.url)) + } + } + drawn = x1 + } + a.drawDescSegment(x, y, maxW, lineH, drawn, maxW, line, ColText) +} + +// descUnderlineRise lifts a hovered link's underline from the row's bottom edge to just under the baseline. +const descUnderlineRise = 3 + +// drawDescSegment draws the pixels lo..hi of a description row in col; the row is laid out whole so segments line up. +func (a *App) drawDescSegment(x, y, maxW, lineH, lo, hi int32, line string, col sdl.Color) { + if hi <= lo { + return + } + c := a.ctx + prev, had := c.pushClip(sdl.Rect{X: x + lo, Y: y, W: hi - lo, H: lineH}) + c.LabelClipped(x, y, maxW, line, col) + c.popClip(prev, had) } // serverRowTooltip shows a row's connect URL and advertised description on hover. From 006b3d18ea231a9fe028b7ce4be44b8b62c94a1c Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:50:56 +0100 Subject: [PATCH 14/43] ui: draw the log row the bottom edge cuts in half (#116) The IC log, both OOC logs and the notebook stopped before a row that would cross the list's bottom edge, though the clip already cuts it, so the last line vanished early while the top edge showed its half row. Co-Authored-By: Claude Opus 5.5 --- internal/ui/app_room.go | 2 +- internal/ui/logbottomrow_test.go | 56 ++++++++++++++++++++++++++++++++ internal/ui/notebook.go | 2 +- internal/ui/qol.go | 3 ++ internal/ui/screensooc.go | 12 +++---- 5 files changed, 67 insertions(+), 8 deletions(-) create mode 100644 internal/ui/logbottomrow_test.go diff --git a/internal/ui/app_room.go b/internal/ui/app_room.go index 04051ff5..0cd9a716 100644 --- a/internal/ui/app_room.go +++ b/internal/ui/app_room.go @@ -555,7 +555,7 @@ type splitLogRow struct { func (a *App) drawSplitLog(r sdl.Rect, s *sessionState) { c := a.ctx font := c.LogFont(a.logPct) - lineH := int32(font.Height()) + 2 + lineH := int32(font.Height()) + logRowGapPx wrapW := r.W - 8 if wrapW != a.splitWrapW || s.icLogSeq != a.splitWrapSeq || a.splitPinEpoch != a.splitWrapEpoch || a.logPct != a.splitWrapPct || c.fontChainGen != a.splitWrapGen { diff --git a/internal/ui/logbottomrow_test.go b/internal/ui/logbottomrow_test.go new file mode 100644 index 00000000..ed6d2bf6 --- /dev/null +++ b/internal/ui/logbottomrow_test.go @@ -0,0 +1,56 @@ +package ui + +import ( + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/render" + "github.com/SyntaxNyah/AsyncAO/internal/sdl" +) + +// Issue #116: a log row the bottom edge cuts in half still draws, as the top edge's half row does. +func TestOOCLogDrawsHalfVisibleBottomRow(t *testing.T) { + const ( + targetW, targetH = int32(400), int32(200) + visibleRows = 2 + lineCount = 6 + listX, listY = int32(10), int32(10) + listW = int32(300) + pointerAway = int32(-1000) + ) + ren, cleanup := newCaptureHarness(t) + defer cleanup() + ctx, err := NewCtx(ren) + if err != nil { + t.Skipf("Ctx unavailable: %v", err) + } + ct, err := render.NewCaptureTarget(ren, targetW, targetH) + if err != nil { + t.Skipf("capture target unavailable: %v", err) + } + defer ct.Close() + + a := testTabApp(t) + a.ctx = ctx + a.oocPct = DefaultScalePct + for range lineCount { + a.pushOOC("MMMMMMMMMMMMMMMM", "") + } + lineH := int32(a.elemFont(elemServerChatlog, a.oocPct).Height()) + logRowGapPx + list := sdl.Rect{X: listX, Y: listY, W: listW, H: visibleRows*lineH + lineH/2} + a.oocScroll, a.oocStick = 0, false + ctx.mouseX, ctx.mouseY = pointerAway, pointerAway + + frame, err := ct.Capture(ren, func(sdl.Rect) { a.drawOOCLogList(list, false) }) + if err != nil { + t.Skipf("offscreen capture unavailable headlessly: %v", err) + } + bg := frame.RGBAAt(int(targetW-1), int(targetH-1)) + for y := list.Y + visibleRows*lineH; y < list.Y+list.H; y++ { + for x := list.X; x < list.X+list.W/2; x++ { + if frame.RGBAAt(int(x), int(y)) != bg { + return + } + } + } + t.Fatalf("no ink in the half-visible bottom row (y %d..%d)", list.Y+visibleRows*lineH, list.Y+list.H) +} diff --git a/internal/ui/notebook.go b/internal/ui/notebook.go index 6ae8fd58..8e14635f 100644 --- a/internal/ui/notebook.go +++ b/internal/ui/notebook.go @@ -78,7 +78,7 @@ func (a *App) drawNotesTab(r sdl.Rect) { y := list.Y - a.noteScroll removeIdx := -1 for i, line := range lines { - if y > list.Y+list.H-lineH { + if y >= list.Y+list.H { break } if y >= list.Y-lineH { diff --git a/internal/ui/qol.go b/internal/ui/qol.go index 410a56eb..46f30823 100644 --- a/internal/ui/qol.go +++ b/internal/ui/qol.go @@ -1358,6 +1358,9 @@ type icWrapLine struct { // logWrapIndentPx is the hanging indent of wrapped rows; drawers wrap against width-logWrapIndentPx. const logWrapIndentPx = 14 +// logRowGapPx is the space between log rows, added to the font height. +const logRowGapPx = 2 + // icRowIsEntryStart reports whether row li of a.icWrap begins a new icLog entry rather than continuing the row above. func (a *App) icRowIsEntryStart(li int) bool { return li <= 0 || li >= len(a.icWrap) || a.icWrap[li-1].entry != a.icWrap[li].entry diff --git a/internal/ui/screensooc.go b/internal/ui/screensooc.go index 90ab942b..32344df7 100644 --- a/internal/ui/screensooc.go +++ b/internal/ui/screensooc.go @@ -94,7 +94,7 @@ func (a *App) drawICLogList(list sdl.Rect, canvasInk bool) { // the same icPct or wrap and draw disagree. icPct := a.elemPct(elemICChatlog, a.logPct) font := a.elemFont(elemICChatlog, a.logPct) - lineH := int32(font.Height()) + 2 + lineH := int32(font.Height()) + logRowGapPx wrapW := list.W - scrollBarW - scrollBarGap // Wrap against the indented width so continuation rows (drawn at +logWrapIndentPx) cannot overflow. rows := a.icWrapped(wrapW-logWrapIndentPx, a.d.Prefs.Load().ICTimestamps) // per-frame pref read, like the IC counter @@ -185,7 +185,7 @@ func (a *App) drawICLogList(list sdl.Rect, canvasInk bool) { clipPrev, clipHad := c.pushClip(list) y := list.Y - visScroll for ri := range rows { - if y > list.Y+list.H-lineH { + if y >= list.Y+list.H { break } if y >= list.Y-lineH { @@ -309,7 +309,7 @@ func (a *App) drawOOCLogList(list sdl.Rect, canvasInk bool) { oocInk := a.elemInkOr(elemServerChatlog, canvasInk, ColText) // The theme's server_chatlog size/family/bold (AO2 folds ms_chatlog in), folded with the OOC zoom. font := a.elemFont(elemServerChatlog, a.oocPct) - lineH := int32(font.Height()) + 2 + lineH := int32(font.Height()) + logRowGapPx wrapW := list.W - scrollBarW - scrollBarGap // Wrap against the indented width so continuation rows (drawn at +logWrapIndentPx) cannot overflow. lines := a.oocWrapped(wrapW - logWrapIndentPx) // MOTDs wrap — never truncate @@ -349,7 +349,7 @@ func (a *App) drawOOCLogList(list sdl.Rect, canvasInk bool) { clipPrev, clipHad := c.pushClip(list) // top/bottom row clipped to the rect, not the tabs y := list.Y - a.oocScroll for li, line := range lines { - if y > list.Y+list.H-lineH { + if y >= list.Y+list.H { break } if y >= list.Y-lineH { @@ -497,7 +497,7 @@ func (a *App) drawOOCPanel(r sdl.Rect, withInput bool) { // Same server_chatlog resolution as drawOOCLogList (this is the other copy of the OOC scrollback). font := a.elemFont(elemServerChatlog, a.oocPct) - lineH := int32(font.Height()) + 2 + lineH := int32(font.Height()) + logRowGapPx wrapW := list.W - scrollBarW - scrollBarGap // Wrap against the indented width so continuation rows (drawn at +logWrapIndentPx) cannot overflow. lines := a.oocWrapped(wrapW - logWrapIndentPx) // MOTDs wrap — never truncate @@ -538,7 +538,7 @@ func (a *App) drawOOCPanel(r sdl.Rect, withInput bool) { clipPrev, clipHad := c.pushClip(list) // scrollback only; restored before the fields below y := list.Y - a.oocScroll for li, line := range lines { - if y > list.Y+list.H-lineH { + if y >= list.Y+list.H { break } if y >= list.Y-lineH { From 9b5340e96eecad8489dcc5f4022d3f6a686ee883 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:50:56 +0100 Subject: [PATCH 15/43] assets: archive and export find the player's files in every format ResolveRawLayered and ResolveRawFull walked the server's format list through cache, folders and web per URL, so a PNG character in a mounted folder was missed on a host whose extensions.json lists only WebP. They now share resolveIn, in the live chain's order: memory and disk cache, then the folders in every format, then the web. A folder hit teaches the host no format. Plan: the CodeQL item is done; no alert is open. Co-Authored-By: Claude Opus 5.5 --- docs/RESTRUCTURING_PLAN.md | 4 +- internal/assets/manager.go | 98 ++++++++++++++++++++------------- internal/assets/manager_test.go | 14 ++--- 3 files changed, 69 insertions(+), 47 deletions(-) diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index 3a51719f..2fee829a 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -75,8 +75,8 @@ in **Status**. Update Status in the same commit that completes a step. - [ ] first release run: signing, the Flatpak and publishing have never run; use a `v0.0.0-ci.1` prerelease and delete it - [ ] `netproxy` against a real proxy, which has not been tried - [ ] the owner requires `ci-ok`; until then a red PR can merge, though it cannot release untested - - [ ] fix the real CodeQL findings, in their own PR: RGB values wrap instead of clamping (`theme.go`, `stylesheet.go`), and - check `ResizeWindow`'s sizes. The workflow-permission alerts close once this branch merges + - [x] CodeQL findings: RGB values clamp through `parse.Uint8`, every `ResizeWindow` size goes through + `ClampWindowSize`, and the workflow-permission alerts closed with the merge. No alert is open (checked 2026-11-14) - [ ] 3. Feature extraction and stable boundaries (decided 2026-11-01; replaces splitting the monolith first). Take tertiary functions out of `courtroom.Courtroom` and `internal/ui` into purpose-built types that own their state. Every move starts from a benchmark and is measured again after it; a cheap rewrite or optimisation found on the way is welcome. diff --git a/internal/assets/manager.go b/internal/assets/manager.go index 036e14a9..eb95fb60 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -2,12 +2,14 @@ package assets import ( "context" + "slices" "strings" "sync/atomic" "time" "github.com/SyntaxNyah/AsyncAO/internal/cache" "github.com/SyntaxNyah/AsyncAO/internal/config" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/network" ) @@ -373,30 +375,45 @@ func (m *Manager) FetchRaw(ctx context.Context, url string) ([]byte, error) { // fetchRaw is FetchRaw that also says whether the bytes came from the player's folders. func (m *Manager) fetchRaw(ctx context.Context, url string) (data []byte, fromPack bool, err error) { - if data, ok := m.t2.Get(url); ok { - m.t2Hits.Add(1) + if data, ok := m.cachedRaw(url); ok { return data, false, nil } - if !skipDisk(url) { - if data, ok := m.disk.Get(url); ok { - m.diskHits.Add(1) - m.t2.Add(url, data, int64(len(data))) - return data, false, nil - } - } if data, ok := m.bridge.folders.read(url); ok { return data, true, nil // counted by the folder source } - data, err = m.netFetch(ctx, url) + data, err = m.remoteRaw(ctx, url) + return data, false, err +} + +// cachedRaw reads a URL from memory or the disk cache. +func (m *Manager) cachedRaw(url string) ([]byte, bool) { + if data, ok := m.t2.Get(url); ok { + m.t2Hits.Add(1) + return data, true + } + if skipDisk(url) { + return nil, false + } + data, ok := m.disk.Get(url) + if ok { + m.diskHits.Add(1) + m.t2.Add(url, data, int64(len(data))) + } + return data, ok +} + +// remoteRaw fetches a URL from the web and keeps it in memory and the disk cache. +func (m *Manager) remoteRaw(ctx context.Context, url string) ([]byte, error) { + data, err := m.netFetch(ctx, url) if err != nil { - return nil, false, err + return nil, err } m.netFetches.Add(1) m.t2.Add(url, data, int64(len(data))) if !skipDisk(url) { m.disk.Put(url, data) } - return data, false, nil + return data, nil } // ResolveRaw returns the first candidate whose bytes fetch and learns its format; export and replay share this order. @@ -411,17 +428,9 @@ func (m *Manager) ResolveRawLayered(base string, t AssetType) (url string, data if base == "" || !t.Valid() { return "", nil, false, false } - host := hostOf(base) - cands := m.resolver.BuildCandidates(base, t, host) + cands := m.resolver.BuildCandidates(base, t, hostOf(base)) defer m.resolver.PutCandidates(cands) - for _, url := range cands.URLs { - data, fromPack, err := m.fetchRaw(context.Background(), url) - if err == nil && len(data) > 0 { - m.resolver.RecordSuccess(host, t, url[len(base):]) // learn the winning ext - return url, data, fromPack, true - } - } - return "", nil, false, false + return m.resolveIn(base, t, cands.URLs) } // ResolveRawFull is ResolveRaw for report and export passes: the learned format, then the full probe chain. @@ -429,25 +438,40 @@ func (m *Manager) ResolveRawFull(base string, t AssetType) (string, []byte, bool if base == "" || !t.Valid() { return "", nil, false } + exts := fullProbeChain(m.prefs, t) + if ext, ok := m.resolver.Learned(hostOf(base), t); ok { + exts = append([]string{ext}, slices.DeleteFunc(exts, func(e string) bool { return e == ext })...) + } + urls := make([]string, len(exts)) + for i, ext := range exts { + urls[i] = base + ext + } + url, data, _, ok := m.resolveIn(base, t, urls) + return url, data, ok +} + +// resolveIn finds one name in the live chain's order: memory and the disk cache, then the player's folders in every +// format, then the web. Server hits teach the host's format; a folder hit teaches nothing, as the files are the player's. +func (m *Manager) resolveIn(base string, t AssetType, urls []string) (url string, data []byte, fromPack, ok bool) { host := hostOf(base) - // A learned format is the fast single-probe path. - if ext, ok := m.resolver.Learned(host, t); ok { - url := base + ext - if data, err := m.FetchRaw(context.Background(), url); err == nil && len(data) > 0 { - return url, data, true + for _, u := range urls { + if data, ok := m.cachedRaw(u); ok { + m.resolver.RecordSuccess(host, t, u[len(base):]) + return u, data, false, true + } + } + for _, f := range media.EveryFormat(media.Key{Class: classOf(t)}, base) { + if data, ok := m.bridge.folders.read(string(f)); ok { + return string(f), data, true, true } - // fall through to the full walk - } - // Learn the winner; a different-format sibling still reaches this walk via the fall-through above. - for _, ext := range fullProbeChain(m.prefs, t) { - url := base + ext - data, err := m.FetchRaw(context.Background(), url) - if err == nil && len(data) > 0 { - m.resolver.RecordSuccess(host, t, ext) // learn so a repeat pass is single-probe - return url, data, true + } + for _, u := range urls { + if data, err := m.remoteRaw(context.Background(), u); err == nil && len(data) > 0 { + m.resolver.RecordSuccess(host, t, u[len(base):]) + return u, data, false, true } } - return "", nil, false + return "", nil, false, false } // fullProbeChain is the configured order then the type's fallback chain, deduped, covering each decoder's formats. diff --git a/internal/assets/manager_test.go b/internal/assets/manager_test.go index d73c2d49..c2ed8702 100644 --- a/internal/assets/manager_test.go +++ b/internal/assets/manager_test.go @@ -96,17 +96,15 @@ func TestResolveRawFromLocalArchive(t *testing.T) { t.Errorf("relpath = %q, want characters/Phoenix/(a)normal.webp", rel) } - // Robustness: a NON-default format (.png, e.g. an older server) MISSES until - // the archive's recorded format is seeded for the archive host — which is - // exactly what replaying a bundled archive does from its format manifest. + // The player's folders are searched in every format, whatever the host's list says, and a hit there teaches the + // host nothing. write("characters/Edgeworth/(a)normal.png", []byte("PNG")) pbase := local.BaseURL() + "characters/Edgeworth/(a)normal" - if _, _, ok := rig.manager.ResolveRaw(pbase, AssetTypeCharSprite); ok { - t.Fatal("expected .png to MISS before seeding (default probe list is webp-only)") - } - rig.resolver.RecordSuccess(hostOf(pbase), AssetTypeCharSprite, config.ExtPNG) if url, data, ok := rig.manager.ResolveRaw(pbase, AssetTypeCharSprite); !ok || string(data) != "PNG" { - t.Fatalf("seeded .png archive asset not resolved: ok=%v url=%q", ok, url) + t.Fatalf("folder .png not resolved: ok=%v url=%q", ok, url) + } + if ext, ok := rig.resolver.Learned(hostOf(pbase), AssetTypeCharSprite); ok && ext == config.ExtPNG { + t.Errorf("a folder hit taught the host %q", ext) } } From 7505b0adb3c9017a41b8858f5b636def69271858 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:12:15 +0100 Subject: [PATCH 16/43] saver: one background file writer for jukebox, notebook and wardrobe Each store had its own debounce timer and its own temp-file-and-rename copy, and prefs had a fourth. internal/saver holds both: Changed schedules one write a delay after the first change (a burst no longer pushes it back), Flush and Close write now, Discard drops a waiting write, and WriteFile is the one atomic replace. The stores embed the saver; prefs writes through WriteFile. learned.json is next to use it. Co-Authored-By: Claude Opus 5.5 --- .golangci.yml | 2 +- CLAUDE.md | 1 + internal/config/jukebox.go | 58 +++----------- internal/config/jukebox_test.go | 23 ++++-- internal/config/notebook.go | 58 ++++---------- internal/config/notebook_test.go | 6 +- internal/config/preferences.go | 57 +------------- internal/config/wardrobe.go | 43 +++-------- internal/saver/saver.go | 120 +++++++++++++++++++++++++++++ internal/saver/saver_test.go | 125 +++++++++++++++++++++++++++++++ 10 files changed, 302 insertions(+), 191 deletions(-) create mode 100644 internal/saver/saver.go create mode 100644 internal/saver/saver_test.go diff --git a/.golangci.yml b/.golangci.yml index 947a5b02..1d3ad60f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -45,7 +45,7 @@ linters: exclusions: rules: # mnd applies per package: one joins this list once clean and never leaves it. - - path-except: ^internal[/\\](network|safepath|hwid|metrics|presence|render|theme|helper|protocol|config|courtroom|sdl|ttf|mix|platform|netproxy|media)[/\\] + - path-except: ^internal[/\\](network|safepath|hwid|metrics|presence|render|theme|helper|protocol|config|courtroom|sdl|ttf|mix|platform|netproxy|media|saver)[/\\] linters: - mnd - path: _test\.go diff --git a/CLAUDE.md b/CLAUDE.md index 58684a2a..0cf9255e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -142,6 +142,7 @@ heap corruption. |---|---|---| | `internal/safepath` | the ONE copy of the zip-slip / symlink / `..` / depth guards (shared by mounts and theme bundles) | no | | `internal/netproxy` | the socket factory: opens every outbound connection (direct or through an HTTP proxy) by the one configuration | no | +| `internal/saver` | the one background file writer: a change schedules one whole-file replace (temp file + rename) | no | | `internal/config` | preferences + debounced atomic saver; favorites; local mounts; the Wardrobe's `wardrobe.json` | no | | `internal/cache` | ByteBudgetLRU (T1/T2) + async disk tier (T3, xxhash full-URL keys) | no | | `internal/network` | dedup HTTP client (singleflight, 404 TTL, backoff, DNS warm), request priority, master list + tiers + direct connect | no | diff --git a/internal/config/jukebox.go b/internal/config/jukebox.go index fd5ea76f..27ba8dae 100644 --- a/internal/config/jukebox.go +++ b/internal/config/jukebox.go @@ -12,6 +12,7 @@ import ( "time" "github.com/SyntaxNyah/AsyncAO/internal/helper/text" + "github.com/SyntaxNyah/AsyncAO/internal/saver" ) const ( @@ -44,12 +45,11 @@ type Playlist struct { Entries []JukeboxEntry `json:"entries,omitempty"` } -// Jukebox is safe for concurrent use; the flush goroutine is the only disk writer. +// Jukebox is safe for concurrent use; its saver is the only disk writer. type Jukebox struct { + *saver.Saver mu sync.Mutex - path string playlists []Playlist - timer *time.Timer // rev bumps on every mutation so the UI can cache its snapshot and search index instead of copying per frame. rev int64 } @@ -81,7 +81,8 @@ func OpenJukebox(path string) *Jukebox { return loadJukeboxFile(path) } // loadJukeboxFile treats an absent or corrupt file as a fresh library. func loadJukeboxFile(path string) *Jukebox { - j := &Jukebox{path: path} + j := &Jukebox{} + j.Saver = saver.New(path, jukeboxSaveDelay, j.encode) data, err := os.ReadFile(path) if err != nil { return j @@ -453,55 +454,16 @@ func totalEntries(pls []Playlist) int { func (j *Jukebox) totalLocked() int { return totalEntries(j.playlists) } -// touchLocked bumps the revision and rearms the debounced flush; the caller holds j.mu. +// touchLocked bumps the revision and schedules a write; the caller holds j.mu. func (j *Jukebox) touchLocked() { j.rev++ - if j.timer != nil { - j.timer.Stop() - } - j.timer = time.AfterFunc(jukeboxSaveDelay, func() { _ = j.Flush() }) + j.Changed() } -// Flush writes atomically (tmp + rename); also called on exit so nothing rides only on the debounce. -func (j *Jukebox) Flush() error { +// encode snapshots the library for the saver. +func (j *Jukebox) encode() ([]byte, error) { j.mu.Lock() snapshot := jukeboxJSON{Playlists: clonePlaylists(j.playlists)} - path := j.path j.mu.Unlock() - if path == "" { - return nil - } - data, err := json.MarshalIndent(snapshot, jsonMarshalPrefix, jsonMarshalIndent) - if err != nil { - return err - } - if err := os.MkdirAll(filepath.Dir(path), prefsDirPerm); err != nil { - return err - } - tmp, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".*.tmp") - if err != nil { - return err - } - tmpName := tmp.Name() - if _, err := tmp.Write(data); err != nil { - tmp.Close() - os.Remove(tmpName) - return err - } - if err := tmp.Close(); err != nil { - os.Remove(tmpName) - return err - } - return os.Rename(tmpName, path) -} - -// Close stops the debounce timer and writes any pending change; the caller guards against nil. -func (j *Jukebox) Close() error { - j.mu.Lock() - if j.timer != nil { - j.timer.Stop() - j.timer = nil - } - j.mu.Unlock() - return j.Flush() + return json.MarshalIndent(snapshot, jsonMarshalPrefix, jsonMarshalIndent) } diff --git a/internal/config/jukebox_test.go b/internal/config/jukebox_test.go index f8efc35f..5992b590 100644 --- a/internal/config/jukebox_test.go +++ b/internal/config/jukebox_test.go @@ -8,14 +8,21 @@ import ( ) func newTestJukebox(t *testing.T) *Jukebox { - t.Helper() - j := &Jukebox{path: filepath.Join(t.TempDir(), JukeboxFileName)} - t.Cleanup(func() { _ = j.Close() }) // stop the debounce timer before TempDir cleanup + j, _ := newTestJukeboxAt(t) return j } +// newTestJukeboxAt also returns the file it saves to. +func newTestJukeboxAt(t *testing.T) (*Jukebox, string) { + t.Helper() + path := filepath.Join(t.TempDir(), JukeboxFileName) + j := loadJukeboxFile(path) + t.Cleanup(func() { _ = j.Close() }) // stop the waiting write before TempDir cleanup + return j, path +} + func TestJukeboxRoundTrip(t *testing.T) { - j := newTestJukebox(t) + j, path := newTestJukeboxAt(t) if !j.AddPlaylist("Battle Themes") { t.Fatal("AddPlaylist failed") } @@ -29,7 +36,7 @@ func TestJukeboxRoundTrip(t *testing.T) { t.Fatalf("Flush: %v", err) } - got := loadJukeboxFile(j.path).Playlists() + got := loadJukeboxFile(path).Playlists() if len(got) != 1 || got[0].Name != "Battle Themes" || len(got[0].Entries) != 2 { t.Fatalf("reloaded = %+v", got) } @@ -45,7 +52,7 @@ func TestJukeboxRoundTrip(t *testing.T) { // (sanitizePlaylists on the load path must carry Fav through, else stars vanish // on restart.) func TestJukeboxFavRoundTrip(t *testing.T) { - j := newTestJukebox(t) + j, path := newTestJukeboxAt(t) j.AddPlaylist("P") j.AddEntry(0, "Starred", "https://youtu.be/a") j.AddEntry(0, "Plain", "https://youtu.be/b") @@ -53,7 +60,7 @@ func TestJukeboxFavRoundTrip(t *testing.T) { if err := j.Flush(); err != nil { t.Fatalf("Flush: %v", err) } - got := loadJukeboxFile(j.path).Playlists() + got := loadJukeboxFile(path).Playlists() if len(got) != 1 || len(got[0].Entries) != 2 { t.Fatalf("reloaded = %+v", got) } @@ -68,7 +75,7 @@ func TestJukeboxFavRoundTrip(t *testing.T) { if err := j.Flush(); err != nil { t.Fatalf("Flush: %v", err) } - if loadJukeboxFile(j.path).Playlists()[0].Entries[0].Fav { + if loadJukeboxFile(path).Playlists()[0].Entries[0].Fav { t.Error("unstar should persist") } } diff --git a/internal/config/notebook.go b/internal/config/notebook.go index 05315fe8..f0643ca9 100644 --- a/internal/config/notebook.go +++ b/internal/config/notebook.go @@ -11,6 +11,8 @@ import ( "strings" "sync" "time" + + "github.com/SyntaxNyah/AsyncAO/internal/saver" ) const ( @@ -26,12 +28,11 @@ const ( notebookKeyMax = 48 ) -// Notebook is safe for concurrent use; the flush goroutine is the only disk writer. +// Notebook is safe for concurrent use; its saver is the only disk writer. type Notebook struct { + *saver.Saver mu sync.Mutex - path string lines []string - timer *time.Timer // rev bumps on every mutation so the UI can cache its Lines() snapshot instead of copying per frame. rev int64 } @@ -43,16 +44,13 @@ func (n *Notebook) Rev() int64 { return n.rev } -// Clear also stops the pending flush, which would otherwise recreate the file WipeNotebooks deletes. +// Clear also drops the waiting write, which would otherwise recreate the file WipeNotebooks deletes. func (n *Notebook) Clear() { n.mu.Lock() n.lines = nil - if n.timer != nil { - n.timer.Stop() - n.timer = nil - } n.rev++ n.mu.Unlock() + n.Discard() } // notebookJSON is the on-disk shape. @@ -111,7 +109,8 @@ func LoadNotebook(serverKey string) (*Notebook, error) { // loadNotebookFile treats an absent or corrupt file as a fresh notebook. func loadNotebookFile(path string) *Notebook { - n := &Notebook{path: path} + n := &Notebook{} + n.Saver = saver.New(path, notebookSaveDelay, n.encode) data, err := os.ReadFile(path) if err != nil { return n @@ -141,7 +140,7 @@ func (n *Notebook) Add(line string) { n.lines = n.lines[len(n.lines)-notebookLineCap:] } n.rev++ - n.flushSoonLocked() + n.Changed() n.mu.Unlock() } @@ -151,7 +150,7 @@ func (n *Notebook) Remove(i int) { if i >= 0 && i < len(n.lines) { n.lines = append(n.lines[:i], n.lines[i+1:]...) n.rev++ - n.flushSoonLocked() + n.Changed() } n.mu.Unlock() } @@ -172,41 +171,10 @@ func (n *Notebook) Len() int { return len(n.lines) } -// flushSoonLocked rearms the debounce timer; the caller holds n.mu. -func (n *Notebook) flushSoonLocked() { - if n.timer != nil { - n.timer.Stop() - } - n.timer = time.AfterFunc(notebookSaveDelay, func() { _ = n.Flush() }) -} - -// Flush writes atomically (tmp + rename); also called on disconnect so nothing rides only on the debounce. -func (n *Notebook) Flush() error { +// encode snapshots the pins for the saver. +func (n *Notebook) encode() ([]byte, error) { n.mu.Lock() snapshot := notebookJSON{Lines: append([]string(nil), n.lines...)} - path := n.path n.mu.Unlock() - - data, err := json.MarshalIndent(snapshot, jsonMarshalPrefix, jsonMarshalIndent) - if err != nil { - return err - } - if err := os.MkdirAll(filepath.Dir(path), prefsDirPerm); err != nil { - return err - } - tmp, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".*.tmp") - if err != nil { - return err - } - tmpName := tmp.Name() - if _, err := tmp.Write(data); err != nil { - tmp.Close() - os.Remove(tmpName) - return err - } - if err := tmp.Close(); err != nil { - os.Remove(tmpName) - return err - } - return os.Rename(tmpName, path) + return json.MarshalIndent(snapshot, jsonMarshalPrefix, jsonMarshalIndent) } diff --git a/internal/config/notebook_test.go b/internal/config/notebook_test.go index 8a337559..0721ad2e 100644 --- a/internal/config/notebook_test.go +++ b/internal/config/notebook_test.go @@ -10,7 +10,7 @@ import ( // atomic flush, and reload from disk. func TestNotebookRoundTrip(t *testing.T) { path := filepath.Join(t.TempDir(), "nb.json") - nb := &Notebook{path: path} + nb := loadNotebookFile(path) nb.Add(" first pin ") nb.Add(strings.Repeat("x", notebookLineMax+100)) // truncates @@ -33,7 +33,7 @@ func TestNotebookRoundTrip(t *testing.T) { // TestNotebookCap pins the bound: the oldest pins fall off past the cap. func TestNotebookCap(t *testing.T) { - nb := &Notebook{path: filepath.Join(t.TempDir(), "nb.json")} + nb := loadNotebookFile(filepath.Join(t.TempDir(), "nb.json")) for i := 0; i < notebookLineCap+50; i++ { nb.Add(strings.Repeat("a", 4) + string(rune('0'+i%10))) } @@ -44,7 +44,7 @@ func TestNotebookCap(t *testing.T) { // TestNotebookClear pins the Wipe-everything path: Clear empties the notebook. func TestNotebookClear(t *testing.T) { - nb := &Notebook{path: filepath.Join(t.TempDir(), "nb.json")} + nb := loadNotebookFile(filepath.Join(t.TempDir(), "nb.json")) nb.Add("a pin") nb.Add("another") nb.Clear() diff --git a/internal/config/preferences.go b/internal/config/preferences.go index d352c539..10483ec9 100644 --- a/internal/config/preferences.go +++ b/internal/config/preferences.go @@ -20,6 +20,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/helper/text" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" + "github.com/SyntaxNyah/AsyncAO/internal/saver" "github.com/SyntaxNyah/AsyncAO/internal/theme" ) @@ -1104,7 +1105,7 @@ func (p *AssetPreferences) SaveNow() error { if err != nil { return fmt.Errorf("config: marshaling preferences: %w", err) } - return atomicWriteFile(p.path, data, prefsFilePerm) + return saver.WriteFile(p.path, data) } // Close stops the saver and flushes; only the first call does work. @@ -1120,40 +1121,6 @@ func (p *AssetPreferences) Close() error { return err } -// atomicWriteFile writes a synced temp file and renames it over path, so readers never see a partial file. -func atomicWriteFile(path string, data []byte, perm os.FileMode) error { - dir := filepath.Dir(path) - if err := os.MkdirAll(dir, prefsDirPerm); err != nil { - return fmt.Errorf("config: creating %s: %w", dir, err) - } - tmp, err := os.CreateTemp(dir, prefsTmpPattern) - if err != nil { - return fmt.Errorf("config: creating temp file: %w", err) - } - tmpName := tmp.Name() - cleanup := func(err error) error { - tmp.Close() - os.Remove(tmpName) - return err - } - if _, err := tmp.Write(data); err != nil { - return cleanup(fmt.Errorf("config: writing %s: %w", tmpName, err)) - } - if err := tmp.Sync(); err != nil { - return cleanup(fmt.Errorf("config: syncing %s: %w", tmpName, err)) - } - if err := tmp.Close(); err != nil { - return cleanup(fmt.Errorf("config: closing %s: %w", tmpName, err)) - } - // Best effort: CreateTemp uses 0600; widen to perm where supported. - _ = os.Chmod(tmpName, perm) - if err := os.Rename(tmpName, path); err != nil { - os.Remove(tmpName) - return fmt.Errorf("config: replacing %s: %w", path, err) - } - return nil -} - // FormatGeneration changes on any probe-list mutation, so derived caches rebuild without holding locks. func (p *AssetPreferences) FormatGeneration() uint64 { return p.formatGen.Load() @@ -3250,25 +3217,7 @@ func (p *AssetPreferences) ImportSettings(srcPath string) error { if err := json.Unmarshal(data, &probe); err != nil { return fmt.Errorf("config: not a settings file: %w", err) } - dir := filepath.Dir(p.path) - if err := os.MkdirAll(dir, prefsDirPerm); err != nil { - return err - } - tmp, err := os.CreateTemp(dir, prefsTmpPattern) - if err != nil { - return err - } - tmpName := tmp.Name() - if _, err := tmp.Write(data); err != nil { - tmp.Close() - os.Remove(tmpName) - return err - } - if err := tmp.Close(); err != nil { - os.Remove(tmpName) - return err - } - if err := os.Rename(tmpName, p.path); err != nil { + if err := saver.WriteFile(p.path, data); err != nil { return err } // Freeze the saver so the live session can't write its old state over the import. diff --git a/internal/config/wardrobe.go b/internal/config/wardrobe.go index b9a9f2fd..e471466c 100644 --- a/internal/config/wardrobe.go +++ b/internal/config/wardrobe.go @@ -15,6 +15,7 @@ import ( "time" "github.com/SyntaxNyah/AsyncAO/internal/helper/text" + "github.com/SyntaxNyah/AsyncAO/internal/saver" ) const ( @@ -64,14 +65,13 @@ type WardrobeFolder struct { Image string `json:"image,omitempty"` } -// Wardrobe is safe for concurrent use; the flush goroutine is the only disk writer. Entry and folder order is the -// player's own order. +// Wardrobe is safe for concurrent use; its saver is the only disk writer. Entry and folder order is the player's own +// order. type Wardrobe struct { + *saver.Saver mu sync.Mutex - path string entries []WardrobeEntry folders []WardrobeFolder - timer *time.Timer // rev bumps on every change so the UI rebuilds its views only then. rev int64 } @@ -111,7 +111,8 @@ func LoadWardrobe(old *Settings) (*Wardrobe, error) { // OpenWardrobe is LoadWardrobe at an explicit path. A corrupt file opens empty and is not migrated again. func OpenWardrobe(path string, old *Settings) *Wardrobe { - w := &Wardrobe{path: path} + w := &Wardrobe{} + w.Saver = saver.New(path, wardrobeSaveDelay, w.encode) data, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { w.entries, w.folders = migrateWardrobe(old) @@ -559,40 +560,18 @@ func (w *Wardrobe) Clear() { w.touchLocked() } -// touchLocked bumps the revision and rearms the debounced flush; the caller holds w.mu. +// touchLocked bumps the revision and schedules a write; the caller holds w.mu. func (w *Wardrobe) touchLocked() { w.rev++ - if w.timer != nil { - w.timer.Stop() - } - w.timer = time.AfterFunc(wardrobeSaveDelay, func() { _ = w.Flush() }) + w.Changed() } -// Flush writes the file atomically; Close calls it so nothing waits only on the debounce. -func (w *Wardrobe) Flush() error { +// encode snapshots the Wardrobe for the saver. +func (w *Wardrobe) encode() ([]byte, error) { w.mu.Lock() snapshot := wardrobeJSON{Entries: cloneWardrobeEntries(w.entries), Folders: slices.Clone(w.folders)} - path := w.path - w.mu.Unlock() - if path == "" { - return nil - } - data, err := json.MarshalIndent(snapshot, jsonMarshalPrefix, jsonMarshalIndent) - if err != nil { - return err - } - return atomicWriteFile(path, data, prefsFilePerm) -} - -// Close stops the debounce timer and writes any pending change; the caller guards against nil. -func (w *Wardrobe) Close() error { - w.mu.Lock() - if w.timer != nil { - w.timer.Stop() - w.timer = nil - } w.mu.Unlock() - return w.Flush() + return json.MarshalIndent(snapshot, jsonMarshalPrefix, jsonMarshalIndent) } // WipeWardrobeImages deletes the folder images for Wipe everything. diff --git a/internal/saver/saver.go b/internal/saver/saver.go new file mode 100644 index 00000000..2064246c --- /dev/null +++ b/internal/saver/saver.go @@ -0,0 +1,120 @@ +// Package saver writes small files in the background: a change schedules one write a short while later, and a write +// replaces the file whole, so a reader never sees half of one. +package saver + +import ( + "fmt" + "os" + "path/filepath" + "sync" + "time" +) + +const ( + // FilePerm is the mode of a saved file. + FilePerm = 0o644 + // DirPerm is the mode of a folder made for one. + DirPerm = 0o755 +) + +// Saver writes one file a delay after the first change, off the caller's thread, so a burst of changes costs one write. +// The zero path saves nothing, for stores that live only in memory. +type Saver struct { + path string + delay time.Duration + encode func() ([]byte, error) + + // writing keeps writes in order, so an older snapshot never lands after a newer one. + writing sync.Mutex + + mu sync.Mutex + pending *time.Timer + closed bool +} + +// New saves to path what encode returns; encode runs on the saver's goroutine and must take its own snapshot. +func New(path string, delay time.Duration, encode func() ([]byte, error)) *Saver { + return &Saver{path: path, delay: delay, encode: encode} +} + +// Changed schedules a write, unless one is already waiting; it never blocks on the disk. +func (s *Saver) Changed() { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed || s.pending != nil || s.path == "" { + return + } + s.pending = time.AfterFunc(s.delay, func() { + s.mu.Lock() + s.pending = nil + s.mu.Unlock() + _ = s.Flush() + }) +} + +// Discard drops a waiting write, for a store whose file is about to be deleted. +func (s *Saver) Discard() { + s.mu.Lock() + defer s.mu.Unlock() + if s.pending != nil { + s.pending.Stop() + s.pending = nil + } +} + +// Flush writes now, on the caller's thread. +func (s *Saver) Flush() error { + if s.path == "" { + return nil + } + s.writing.Lock() + defer s.writing.Unlock() + data, err := s.encode() + if err != nil { + return err + } + return WriteFile(s.path, data) +} + +// Close drops the waiting write, writes once more and schedules nothing after. +func (s *Saver) Close() error { + s.mu.Lock() + s.closed = true + s.mu.Unlock() + s.Discard() + return s.Flush() +} + +// WriteFile replaces path with data through a synced temporary file in the same folder. +func WriteFile(path string, data []byte) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, DirPerm); err != nil { + return fmt.Errorf("saver: creating %s: %w", dir, err) + } + tmp, err := os.CreateTemp(dir, filepath.Base(path)+".*.tmp") + if err != nil { + return fmt.Errorf("saver: creating a temporary file: %w", err) + } + tmpName := tmp.Name() + fail := func(err error) error { + tmp.Close() + os.Remove(tmpName) + return err + } + if _, err := tmp.Write(data); err != nil { + return fail(fmt.Errorf("saver: writing %s: %w", tmpName, err)) + } + if err := tmp.Sync(); err != nil { + return fail(fmt.Errorf("saver: syncing %s: %w", tmpName, err)) + } + if err := tmp.Close(); err != nil { + return fail(fmt.Errorf("saver: closing %s: %w", tmpName, err)) + } + // CreateTemp makes the file 0600; widen it where the OS allows. + _ = os.Chmod(tmpName, FilePerm) + if err := os.Rename(tmpName, path); err != nil { + os.Remove(tmpName) + return fmt.Errorf("saver: replacing %s: %w", path, err) + } + return nil +} diff --git a/internal/saver/saver_test.go b/internal/saver/saver_test.go new file mode 100644 index 00000000..e6c7656e --- /dev/null +++ b/internal/saver/saver_test.go @@ -0,0 +1,125 @@ +package saver + +import ( + "os" + "path/filepath" + "strconv" + "sync/atomic" + "testing" + "time" +) + +const ( + testDelay = 20 * time.Millisecond + testTimeout = 2 * time.Second + burst = 50 +) + +// counter is a store whose encode counts its writes and saves its current value. +type counter struct { + value atomic.Int64 + writes atomic.Int64 +} + +func (c *counter) encode() ([]byte, error) { + c.writes.Add(1) + return []byte(strconv.FormatInt(c.value.Load(), 10)), nil +} + +func readBack(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(data) +} + +func waitFor(t *testing.T, cond func() bool) { + t.Helper() + deadline := time.Now().Add(testTimeout) + for !cond() { + if time.Now().After(deadline) { + t.Fatal("timed out") + } + time.Sleep(testDelay) + } +} + +func TestBurstOfChangesIsOneWriteOfTheLatestValue(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.json") + var c counter + s := New(path, testDelay, c.encode) + for i := range burst { + c.value.Store(int64(i)) + s.Changed() + } + waitFor(t, func() bool { return c.writes.Load() > 0 }) + time.Sleep(testDelay * 2) + if n := c.writes.Load(); n != 1 { + t.Errorf("%d writes, want 1", n) + } + if got := readBack(t, path); got != strconv.Itoa(burst-1) { + t.Errorf("file holds %q, want %d", got, burst-1) + } +} + +func TestCloseWritesAndSchedulesNothingAfter(t *testing.T) { + path := filepath.Join(t.TempDir(), "sub", "store.json") + var c counter + s := New(path, time.Hour, c.encode) + c.value.Store(burst) + s.Changed() + if err := s.Close(); err != nil { + t.Fatal(err) + } + if got := readBack(t, path); got != strconv.Itoa(burst) { + t.Errorf("file holds %q", got) + } + s.Changed() + time.Sleep(testDelay) + if n := c.writes.Load(); n != 1 { + t.Errorf("%d writes after Close, want 1", n) + } +} + +func TestDiscardDropsTheWaitingWrite(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.json") + var c counter + s := New(path, testDelay, c.encode) + s.Changed() + s.Discard() + time.Sleep(testDelay * 3) + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("file written after Discard: %v", err) + } +} + +func TestNoPathSavesNothing(t *testing.T) { + var c counter + s := New("", testDelay, c.encode) + s.Changed() + if err := s.Close(); err != nil { + t.Fatal(err) + } + if n := c.writes.Load(); n != 0 { + t.Errorf("%d writes without a path", n) + } +} + +func TestWriteFileReplacesAndLeavesNoTemporaryFiles(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "store.json") + for _, body := range []string{"first", "second"} { + if err := WriteFile(path, []byte(body)); err != nil { + t.Fatal(err) + } + } + if got := readBack(t, path); got != "second" { + t.Errorf("file holds %q", got) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 1 { + t.Errorf("folder holds %d files, want 1", len(entries)) + } +} From 0922248ddc06092925c6880982feddd57a04ba4e Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:13:25 +0100 Subject: [PATCH 17/43] media: ask the disk cache until its index is scanned Until the startup walk landed, the disk index answered no for every file, so anything asked for in that window was downloaded again though it sat in the cache. Before the first scan the disk source now answers unknown for a file it hasn't indexed, so a disk worker tries it before the web. Co-Authored-By: Claude Opus 5.5 --- internal/media/sources.go | 12 ++++++++-- internal/media/sources_test.go | 42 +++++++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/internal/media/sources.go b/internal/media/sources.go index f0a8ba0b..a595c749 100644 --- a/internal/media/sources.go +++ b/internal/media/sources.go @@ -15,10 +15,13 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/network" ) -// DiskSource answers from an index of the cache's file names, so a miss never touches the disk. +// DiskSource answers from an index of the cache's file names, so once the index is scanned a miss never touches the +// disk. type DiskSource struct { disk *cache.DiskCache index map[string]struct{} + // scanned is set by the first Adopt; before it, a file outside the index may still be on disk. + scanned bool } // NewDiskSource starts with an empty index; Adopt fills it from ScanDiskIndex. @@ -49,6 +52,7 @@ func (s *DiskSource) Adopt(keys []string) { for _, k := range keys { s.add(k) } + s.scanned = true } // Keep queues bytes for the disk writer and indexes them; a dropped write heals through a failed read. @@ -65,11 +69,15 @@ func (s *DiskSource) add(key string) { s.index[key] = struct{}{} } -// Has answers from the index. +// Has answers from the index; until the first scan lands, a file outside it is Unknown, so the disk is asked before +// the web. func (s *DiskSource) Has(f File) Answer { if _, ok := s.index[cache.Key(string(f))]; ok { return Yes } + if !s.scanned { + return Unknown + } return No } diff --git a/internal/media/sources_test.go b/internal/media/sources_test.go index dfcfa4dd..665083d4 100644 --- a/internal/media/sources_test.go +++ b/internal/media/sources_test.go @@ -317,8 +317,12 @@ func TestDiskIndexHealsAndScans(t *testing.T) { } defer disk.Close() src := NewDiskSource(disk) + if src.Has("http://x/a") != Unknown { + t.Fatal("before the first scan the disk must still be asked") + } + src.Adopt(nil) if src.Has("http://x/a") != No { - t.Fatal("empty index answered yes") + t.Fatal("a scanned empty index answered other than no") } src.Keep("http://x/a", []byte("data")) if src.Has("http://x/a") != Yes { @@ -342,6 +346,42 @@ func TestDiskIndexHealsAndScans(t *testing.T) { } } +// Before the disk index is scanned, a cached file is read from the disk rather than downloaded again. +func TestCachedFileBeforeTheScanComesFromDisk(t *testing.T) { + disk, err := cache.NewDiskCache(t.TempDir(), 0) + if err != nil { + t.Fatal(err) + } + defer disk.Close() + const cached = testOrigin + "c/e.webp" + disk.Put(cached, []byte("x")) + waitUntil(t, func() bool { _, ok := disk.Get(cached); return ok }) + + fetch := &fakeFetcher{files: map[string][]byte{cached: []byte("x")}} + builder := NewCandidateBuilder() + remote := NewRemoteSource(context.Background(), fetch, testShortTTL, time.Now) + diskP := NewPool("disk", testWorkers, 0) + net := NewPool("network", testRemotePool, 0) + compute := NewPool("compute", testWorkers, 1) + m := NewManager(Config{ + Chains: map[Place]*Chain{PlaceServer: NewChain( + Entry{Source: NewDiskSource(disk), Pool: diskP}, Entry{Source: remote, Pool: net})}, + Formats: map[Kind]Format{KindImage: &fakeFormat{}}, + Candidates: builder.Build, + Compute: compute, + }) + defer func() { m.Close(); diskP.Close(); net.Close(); compute.Close() }() + + a := m.Get(sprite("c/e"), Now, 0) + waitFinal(t, a) + if !a.Ready() { + t.Fatalf("state %d err %v", a.State(), a.Err()) + } + if asked := fetch.askedFor(); len(asked) != 0 { + t.Errorf("downloaded %v though the disk held it", asked) + } +} + func TestScanOfAMissingFolderIsEmpty(t *testing.T) { keys, err := ScanDiskIndex(filepath.Join(t.TempDir(), "nothing")) if err != nil || len(keys) != 0 { From afe956d58f122325b2f46991387b7ace30a14f04 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:19:44 +0100 Subject: [PATCH 18/43] media, assets: keep learned formats and winners in learned.json The media system relearned every host's formats each session, and its winner table (the file each key was last found as) started empty, so the first messages on a host without extensions.json paid the full format walk again. media.Remember and media.Recall copy both tables out of and into a Manager and its CandidateBuilder on the Manager's goroutine; Manager.Call waits for that from another goroutine. The assets bridge reads learned.json on a disk worker at start, schedules a save on each find, and writes it on close before the media system stops. A write before the file is read is refused, so an early find can't replace it with one session's worth. Saved counts are halved on load, so a host that changes formats is relearned within a few sessions; at most 256 origins are kept. The saver now writes on Close only when something changed, so an idle session doesn't rewrite the file, and Discard forgets the unsaved change. Co-Authored-By: Claude Opus 5.5 --- cmd/asyncao/main.go | 21 ++++-- internal/assets/learned_test.go | 58 +++++++++++++++ internal/assets/manager.go | 5 ++ internal/assets/manager_test.go | 19 +++-- internal/assets/mediabridge.go | 71 +++++++++++++++++- internal/config/preferences.go | 12 +++ internal/media/candidates.go | 3 +- internal/media/learned.go | 125 ++++++++++++++++++++++++++++++++ internal/media/learned_test.go | 70 ++++++++++++++++++ internal/saver/saver.go | 26 ++++++- internal/saver/saver_test.go | 11 +++ 11 files changed, 400 insertions(+), 21 deletions(-) create mode 100644 internal/assets/learned_test.go create mode 100644 internal/media/learned.go create mode 100644 internal/media/learned_test.go diff --git a/cmd/asyncao/main.go b/cmd/asyncao/main.go index dc61ca0a..01262a05 100644 --- a/cmd/asyncao/main.go +++ b/cmd/asyncao/main.go @@ -253,15 +253,20 @@ func run(rt *host.Runtime, serverURL, masterURL string, gpuOpts host.GraphicsOpt // --- asset pipeline --- // Packages beside the executable; the UI appends them after the manual mounts, so an explicit folder wins. autoMounts := config.DiscoverPackages(config.ExecutableDir()) + learnedPath, err := config.LearnedPath() + if err != nil { + log.Printf("learned formats won't be kept: %v", err) + } manager := assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: prefs, - T2: t2, - Disk: disk, - Source: client, - Decoder: decoder, - T1Contains: store.ContainsAnimated, - T1Failed: store.FailedRecently, + Resolver: resolver, + Prefs: prefs, + T2: t2, + Disk: disk, + Source: client, + Decoder: decoder, + T1Contains: store.ContainsAnimated, + T1Failed: store.FailedRecently, + LearnedPath: learnedPath, }) defer manager.CloseMedia() // 0 = unlimited. diff --git a/internal/assets/learned_test.go b/internal/assets/learned_test.go new file mode 100644 index 00000000..e58ebb92 --- /dev/null +++ b/internal/assets/learned_test.go @@ -0,0 +1,58 @@ +package assets + +import ( + "image/color" + "os" + "path/filepath" + "testing" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/netproxy" + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +// waitRecalled waits until a Manager has read its learned.json. +func waitRecalled(t *testing.T, m *Manager) { + t.Helper() + deadline := time.Now().Add(managerWait) + for { + recalled := false + m.bridge.media.Call(func() { recalled = m.bridge.recalled }) + if recalled { + return + } + if time.Now().After(deadline) { + t.Fatal("learned.json never read") + } + time.Sleep(time.Millisecond) + } +} + +// A host learned in one session is asked in its format first in the next. +func TestLearnedFormatOutlivesTheSession(t *testing.T) { + const side = 4 + png := encodePNG(t, side, side, color.White) + cs := newCountingServer(t, map[string][]byte{ + "/characters/a/(a)x.png": png, + "/characters/a/(a)y.png": png, + }) + learned := filepath.Join(t.TempDir(), "learned.json") + + first := newRigAt(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false, learned) + waitRecalled(t, first.manager) + first.manager.Prefetch(cs.srv.URL+"/characters/a/(a)x", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + waitDecoded(t, first.manager).Asset.Release() + first.manager.CloseMedia() + if _, err := os.Stat(learned); err != nil { + t.Fatalf("learned.json not written: %v", err) + } + + next := newRigAt(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false, learned) + waitRecalled(t, next.manager) + before := cs.total() + next.manager.Prefetch(cs.srv.URL+"/characters/a/(a)y", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + waitDecoded(t, next.manager).Asset.Release() + if n := cs.total() - before; n != 1 { + t.Errorf("the next session needed %d requests, want 1", n) + } +} diff --git a/internal/assets/manager.go b/internal/assets/manager.go index eb95fb60..945830d1 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -76,6 +76,8 @@ type Manager struct { disk *cache.DiskCache client Fetcher decoder *DecoderPool + // learnedPath is where the media system's learned formats and winners are kept between sessions. + learnedPath string // t1Contains reports whether a texture is uploaded; pass the upload's key: base if probed, full URL if exact. t1Contains func(url string) bool @@ -199,6 +201,8 @@ type ManagerDeps struct { Decoder *DecoderPool T1Contains func(url string) bool T1Failed func(base string) bool + // LearnedPath is the learned.json the media system's learned formats and winners are kept in; "" keeps none. + LearnedPath string } // NewManager builds the Manager and starts its media system; CloseMedia stops it. @@ -212,6 +216,7 @@ func NewManager(deps ManagerDeps) *Manager { decoder: deps.Decoder, t1Contains: deps.T1Contains, t1Failed: deps.T1Failed, + learnedPath: deps.LearnedPath, decodedCh: make(chan DecodedAsset, decodedChanCap), audioCh: make(chan AudioAsset, audioChanCap), warningCh: make(chan Warning, warningChanCap), diff --git a/internal/assets/manager_test.go b/internal/assets/manager_test.go index c2ed8702..a958fa12 100644 --- a/internal/assets/manager_test.go +++ b/internal/assets/manager_test.go @@ -32,6 +32,12 @@ type testRig struct { // newRig builds a Manager on source; localMode mounts a LocalFetcher source's folders, as "only use my folders" does. func newRig(tb testing.TB, source Fetcher, localMode bool) *testRig { + tb.Helper() + return newRigAt(tb, source, localMode, "") +} + +// newRigAt is newRig keeping learned formats and winners in learnedPath. +func newRigAt(tb testing.TB, source Fetcher, localMode bool, learnedPath string) *testRig { tb.Helper() prefs := newTestPrefs(tb) resolver := NewResolver(prefs) @@ -48,12 +54,13 @@ func newRig(tb testing.TB, source Fetcher, localMode bool) *testRig { tb.Cleanup(decoder.Close) m := NewManager(ManagerDeps{ - Resolver: resolver, - Prefs: prefs, - T2: t2, - Disk: disk, - Source: source, - Decoder: decoder, + Resolver: resolver, + Prefs: prefs, + T2: t2, + Disk: disk, + Source: source, + Decoder: decoder, + LearnedPath: learnedPath, }) tb.Cleanup(m.CloseMedia) if lf, ok := source.(*LocalFetcher); ok && localMode { diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index 8b86f264..6f055803 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -2,7 +2,9 @@ package assets import ( "context" + "encoding/json" "errors" + "os" "slices" "strings" "sync" @@ -13,6 +15,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/saver" ) const ( @@ -22,8 +25,16 @@ const ( mediaDiskKept = 2 mediaNetworkWorkers = 32 mediaComputeKept = 1 + // learnedSaveDelay is how long after a find learned.json is written, so a busy room writes it once. + learnedSaveDelay = 10 * time.Second ) +// errLearnedNotRecalled refuses a write before the saved file was read, which would replace it with this session alone. +var errLearnedNotRecalled = errors.New("assets: learned.json not read yet") + +// errMediaStopped refuses a write after the media system stopped. +var errMediaStopped = errors.New("assets: media system stopped") + // mediaBridge runs the Manager's requests on internal/media, so every caller moves at once; it goes when callers use media directly. type mediaBridge struct { m *Manager @@ -42,6 +53,11 @@ type mediaBridge struct { hostLists sync.Map hostListsGen atomic.Uint64 pin *sceneryPin + // learned keeps learned.json. recalled and foundEarly are the Manager's goroutine's: whether the saved file was + // read, and whether something was found before it was. + learned *saver.Saver + recalled bool + foundEarly bool } func newMediaBridge(m *Manager) *mediaBridge { @@ -54,7 +70,8 @@ func newMediaBridge(m *Manager) *mediaBridge { pin: newSceneryPin(), } b.folders = newBridgeFolders(m) - cfg := media.Config{Candidates: b.builder.Build, AllFormats: media.EveryFormat, Found: b.builder.Found, + b.learned = saver.New(m.learnedPath, learnedSaveDelay, b.encodeLearned) + cfg := media.Config{Candidates: b.builder.Build, AllFormats: media.EveryFormat, Found: b.found, Finished: b.finished, Compute: b.compute} b.remote = media.NewRemoteSource(ctx, bridgeFetcher{m}, media.DefaultMissingTTL, time.Now) cfg.Chains = map[media.Place]*media.Chain{media.PlaceServer: media.NewChain( @@ -66,9 +83,60 @@ func newMediaBridge(m *Manager) *mediaBridge { cfg.Formats = map[media.Kind]media.Format{media.KindImage: bridgeImage{b}, media.KindSound: bridgeSound{b}} b.media = media.NewManager(cfg) b.scanDisk() + b.recallLearned() return b } +// found learns the format a key turned up in, and schedules a save. +func (b *mediaBridge) found(k media.Key, f media.File) { + b.builder.Found(k, f) + if !b.recalled { + b.foundEarly = true + } + b.learned.Changed() +} + +// recallLearned reads learned.json on a disk worker and adds it to what this session knows. +func (b *mediaBridge) recallLearned() { + path := b.m.learnedPath + b.media.Run(b.diskP, media.Later, func() any { + var l media.Learned + if path == "" { + return l + } + if data, err := os.ReadFile(path); err == nil { + _ = json.Unmarshal(data, &l) // a damaged file is a fresh start + } + return l + }, func(v any) { + media.Recall(b.media, b.builder, v.(media.Learned)) + b.recalled = true + if b.foundEarly { + b.learned.Changed() + } + }) +} + +// encodeLearned snapshots the learned formats and winners on the Manager's goroutine for the saver. +func (b *mediaBridge) encodeLearned() ([]byte, error) { + var l media.Learned + var err error + ran := b.media.Call(func() { + if !b.recalled { + err = errLearnedNotRecalled + return + } + l = media.Remember(b.media, b.builder) + }) + if !ran { + return nil, errMediaStopped + } + if err != nil { + return nil, err + } + return json.Marshal(l) +} + // scanDisk fills the disk index; until it lands, a cached file is fetched again, which is only slower. func (b *mediaBridge) scanDisk() { b.media.Run(b.diskP, media.Later, func() any { @@ -325,6 +393,7 @@ func (m *Manager) CloseMedia() { b := m.bridge b.closing.Do(func() { b.cancel() + _ = b.learned.Close() // before the media system stops, as the snapshot is taken on its goroutine b.media.Close() // A worker blocked delivering to a channel nobody drains at exit must not hold the process open. go func() { diff --git a/internal/config/preferences.go b/internal/config/preferences.go index 10483ec9..6b9baa34 100644 --- a/internal/config/preferences.go +++ b/internal/config/preferences.go @@ -799,6 +799,18 @@ func DefaultPath() (string, error) { return filepath.Join(dir, PrefsFileName), nil } +// LearnedFileName holds the media system's learned formats and winners, beside the prefs file. +const LearnedFileName = "learned.json" + +// LearnedPath is learned.json beside the prefs file. +func LearnedPath() (string, error) { + base, err := DefaultPath() + if err != nil { + return "", err + } + return filepath.Join(filepath.Dir(base), LearnedFileName), nil +} + // New loads preferences and starts the saver; an error reports a bad file replaced by defaults. Close flushes. func New(path string) (*AssetPreferences, error) { return newWithDebounce(path, DefaultSaveDebounce) diff --git a/internal/media/candidates.go b/internal/media/candidates.go index bc4034fb..9f933f92 100644 --- a/internal/media/candidates.go +++ b/internal/media/candidates.go @@ -228,8 +228,7 @@ func cleanExts(in []string) []string { if strings.HasPrefix(e, config.ExtWebP+".") { e = config.ExtWebP } - known := slices.Contains(defaultImageOrder, e) || slices.Contains(defaultAudioOrder, e) - if known && !slices.Contains(out, e) && len(out) < manifestExtCap { + if knownExt(e) && !slices.Contains(out, e) && len(out) < manifestExtCap { out = append(out, e) } } diff --git a/internal/media/learned.go b/internal/media/learned.go new file mode 100644 index 00000000..1bed84be --- /dev/null +++ b/internal/media/learned.go @@ -0,0 +1,125 @@ +package media + +import ( + "maps" + "slices" +) + +const ( + // LearnedVersion changes whenever Key, Class or Place change meaning; a saved file of another version is ignored. + LearnedVersion = 1 + // learnedOriginsCap bounds the origins kept between sessions; the ones with the fewest finds go first. + learnedOriginsCap = 256 +) + +// Learned is what searches taught a Manager and its CandidateBuilder, kept between sessions. +type Learned struct { + Version int `json:"version"` + // Formats counts, per origin and class, how often each format was found. + Formats map[string]map[Class]map[string]int `json:"formats"` + Winners []Winner `json:"winners"` +} + +// Winner is the file a key was last found as. +type Winner struct { + Key Key `json:"key"` + File File `json:"file"` +} + +// Remember copies what m and b have learned; call it on the Manager's goroutine (Do or Call). +func Remember(m *Manager, b *CandidateBuilder) Learned { + l := Learned{Version: LearnedVersion, Formats: map[string]map[Class]map[string]int{}} + for origin, h := range b.origins { + if len(h.learned) == 0 { + continue + } + classes := make(map[Class]map[string]int, len(h.learned)) + for class, counts := range h.learned { + classes[class] = maps.Clone(counts) + } + l.Formats[origin] = classes + } + if len(l.Formats) > learnedOriginsCap { + origins := slices.SortedFunc(maps.Keys(l.Formats), func(x, y string) int { + return finds(l.Formats[y]) - finds(l.Formats[x]) + }) + for _, origin := range origins[learnedOriginsCap:] { + delete(l.Formats, origin) + } + } + l.Winners = make([]Winner, 0, len(m.winners)) + for k, f := range m.winners { + l.Winners = append(l.Winners, Winner{Key: k, File: f}) + } + return l +} + +// finds totals one origin's counts. +func finds(classes map[Class]map[string]int) int { + n := 0 + for _, counts := range classes { + for _, c := range counts { + n += c + } + } + return n +} + +// Recall adds a saved Learned to what m and b know; call it on the Manager's goroutine. Saved counts are halved, so a +// host that changed its formats is relearned in a few sessions, and what this session already learned stays. +func Recall(m *Manager, b *CandidateBuilder, l Learned) { + if l.Version != LearnedVersion { + return + } + for origin, classes := range l.Formats { + for class, counts := range classes { + if class == ClassExact || class > ClassBlips { + continue + } + for ext, c := range counts { + if c <= 0 || !knownExt(ext) { + continue + } + h := b.hints(origin) + if h.learned[class] == nil { + h.learned[class] = map[string]int{} + } + h.learned[class][ext] += (c + 1) / 2 + } + } + } + for _, w := range l.Winners { + if len(m.winners) >= winnersCap { + break + } + if _, ok := m.winners[w.Key]; !ok && w.Key.Path != "" && w.File != "" { + m.winners[w.Key] = w.File + } + } +} + +// knownExt reports whether ext is a format some decoder reads. +func knownExt(ext string) bool { + return slices.Contains(defaultImageOrder, ext) || slices.Contains(defaultAudioOrder, ext) +} + +// Call runs fn on the Manager's goroutine and waits for it; false when the Manager stopped first. Never call it from +// the Manager's goroutine. +func (m *Manager) Call(fn func()) bool { + done := make(chan struct{}) + m.Do(func() { + fn() + close(done) + }) + select { + case <-done: + return true + case <-m.stopped: + select { + case <-done: + return true + default: + return false + } + } +} diff --git a/internal/media/learned_test.go b/internal/media/learned_test.go new file mode 100644 index 00000000..b6795a58 --- /dev/null +++ b/internal/media/learned_test.go @@ -0,0 +1,70 @@ +package media + +import ( + "encoding/json" + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/config" +) + +// rememberJSON is what a session would write to learned.json. +func rememberJSON(t *testing.T, r *remoteRig) []byte { + t.Helper() + var l Learned + if !r.m.Call(func() { l = Remember(r.m, r.builder) }) { + t.Fatal("manager stopped") + } + data, err := json.Marshal(l) + if err != nil { + t.Fatal(err) + } + return data +} + +// recallJSON is what the next session does with it. +func recallJSON(t *testing.T, r *remoteRig, data []byte) { + t.Helper() + var l Learned + if err := json.Unmarshal(data, &l); err != nil { + t.Fatal(err) + } + r.m.Call(func() { Recall(r.m, r.builder, l) }) +} + +func TestNextSessionAsksTheLearnedFormatAndWinnerFirst(t *testing.T) { + files := map[string][]byte{ + testOrigin + "a" + config.ExtPNG: []byte("x"), + testOrigin + "b" + config.ExtPNG: []byte("y"), + } + first := newRemoteRig(t, files) + waitFinal(t, first.m.Get(sprite("a"), Now, 0)) + saved := rememberJSON(t, first) + + next := newRemoteRig(t, files) + recallJSON(t, next, saved) + waitFinal(t, next.m.Get(sprite("a"), Now, 0)) + waitFinal(t, next.m.Get(sprite("b"), Now, 0)) + want := []string{testOrigin + "a" + config.ExtPNG, testOrigin + "b" + config.ExtPNG} + if asked := next.fetch.askedFor(); len(asked) != len(want) || asked[0] != want[0] || asked[1] != want[1] { + t.Fatalf("asked %v, want %v", asked, want) + } +} + +func TestRecallIgnoresAnotherVersionAndUnknownFormats(t *testing.T) { + r := newRemoteRig(t, nil) + recallJSON(t, r, []byte(`{"version":999,"formats":{"`+testOrigin+`":{"2":{".png":50}}}}`)) + recallJSON(t, r, []byte(`{"version":1,"formats":{"`+testOrigin+`":{"2":{".exe":50}}}}`)) + var l Learned + r.m.Call(func() { l = Remember(r.m, r.builder) }) + if len(l.Formats) != 0 { + t.Fatalf("recalled %v", l.Formats) + } +} + +func TestCallReportsAStoppedManager(t *testing.T) { + r := newRemoteRig(t, nil) + r.m.Close() + if r.m.Call(func() {}) { + t.Fatal("Call ran on a stopped manager") + } +} diff --git a/internal/saver/saver.go b/internal/saver/saver.go index 2064246c..5c44923c 100644 --- a/internal/saver/saver.go +++ b/internal/saver/saver.go @@ -30,6 +30,8 @@ type Saver struct { mu sync.Mutex pending *time.Timer closed bool + // changed is set by Changed and cleared by a write, so Close writes only what isn't saved yet. + changed bool } // New saves to path what encode returns; encode runs on the saver's goroutine and must take its own snapshot. @@ -41,6 +43,7 @@ func New(path string, delay time.Duration, encode func() ([]byte, error)) *Saver func (s *Saver) Changed() { s.mu.Lock() defer s.mu.Unlock() + s.changed = true if s.closed || s.pending != nil || s.path == "" { return } @@ -52,10 +55,11 @@ func (s *Saver) Changed() { }) } -// Discard drops a waiting write, for a store whose file is about to be deleted. +// Discard drops the unsaved change and its waiting write, for a store whose file is about to be deleted. func (s *Saver) Discard() { s.mu.Lock() defer s.mu.Unlock() + s.changed = false if s.pending != nil { s.pending.Stop() s.pending = nil @@ -69,19 +73,33 @@ func (s *Saver) Flush() error { } s.writing.Lock() defer s.writing.Unlock() + s.setChanged(false) data, err := s.encode() + if err == nil { + err = WriteFile(s.path, data) + } if err != nil { - return err + s.setChanged(true) } - return WriteFile(s.path, data) + return err +} + +func (s *Saver) setChanged(v bool) { + s.mu.Lock() + s.changed = v + s.mu.Unlock() } -// Close drops the waiting write, writes once more and schedules nothing after. +// Close drops the waiting write, writes what isn't saved yet and schedules nothing after. func (s *Saver) Close() error { s.mu.Lock() s.closed = true + changed := s.changed s.mu.Unlock() s.Discard() + if !changed { + return nil + } return s.Flush() } diff --git a/internal/saver/saver_test.go b/internal/saver/saver_test.go index e6c7656e..2443b773 100644 --- a/internal/saver/saver_test.go +++ b/internal/saver/saver_test.go @@ -83,6 +83,17 @@ func TestCloseWritesAndSchedulesNothingAfter(t *testing.T) { } } +func TestCloseWithoutAChangeWritesNothing(t *testing.T) { + var c counter + s := New(filepath.Join(t.TempDir(), "store.json"), testDelay, c.encode) + if err := s.Close(); err != nil { + t.Fatal(err) + } + if n := c.writes.Load(); n != 0 { + t.Errorf("%d writes with nothing changed", n) + } +} + func TestDiscardDropsTheWaitingWrite(t *testing.T) { path := filepath.Join(t.TempDir(), "store.json") var c counter From 9f3157a7a61bfb07cab804afad933b4bc5e32bd5 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:39:47 +0100 Subject: [PATCH 19/43] assets, config, ui: one learned-formats table; remove the format overrides The old resolver kept a second learned table in prefs that only archive, export and replay read, and Settings -> Formats edited per-server pins, an auto-detect toggle, per-type orders and fallback chains that live play has ignored since it moved to the media system. Removed: assets.Resolver and its manifest seeding, prefs.LearnedFormats, the format override settings (assetTypes, extProfiles, formatAutoDetect, globalFallbacksEnabled) with no migration, the Formats tab, and the learned formats Export/Import buttons. Old prefs files drop those keys on their next save. The raw walks (archive, export, content report) ask the media builder for their candidates and teach it what they find; a replay archive's recorded formats go in through AllowFormats. extensions.json is always read on connect; the official vanilla server, which publishes none, gets its built-in list through AllowManifest. Settings -> Cache -> Learned formats counts, clears and fixes from learned.json, as does the factory reset. Goldens regenerated by name with the removed keys gone; the frozen SHA constants were updated to match. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 +- cmd/asyncao-cache/main.go | 12 +- cmd/asyncao/main.go | 8 - docs/FEATURES.md | 21 +- docs/RESTRUCTURING_PLAN.md | 6 +- docs/user/asset-preferences.md | 36 +- internal/archive/archive.go | 9 +- internal/archive/archive_test.go | 19 +- internal/assets/folders_test.go | 19 +- internal/assets/fuzz_test.go | 43 -- internal/assets/manager.go | 71 +- internal/assets/manager_test.go | 29 +- internal/assets/manifest.go | 132 ---- internal/assets/manifest_test.go | 155 ---- internal/assets/mediabridge.go | 61 +- internal/assets/mediabridge_test.go | 15 +- internal/assets/mixedfleet_test.go | 148 ---- internal/assets/musicexact_test.go | 38 - internal/assets/notify_test.go | 2 +- internal/assets/resolver.go | 292 ------- internal/assets/resolver_test.go | 288 ------- internal/config/collection_helpers.go | 13 - internal/config/collection_helpers_test.go | 18 - internal/config/defaults.go | 58 -- internal/config/preferences.go | 308 -------- internal/config/preferences_test.go | 366 +-------- internal/config/prefs_golden_freeze_test.go | 10 +- internal/config/prefs_setter_map_test.go | 1 - internal/config/prefs_swap.go | 16 - internal/config/qol_prefs_test.go | 16 - internal/config/settings.go | 5 - internal/config/settings_clone.go | 378 ++++------ internal/config/settings_clone_test.go | 3 - internal/config/testdata/load_golden.json | 797 +++++++++----------- internal/config/testdata/prefs_default.json | 72 -- internal/config/testdata/prefs_golden.json | 432 +++++------ internal/courtroom/bgfallback_test.go | 2 +- internal/courtroom/courtroom_test.go | 3 +- internal/courtroom/messageneeds_test.go | 2 +- internal/media/candidates.go | 18 + internal/media/manifest_fuzz_test.go | 31 + internal/metrics/profiler.go | 1 - internal/render/pump_test.go | 13 +- internal/saver/saver_test.go | 9 +- internal/ui/app.go | 5 +- internal/ui/app_connect.go | 81 +- internal/ui/apptypes.go | 4 +- internal/ui/conclusivemiss_ui_test.go | 18 +- internal/ui/contentjob.go | 31 +- internal/ui/contentjob_test.go | 31 +- internal/ui/contentseed_test.go | 49 +- internal/ui/debugpanel.go | 7 +- internal/ui/deskmissing_relay_test.go | 4 - internal/ui/emotepreviewfollow_test.go | 12 +- internal/ui/exportstall_test.go | 12 +- internal/ui/frameharness_test.go | 25 +- internal/ui/gifexport.go | 23 +- internal/ui/gifexport_async_test.go | 37 +- internal/ui/missingno_noblip_test.go | 25 +- internal/ui/newroom_test.go | 24 +- internal/ui/packcharini_test.go | 11 +- internal/ui/replay.go | 2 +- internal/ui/replaywarm.go | 15 +- internal/ui/replaywarm_test.go | 66 +- internal/ui/sendonchange_test.go | 2 +- internal/ui/settings.go | 36 +- internal/ui/settings_search_test.go | 18 - internal/ui/settingsasync.go | 59 -- internal/ui/settingscache.go | 38 +- internal/ui/settingscache_test.go | 16 - internal/ui/settingsformats.go | 499 ------------ internal/ui/settingsformats_test.go | 155 ---- internal/ui/settingspower.go | 7 - internal/ui/settingstabs.go | 2 +- internal/ui/themeeditorpreview_test.go | 12 +- 75 files changed, 1076 insertions(+), 4232 deletions(-) delete mode 100644 internal/assets/fuzz_test.go delete mode 100644 internal/assets/manifest.go delete mode 100644 internal/assets/manifest_test.go delete mode 100644 internal/assets/mixedfleet_test.go delete mode 100644 internal/assets/resolver.go delete mode 100644 internal/assets/resolver_test.go create mode 100644 internal/media/manifest_fuzz_test.go delete mode 100644 internal/ui/settingsformats.go delete mode 100644 internal/ui/settingsformats_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 0cf9255e..01c0cf54 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,7 +146,7 @@ heap corruption. | `internal/config` | preferences + debounced atomic saver; favorites; local mounts; the Wardrobe's `wardrobe.json` | no | | `internal/cache` | ByteBudgetLRU (T1/T2) + async disk tier (T3, xxhash full-URL keys) | no | | `internal/network` | dedup HTTP client (singleflight, 404 TTL, backoff, DNS warm), request priority, master list + tiers + direct connect | no | -| `internal/assets` | AssetType enum, lock-free resolver (learned formats), `Manager` over `internal/media` (the bridge), the player's folders as a media source, decode pool (magic-byte sniffing), WebP/AVIF CGO binding + fallback, Markov prefetcher | no (decoder is SDL-free by rule) | +| `internal/assets` | AssetType enum, `Manager` over `internal/media` (the bridge; learned formats and winners kept in `learned.json`), the player's folders as a media source, decode pool (magic-byte sniffing), WebP/AVIF CGO binding + fallback, Markov prefetcher | no (decoder is SDL-free by rule) | | `internal/media` | the media system every asset request goes through: `Manager` owns every table on one goroutine, `Get` is safe from any thread, pools run single steps; sources memory → disk cache → `Folders` (the player's folders and .zip packs) → web | no | | `internal/protocol` | AO wire (delegated to aolib-go: FantaCode + JSON), MS 2.6/2.8 parse/build, pairing semantics, FeatureSet, WebSocket conn | no | | `internal/packetutil` | thin bridge over aolib-go: FantaCode primitives, enum maps, typed-parser dispatch, MS both-wire codec | no | @@ -203,8 +203,8 @@ Protocol gotchas already encoded in code/tests — don't "fix" them: Theme text colors apply only while the theme's own skin drew: they're designed for that skin (black-on-paper), not our flat dark panel. - `extensions.json` at the asset origin (webAO convention) is the format - manifest; autodetect (default ON) seeds per-host learned formats from - it. `.webp.static`/`.webp.animated` pseudo-suffixes normalize to .webp. + manifest; it is read on every connect and sets that host's formats and + their order, as written. `.webp.static`/`.webp.animated` pseudo-suffixes normalize to .webp. - Theme textures live in T1 under `theme://` keys; the scheme prefix can't collide with asset URLs. They heal on eviction via themePage. diff --git a/cmd/asyncao-cache/main.go b/cmd/asyncao-cache/main.go index 7a39772f..fd43c0c0 100644 --- a/cmd/asyncao-cache/main.go +++ b/cmd/asyncao-cache/main.go @@ -29,9 +29,9 @@ import ( "sync/atomic" "time" - "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/cache" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/netproxy" "github.com/SyntaxNyah/AsyncAO/internal/platform" ) @@ -253,7 +253,7 @@ func cmdWarm(args []string) error { for _, name := range names { urls = append(urls, strings.TrimRight(*base, "/")+"/characters/"+name+"/"+charIconStem+ext) } - fmt.Printf("warming %d char icons as %s (extension via %s)\n", len(urls), ext, assets.ManifestFileName) + fmt.Printf("warming %d char icons as %s (extension via %s)\n", len(urls), ext, media.ManifestFile) default: return fmt.Errorf("warm needs -list, or -base with -chars") } @@ -335,15 +335,15 @@ func fetch(client *http.Client, url string) ([]byte, int) { //nolint:forbidigo / // manifestIconExt reads the extension from extensions.json, defaulting to .png as webAO does. func manifestIconExt(base string) string { client := newHTTPClient() - data, status := fetch(client, base+"/"+assets.ManifestFileName) + data, status := fetch(client, base+"/"+media.ManifestFile) if status != http.StatusOK { return ".png" } - m, err := assets.ParseManifest(data) - if err != nil || len(m.CharIcon) == 0 { + lists, err := media.ParseManifest(data) + if err != nil || len(lists[media.ClassCharIcon]) == 0 { return ".png" } - return m.CharIcon[0] + return lists[media.ClassCharIcon][0] } func readLines(path string) ([]string, error) { diff --git a/cmd/asyncao/main.go b/cmd/asyncao/main.go index 01262a05..70c07f0f 100644 --- a/cmd/asyncao/main.go +++ b/cmd/asyncao/main.go @@ -115,8 +115,6 @@ func run(rt *host.Runtime, serverURL, masterURL string, gpuOpts host.GraphicsOpt configQuarantine := prefs.Quarantine() defer prefs.Close() - resolver := assets.NewResolver(prefs) - t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { return err @@ -258,7 +256,6 @@ func run(rt *host.Runtime, serverURL, masterURL string, gpuOpts host.GraphicsOpt log.Printf("learned formats won't be kept: %v", err) } manager := assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, Prefs: prefs, T2: t2, Disk: disk, @@ -291,10 +288,6 @@ func run(rt *host.Runtime, serverURL, masterURL string, gpuOpts host.GraphicsOpt s := client.Stats() return s.Requests, s.Cached404s }, - LearnedHits: func() (int64, int64) { - s := resolver.Stats() - return s.LearnedHits, s.LearnedMisses - }, }) profiler.Start() defer profiler.Stop() @@ -322,7 +315,6 @@ func run(rt *host.Runtime, serverURL, masterURL string, gpuOpts host.GraphicsOpt app := ui.NewApp(uiCtx, ui.Deps{ Profiler: profiler, Prefs: prefs, - Resolver: resolver, Manager: manager, Disk: disk, Client: client, diff --git a/docs/FEATURES.md b/docs/FEATURES.md index fdf72ab4..e46fed13 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -29,12 +29,13 @@ canonical reference it mirrors. AO2-Client wins every semantic conflict ## Streaming & performance -- **Format autodetect (default ON)**: `/extensions.json` (webAO - convention — every server ships its own mix) seeds the per-host learned - formats on connect, so each asset class costs ~one probe stone cold. - Manual per-type probing in Settings stays authoritative when autodetect - is off and covers manifest-less servers. `.webp.static`-style pseudo - suffixes are normalized away (animation is a payload property here). +- **Formats from the server**: `/extensions.json` (webAO convention + — every server ships its own mix) is read on connect and sets that host's + formats and their order, so each asset class costs ~one request stone + cold. Without one, formats that worked there go first, then a built-in + order; what worked and each asset's file are kept in `learned.json` + between sessions. `.webp.static`-style pseudo suffixes are normalized + away (animation is a payload property here). A server can also declare `sfx_extensions` / `blips_extensions` to seed its sound-effect and blip formats; audio classes the manifest doesn't cover fall back to `.opus` → `.ogg` → `.mp3` → `.wav`. @@ -46,11 +47,9 @@ canonical reference it mirrors. AO2-Client wins every semantic conflict searched again. Each host, the server's own included, shows whether its format list was read, is absent, couldn't be read, or isn't checked yet, and the debug log gets one line per extra host when its result lands. -- **Desks follow the manifest by default** (Settings → Formats): desk overlays - auto-detect from the server's `extensions.json` like every other class - (desks share the manifest's background class). Tick "Always use WebP for - desks" to pin them to `.webp` on servers whose manifest is wrong for desks; - the per-type format picker covers every format either way. +- **Desks follow the manifest**: desk overlays take their formats from the + server's `extensions.json` like every other class (desks share the + manifest's background class). - **Live-scene self-heal**: if the background, desk, **or a character sprite** is evicted from the texture cache mid-message (memory pressure in a packed room, or a hover-preview fetch), it is re-demanded at high priority within a diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index 2fee829a..cf41c058 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -97,7 +97,11 @@ in **Status**. Update Status in the same commit that completes a step. - [x] core: `Manager` on its own goroutine, `Get` over a concurrent map, `Pool`, `Chain`, `Source`. Not used by the client yet - [x] sources: memory, disk index, remote index with host limits (1 worker until a host answers, then 16); candidates, format learning and `extensions.json`; withdrawing and raising requests. Not used by the client yet - - [ ] sources still to build: saving the disk index and learned formats, character mapping + - [x] saving between sessions (2026-11-14): learned formats and the winner table in `learned.json` through + `internal/saver`; the disk index is not saved, and the disk is asked until its startup scan lands; 404s are + never saved. The old resolver, `prefs.LearnedFormats`, the Formats tab and every format override setting + are gone; archive, export and replay use the media table + - [ ] sources still to build: character mapping - [x] extra asset hosts per server: the user adds them in a fixed order with no speed ranking, the ASS packet's host is always first; Settings → Assets edits them. Raw fetch paths not on the media system yet don't ask them - [x] the client runs on it: `assets.Manager`'s requests go through `internal/media`, so callers and `Pump` are unchanged, and diff --git a/docs/user/asset-preferences.md b/docs/user/asset-preferences.md index 63e76c2d..eb0dd029 100644 --- a/docs/user/asset-preferences.md +++ b/docs/user/asset-preferences.md @@ -2,35 +2,21 @@ Open **Settings** from the lobby or the courtroom. -## Format probing +## Formats -AsyncAO asks the server for exactly **one file format per asset type** by -default: - -| Asset | Default | Why | -|---|---|---| -| Character icons | `.png` | servers ship PNG icons, not WebP | -| Sprites, backgrounds, bubbles, misc | `.webp` | modern, small, animated-capable | -| Sounds, music, blips | `.opus` | modern, small | - -If your server still ships older formats you have two options: - -- **Per-type checkboxes** — tick the extra formats (`.apng`, `.gif`, `.png`, - `.jpg`) you want probed for that type. The type's default stays first. -- **Enable format fallbacks globally** — appends the classic legacy chain to - every type (sprites: `.apng → .gif → .png`, audio: `.ogg → .wav → .mp3`). - -When an asset doesn't exist in *any* enabled format you get a visible warning -naming the formats tried — that's your cue to tick a fallback box or ask the -server owner to upgrade their pack. +AsyncAO reads each server's `extensions.json` when you join and asks for its +art in exactly the formats and order it lists. A server without one is asked +in a built-in order (images: `.webp`, `.png`, `.apng`, `.gif`, `.avif`, `.jpg`; +sounds: `.opus`, `.ogg`, `.mp3`, `.wav`), with the formats that have worked +there going first. Files in your own folders and packs are found in any +format. There is nothing to configure. ## Learned formats -The first format that works for a server is remembered (per server, per asset -type) and persisted. From then on that server costs one perfectly-aimed -request per asset — and after the disk cache warms, zero. **Clear Learned -Formats** resets this memory; changing a type's format list resets it for -that type automatically. +What worked on each server, and the exact file each asset was found as, is +kept in `learned.json` beside your settings, so the next visit asks the right +file first. **Settings → Assets → Cache → Learned formats → Clear** forgets it; +**Fix stuck images** forgets it and clears the disk cache together. ## Play Animations diff --git a/internal/archive/archive.go b/internal/archive/archive.go index 7c1c92af..0ab7eaa7 100644 --- a/internal/archive/archive.go +++ b/internal/archive/archive.go @@ -126,12 +126,13 @@ func DiskPath(rel string) string { return strings.Join(out, "/") } -// SeedFormats teaches a replay resolver the archive's formats, so non-webp files resolve on the first probe. -func SeedFormats(resolver *assets.Resolver, origin string, formats map[string]string) { - host := assets.HostOf(origin) +// SeedFormats gives a replay's origin the archive's recorded formats, so non-webp files resolve on the first probe. +func SeedFormats(mgr *assets.Manager, origin string, formats map[string]string) { + byType := make(map[assets.AssetType]string, len(formats)) for name, ext := range formats { if t, ok := assets.TypeFromName(name); ok { - resolver.RecordSuccess(host, t, ext) + byType[t] = ext } } + mgr.AllowFormats(origin, byType) } diff --git a/internal/archive/archive_test.go b/internal/archive/archive_test.go index af274944..d65131cb 100644 --- a/internal/archive/archive_test.go +++ b/internal/archive/archive_test.go @@ -14,14 +14,13 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/protocol" ) -func buildManager(t *testing.T, source assets.Fetcher, localMode bool) (*assets.Manager, *assets.Resolver) { +func buildManager(t *testing.T, source assets.Fetcher, localMode bool) *assets.Manager { t.Helper() prefs, err := config.New(filepath.Join(t.TempDir(), config.PrefsFileName)) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = prefs.Close() }) - resolver := assets.NewResolver(prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -34,14 +33,14 @@ func buildManager(t *testing.T, source assets.Fetcher, localMode bool) (*assets. decoder := assets.NewDecoderPool(2) t.Cleanup(decoder.Close) mgr := assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, Prefs: prefs, T2: t2, Disk: disk, + Prefs: prefs, T2: t2, Disk: disk, Source: source, Decoder: decoder, }) t.Cleanup(mgr.CloseMedia) if lf, ok := source.(*assets.LocalFetcher); ok && localMode { mgr.SetFolders(lf.Mounts(), nil) } - return mgr, resolver + return mgr } func writeFixture(t *testing.T, dir, rel string, data []byte) { @@ -79,7 +78,7 @@ func TestExportReplayRoundTrip(t *testing.T) { writeFixture(t, srcDir, rel(urls.Emote("Phoenix", "normal", courtroom.EmoteTalk)), []byte("PHOENIX-TALK")) writeFixture(t, srcDir, rel(urls.Background("gs4", bgPart)), []byte("BG")) writeFixture(t, srcDir, rel(urls.Background("gs4", deskPart)), []byte("DESK")) - srcMgr, _ := buildManager(t, srcLocal, true) + srcMgr := buildManager(t, srcLocal, true) events := []courtroom.Event{ {Kind: courtroom.EventBackground, Text: "gs4"}, @@ -102,8 +101,8 @@ func TestExportReplayRoundTrip(t *testing.T) { // REPLAY: a SEPARATE manager over the archive (source is gone), seeded from // the export's format manifest — exactly what replaying a bundled .aorec does. repLocal := assets.NewLocalFetcher([]string{archDir}) - repMgr, repResolver := buildManager(t, repLocal, true) - SeedFormats(repResolver, repLocal.BaseURL(), res.Formats) + repMgr := buildManager(t, repLocal, true) + SeedFormats(repMgr, repLocal.BaseURL(), res.Formats) repUrls := courtroom.NewURLBuilder(repLocal.BaseURL()) idle := repUrls.Emote("Phoenix", "normal", courtroom.EmoteIdle) @@ -136,7 +135,7 @@ func TestExportNestedBackgroundSubfolder(t *testing.T) { writeFixture(t, srcDir, rel(urls.Emote("Phoenix", "normal", courtroom.EmoteTalk)), []byte("TALK")) writeFixture(t, srcDir, rel(urls.Background(nestedBg, bgPart)), []byte("BG")) writeFixture(t, srcDir, rel(urls.Background(nestedBg, deskPart)), []byte("DESK")) - srcMgr, _ := buildManager(t, srcLocal, true) + srcMgr := buildManager(t, srcLocal, true) events := []courtroom.Event{ {Kind: courtroom.EventBackground, Text: nestedBg}, @@ -186,7 +185,7 @@ func TestExportDecodesBundleNames(t *testing.T) { bgPart, deskPart := "witnessempty", "stand" // legacy art; the export bundles every name and each name's desk writeFixture(t, srcDir, rel(urls.Background("gs4", bgPart)), []byte("BG")) writeFixture(t, srcDir, rel(urls.Background("gs4", deskPart)), []byte("DESK")) - srcMgr, _ := buildManager(t, srcLocal, true) + srcMgr := buildManager(t, srcLocal, true) events := []courtroom.Event{ {Kind: courtroom.EventBackground, Text: "gs4"}, @@ -213,7 +212,7 @@ func TestExportDecodesBundleNames(t *testing.T) { // And it still replays: a separate manager over the clean archive resolves the // escaped URL via the local fetcher's decoded-spelling attempt. repLocal := assets.NewLocalFetcher([]string{archDir}) - repMgr, _ := buildManager(t, repLocal, true) + repMgr := buildManager(t, repLocal, true) repUrls := courtroom.NewURLBuilder(repLocal.BaseURL()) _, data, ok := repMgr.ResolveRaw(repUrls.Emote(char, "normal", courtroom.EmoteIdle), assets.AssetTypeCharSprite) if !ok { diff --git a/internal/assets/folders_test.go b/internal/assets/folders_test.go index f7a7618a..04ca8de7 100644 --- a/internal/assets/folders_test.go +++ b/internal/assets/folders_test.go @@ -1,6 +1,8 @@ package assets import ( + "github.com/SyntaxNyah/AsyncAO/internal/media" + "context" "image/color" "net/http" @@ -179,14 +181,11 @@ func TestFolderTextNeverTeachesLearnedFormats(t *testing.T) { map[string]string{}, map[string]string{"characters/witch/char.ini": "PACK INI"}, ) - host := HostOf(pr.origin) - before := pr.rig.manager.resolver.LearnedList(host, AssetTypeCharSprite) - if _, err := pr.rig.manager.FetchRaw(context.Background(), pr.base("characters/witch/char.ini")); err != nil { t.Fatalf("FetchRaw: %v", err) } - if after := pr.rig.manager.resolver.LearnedList(host, AssetTypeCharSprite); len(after) != len(before) { - t.Errorf("the folder taught the server host a format: %v -> %v", before, after) + if n := pr.rig.manager.LearnedHosts(); n != 0 { + t.Errorf("the folder taught %d hosts a format", n) } } @@ -194,13 +193,13 @@ func TestFolderTextNeverTeachesLearnedFormats(t *testing.T) { // current host's format order from the folder author's conventions. func TestFolderNeverAnswersTheServerFormatList(t *testing.T) { pr := newPackRig(t, - map[string]string{"/base/" + ManifestFileName: "SERVER MANIFEST"}, - map[string]string{ManifestFileName: "PACK MANIFEST"}, + map[string]string{"/base/" + media.ManifestFile: "SERVER MANIFEST"}, + map[string]string{media.ManifestFile: "PACK MANIFEST"}, ) - data, err := pr.rig.manager.FetchRaw(context.Background(), pr.base(ManifestFileName)) + data, err := pr.rig.manager.FetchRaw(context.Background(), pr.base(media.ManifestFile)) if err != nil { - t.Fatalf("FetchRaw(%s): %v", ManifestFileName, err) + t.Fatalf("FetchRaw(%s): %v", media.ManifestFile, err) } if string(data) != "SERVER MANIFEST" { t.Errorf("got %q — the folder answered for the server's own format list", data) @@ -268,7 +267,7 @@ func TestFileDroppedInAfterAMissIsFoundOnRecheck(t *testing.T) { func TestFolderSpriteIsFoundInAFormatTheServerDoesNotList(t *testing.T) { const spritePx = 4 pr := newPackRig(t, - map[string]string{"/base/" + ManifestFileName: `{"emote_extensions": [".webp"]}`}, + map[string]string{"/base/" + media.ManifestFile: `{"emote_extensions": [".webp"]}`}, map[string]string{"characters/witch/normal.png": string(encodePNG(t, spritePx, spritePx, color.White))}, ) if _, err := pr.rig.manager.FetchManifest(context.Background(), pr.origin); err != nil { diff --git a/internal/assets/fuzz_test.go b/internal/assets/fuzz_test.go deleted file mode 100644 index 944d5a0f..00000000 --- a/internal/assets/fuzz_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package assets - -import "testing" - -// FuzzParseManifest drives the extensions.json parser (manifest.go): every -// server ships its own manifest at the asset origin (webAO convention), so the -// bytes are attacker-controlled. Contract is robustness — no panic, no hang, and -// every sanitized list stays bounded (rules #4, #7). encoding/json already -// rejects malformed JSON with an error, so the interesting surface is the -// post-decode sanitize (dedupe/cap/pseudo-suffix normalization). -func FuzzParseManifest(f *testing.F) { - // Real shapes, pseudo-suffix normalization, over-cap dedupe, and degenerate - // JSON (wrong shape / null / truncated) — the last three exercise the decode - // error path, the rest the post-decode sanitize. - seeds := []string{ - bundledVanillaManifestJSON, - `{"charicon_extensions":[".png"],"emote_extensions":[".webp.static",".webp.animated",".webp"]}`, - `{"background_extensions":[".gif",".GIF",".gif",".png",".jpg",".avif",".apng",".png",".bmp"]}`, - `{"emotions_extensions":[" .PNG ",".exe",".webp.static"]}`, - `{}`, - `[]`, - `null`, - `{"emote_extensions":null}`, - ``, - `{`, - } - for _, s := range seeds { - f.Add([]byte(s)) - } - f.Fuzz(func(t *testing.T, data []byte) { - m, err := ParseManifest(data) - if err != nil { - return // malformed JSON is rejected, not a crash - } - // Every sanitized list must stay within the named cap (§17.4). - for _, list := range [][]string{m.CharIcon, m.Emote, m.Emotions, m.Background} { - if len(list) > manifestExtCap { - t.Fatalf("sanitized manifest list of %d exceeds cap %d: %v", len(list), manifestExtCap, list) - } - } - _ = m.manifestSeedTargets() - }) -} diff --git a/internal/assets/manager.go b/internal/assets/manager.go index 945830d1..f66c3571 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -69,13 +69,12 @@ type Fetcher interface { // Manager answers asset requests through internal/media, in the order memory, disk cache, the player's folders, // then the web, and hands results to the render thread and the audio system. type Manager struct { - bridge *mediaBridge - resolver *Resolver - prefs *config.AssetPreferences - t2 *cache.ByteBudgetLRU[string, []byte] - disk *cache.DiskCache - client Fetcher - decoder *DecoderPool + bridge *mediaBridge + prefs *config.AssetPreferences + t2 *cache.ByteBudgetLRU[string, []byte] + disk *cache.DiskCache + client Fetcher + decoder *DecoderPool // learnedPath is where the media system's learned formats and winners are kept between sessions. learnedPath string @@ -192,10 +191,9 @@ func (m *Manager) ColdLoadStats() (fetch, decode time.Duration) { // ManagerDeps wires a Manager; every field is required except T1Contains and T1Failed. type ManagerDeps struct { - Resolver *Resolver - Prefs *config.AssetPreferences - T2 *cache.ByteBudgetLRU[string, []byte] - Disk *cache.DiskCache + Prefs *config.AssetPreferences + T2 *cache.ByteBudgetLRU[string, []byte] + Disk *cache.DiskCache // Source is the network client, or a fake in tests. Source Fetcher Decoder *DecoderPool @@ -208,7 +206,6 @@ type ManagerDeps struct { // NewManager builds the Manager and starts its media system; CloseMedia stops it. func NewManager(deps ManagerDeps) *Manager { m := &Manager{ - resolver: deps.Resolver, prefs: deps.Prefs, t2: deps.T2, disk: deps.Disk, @@ -433,23 +430,20 @@ func (m *Manager) ResolveRawLayered(base string, t AssetType) (url string, data if base == "" || !t.Valid() { return "", nil, false, false } - cands := m.resolver.BuildCandidates(base, t, hostOf(base)) - defer m.resolver.PutCandidates(cands) - return m.resolveIn(base, t, cands.URLs) + return m.resolveIn(base, t, m.bridge.candidates(base, t)) } -// ResolveRawFull is ResolveRaw for report and export passes: the learned format, then the full probe chain. +// ResolveRawFull is ResolveRawLayered for report and export passes, which also ask the formats the host's list leaves +// out. func (m *Manager) ResolveRawFull(base string, t AssetType) (string, []byte, bool) { if base == "" || !t.Valid() { return "", nil, false } - exts := fullProbeChain(m.prefs, t) - if ext, ok := m.resolver.Learned(hostOf(base), t); ok { - exts = append([]string{ext}, slices.DeleteFunc(exts, func(e string) bool { return e == ext })...) - } - urls := make([]string, len(exts)) - for i, ext := range exts { - urls[i] = base + ext + urls := m.bridge.candidates(base, t) + for _, f := range media.EveryFormat(media.Key{Class: classOf(t)}, base) { + if !slices.Contains(urls, string(f)) { + urls = append(urls, string(f)) + } } url, data, _, ok := m.resolveIn(base, t, urls) return url, data, ok @@ -458,10 +452,9 @@ func (m *Manager) ResolveRawFull(base string, t AssetType) (string, []byte, bool // resolveIn finds one name in the live chain's order: memory and the disk cache, then the player's folders in every // format, then the web. Server hits teach the host's format; a folder hit teaches nothing, as the files are the player's. func (m *Manager) resolveIn(base string, t AssetType, urls []string) (url string, data []byte, fromPack, ok bool) { - host := hostOf(base) for _, u := range urls { if data, ok := m.cachedRaw(u); ok { - m.resolver.RecordSuccess(host, t, u[len(base):]) + m.bridge.learn(base, t, u) return u, data, false, true } } @@ -472,39 +465,13 @@ func (m *Manager) resolveIn(base string, t AssetType, urls []string) (url string } for _, u := range urls { if data, err := m.remoteRaw(context.Background(), u); err == nil && len(data) > 0 { - m.resolver.RecordSuccess(host, t, u[len(base):]) + m.bridge.learn(base, t, u) return u, data, false, true } } return "", nil, false, false } -// fullProbeChain is the configured order then the type's fallback chain, deduped, covering each decoder's formats. -func fullProbeChain(prefs *config.AssetPreferences, t AssetType) []string { - name := t.Name() - var order []string - if prefs != nil { - order = prefs.Load().FormatOrder(name) // configured order (defaults to the zero-fallback list) - } - if len(order) == 0 { - order = config.DefaultFormatOrder(name) - } - out := make([]string, 0, len(order)+len(config.LegacyFallbackChain(name))) - seen := map[string]bool{} - appendExt := func(exts []string) { - for _, e := range exts { - if e == "" || seen[e] { - continue - } - seen[e] = true - out = append(out, e) - } - } - appendExt(order) - appendExt(config.LegacyFallbackChain(name)) - return out -} - // onDecoded hands one decoded page to the render thread. func (m *Manager) onDecoded(url, base string, t AssetType, fromPack bool, d *Decoded, err error) { m.decodedCh <- DecodedAsset{URL: url, Base: base, Type: t, Asset: d, Err: err, FromPack: fromPack} diff --git a/internal/assets/manager_test.go b/internal/assets/manager_test.go index a958fa12..59b2387a 100644 --- a/internal/assets/manager_test.go +++ b/internal/assets/manager_test.go @@ -22,15 +22,24 @@ const managerWait = 5 * time.Second // testRig wires a full pipeline against an httptest server. type testRig struct { - prefs *config.AssetPreferences - resolver *Resolver - manager *Manager - decoder *DecoderPool - disk *cache.DiskCache - t2 *cache.ByteBudgetLRU[string, []byte] + prefs *config.AssetPreferences + manager *Manager + decoder *DecoderPool + disk *cache.DiskCache + t2 *cache.ByteBudgetLRU[string, []byte] } // newRig builds a Manager on source; localMode mounts a LocalFetcher source's folders, as "only use my folders" does. +func newTestPrefs(tb testing.TB) *config.AssetPreferences { + tb.Helper() + p, err := config.New(filepath.Join(tb.TempDir(), config.PrefsFileName)) + if err != nil { + tb.Fatalf("config.New: %v", err) + } + tb.Cleanup(func() { _ = p.Close() }) + return p +} + func newRig(tb testing.TB, source Fetcher, localMode bool) *testRig { tb.Helper() return newRigAt(tb, source, localMode, "") @@ -40,7 +49,6 @@ func newRig(tb testing.TB, source Fetcher, localMode bool) *testRig { func newRigAt(tb testing.TB, source Fetcher, localMode bool, learnedPath string) *testRig { tb.Helper() prefs := newTestPrefs(tb) - resolver := NewResolver(prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { tb.Fatal(err) @@ -54,7 +62,6 @@ func newRigAt(tb testing.TB, source Fetcher, localMode bool, learnedPath string) tb.Cleanup(decoder.Close) m := NewManager(ManagerDeps{ - Resolver: resolver, Prefs: prefs, T2: t2, Disk: disk, @@ -66,7 +73,7 @@ func newRigAt(tb testing.TB, source Fetcher, localMode bool, learnedPath string) if lf, ok := source.(*LocalFetcher); ok && localMode { m.SetFolders(lf.Mounts(), nil) } - return &testRig{prefs: prefs, resolver: resolver, manager: m, decoder: decoder, disk: disk, t2: t2} + return &testRig{prefs: prefs, manager: m, decoder: decoder, disk: disk, t2: t2} } // TestResolveRawFromLocalArchive is the load-bearing round-trip proof for the @@ -110,8 +117,8 @@ func TestResolveRawFromLocalArchive(t *testing.T) { if url, data, ok := rig.manager.ResolveRaw(pbase, AssetTypeCharSprite); !ok || string(data) != "PNG" { t.Fatalf("folder .png not resolved: ok=%v url=%q", ok, url) } - if ext, ok := rig.resolver.Learned(hostOf(pbase), AssetTypeCharSprite); ok && ext == config.ExtPNG { - t.Errorf("a folder hit taught the host %q", ext) + if n := rig.manager.LearnedHosts(); n != 0 { + t.Errorf("folder hits taught %d hosts a format", n) } } diff --git a/internal/assets/manifest.go b/internal/assets/manifest.go deleted file mode 100644 index 3e265c43..00000000 --- a/internal/assets/manifest.go +++ /dev/null @@ -1,132 +0,0 @@ -package assets - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/SyntaxNyah/AsyncAO/internal/config" -) - -// extensions.json at the asset origin (webAO fetchLists.ts fetchExtensions) declares extension order per class; -// seeding the learned table from it gives one fetch per asset. - -const ( - ManifestFileName = "extensions.json" - // manifestExtCap bounds each parsed list (hard rule 4). - manifestExtCap = 8 -) - -// Manifest mirrors webAO's extensions.json shape. -type Manifest struct { - CharIcon []string `json:"charicon_extensions"` - Emote []string `json:"emote_extensions"` - Emotions []string `json:"emotions_extensions"` - Background []string `json:"background_extensions"` - // Optional: webAO's file declares only image classes; absent, the default order and learning apply. - SFX []string `json:"sfx_extensions"` - Blips []string `json:"blips_extensions"` -} - -// manifestKnownExts is what a manifest may declare; a wrong-kind extension on a class self-corrects on probe. -var manifestKnownExts = map[string]bool{ - config.ExtWebP: true, - config.ExtAVIF: true, - config.ExtAPNG: true, - config.ExtGIF: true, - config.ExtPNG: true, - config.ExtJPG: true, - config.ExtOpus: true, - config.ExtOgg: true, - config.ExtMP3: true, - config.ExtWAV: true, -} - -// bundledVanillaManifestJSON is the vanilla AO extensions.json, the default for servers without one, as vanilla is PNG. -const bundledVanillaManifestJSON = `{ - "charicon_extensions": [".png"], - "emote_extensions": [".apng", ".webp", ".png"], - "emotions_extensions": [".png"], - "background_extensions": [".png"] -}` - -// BundledVanillaManifestJSON is that manifest as text, offered as the example for per-server format profiles. -const BundledVanillaManifestJSON = bundledVanillaManifestJSON - -// ParseManifest decodes and sanitizes extensions.json content. -func ParseManifest(data []byte) (*Manifest, error) { - var m Manifest - if err := json.Unmarshal(data, &m); err != nil { - return nil, fmt.Errorf("assets: parsing %s: %w", ManifestFileName, err) - } - m.CharIcon = sanitizeManifestExts(m.CharIcon) - m.Emote = sanitizeManifestExts(m.Emote) - m.Emotions = sanitizeManifestExts(m.Emotions) - m.Background = sanitizeManifestExts(m.Background) - m.SFX = sanitizeManifestExts(m.SFX) - m.Blips = sanitizeManifestExts(m.Blips) - return &m, nil -} - -// sanitizeManifestExts lowercases, maps .webp.static/.webp.animated to .webp, drops unknowns, dedupes and caps. -func sanitizeManifestExts(in []string) []string { - out := make([]string, 0, len(in)) - seen := map[string]bool{} - for _, e := range in { - e = strings.ToLower(strings.TrimSpace(e)) - if e == ".webp.static" || e == ".webp.animated" { - e = config.ExtWebP - } - if !manifestKnownExts[e] || seen[e] { - continue - } - seen[e] = true - out = append(out, e) - if len(out) >= manifestExtCap { - break - } - } - return out -} - -// manifestSeedTargets maps classes to types; misc is not seeded from emotes, as mirrors such as miku.pizza differ. -func (m *Manifest) manifestSeedTargets() []struct { - exts []string - types []AssetType -} { - return []struct { - exts []string - types []AssetType - }{ - {m.CharIcon, []AssetType{AssetTypeCharIcon}}, - {m.Emote, []AssetType{AssetTypeCharSprite, AssetTypeShoutBubble}}, - {m.Emotions, []AssetType{AssetTypeEmoteButton}}, - {m.Background, []AssetType{AssetTypeBackground, AssetTypeDeskOverlay}}, - {m.SFX, []AssetType{AssetTypeSFX}}, - {m.Blips, []AssetType{AssetTypeBlip}}, - } -} - -// SeedLearned writes every declared extension in order, as servers such as umineko.online genuinely mix formats. -// Call Resolver.WarmFromPrefs afterwards. -func (m *Manifest) SeedLearned(prefs *config.AssetPreferences, host string) int { - if prefs == nil || host == "" { - return 0 - } - // Desks follow the manifest unless the user opts out for servers with wrong manifests. - deskFollows := prefs.Load().DeskFollowManifest - seeded := 0 - for _, target := range m.manifestSeedTargets() { - if len(target.exts) == 0 { - continue - } - for _, t := range target.types { - if t == AssetTypeDeskOverlay && !deskFollows { - continue - } - prefs.RecordLearnedList(host, t.Name(), target.exts) - seeded++ - } - } - return seeded -} diff --git a/internal/assets/manifest_test.go b/internal/assets/manifest_test.go deleted file mode 100644 index be9839f3..00000000 --- a/internal/assets/manifest_test.go +++ /dev/null @@ -1,155 +0,0 @@ -package assets - -import ( - "path/filepath" - "testing" - - "github.com/SyntaxNyah/AsyncAO/internal/config" -) - -// TestManifestParseSanitizes pins the extensions.json hygiene: webAO's -// ".webp.static" pseudo-suffix maps to .webp, casing normalizes, unknown -// extensions drop, duplicates collapse. -func TestManifestParseSanitizes(t *testing.T) { - data := []byte(`{ - "charicon_extensions": [".PNG", ".bogus"], - "emote_extensions": [".webp.static", ".gif", ".webp"], - "emotions_extensions": [], - "background_extensions": [".png", ".apng"] - }`) - m, err := ParseManifest(data) - if err != nil { - t.Fatal(err) - } - if len(m.CharIcon) != 1 || m.CharIcon[0] != config.ExtPNG { - t.Errorf("charicon = %v", m.CharIcon) - } - // .webp.static → .webp (kept first), .gif kept, trailing .webp dedupes. - if len(m.Emote) != 2 || m.Emote[0] != config.ExtWebP || m.Emote[1] != config.ExtGIF { - t.Errorf("emote = %v", m.Emote) - } - if len(m.Background) != 2 { - t.Errorf("background = %v", m.Background) - } - if _, err := ParseManifest([]byte("not json")); err == nil { - t.Error("malformed manifest parsed") - } -} - -// TestManifestSeedLearned pins the seeding fan-out: emote art covers -// sprites + shout bubbles (NOT misc — extensions.json has no misc key, and -// live mirrors ship png misc art beside webp emotes), backgrounds cover desk -// overlays, empty classes seed nothing, and the learned entry keeps EVERY -// declared extension in the manifest's own order. -// -// The full list, not just the first: a server declaring two formats for a class -// serves both, and truncating to exts[0] left the other half of its fleet behind -// a single candidate with no way to fall back (see learnedTable / promoteExt). -func TestManifestSeedLearned(t *testing.T) { - prefs, err := config.New(filepath.Join(t.TempDir(), config.PrefsFileName)) - if err != nil { - t.Fatal(err) - } - defer prefs.Close() - - m := &Manifest{ - CharIcon: []string{config.ExtPNG}, - Emote: []string{config.ExtWebP, config.ExtGIF}, - Background: []string{config.ExtPNG}, - } - const host = "miku.pizza" - // Desks follow the manifest by default (deliberate default flip, user order - // 2026-08-08 — desks auto-detect like every other class), so the background - // class seeds background AND desk: charicon(1) + emote(sprite, bubble = 2) - // + background(bg, desk = 2) = 5; Misc unseeded by design. - if n := m.SeedLearned(prefs, host); n != 5 { - t.Fatalf("seeded %d, want 5 (desks follow by default, misc never)", n) - } - snap := prefs.Load().LearnedSnapshot() - // The emote class declares TWO formats, so sprites and shout bubbles must - // carry both — .webp first (probed), .gif behind it (the recovery ladder). - checks := map[string][]string{ - config.LearnedKey(host, config.TypeCharIcon): {config.ExtPNG}, - config.LearnedKey(host, config.TypeCharSprite): {config.ExtWebP, config.ExtGIF}, - config.LearnedKey(host, config.TypeShoutBubble): {config.ExtWebP, config.ExtGIF}, - config.LearnedKey(host, config.TypeBackground): {config.ExtPNG}, - config.LearnedKey(host, config.TypeDeskOverlay): {config.ExtPNG}, - } - for key, want := range checks { - got := snap[key] - if len(got) != len(want) { - t.Errorf("learned[%s] = %v, want %v", key, got, want) - continue - } - for i := range want { - if got[i] != want[i] { - t.Errorf("learned[%s] = %v, want %v (order matters: front is probed first)", key, got, want) - break - } - } - } - if _, ok := snap[config.LearnedKey(host, config.TypeMisc)]; ok { - t.Error("Misc seeded from the emote class (png misc art beside webp emotes is real — it must learn per host)") - } - if _, ok := snap[config.LearnedKey(host, config.TypeEmoteButton)]; ok { - t.Error("empty emotions class seeded EmoteButton") - } - - // Opt out: pin desks to WebP; the manifest may no longer touch DeskOverlay. - // The clear mirrors what the Settings toggle does, so the pin is observable - // as an ABSENT entry rather than a stale seeded one. - prefs.Update(func( - sn *config. - Settings) { - - sn. - DeskFollowManifest = - - false - - }) - - prefs.ClearLearnedType(config.TypeDeskOverlay) - if n := m.SeedLearned(prefs, host); n != 4 { - t.Fatalf("seeded %d with the WebP pin on, want 4 (desk exempt)", n) - } - if got, ok := prefs.Load().LearnedSnapshot()[config.LearnedKey(host, config.TypeDeskOverlay)]; ok { - t.Errorf("DeskOverlay seeded from the manifest despite the WebP pin: %v", got) - } -} - -// TestManifestSeedLearnedAudio pins the optional audio classes: a manifest that -// declares sfx_extensions / blips_extensions seeds the SFX and Blip learned -// tables (declaration order, full list), and an absent class seeds nothing (the -// type keeps its default opus-first order + per-host learning). -func TestManifestSeedLearnedAudio(t *testing.T) { - m, err := ParseManifest([]byte(`{ - "sfx_extensions": [".opus", ".ogg"], - "blips_extensions": [".wav", ".WAV", ".bogus"] - }`)) - if err != nil { - t.Fatal(err) - } - if len(m.SFX) != 2 || m.SFX[0] != config.ExtOpus || m.SFX[1] != config.ExtOgg { - t.Errorf("sfx = %v, want [.opus .ogg]", m.SFX) - } - if len(m.Blips) != 1 || m.Blips[0] != config.ExtWAV { - t.Errorf("blips = %v, want [.wav] (dupe collapsed, .bogus dropped)", m.Blips) - } - prefs, err := config.New(filepath.Join(t.TempDir(), config.PrefsFileName)) - if err != nil { - t.Fatal(err) - } - defer prefs.Close() - const host = "kfo.test" - if n := m.SeedLearned(prefs, host); n != 2 { - t.Fatalf("seeded %d, want 2 (sfx + blip only; image classes absent)", n) - } - snap := prefs.Load().LearnedSnapshot() - if got := snap[config.LearnedKey(host, config.TypeSFX)]; len(got) != 2 || got[0] != config.ExtOpus || got[1] != config.ExtOgg { - t.Errorf("learned[SFX] = %v, want [.opus .ogg]", got) - } - if got := snap[config.LearnedKey(host, config.TypeBlip)]; len(got) != 1 || got[0] != config.ExtWAV { - t.Errorf("learned[Blip] = %v, want [.wav]", got) - } -} diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index 6f055803..d79eb45f 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -58,6 +58,8 @@ type mediaBridge struct { learned *saver.Saver recalled bool foundEarly bool + // learnedHosts mirrors builder.LearnedOrigins for other threads. + learnedHosts atomic.Int64 } func newMediaBridge(m *Manager) *mediaBridge { @@ -93,9 +95,65 @@ func (b *mediaBridge) found(k media.Key, f media.File) { if !b.recalled { b.foundEarly = true } + b.learnedHosts.Store(int64(b.builder.LearnedOrigins())) b.learned.Changed() } +// learn is found for a raw walk on a worker: url turned up for base. +func (b *mediaBridge) learn(base string, t AssetType, url string) { + b.media.Do(func() { b.found(chainKey(base, t), media.File(url)) }) +} + +// candidates lists the URLs base may be, in the order the live chain asks; for workers, as it waits on the Manager. +func (b *mediaBridge) candidates(base string, t AssetType) []string { + var files []media.File + b.media.Call(func() { files = b.builder.Build(chainKey(base, t), base) }) + urls := make([]string, len(files)) + for i, f := range files { + urls[i] = string(f) + } + return urls +} + +// AllowFormats gives origin a format list per asset type, as its extensions.json would, such as a replay archive's +// recorded formats. +func (m *Manager) AllowFormats(origin string, byType map[AssetType]string) { + allowed := map[media.Class][]string{} + for t, ext := range byType { + if c := classOf(t); c != media.ClassExact && !slices.Contains(allowed[c], ext) { + allowed[c] = append(allowed[c], ext) + } + } + m.bridge.media.Do(func() { m.bridge.builder.Allow(origin, allowed) }) +} + +// AllowManifest gives origin the formats an extensions.json lists, for a host known to publish none; false when it +// doesn't parse. +func (m *Manager) AllowManifest(origin string, data []byte) bool { + allowed, err := media.ParseManifest(data) + if err != nil { + return false + } + m.bridge.media.Do(func() { m.bridge.builder.Allow(origin, allowed) }) + return true +} + +// ForgetLearned drops every learned format and remembered file, here and in learned.json. +func (m *Manager) ForgetLearned() { + b := m.bridge + b.media.Do(func() { + b.builder.ForgetLearned() + b.media.ForgetWinners(func(media.Key, media.File) bool { return true }) + b.learnedHosts.Store(0) + b.learned.Changed() + }) +} + +// LearnedHosts counts the hosts a format was learned for; safe from any thread. +func (m *Manager) LearnedHosts() int { + return int(m.bridge.learnedHosts.Load()) +} + // recallLearned reads learned.json on a disk worker and adds it to what this session knows. func (b *mediaBridge) recallLearned() { path := b.m.learnedPath @@ -111,6 +169,7 @@ func (b *mediaBridge) recallLearned() { }, func(v any) { media.Recall(b.media, b.builder, v.(media.Learned)) b.recalled = true + b.learnedHosts.Store(int64(b.builder.LearnedOrigins())) if b.foundEarly { b.learned.Changed() } @@ -300,7 +359,7 @@ func (b *mediaBridge) finished(a *media.Asset) { // FetchManifest reads a server's extensions.json straight from its host, so a change is seen and the answer proves it is alive. func (m *Manager) FetchManifest(ctx context.Context, origin string) ([]byte, error) { - file := origin + ManifestFileName + file := origin + media.ManifestFile data, err := m.netFetch(ctx, file) m.bridge.noteManifest(origin, file, data, err) return data, err diff --git a/internal/assets/mediabridge_test.go b/internal/assets/mediabridge_test.go index 4e0866b7..0e4f6e8a 100644 --- a/internal/assets/mediabridge_test.go +++ b/internal/assets/mediabridge_test.go @@ -64,7 +64,6 @@ func (h *bridgeFakeHost) askedFor() []string { func newBridgeRig(t *testing.T, host *bridgeFakeHost) *testRig { t.Helper() prefs := newTestPrefs(t) - resolver := NewResolver(prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -76,9 +75,9 @@ func newBridgeRig(t *testing.T, host *bridgeFakeHost) *testRig { t.Cleanup(disk.Close) decoder := NewDecoderPool(bridgeTestWorkers) t.Cleanup(decoder.Close) - m := NewManager(ManagerDeps{Resolver: resolver, Prefs: prefs, T2: t2, Disk: disk, Source: host, Decoder: decoder}) + m := NewManager(ManagerDeps{Prefs: prefs, T2: t2, Disk: disk, Source: host, Decoder: decoder}) t.Cleanup(m.CloseMedia) - return &testRig{prefs: prefs, resolver: resolver, manager: m, decoder: decoder, disk: disk, t2: t2} + return &testRig{prefs: prefs, manager: m, decoder: decoder, disk: disk, t2: t2} } // nextDecoded waits for the final page of base, releasing partial ones as the upload pump does. @@ -227,8 +226,8 @@ const bridgeSettle = 50 * time.Millisecond func TestBridgeManifestSetsOrderAndIsFetchedFresh(t *testing.T) { webp := fixture(t, "sprite_256x192.webp") host := &bridgeFakeHost{files: map[string][]byte{ - bridgeTestOrigin + ManifestFileName: []byte(`{"emote_extensions": [".png", ".webp"]}`), - bridgeTestOrigin + "e.webp": webp, + bridgeTestOrigin + media.ManifestFile: []byte(`{"emote_extensions": [".png", ".webp"]}`), + bridgeTestOrigin + "e.webp": webp, }} r := newBridgeRig(t, host) for range bridgeTestWorkers { @@ -239,7 +238,7 @@ func TestBridgeManifestSetsOrderAndIsFetchedFresh(t *testing.T) { base := bridgeTestOrigin + "e" r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) nextDecoded(t, r.manager, base) - want := []string{bridgeTestOrigin + ManifestFileName, bridgeTestOrigin + ManifestFileName, base + ".png", base + ".webp"} + want := []string{bridgeTestOrigin + media.ManifestFile, bridgeTestOrigin + media.ManifestFile, base + ".png", base + ".webp"} if asked := host.askedFor(); !slices.Equal(asked, want) { t.Fatalf("asked %v, want %v", asked, want) } @@ -287,7 +286,7 @@ func TestBridgeExtraHostServesWhatTheServerLacks(t *testing.T) { if d.Err != nil || d.Asset == nil || d.URL != mirror+"c/e.webp" { t.Fatalf("url %q err %v", d.URL, d.Err) } - if !slices.Contains(host.askedFor(), mirror+ManifestFileName) { + if !slices.Contains(host.askedFor(), mirror+media.ManifestFile) { t.Fatal("the mirror's extensions.json was not read") } waitUntil(t, "the mirror to report no list", func() bool { return r.manager.HostListState(mirror) == media.ManifestAbsent }) @@ -295,7 +294,7 @@ func TestBridgeExtraHostServesWhatTheServerLacks(t *testing.T) { func TestBridgeReportsAnExtraHostsListAndForgetsARemovedHost(t *testing.T) { const mirror = "http://mirror.test/ao/" - host := &bridgeFakeHost{files: map[string][]byte{mirror + ManifestFileName: []byte(`{"emote_extensions": [".png"]}`)}} + host := &bridgeFakeHost{files: map[string][]byte{mirror + media.ManifestFile: []byte(`{"emote_extensions": [".png"]}`)}} r := newBridgeRig(t, host) if s := r.manager.HostListState(mirror); s != media.ManifestUnchecked { t.Fatalf("before joining: %d, want unchecked", s) diff --git a/internal/assets/mixedfleet_test.go b/internal/assets/mixedfleet_test.go deleted file mode 100644 index 4719b616..00000000 --- a/internal/assets/mixedfleet_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package assets - -import ( - "path/filepath" - "testing" - - "github.com/SyntaxNyah/AsyncAO/internal/config" -) - -// newMixedFleetResolver is a resolver over throwaway prefs, seeded from a -// manifest that declares BOTH formats for the emote-button class — exactly what -// umineko.online publishes ("emotions_extensions": [".png", ".webp"]). -func newMixedFleetResolver(t *testing.T, host string) (*Resolver, *config.AssetPreferences) { - t.Helper() - prefs, err := config.New(filepath.Join(t.TempDir(), config.PrefsFileName)) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = prefs.Close() }) - - m, err := ParseManifest([]byte(`{"emotions_extensions": [".png", ".webp"]}`)) - if err != nil { - t.Fatal(err) - } - if n := m.SeedLearned(prefs, host); n == 0 { - t.Fatal("the manifest seeded nothing") - } - r := NewResolver(prefs) - return r, prefs -} - -// TestMixedFleetBothFormatsStayReachable is the regression test for the -// umineko.online "every emote button shows the same icon" report. -// -// That server declares its emote buttons as [".png", ".webp"] and genuinely -// ships both (~560 PNG-button characters, ~490 WebP-button). The learned table -// used to hold ONE extension per (host, type), so the first WebP character to -// load flipped the host to .webp for everyone — and a PNG-only character then -// probed .webp, 404'd, and had nothing left to try, because EmoteButton's -// configured list (config.defaultFormatOrders) is the single entry .webp. The -// grid fell back to the character icon in every cell. -// -// The invariant this pins: whichever format most recently succeeded, the OTHER -// one the server declared is still reachable on the recovery path. Order may -// churn; membership must not shrink. -func TestMixedFleetBothFormatsStayReachable(t *testing.T) { - const host = "umineko.online" - r, _ := newMixedFleetResolver(t, host) - - const base = "https://umineko.online/base/characters/don%20lc/emotions/button1_off" - reachable := func() []string { - // What the manager can probe in total: the learned-first candidate, then - // the recovery list once that 404s (manager.tryBase). - c := r.BuildCandidates(base, AssetTypeEmoteButton, host) - got := append([]string(nil), c.URLs...) - r.PutCandidates(c) - full := r.BuildFullListCandidates(base, AssetTypeEmoteButton, host) - for _, u := range full.URLs { - if !containsExt(got, u) { - got = append(got, u) - } - } - r.PutCandidates(full) - return got - } - hasExt := func(urls []string, ext string) bool { - for _, u := range urls { - if u == base+ext { - return true - } - } - return false - } - - // Seeded from the manifest: .png is probed first, .webp is behind it. - if got, want := r.BuildCandidates(base, AssetTypeEmoteButton, host), base+config.ExtPNG; true { - if len(got.URLs) != 1 || got.URLs[0] != want { - t.Errorf("seeded probe = %v, want exactly [%s] (one probe per asset)", got.URLs, want) - } - r.PutCandidates(got) - } - - // A WebP-button character loads and succeeds on .webp. This is the event that - // used to strand every PNG character on the server. - r.RecordSuccess(host, AssetTypeEmoteButton, config.ExtWebP) - - if got, want := r.LearnedList(host, AssetTypeEmoteButton), config.ExtWebP; len(got) == 0 || got[0] != want { - t.Errorf("after a .webp success the preferred format = %v, want %s first", got, want) - } - after := reachable() - if !hasExt(after, config.ExtPNG) { - t.Fatalf("REGRESSION: .png is unreachable after a .webp success — reachable = %v", after) - } - if !hasExt(after, config.ExtWebP) { - t.Errorf(".webp unreachable after succeeding: %v", after) - } - - // ...and back the other way: a PNG character now succeeds. The flip must be - // symmetric — the old table only ratcheted png -> webp and never returned. - r.RecordSuccess(host, AssetTypeEmoteButton, config.ExtPNG) - back := reachable() - if !hasExt(back, config.ExtWebP) { - t.Errorf("REGRESSION: .webp unreachable after a .png success — reachable = %v", back) - } - if !hasExt(back, config.ExtPNG) { - t.Errorf(".png unreachable after succeeding: %v", back) - } -} - -// TestLearnedListSurvivesRestart pins that a two-format host comes back with -// BOTH formats after a reload. WarmFromPrefs used to take exts[0] only, so a -// restart quietly re-truncated the list and re-armed the dead end. -func TestLearnedListSurvivesRestart(t *testing.T) { - const host = "umineko.online" - _, prefs := newMixedFleetResolver(t, host) - prefs2 := prefs // same prefs object; WarmFromPrefs reads the persisted snapshot - - fresh := NewResolver(prefs2) - got := fresh.LearnedList(host, AssetTypeEmoteButton) - if len(got) != 2 || got[0] != config.ExtPNG || got[1] != config.ExtWebP { - t.Errorf("after a warm-from-prefs the learned list = %v, want [%s %s]", got, config.ExtPNG, config.ExtWebP) - } -} - -// TestPromoteExtKeepsTheLoser pins promoteExt directly: it reorders, it never -// discards, it stays inside the cap, and it returns the SAME slice when nothing -// changes (the steady-state no-alloc, no-CAS path in RecordSuccess). -func TestPromoteExtKeepsTheLoser(t *testing.T) { - prev := []string{".png", ".webp"} - got := promoteExt(prev, ".webp") - if len(got) != 2 || got[0] != ".webp" || got[1] != ".png" { - t.Errorf("promoteExt(%v, .webp) = %v, want [.webp .png]", prev, got) - } - if prev[0] != ".png" || prev[1] != ".webp" { - t.Errorf("promoteExt mutated the published slice: %v", prev) - } - if same := promoteExt(got, ".webp"); &same[0] != &got[0] { - t.Error("promoting the existing front reallocated; the steady state must be free") - } - if got := promoteExt(nil, ".png"); len(got) != 1 || got[0] != ".png" { - t.Errorf("promoteExt(nil, .png) = %v, want [.png]", got) - } - // Cap: an absurd manifest must not grow the probe list without bound. - long := []string{".a", ".b", ".c", ".d", ".e", ".f"} - if got := promoteExt(long, ".z"); len(got) != learnedExtCap { - t.Errorf("promoteExt over-cap returned %d entries, want the %d cap", len(got), learnedExtCap) - } -} diff --git a/internal/assets/musicexact_test.go b/internal/assets/musicexact_test.go index f979ce26..3f4581d5 100644 --- a/internal/assets/musicexact_test.go +++ b/internal/assets/musicexact_test.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/netproxy" "github.com/SyntaxNyah/AsyncAO/internal/network" ) @@ -63,40 +62,3 @@ func TestMP3MusicFetchesExactlyTheURLItWasGiven(t *testing.T) { t.Errorf("origin saw %v, want exactly one request for the .mp3 (no format probing)", seen) } } - -// TestMusicFallbackChainReachesMP3 pins the second half: when a music asset DOES -// walk a chain — the diagnostic/export pass, the only music caller that ever -// does — mp3 is in it, after opus and ogg. -// -// The order is the contract, not just the membership: opus is the modern AO -// default and the zero-fallback single probe, ogg is the legacy bulk of live -// mirrors, and mp3 is the long tail. Putting mp3 earlier would spend a probe per -// track on servers that have none. Reading it through fullProbeChain rather than -// re-listing config's table is deliberate — this asserts what the manager will -// actually walk, so moving the table without moving the behavior still fails. -func TestMusicFallbackChainReachesMP3(t *testing.T) { - got := fullProbeChain(nil, AssetTypeMusic) - want := []string{config.ExtOpus, config.ExtOgg, config.ExtMP3} - if len(got) != len(want) { - t.Fatalf("music probe chain = %v, want %v", got, want) - } - for i := range want { - if got[i] != want[i] { - t.Fatalf("music probe chain = %v, want %v", got, want) - } - } - - // The three chain formats must all be ones the mixer can actually decode. - // A chain entry the audio backend never initialised is the v1.71 INIT_FLAC - // ghost: the fetch succeeds, the decode silently fails, and the track is - // "just broken". The shipped SDL3_mixer decodes Ogg, MP3 and FLAC itself and - // Opus through opusfile, so opus/ogg/mp3 are all covered — this pin fails the day - // someone adds a fourth format here without checking that. - for _, ext := range got { - switch ext { - case config.ExtOpus, config.ExtOgg, config.ExtMP3, config.ExtWAV: - default: - t.Errorf("music chain offers %s, which the SDL_mixer Init list does not cover", ext) - } - } -} diff --git a/internal/assets/notify_test.go b/internal/assets/notify_test.go index fc65ffdd..4226cfe3 100644 --- a/internal/assets/notify_test.go +++ b/internal/assets/notify_test.go @@ -36,7 +36,7 @@ func TestManagerDeliveryNotify(t *testing.T) { }) base := local.BaseURL() + "characters/witch/emotions/button1_off" - rig.resolver.RecordSuccess(HostOf(base), AssetTypeEmoteButton, config.ExtPNG) + rig.manager.AllowFormats(local.BaseURL(), map[AssetType]string{AssetTypeEmoteButton: config.ExtPNG}) rig.manager.Prefetch(base, AssetTypeEmoteButton, network.PriorityHigh) // AssetType: EmoteButton (test) deadline := time.After(managerWait) diff --git a/internal/assets/resolver.go b/internal/assets/resolver.go deleted file mode 100644 index 036d48e7..00000000 --- a/internal/assets/resolver.go +++ /dev/null @@ -1,292 +0,0 @@ -package assets - -import ( - "sync" - "sync/atomic" - - "github.com/SyntaxNyah/AsyncAO/internal/config" -) - -// candidatePoolMaxCap caps the slice capacity worth pooling; anything bigger is left to the GC. -const candidatePoolMaxCap = 8 - -// Candidates is a pooled probe list; pooling the struct keeps the learned path at one allocation. -type Candidates struct { - // URLs are the candidate URLs in probe order. - URLs []string - // Learned reports whether the list came from the learned table. - Learned bool -} - -// learnedExtCap bounds a learned list (hard rule 4), so a hostile extensions.json cannot grow the probes. -const learnedExtCap = 4 - -// learnedTable is the immutable snapshot behind the atomic pointer: lock-free reads (hard rule 5), copy-on-write. -type learnedTable struct { - hosts map[string]*[AssetTypeCount][]string -} - -var emptyLearnedTable = &learnedTable{hosts: map[string]*[AssetTypeCount][]string{}} - -// promoteExt returns prev with ext moved to the front as a fresh slice, or prev itself if already front. -func promoteExt(prev []string, ext string) []string { - if len(prev) > 0 && prev[0] == ext { - return prev - } - next := make([]string, 0, min(len(prev)+1, learnedExtCap)) - next = append(next, ext) - for _, e := range prev { - if e == ext { // already at the front - continue - } - if len(next) == learnedExtCap { - break - } - next = append(next, e) - } - return next -} - -// formatListCache is a per-generation snapshot of probe lists, so a miss costs an atomic load, not an RLock. -type formatListCache struct { - gen uint64 - lists [AssetTypeCount][]string -} - -// Resolver turns (base, type, host) into URLs to probe, learning working formats per (host, type). -type Resolver struct { - table atomic.Pointer[learnedTable] - formats atomic.Pointer[formatListCache] - prefs *config.AssetPreferences - pool sync.Pool // *Candidates - - learnedHits atomic.Int64 - learnedMisses atomic.Int64 -} - -// NewResolver builds a resolver reading format policy from prefs and warms the learned table. -func NewResolver(prefs *config.AssetPreferences) *Resolver { - r := &Resolver{prefs: prefs} - r.table.Store(emptyLearnedTable) - r.pool.New = func() any { - return &Candidates{URLs: make([]string, 0, candidatePoolMaxCap)} - } - r.WarmFromPrefs() - return r -} - -// WarmFromPrefs seeds the learned table from preferences, so the next session's cold load probes once per asset. -func (r *Resolver) WarmFromPrefs() { - if r.prefs == nil { - return - } - snapshot := r.prefs.Load().LearnedSnapshot() - if len(snapshot) == 0 { - return - } - hosts := map[string]*[AssetTypeCount][]string{} - for key, exts := range snapshot { - host, typeName, ok := splitLearnedKey(key) - if !ok || len(exts) == 0 { - continue - } - t, ok := TypeFromName(typeName) - if !ok { - continue - } - arr := hosts[host] - if arr == nil { - arr = new([AssetTypeCount][]string) - hosts[host] = arr - } - // Restore the whole list, or a host with two formats gets stuck on one; clamp for hand-edited prefs. - if len(exts) > learnedExtCap { - exts = exts[:learnedExtCap] - } - arr[t] = exts - } - r.table.Store(&learnedTable{hosts: hosts}) -} - -// splitLearnedKey splits "|" on the last separator so host:port and IPv6-like hosts survive. -func splitLearnedKey(key string) (host, typeName string, ok bool) { - for i := len(key) - 1; i >= 0; i-- { - if key[i:i+1] == config.LearnedKeySeparator { - return key[:i], key[i+1:], true - } - } - return "", "", false -} - -// Learned returns the preferred extension for (host, t): the format that most recently worked. -func (r *Resolver) Learned(host string, t AssetType) (string, bool) { - exts := r.LearnedList(host, t) - if len(exts) == 0 { - return "", false - } - return exts[0], true -} - -// LearnedList returns every format learned for (host, t), preferred first; the slice is read-only. -func (r *Resolver) LearnedList(host string, t AssetType) []string { - arr := r.table.Load().hosts[host] - if arr == nil { - return nil - } - return arr[t] -} - -// BuildCandidates returns URLs to probe: one on a learned hit, else FormatList; return it via PutCandidates. -func (r *Resolver) BuildCandidates(base string, t AssetType, host string) *Candidates { - c := r.pool.Get().(*Candidates) - c.URLs = c.URLs[:0] - - tbl := r.table.Load() - if arr := tbl.hosts[host]; arr != nil { - // Only the front: the default is one probe per asset, and the rest wait for a 404 (BuildFullListCandidates). - if exts := arr[t]; len(exts) > 0 { - r.learnedHits.Add(1) - c.Learned = true - c.URLs = append(c.URLs, base+exts[0]) - return c - } - } - - r.learnedMisses.Add(1) - c.Learned = false - for _, ext := range r.formatList(t) { - c.URLs = append(c.URLs, base+ext) - } - return c -} - -// BuildFullListCandidates lists the learned then configured formats, never writing the learned table, -// so a stale-format re-probe cannot affect concurrent readers; BuildCandidates already counted this miss. -func (r *Resolver) BuildFullListCandidates(base string, t AssetType, host string) *Candidates { - c := r.pool.Get().(*Candidates) - c.URLs = c.URLs[:0] - c.Learned = false - // Learned first: the configured list may be the single entry that just 404'd, leaving nothing to try. - for _, ext := range r.LearnedList(host, t) { - c.URLs = append(c.URLs, base+ext) - } - for _, ext := range r.formatList(t) { - if containsExt(r.LearnedList(host, t), ext) { - continue // already queued above; probing it twice wastes a round trip - } - c.URLs = append(c.URLs, base+ext) - } - return c -} - -// containsExt is a linear scan of a list capped at learnedExtCap, on the recovery path only. -func containsExt(exts []string, ext string) bool { - for _, e := range exts { - if e == ext { - return true - } - } - return false -} - -// formatList returns the cached list for t, rebuilt per format generation; a racing rebuild is identical. -func (r *Resolver) formatList(t AssetType) []string { - gen := r.prefs.FormatGeneration() - if cached := r.formats.Load(); cached != nil && cached.gen == gen { - return cached.lists[t] - } - fresh := &formatListCache{gen: gen} - for tt := AssetType(0); tt < AssetTypeCount; tt++ { - fresh.lists[tt] = r.prefs.Load().FormatList(tt.Name()) - } - r.formats.Store(fresh) - return fresh.lists[t] -} - -// PutCandidates returns c to the pool; the caller must not touch it afterwards. -func (r *Resolver) PutCandidates(c *Candidates) { - if c == nil || cap(c.URLs) > candidatePoolMaxCap { - return - } - c.URLs = c.URLs[:0] - c.Learned = false - r.pool.Put(c) -} - -// RecordSuccess learns ext with a copy-on-write CAS loop and marks preferences dirty (hard rules 3 and 5). -func (r *Resolver) RecordSuccess(host string, t AssetType, ext string) { - if !t.Valid() || host == "" || ext == "" { - return - } - for { - old := r.table.Load() - var prev []string - if arr := old.hosts[host]; arr != nil { - prev = arr[t] - } - if len(prev) > 0 && prev[0] == ext { - return - } - next := cloneTableForHost(old, host) - next.hosts[host][t] = promoteExt(prev, ext) - if r.table.CompareAndSwap(old, next) { - break - } - // Lost the race with another learn: retry against the new table. - } - if r.prefs != nil { - r.prefs.RecordLearned(host, t.Name(), ext) - } -} - -// Invalidate forgets the learned format for (host, t), for example after a server-side repack. -func (r *Resolver) Invalidate(host string, t AssetType) { - if !t.Valid() { - return - } - for { - old := r.table.Load() - arr := old.hosts[host] - if arr == nil || len(arr[t]) == 0 { - return - } - next := cloneTableForHost(old, host) - next.hosts[host][t] = nil - if r.table.CompareAndSwap(old, next) { - return - } - } -} - -// InvalidateAll wipes the in-memory learned table; the config mutators handle the preferences side. -func (r *Resolver) InvalidateAll() { - r.table.Store(emptyLearnedTable) -} - -// cloneTableForHost copies the host map and touched array; lists stay shared, as promoteExt never writes one. -func cloneTableForHost(old *learnedTable, host string) *learnedTable { - hosts := make(map[string]*[AssetTypeCount][]string, len(old.hosts)+1) - for h, arr := range old.hosts { - hosts[h] = arr - } - fresh := new([AssetTypeCount][]string) - if prev := old.hosts[host]; prev != nil { - *fresh = *prev - } - hosts[host] = fresh - return &learnedTable{hosts: hosts} -} - -// ResolverStats is a point-in-time counter snapshot. -type ResolverStats struct { - LearnedHits int64 - LearnedMisses int64 -} - -// Stats snapshots the resolver's counters. -func (r *Resolver) Stats() ResolverStats { - return ResolverStats{ - LearnedHits: r.learnedHits.Load(), - LearnedMisses: r.learnedMisses.Load(), - } -} diff --git a/internal/assets/resolver_test.go b/internal/assets/resolver_test.go deleted file mode 100644 index 3e9f255d..00000000 --- a/internal/assets/resolver_test.go +++ /dev/null @@ -1,288 +0,0 @@ -package assets - -import ( - "fmt" - "path/filepath" - "sync" - "testing" - "time" - - "github.com/SyntaxNyah/AsyncAO/internal/config" -) - -// testing.TB rather than *testing.T so a benchmark can build the same rig. -func newTestPrefs(tb testing.TB) *config.AssetPreferences { - tb.Helper() - p, err := config.New(filepath.Join(tb.TempDir(), config.PrefsFileName)) - if err != nil { - tb.Fatalf("config.New: %v", err) - } - tb.Cleanup(func() { _ = p.Close() }) - return p -} - -// TestTypeNamesMatchConfig pins the enum ↔ config-name correspondence both -// ways, including declaration order. -func TestTypeNamesMatchConfig(t *testing.T) { - if len(config.TypeNames) != int(AssetTypeCount) { - t.Fatalf("config.TypeNames has %d entries, AssetTypeCount = %d", len(config.TypeNames), AssetTypeCount) - } - for i, name := range config.TypeNames { - at := AssetType(i) - if at.Name() != name { - t.Errorf("AssetType(%d).Name() = %q, config.TypeNames[%d] = %q", i, at.Name(), i, name) - } - back, ok := TypeFromName(name) - if !ok || back != at { - t.Errorf("TypeFromName(%q) = %v,%v, want %v", name, back, ok, at) - } - } -} - -func TestBuildCandidatesZeroFallbackDefaults(t *testing.T) { - r := NewResolver(newTestPrefs(t)) - const host = "assets.example.com" - const base = "http://assets.example.com/characters/phoenix/(a)normal" - - c := r.BuildCandidates(base, AssetTypeCharSprite, host) - defer r.PutCandidates(c) - if len(c.URLs) != 1 || c.URLs[0] != base+config.ExtWebP { - t.Errorf("sprite candidates = %v, want exactly [%s]", c.URLs, base+config.ExtWebP) - } - if c.Learned { - t.Error("fresh resolver claims learned") - } - - icon := r.BuildCandidates(base, AssetTypeCharIcon, host) - defer r.PutCandidates(icon) - if len(icon.URLs) != 1 || icon.URLs[0] != base+config.ExtPNG { - t.Errorf("icon candidates = %v, want exactly [%s] (PNG only, no webp fallback)", icon.URLs, base+config.ExtPNG) - } -} - -func TestBuildCandidatesLearnedSingleProbe(t *testing.T) { - prefs := newTestPrefs(t) - prefs.SetGlobalFallbacks(true) // 4-format list when unlearned - r := NewResolver(prefs) - const host = "assets.example.com" - const base = "http://assets.example.com/characters/edgeworth/(b)normal" - - before := r.BuildCandidates(base, AssetTypeCharSprite, host) - if len(before.URLs) != 4 { - t.Fatalf("unlearned candidates = %v, want 4 (webp+legacy chain)", before.URLs) - } - r.PutCandidates(before) - - r.RecordSuccess(host, AssetTypeCharSprite, config.ExtGIF) - after := r.BuildCandidates(base, AssetTypeCharSprite, host) - defer r.PutCandidates(after) - if len(after.URLs) != 1 || after.URLs[0] != base+config.ExtGIF || !after.Learned { - t.Errorf("learned candidates = %+v, want single learned %s", after, base+config.ExtGIF) - } -} - -func TestLearnedIsPerHostAndPerType(t *testing.T) { - r := NewResolver(newTestPrefs(t)) - r.RecordSuccess("host-a.example.com", AssetTypeCharSprite, config.ExtWebP) - - if _, ok := r.Learned("host-b.example.com", AssetTypeCharSprite); ok { - t.Error("learned format leaked across hosts") - } - if _, ok := r.Learned("host-a.example.com", AssetTypeBackground); ok { - t.Error("learned format leaked across types") - } - if ext, ok := r.Learned("host-a.example.com", AssetTypeCharSprite); !ok || ext != config.ExtWebP { - t.Errorf("Learned = %q,%v", ext, ok) - } -} - -func TestInvalidate(t *testing.T) { - r := NewResolver(newTestPrefs(t)) - const host = "h.example.com" - r.RecordSuccess(host, AssetTypeCharSprite, config.ExtWebP) - r.RecordSuccess(host, AssetTypeBackground, config.ExtWebP) - - r.Invalidate(host, AssetTypeCharSprite) - if _, ok := r.Learned(host, AssetTypeCharSprite); ok { - t.Error("Invalidate left the entry") - } - if _, ok := r.Learned(host, AssetTypeBackground); !ok { - t.Error("Invalidate hit an unrelated type") - } - - r.InvalidateAll() - if _, ok := r.Learned(host, AssetTypeBackground); ok { - t.Error("InvalidateAll left an entry") - } -} - -func TestWarmFromPrefsRoundTrip(t *testing.T) { - prefs := newTestPrefs(t) - r1 := NewResolver(prefs) - r1.RecordSuccess("cdn.example.com:8080", AssetTypeMusic, config.ExtOpus) - r1.RecordSuccess("cdn.example.com:8080", AssetTypeCharSprite, config.ExtWebP) - - // A second resolver over the same prefs (fresh session) must wake up - // already knowing the formats. - r2 := NewResolver(prefs) - if ext, ok := r2.Learned("cdn.example.com:8080", AssetTypeMusic); !ok || ext != config.ExtOpus { - t.Errorf("warm start lost music format: %q,%v", ext, ok) - } - if ext, ok := r2.Learned("cdn.example.com:8080", AssetTypeCharSprite); !ok || ext != config.ExtWebP { - t.Errorf("warm start lost sprite format: %q,%v", ext, ok) - } -} - -// TestRecordSuccessCASRace is the §15 CAS race test: concurrent learns on -// distinct (host, type) pairs must all survive the copy-on-write loop. -func TestRecordSuccessCASRace(t *testing.T) { - r := NewResolver(newTestPrefs(t)) - const hosts = 8 - var wg sync.WaitGroup - for h := 0; h < hosts; h++ { - for tt := AssetType(0); tt < AssetTypeCount; tt++ { - wg.Add(1) - go func(h int, tt AssetType) { - defer wg.Done() - r.RecordSuccess(fmt.Sprintf("host%d.example.com", h), tt, config.ExtWebP) - }(h, tt) - } - } - wg.Wait() - - for h := 0; h < hosts; h++ { - for tt := AssetType(0); tt < AssetTypeCount; tt++ { - if _, ok := r.Learned(fmt.Sprintf("host%d.example.com", h), tt); !ok { - t.Fatalf("lost learn for host%d/%v in CAS race", h, tt) - } - } - } -} - -// TestFormatListCacheFollowsSettings pins the generation invalidation: the -// miss-path cache must rebuild the moment any format setting changes. -func TestFormatListCacheFollowsSettings(t *testing.T) { - prefs := newTestPrefs(t) - r := NewResolver(prefs) - const host = "h.example.com" - const base = "http://h.example.com/characters/x/(a)normal" - - c := r.BuildCandidates(base, AssetTypeCharSprite, host) - if len(c.URLs) != 1 { - t.Fatalf("default candidates = %v", c.URLs) - } - r.PutCandidates(c) - - prefs.SetGlobalFallbacks(true) // bumps the format generation - c = r.BuildCandidates(base, AssetTypeCharSprite, host) - if len(c.URLs) != 4 { - t.Errorf("cached format list went stale after settings change: %v", c.URLs) - } - r.PutCandidates(c) - - prefs.SetFormatOrder(AssetTypeCharSprite.Name(), []string{config.ExtGIF}) - c = r.BuildCandidates(base, AssetTypeCharSprite, host) - defer r.PutCandidates(c) - if len(c.URLs) == 0 || c.URLs[0] != base+config.ExtGIF { - t.Errorf("cached format list missed a format-order change: %v", c.URLs) - } -} - -// BenchmarkBuildCandidates_Miss measures the unlearned path (cold icon -// walls): with the generation cache it is lock-free after the first build. -func BenchmarkBuildCandidates_Miss(b *testing.B) { - prefs, err := config.New(filepath.Join(b.TempDir(), config.PrefsFileName)) - if err != nil { - b.Fatal(err) - } - defer prefs.Close() - r := NewResolver(prefs) - const host = "assets.example.com" - const base = "http://assets.example.com/characters/char/char_icon" - - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - c := r.BuildCandidates(base, AssetTypeCharIcon, host) - r.PutCandidates(c) - } -} - -// TestBuildCandidatesLearnedAllocGate enforces the ≤1 alloc budget in plain -// `go test`, not just benchmarks (spec §6). -func TestBuildCandidatesLearnedAllocGate(t *testing.T) { - r := NewResolver(newTestPrefs(t)) - const host = "assets.example.com" - const base = "http://assets.example.com/characters/maya/(a)normal" - r.RecordSuccess(host, AssetTypeCharSprite, config.ExtWebP) - - allocs := testing.AllocsPerRun(2000, func() { - c := r.BuildCandidates(base, AssetTypeCharSprite, host) - r.PutCandidates(c) - }) - if allocs > 1 { - t.Errorf("learned BuildCandidates allocates %.1f objects/op, budget ≤ 1 (the URL string)", allocs) - } -} - -func TestSplitLearnedKey(t *testing.T) { - host, typeName, ok := splitLearnedKey("cdn.example.com:8080" + config.LearnedKeySeparator + config.TypeCharSprite) - if !ok || host != "cdn.example.com:8080" || typeName != config.TypeCharSprite { - t.Errorf("splitLearnedKey = %q,%q,%v", host, typeName, ok) - } - if _, _, ok := splitLearnedKey("no-separator"); ok { - t.Error("splitLearnedKey accepted a key without separator") - } -} - -// BenchmarkBuildCandidates_Learned is the §1 gate: < 100 ns, ≤ 1 alloc/op. -func BenchmarkBuildCandidates_Learned(b *testing.B) { - prefs, err := config.New(filepath.Join(b.TempDir(), config.PrefsFileName)) - if err != nil { - b.Fatal(err) - } - defer prefs.Close() - r := NewResolver(prefs) - const host = "assets.example.com" - const base = "http://assets.example.com/characters/phoenix/(a)normal" - r.RecordSuccess(host, AssetTypeCharSprite, config.ExtWebP) - - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - c := r.BuildCandidates(base, AssetTypeCharSprite, host) - r.PutCandidates(c) - } -} - -// BenchmarkResolveAssets approximates a full char-select resolution pass -// (200 assets): must stay far under 1 ms (spec §15). -func BenchmarkResolveAssets(b *testing.B) { - prefs, err := config.New(filepath.Join(b.TempDir(), config.PrefsFileName)) - if err != nil { - b.Fatal(err) - } - defer prefs.Close() - r := NewResolver(prefs) - const host = "assets.example.com" - const assetCount = 200 - bases := make([]string, assetCount) - for i := range bases { - bases[i] = fmt.Sprintf("http://assets.example.com/characters/char%03d/char_icon", i) - } - r.RecordSuccess(host, AssetTypeCharIcon, config.ExtPNG) - - b.ReportAllocs() - b.ResetTimer() - start := time.Now() - for i := 0; i < b.N; i++ { - for _, base := range bases { - c := r.BuildCandidates(base, AssetTypeCharIcon, host) - r.PutCandidates(c) - } - } - if b.N > 0 { - perPass := time.Since(start) / time.Duration(b.N) - b.ReportMetric(float64(perPass.Nanoseconds()), "ns/200assets") - } -} diff --git a/internal/config/collection_helpers.go b/internal/config/collection_helpers.go index 0f61eb9f..06b625d3 100644 --- a/internal/config/collection_helpers.go +++ b/internal/config/collection_helpers.go @@ -79,16 +79,3 @@ func toggleInt(list []int, v int) ([]int, bool) { } return append(list, v), true } - -// promoteFront moves ext to the front, deduped and capped, so the most recently seen entry leads the preference order. -func promoteFront(list []string, ext string, cap int) []string { - next := make([]string, 0, len(list)+1) - next = append(next, ext) - for _, e := range list { - if e == ext || len(next) == cap { - continue - } - next = append(next, e) - } - return next -} diff --git a/internal/config/collection_helpers_test.go b/internal/config/collection_helpers_test.go index 1867ab0f..454658ab 100644 --- a/internal/config/collection_helpers_test.go +++ b/internal/config/collection_helpers_test.go @@ -94,21 +94,3 @@ func TestCollectionHelpersToggleInt(t *testing.T) { t.Fatalf("remove: got %v now=%v", got, now) } } - -func TestCollectionHelpersPromoteFront(t *testing.T) { - // promote existing to front - got := promoteFront([]string{"a", "b", "c"}, "b", 4) - if !reflect.DeepEqual(got, []string{"b", "a", "c"}) { - t.Fatalf("promote: got %v", got) - } - // new entry leads, deduped - got = promoteFront([]string{"a", "b"}, "x", 4) - if !reflect.DeepEqual(got, []string{"x", "a", "b"}) { - t.Fatalf("new lead: got %v", got) - } - // cap bounds the result - got = promoteFront([]string{"a", "b", "c"}, "x", 3) - if !reflect.DeepEqual(got, []string{"x", "a", "b"}) { - t.Fatalf("cap: got %v", got) - } -} diff --git a/internal/config/defaults.go b/internal/config/defaults.go index 8e607bc6..e07dd81b 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -49,64 +49,6 @@ const ( // OptionalImageFormats are the opt-in probe formats Settings offers, all off by default (zero-fallback policy). var OptionalImageFormats = []string{ExtWebP, ExtAVIF, ExtAPNG, ExtGIF, ExtPNG, ExtJPG} -// defaultFormatOrders is the entire probe list per type while fallbacks are off, so a cold asset costs one probe. -// Misc has two: chatbox skins have no extensions.json key and one mirror can mix chat.png with chatbox.webp. -// There is no ".webp.animated": animation is the VP8X ANIM flag, detected at decode time. -var defaultFormatOrders = map[string][]string{ - TypeCharIcon: {ExtPNG}, - TypeCharSprite: {ExtWebP}, - TypeBackground: {ExtWebP}, - TypeMisc: {ExtPNG, ExtWebP}, // png = AO2's stock misc convention; webp = the modern packs - TypeDeskOverlay: {ExtWebP}, - TypeShoutBubble: {ExtWebP}, - TypeSFX: {ExtOpus}, - TypeMusic: {ExtOpus}, - TypeBlip: {ExtOpus}, - TypeEmoteButton: {ExtWebP}, - // Effect packs mix .webp and .png with no extensions.json key, so the learned list and promote limit probes. - // .webp is get_image_suffix's first choice. - TypeEffect: {ExtWebP}, -} - -// legacyFallbackChains is appended, in order and deduplicated, to the format order when fallbacks are on for a type. -var legacyFallbackChains = map[string][]string{ - TypeCharIcon: {ExtWebP}, - TypeCharSprite: {ExtAPNG, ExtGIF, ExtPNG}, - TypeBackground: {ExtAPNG, ExtGIF, ExtPNG}, - TypeDeskOverlay: {ExtAPNG, ExtGIF, ExtPNG}, - TypeShoutBubble: {ExtAPNG, ExtGIF, ExtPNG}, - TypeMisc: {ExtAPNG, ExtGIF}, // png + webp are both in the default order already - TypeSFX: {ExtOgg, ExtWAV, ExtMP3}, - TypeMusic: {ExtOgg, ExtMP3}, - TypeBlip: {ExtOgg, ExtWAV, ExtMP3}, - // Legacy packs ship PNG buttons; APNG/GIF cover animated button packs. - TypeEmoteButton: {ExtAPNG, ExtGIF, ExtPNG}, - // get_image_suffix's exact order (text_file_functions.cpp:381-404). - TypeEffect: {ExtAPNG, ExtGIF, ExtPNG}, -} - -// DefaultFormatOrder returns a copy of a type's probe list, or nil for an unknown name. -func DefaultFormatOrder(typeName string) []string { - return cloneStrings(defaultFormatOrders[typeName]) -} - -// LegacyFallbackChain returns a copy of a type's legacy fallback chain. -func LegacyFallbackChain(typeName string) []string { - return cloneStrings(legacyFallbackChains[typeName]) -} - -// defaultAssetTypes builds the per-type table with fallbacks off and default format orders. -func defaultAssetTypes() map[string]AssetTypePrefs { - m := make(map[string]AssetTypePrefs, len(TypeNames)) - for _, name := range TypeNames { - m[name] = AssetTypePrefs{ - FormatOrder: DefaultFormatOrder(name), - FallbacksEnabled: false, - } - } - return m -} - func cloneStrings(s []string) []string { if s == nil { return nil diff --git a/internal/config/preferences.go b/internal/config/preferences.go index 6b9baa34..aca4df10 100644 --- a/internal/config/preferences.go +++ b/internal/config/preferences.go @@ -33,9 +33,6 @@ const ( PrefsFileName = "asset_preferences.json" - // LearnedKeySeparator joins learned-format keys: "|". - LearnedKeySeparator = "|" - prefsFilePerm = 0o644 prefsDirPerm = 0o755 prefsTmpPattern = PrefsFileName + ".*.tmp" @@ -52,9 +49,6 @@ const ( // defaultPreferAnimated is a decode and render toggle, never an extra network probe. const defaultPreferAnimated = true -// defaultFormatAutoDetect is on because seeding from a server's extensions.json beats blind probing. -const defaultFormatAutoDetect = true - // Blip cadence: one blip per N revealed letters; mirrors courtroom.DefaultBlipRate, which config can't import. const ( defaultBlipRate = 2 @@ -618,13 +612,6 @@ func DPIScalePercent(dpi float64) int { return pct } -type AssetTypePrefs struct { - // FormatOrder is the ordered probe list; empty means the built-in default. - FormatOrder []string `json:"formatOrder"` - // FallbacksEnabled appends this type's legacy chain to FormatOrder. - FallbacksEnabled bool `json:"fallbacksEnabled"` -} - // AssetPreferences is the persisted configuration; exported methods are safe for concurrent use. type AssetPreferences struct { mu sync.RWMutex @@ -648,9 +635,6 @@ type AssetPreferences struct { // themeFitStampPending records a stamp this load wrote; newWithDebounce clears it by flushing synchronously. themeFitStampPending bool - // formatGen increments on any change to an effective probe list; consumers key derived format tables by it. - formatGen atomic.Uint64 - // wardrobeGen increments on any wardrobe change; char select keys its set by it for lock-free lookups. wardrobeGen atomic.Uint64 @@ -912,7 +896,6 @@ func defaultSettings() *Settings { NameSat: defaultNameColorSat, NameVal: defaultNameColorVal, BgSlideshowSecs: defaultBgSlideshowSecs, - AutoDetectFormats: defaultFormatAutoDetect, BlipRate: defaultBlipRate, ThemeLayoutOn: defaultThemeLayout, ThemeFit: defaultThemeFit, @@ -953,8 +936,6 @@ func defaultSettings() *Settings { TextCrawlMs: DefaultTextCrawlMs, TextStayMs: DefaultTextStayMs, ChatRateLimitMs: DefaultChatRateLimitMs, - AssetTypes: defaultAssetTypes(), - LearnedFormats: map[string][]string{}, } } @@ -1055,7 +1036,6 @@ var resetContentFields = map[string]bool{ "ServerWarm": true, // per-server: char/bg/wardrobe/folders/LOGINS/friends "UserMacros": true, "CallWordList": true, - "LearnedFormats": true, // learned per-host formats (cache-adjacent) "ThemeRectOv": true, // layout-editor overrides "ThemeRectRotations": true, // layout-editor rotation overrides (A4) — user content, survives a settings reset like ThemeRectOv (ClassicRotations is NOT preserved, mirroring ClassicLayout/ClassicAnchors) "LayoutProfiles": true, // saved full-state layout profiles (A6) — user content, survives a settings reset like ThemeRectOv @@ -1084,7 +1064,6 @@ func (p *AssetPreferences) resetLocked(keep map[string]bool) { } } p.settings.Store(fresh) - p.formatGen.Add(1) // format/fallback prefs may have changed; invalidate resolver caches p.wardrobeGen.Add(1) // a reset can wipe ServerWarm (and its wardrobes) p.markDirty() } @@ -1133,132 +1112,6 @@ func (p *AssetPreferences) Close() error { return err } -// FormatGeneration changes on any probe-list mutation, so derived caches rebuild without holding locks. -func (p *AssetPreferences) FormatGeneration() uint64 { - return p.formatGen.Load() -} - -// FormatList returns a fresh slice: the configured list plus, when fallbacks are on, the legacy chain deduplicated. -func (s *Settings) FormatList(typeName string) []string { - - tp, ok := s.AssetTypes[typeName] - order := tp.FormatOrder - if !ok || len(order) == 0 { - order = defaultFormatOrders[typeName] - } - - withFallbacks := s.GlobalFallbacksEnabled || tp.FallbacksEnabled - capacity := len(order) - if withFallbacks { - capacity += len(legacyFallbackChains[typeName]) - } - list := make([]string, 0, capacity) - for _, ext := range order { - if !slices.Contains(list, ext) { - list = append(list, ext) - } - } - if withFallbacks { - for _, ext := range legacyFallbackChains[typeName] { - if !slices.Contains(list, ext) { - list = append(list, ext) - } - } - } - return list -} - -// FormatOrder returns the configured probe order, before fallbacks. -func (s *Settings) FormatOrder(typeName string) []string { - - if tp, ok := s.AssetTypes[typeName]; ok && len(tp.FormatOrder) > 0 { - return cloneStrings(tp.FormatOrder) - } - return DefaultFormatOrder(typeName) -} - -// SetFormatOrder replaces a type's order and invalidates its learned formats, which may no longer lead. -func (p *AssetPreferences) SetFormatOrder(typeName string, order []string) { - changed := false - p.Update(func(sn *Settings) { - tp := sn.AssetTypes[typeName] - if slices.Equal(tp.FormatOrder, order) { - return - } - tp.FormatOrder = cloneStrings(order) - if sn.AssetTypes == nil { - sn.AssetTypes = map[string]AssetTypePrefs{} - } - sn.AssetTypes[typeName] = tp - suffix := LearnedKeySeparator + typeName - for key := range sn.LearnedFormats { - if strings.HasSuffix(key, suffix) { - delete(sn.LearnedFormats, key) - } - } - changed = true - }) - if changed { - p.formatGen.Add(1) - } -} - -// ResetFormatOrder restores the default order and invalidates the type's learned formats. -func (p *AssetPreferences) ResetFormatOrder(typeName string) { - p.SetFormatOrder(typeName, DefaultFormatOrder(typeName)) -} - -// TypeFallbacksEnabled reports the per-type toggle, not the global one. -func (s *Settings) TypeFallbacksEnabled(typeName string) bool { - - return s.AssetTypes[typeName].FallbacksEnabled -} - -// SetTypeFallbacks toggles a type's chain and invalidates its learned formats. -func (p *AssetPreferences) SetTypeFallbacks(typeName string, enabled bool) { - changed := false - p.Update(func(sn *Settings) { - tp := sn.AssetTypes[typeName] - if tp.FallbacksEnabled == enabled { - return - } - tp.FallbacksEnabled = enabled - if len(tp.FormatOrder) == 0 { - tp.FormatOrder = DefaultFormatOrder(typeName) - } - if sn.AssetTypes == nil { - sn.AssetTypes = map[string]AssetTypePrefs{} - } - sn.AssetTypes[typeName] = tp - suffix := LearnedKeySeparator + typeName - for key := range sn.LearnedFormats { - if strings.HasSuffix(key, suffix) { - delete(sn.LearnedFormats, key) - } - } - changed = true - }) - if changed { - p.formatGen.Add(1) - } -} - -// SetGlobalFallbacks toggles all fallbacks and invalidates all learned formats, since every probe list changed. -func (p *AssetPreferences) SetGlobalFallbacks(enabled bool) { - changed := false - p.Update(func(sn *Settings) { - if sn.GlobalFallbacksEnabled == enabled { - return - } - sn.GlobalFallbacksEnabled = enabled - sn.LearnedFormats = map[string][]string{} - changed = true - }) - if changed { - p.formatGen.Add(1) - } -} - // SpriteScalingMode is clamped on read too, so a newer build's value can't index past this build's options. func (p *AssetPreferences) SpriteScalingMode() int { snap := p.Load() @@ -1332,33 +1185,6 @@ func (p *AssetPreferences) EmoteGridGap() int { return value.Clamp(snap.EmoteGridGapPx, MinEmoteGridGapPx, MaxEmoteGridGapPx) } -// ClearLearnedType drops every host's learned format for one type, so the next probe re-derives it. -func (p *AssetPreferences) ClearLearnedType(typeName string) { - p.Update(func(sn *Settings) { - dropLearnedType(sn, typeName) - }) - p.formatGen.Add(1) -} - -// ClearLearnedHost drops one host's formats, sparing other servers a re-probe, and reports how many. -// The separator can't occur in a host, so the prefix match is exact. -func (p *AssetPreferences) ClearLearnedHost(host string) int { - if host == "" { - return 0 - } - prefix := host + LearnedKeySeparator - n := 0 - p.Update(func(sn *Settings) { - for key := range sn.LearnedFormats { - if strings.HasPrefix(key, prefix) { - delete(sn.LearnedFormats, key) - n++ - } - } - }) - return n -} - func (s *Settings) HighlightColorRGB() int { return s.HighlightColor & rgbMask @@ -3237,87 +3063,6 @@ func (p *AssetPreferences) ImportSettings(srcPath string) error { return nil } -func LearnedKey(host, typeName string) string { - return host + LearnedKeySeparator + typeName -} - -// LearnedExtCap mirrors the resolver's cap; they must agree or a reload drops formats the session learned. -const LearnedExtCap = 4 - -// RecordLearned moves ext to the front, since a host can serve several formats for a class. -// Mirrors assets.promoteExt; they must stay in step or a restart resurrects a truncated list. -func (p *AssetPreferences) RecordLearned(host, typeName, ext string) { - if ext == "" { - return - } - key := LearnedKey(host, typeName) - p.Update(func(sn *Settings) { - existing := sn.LearnedFormats[key] - if len(existing) > 0 && existing[0] == ext { - return // already preferred; no write, no dirty - } - if sn.LearnedFormats == nil { - sn.LearnedFormats = map[string][]string{} - } - sn.LearnedFormats[key] = promoteFront(existing, ext, LearnedExtCap) - }) -} - -// RecordLearnedList replaces because a re-read manifest supersedes probing; empty exts keeps what was learned. -func (p *AssetPreferences) RecordLearnedList(host, typeName string, exts []string) { - if len(exts) == 0 { - return - } - if len(exts) > LearnedExtCap { - exts = exts[:LearnedExtCap] - } - key := LearnedKey(host, typeName) - p.Update(func(sn *Settings) { - if equalStrings(sn.LearnedFormats[key], exts) { - return // unchanged; no write, no dirty - } - if sn.LearnedFormats == nil { - sn.LearnedFormats = map[string][]string{} - } - sn.LearnedFormats[key] = cloneStrings(exts) // caller's slice must not alias the stored one - }) -} - -func equalStrings(a, b []string) bool { - if len(a) != len(b) { - return false - } - for i := range a { - if a[i] != b[i] { - return false - } - } - return true -} - -// ExtProfile returns a host's extensions.json profile, or ""; it overrides the manifest and global default. -func (s *Settings) ExtProfile(host string) string { - - return s.ExtProfiles[host] -} - -// SetExtProfile sets or, with "", clears a host's profile. -func (p *AssetPreferences) SetExtProfile(host, profileJSON string) { - if host == "" { - return - } - p.Update(func(sn *Settings) { - if sn.ExtProfiles == nil { - sn.ExtProfiles = map[string]string{} - } - if profileJSON == "" { - delete(sn.ExtProfiles, host) - } else { - sn.ExtProfiles[host] = profileJSON - } - }) -} - // BlipTyping reports one blip per rate revealed letters and whether spaces blip too. func (s *Settings) BlipTyping() (rate int, onSpaces bool) { @@ -3941,59 +3686,6 @@ func (p *AssetPreferences) SetThemeFitPan(x, y int) { }) } -// ExportLearnedJSON returns the table as indented JSON, so one player's warm state can seed another's. -func (p *AssetPreferences) ExportLearnedJSON() ([]byte, error) { - return json.MarshalIndent(p.Load().LearnedSnapshot(), "", jsonMarshalIndent) -} - -// ImportLearnedJSON merges an export, imported entries winning, and reports how many landed. -func (p *AssetPreferences) ImportLearnedJSON(data []byte) (int, error) { - var in map[string][]string - if err := json.Unmarshal(data, &in); err != nil { - return 0, fmt.Errorf("config: parsing learned-format import: %w", err) - } - n := 0 - p.Update(func(sn *Settings) { - for k, v := range in { - if k == "" || len(v) == 0 { - continue - } - if sn.LearnedFormats == nil { - sn.LearnedFormats = map[string][]string{} - } - sn.LearnedFormats[k] = cloneStrings(v) - n++ - } - }) - return n, nil -} - -// LearnedSnapshot returns a deep copy, warming the resolver's snapshot at startup and on connect. -func (s *Settings) LearnedSnapshot() map[string][]string { - - out := make(map[string][]string, len(s.LearnedFormats)) - for k, v := range s.LearnedFormats { - out[k] = cloneStrings(v) - } - return out -} - -func (p *AssetPreferences) ClearLearned() { - p.Update(func(sn *Settings) { - sn.LearnedFormats = map[string][]string{} - }) -} - -// dropLearnedType removes one type's entries across hosts from a snapshot. -func dropLearnedType(sn *Settings, typeName string) { - suffix := LearnedKeySeparator + typeName - for key := range sn.LearnedFormats { - if strings.HasSuffix(key, suffix) { - delete(sn.LearnedFormats, key) - } - } -} - // LocalAssets reports streaming switched off, and the player's folders, searched in order like AO2-Client mount paths. func (p *AssetPreferences) LocalAssets() (enabled bool, mounts []string) { snap := p.Load() diff --git a/internal/config/preferences_test.go b/internal/config/preferences_test.go index 5e8d8bbc..6176479e 100644 --- a/internal/config/preferences_test.go +++ b/internal/config/preferences_test.go @@ -6,7 +6,6 @@ import ( "os" "path/filepath" "reflect" - "slices" "strings" "sync" "testing" @@ -36,63 +35,10 @@ func newTestPrefs(t *testing.T) (*AssetPreferences, string) { return p, path } -// TestSetFormatOrderCompletes is the deadlock regression test demanded by -// spec §5: the drafts held the write lock while calling a Save that took -// the read lock — a guaranteed self-deadlock on Go's non-reentrant RWMutex. -// Mutators must never write disk; this must return almost immediately. -func TestSetFormatOrderCompletes(t *testing.T) { - p, _ := newTestPrefs(t) - - finished := make(chan struct{}) - go func() { - p.SetFormatOrder(TypeCharSprite, []string{ExtAPNG, ExtWebP}) - p.SetGlobalFallbacks(true) - p.SetTypeFallbacks(TypeSFX, true) - p.RecordLearned("example.com", TypeCharSprite, ExtWebP) - p.Update(func( - sn *Settings) { - - sn. - MasterVol = - - 80 - - }) - - p.Update(func( - sn *Settings) { - - sn. - MusicVolMode = - - true - - }) - - p.Update(func( - sn *Settings) { - - sn. - PreferAnimated = - - false - - }) - - close(finished) - }() - - select { - case <-finished: - case <-time.After(5 * time.Second): - t.Fatal("mutators did not complete: probable lock-ordering deadlock (mutator writing disk under lock?)") - } -} - func TestMutatorsDoNotWriteSynchronously(t *testing.T) { p, path := newTestPrefs(t) - p.SetFormatOrder(TypeCharSprite, []string{ExtAPNG}) + p.Update(func(sn *Settings) { sn.PreferAnimated = false }) if _, err := os.Stat(path); !os.IsNotExist(err) { t.Fatalf("preferences file exists immediately after mutation: mutators must never write disk (stat err: %v)", err) } @@ -145,137 +91,6 @@ func TestDebounceCoalescesBurst(t *testing.T) { } } -func TestFormatListZeroFallbackIsExactConfiguredList(t *testing.T) { - p, _ := newTestPrefs(t) - - got := p.Load().FormatList(TypeCharSprite) - want := []string{ExtWebP} - if !slices.Equal(got, want) { - t.Errorf("FormatList(CharSprite) fallbacks-off = %v, want %v (exactly one probe)", got, want) - } - - if got := p.Load().FormatList(TypeCharIcon); !slices.Equal(got, []string{ExtPNG}) { - t.Errorf("FormatList(CharIcon) = %v, want [%s]", got, ExtPNG) - } -} - -func TestFormatListGlobalFallbacksAppendLegacyChain(t *testing.T) { - p, _ := newTestPrefs(t) - p.SetGlobalFallbacks(true) - - got := p.Load().FormatList(TypeCharSprite) - want := []string{ExtWebP, ExtAPNG, ExtGIF, ExtPNG} - if !slices.Equal(got, want) { - t.Errorf("FormatList(CharSprite) global fallbacks = %v, want %v", got, want) - } - - got = p.Load().FormatList(TypeMusic) - want = []string{ExtOpus, ExtOgg, ExtMP3} - if !slices.Equal(got, want) { - t.Errorf("FormatList(Music) global fallbacks = %v, want %v", got, want) - } -} - -func TestFormatListPerTypeFallbackOnlyAffectsThatType(t *testing.T) { - p, _ := newTestPrefs(t) - p.SetTypeFallbacks(TypeBackground, true) - - if got, want := p.Load().FormatList(TypeBackground), []string{ExtWebP, ExtAPNG, ExtGIF, ExtPNG}; !slices.Equal(got, want) { - t.Errorf("FormatList(Background) per-type fallback = %v, want %v", got, want) - } - if got, want := p.Load().FormatList(TypeCharSprite), []string{ExtWebP}; !slices.Equal(got, want) { - t.Errorf("FormatList(CharSprite) must stay zero-fallback, got %v want %v", got, want) - } -} - -func TestFormatListDeduplicatesPreservingOrder(t *testing.T) { - p, _ := newTestPrefs(t) - // User order already contains a legacy-chain member and a duplicate. - p.SetFormatOrder(TypeCharSprite, []string{ExtPNG, ExtWebP, ExtPNG}) - p.SetTypeFallbacks(TypeCharSprite, true) - - got := p.Load().FormatList(TypeCharSprite) - want := []string{ExtPNG, ExtWebP, ExtAPNG, ExtGIF} - if !slices.Equal(got, want) { - t.Errorf("FormatList dedup = %v, want %v", got, want) - } -} - -func TestFormatListUnknownTypeWithFallbacksIsEmpty(t *testing.T) { - p, _ := newTestPrefs(t) - if got := p.Load().FormatList("NoSuchType"); len(got) != 0 { - t.Errorf("FormatList(unknown) = %v, want empty", got) - } -} - -func TestEveryTypeHasDefaultsAndLegacyChain(t *testing.T) { - for _, name := range TypeNames { - if len(DefaultFormatOrder(name)) == 0 { - t.Errorf("type %s has no default format order", name) - } - if len(LegacyFallbackChain(name)) == 0 { - t.Errorf("type %s has no legacy fallback chain", name) - } - } - if len(defaultFormatOrders) != len(TypeNames) { - t.Errorf("defaultFormatOrders has %d entries, want %d", len(defaultFormatOrders), len(TypeNames)) - } - if len(legacyFallbackChains) != len(TypeNames) { - t.Errorf("legacyFallbackChains has %d entries, want %d", len(legacyFallbackChains), len(TypeNames)) - } -} - -// TestMiscFormatDefaultMigration pins the one-shot webp→png default flip for -// Misc (chatbox skins ship as png; the old webp default was the emote class -// bleeding over): a stored order equal to the OLD default was never a user -// choice and advances to the new default on load; any other stored order is -// deliberate and survives byte-for-byte. -func TestMiscFormatDefaultMigration(t *testing.T) { - path := filepath.Join(t.TempDir(), PrefsFileName) - p, err := newWithDebounce(path, testDebounce) - if err != nil { - t.Fatalf("newWithDebounce: %v", err) - } - // Simulate a pre-flip prefs file: Misc stored as the old [.webp] default. - p.Update(func(sn *Settings) { - tp := sn.AssetTypes[TypeMisc] - tp.FormatOrder = []string{ExtWebP} - sn.AssetTypes[TypeMisc] = tp - }) - if err := p.SaveNow(); err != nil { - t.Fatalf("save: %v", err) - } - _ = p.Close() - - re, err := newWithDebounce(path, testDebounce) - if err != nil { - t.Fatalf("reload: %v", err) - } - defer re.Close() - if got := re.Load().AssetTypes[TypeMisc].FormatOrder; len(got) != 2 || got[0] != ExtPNG || got[1] != ExtWebP { - t.Errorf("old-default Misc order = %v after reload, want the new [%s %s]", got, ExtPNG, ExtWebP) - } - - // A customized order (user picked gif-first) must NOT migrate. - re.Update(func(sn *Settings) { - tp := sn.AssetTypes[TypeMisc] - tp.FormatOrder = []string{ExtGIF, ExtWebP} - sn.AssetTypes[TypeMisc] = tp - }) - if err := re.SaveNow(); err != nil { - t.Fatalf("save custom: %v", err) - } - _ = re.Close() - re2, err := newWithDebounce(path, testDebounce) - if err != nil { - t.Fatalf("reload custom: %v", err) - } - defer re2.Close() - if got := re2.Load().AssetTypes[TypeMisc].FormatOrder; len(got) != 2 || got[0] != ExtGIF || got[1] != ExtWebP { - t.Errorf("customized Misc order = %v after reload, want [gif webp] untouched", got) - } -} - // TestSpriteLoadModeDefaultAndMigration pins the Default-mode flip: a fresh install // defaults to Default (strict sequencing); a legacy prefs file that predates the key // (the old Blank default was dropped by omitempty, so the key is simply absent) loads @@ -460,7 +275,6 @@ func TestPersistenceRoundTrip(t *testing.T) { t.Fatalf("newWithDebounce: %v", err) } - p.SetGlobalFallbacks(true) p.Update(func( sn *Settings) { @@ -471,9 +285,6 @@ func TestPersistenceRoundTrip(t *testing.T) { }) - p.SetFormatOrder(TypeCharIcon, []string{ExtWebP, ExtPNG}) - p.SetTypeFallbacks(TypeBlip, true) - p.RecordLearned("assets.example.com", TypeCharSprite, ExtWebP) p.Update(func( sn *Settings) { @@ -513,22 +324,9 @@ func TestPersistenceRoundTrip(t *testing.T) { if err != nil { t.Fatalf("reload: %v", err) } - if !q.Load().GlobalFallbacksEnabled { - t.Error("GlobalFallbacksEnabled lost") - } if q.Load().PreferAnimated { t.Error("PreferAnimated=false lost (absent-field default must not clobber explicit false)") } - if got, want := q.Load().FormatOrder(TypeCharIcon), []string{ExtWebP, ExtPNG}; !slices.Equal(got, want) { - t.Errorf("FormatOrder(CharIcon) = %v, want %v", got, want) - } - if !q.Load().TypeFallbacksEnabled(TypeBlip) { - t.Error("TypeFallbacks(Blip) lost") - } - learned := q.Load().LearnedSnapshot() - if got := learned[LearnedKey("assets.example.com", TypeCharSprite)]; !slices.Equal(got, []string{ExtWebP}) { - t.Errorf("learned format lost, snapshot=%v", learned) - } if got := q.Load().MasterVol; got != 37 { t.Errorf("MasterVolume = %d, want 37", got) } @@ -543,61 +341,6 @@ func TestPersistenceRoundTrip(t *testing.T) { } } -// TestLearnedExportImport pins the warm-state portability path: export → -// clear → import restores the table, and FormatAutoDetect defaults ON -// with an explicit false surviving the round trip. -func TestLearnedExportImport(t *testing.T) { - path := filepath.Join(t.TempDir(), PrefsFileName) - p, err := newWithDebounce(path, testDebounce) - if err != nil { - t.Fatal(err) - } - if !p.Load().AutoDetectFormats { - t.Error("FormatAutoDetect should default ON") - } - p.Update(func( - sn *Settings) { - - sn. - AutoDetectFormats = - - false - - }) - - p.RecordLearned("miku.pizza", TypeCharSprite, ExtWebP) - p.RecordLearned("other.example", TypeCharIcon, ExtPNG) - - data, err := p.ExportLearnedJSON() - if err != nil { - t.Fatal(err) - } - p.ClearLearned() - if len(p.Load().LearnedSnapshot()) != 0 { - t.Fatal("clear did not clear") - } - n, err := p.ImportLearnedJSON(data) - if err != nil || n != 2 { - t.Fatalf("import = %d, %v", n, err) - } - if got := p.Load().LearnedSnapshot()[LearnedKey("miku.pizza", TypeCharSprite)]; len(got) != 1 || got[0] != ExtWebP { - t.Errorf("imported entry = %v", got) - } - if _, err := p.ImportLearnedJSON([]byte("junk")); err == nil { - t.Error("junk import accepted") - } - if err := p.Close(); err != nil { - t.Fatal(err) - } - q, err := load(path) - if err != nil { - t.Fatal(err) - } - if q.Load().AutoDetectFormats { - t.Error("explicit FormatAutoDetect=false lost on reload") - } -} - // TestExportSettingsRedactsPassword pins the security rule: the new-PC // bundle carries everything EXCEPT saved passwords — the username and the // auto-login choice survive (one retype restores the flow), the password @@ -823,20 +566,12 @@ func TestLoadDefaults(t *testing.T) { if err != nil { t.Fatalf("load(absent) returned error: %v", err) } - if p.Load().GlobalFallbacksEnabled { - t.Error("GlobalFallbacksEnabled default must be false (zero fallbacks by default)") - } if !p.Load().PreferAnimated { t.Error("PreferAnimated default must be true") } if p.Load().CatchUpOn { t.Error("CatchUpOn default must be false (the OG-client queue)") } - for _, name := range TypeNames { - if _, ok := p.Load().AssetTypes[name]; !ok { - t.Errorf("default AssetTypes missing %s", name) - } - } } func TestLoadCorruptFileFallsBackToDefaults(t *testing.T) { @@ -848,7 +583,7 @@ func TestLoadCorruptFileFallsBackToDefaults(t *testing.T) { if err == nil { t.Error("load(corrupt) must report the parse error") } - if p == nil || !p.Load().PreferAnimated || len(p.Load().AssetTypes) != len(TypeNames) { + if p == nil || !p.Load().PreferAnimated { t.Error("load(corrupt) must still return usable defaults") } } @@ -923,89 +658,6 @@ func TestCloseFlushesPendingChanges(t *testing.T) { } } -func TestLearnedInvalidation(t *testing.T) { - p, _ := newTestPrefs(t) - const host = "cdn.example.com" - otherKey := LearnedKey(host, TypeBackground) - - seed := func() { - p.RecordLearned(host, TypeCharSprite, ExtWebP) - p.RecordLearned(host, TypeBackground, ExtWebP) - } - - seed() - p.SetFormatOrder(TypeCharSprite, []string{ExtAPNG}) - learned := p.Load().LearnedSnapshot() - if _, ok := learned[LearnedKey(host, TypeCharSprite)]; ok { - t.Error("SetFormatOrder must invalidate learned formats for that type") - } - if _, ok := learned[otherKey]; !ok { - t.Error("SetFormatOrder must not invalidate other types") - } - - seed() - p.SetTypeFallbacks(TypeCharSprite, true) - learned = p.Load().LearnedSnapshot() - if _, ok := learned[LearnedKey(host, TypeCharSprite)]; ok { - t.Error("SetTypeFallbacks must invalidate learned formats for that type") - } - - seed() - p.SetGlobalFallbacks(true) - if n := len(p.Load().LearnedSnapshot()); n != 0 { - t.Errorf("SetGlobalFallbacks must invalidate all learned formats, %d left", n) - } - - seed() - p.ClearLearned() - if n := len(p.Load().LearnedSnapshot()); n != 0 { - t.Errorf("ClearLearned left %d entries", n) - } -} - -// TestClearLearnedHostIsScoped pins the whole point of ClearLearnedHost: it is -// the fix for ONE server, so every other server's warm state must survive it. -// A wipe that took the rest with it would trade one server's missing art for a -// cold re-probe of every server the player has ever visited. -func TestClearLearnedHostIsScoped(t *testing.T) { - p, _ := newTestPrefs(t) - const bad, good = "repacked.example.com", "fine.example.com" - p.RecordLearned(bad, TypeCharSprite, ExtWebP) - p.RecordLearned(bad, TypeBackground, ExtWebP) - p.RecordLearned(good, TypeCharSprite, ExtPNG) - - if n := p.ClearLearnedHost(bad); n != 2 { - t.Errorf("ClearLearnedHost dropped %d entries, want 2", n) - } - learned := p.Load().LearnedSnapshot() - if _, ok := learned[LearnedKey(bad, TypeCharSprite)]; ok { - t.Error("the target host's sprite entry survived") - } - if _, ok := learned[LearnedKey(bad, TypeBackground)]; ok { - t.Error("the target host's background entry survived") - } - if got, ok := learned[LearnedKey(good, TypeCharSprite)]; !ok || len(got) != 1 || got[0] != ExtPNG { - t.Errorf("another host's entry = %v (present %v), want [%s] — the wipe must be scoped", got, ok, ExtPNG) - } - if n := p.ClearLearnedHost(bad); n != 0 { - t.Errorf("second ClearLearnedHost dropped %d entries, want 0", n) - } - if n := p.ClearLearnedHost(""); n != 0 { - t.Errorf("ClearLearnedHost(\"\") dropped %d entries, want 0", n) - } - - // A host is a PREFIX of the key, so a different host whose name merely - // starts with the target's must not be caught. - p.RecordLearned(bad, TypeCharSprite, ExtWebP) - p.RecordLearned(bad+".cdn.example.com", TypeCharSprite, ExtWebP) - if n := p.ClearLearnedHost(bad); n != 1 { - t.Errorf("ClearLearnedHost dropped %d entries, want 1 (a longer host name is a different host)", n) - } - if _, ok := p.Load().LearnedSnapshot()[LearnedKey(bad+".cdn.example.com", TypeCharSprite)]; !ok { - t.Error("a host whose name starts with the target's was wrongly cleared") - } -} - func TestMasterVolumeClamping(t *testing.T) { p, _ := newTestPrefs(t) p.Update(func( @@ -1044,6 +696,8 @@ func TestConcurrentAccess(t *testing.T) { const ( goroutines = 8 iterations = 200 + // concurrentCases is how many operations the goroutines rotate through. + concurrentCases = 2 ) var wg sync.WaitGroup for g := 0; g < goroutines; g++ { @@ -1051,16 +705,10 @@ func TestConcurrentAccess(t *testing.T) { go func(seed int) { defer wg.Done() for i := 0; i < iterations; i++ { - switch (seed + i) % 6 { + switch (seed + i) % concurrentCases { case 0: - p.SetFormatOrder(TypeCharSprite, []string{ExtWebP, ExtAPNG}) + _ = p.Load().MasterVol case 1: - p.RecordLearned("h.example.com", TypeNames[i%len(TypeNames)], ExtWebP) - case 2: - _ = p.Load().FormatList(TypeNames[i%len(TypeNames)]) - case 3: - _ = p.Load().LearnedSnapshot() - case 4: p.Update(func( sn *Settings) { @@ -1073,8 +721,6 @@ func TestConcurrentAccess(t *testing.T) { }) - case 5: - p.SetGlobalFallbacks(i%2 == 0) } } }(g) diff --git a/internal/config/prefs_golden_freeze_test.go b/internal/config/prefs_golden_freeze_test.go index 23f5cb3a..e13d0e42 100644 --- a/internal/config/prefs_golden_freeze_test.go +++ b/internal/config/prefs_golden_freeze_test.go @@ -15,12 +15,12 @@ import ( ) const ( - loadGoldenSHA256 = "61988be9a6dd905b0877179185bdb0ff91b699ef7a1c357fc9aa1e1683c60d77" - loadGoldenCompactSHA = "22e0cb397d2c5b66e5cefe4ff8308b9c1ffe10ad88b61a177fd211370ade6f12" - malformedGoldenSHA = "8b007e5163b90b7f93bdd051b94b0013006a3c6a88d974be4ad7f39b28b2402e" + loadGoldenSHA256 = "2f12d3d0ece77327a0c2e4bc5e5be0f051aaa83b88dd41f79413a39bdcd429bd" + loadGoldenCompactSHA = "d5fc422f5435bcda0a8dea2066dc7c7016cc9acd84196190592902fef61e1234" + malformedGoldenSHA = "71c9bc35d1f51380302fee3455848ad9e26e69531afd358d9d9c7f3bf7f98bf1" malformedCompactSHA = "a20792b6c36e1dc8730f83d8949d47d84f3dad3d3ea9d608beda113a3f8a1715" - defaultPrefsSHA = "dc72c873f49d15787f52f53f156c97f95b940edba56e33b5c02c7c77f145236f" - prefsGoldenSHA256 = "ee2899f27d1ac3f6c89bb0975e18dd2b262c81e86ec173948e6ce554753d47dd" + defaultPrefsSHA = "da4b6333aacfcf333cac15dca529aedf7747242744a4cd9b1c737470aed7405d" + prefsGoldenSHA256 = "32fc839da97d8dd93fc5555036884d1827b796a736c7d934acf97b4d0114ba30" settersGoldenSHA = "4679f9c7120659feee3b12230c588ae6930c89cffc409d8477a0f726f1b758fc" settersCompactSHA = "24be0149ad243bfb76a27e118ba5049662fd8c8d530938a8ff819455a2552ce1" ) diff --git a/internal/config/prefs_setter_map_test.go b/internal/config/prefs_setter_map_test.go index c76106c8..0a99d240 100644 --- a/internal/config/prefs_setter_map_test.go +++ b/internal/config/prefs_setter_map_test.go @@ -66,7 +66,6 @@ var setterFieldMap = map[string]setterField{ "SetFontCensus": {field: "FontCensus"}, "SetFontEverywhere": {field: "FontEverywhere"}, "SetForceCharNames": {field: "ForceCharNames"}, - "SetFormatAutoDetect": {field: "AutoDetectFormats"}, "SetFrameLimiterDisabled": {field: "DisableFrameLimiter"}, "SetFriendGlowPulse": {field: "FriendGlowPulse"}, "SetFriendHighlight": {field: "FriendHighlight"}, diff --git a/internal/config/prefs_swap.go b/internal/config/prefs_swap.go index 9d77c28a..db3605bc 100644 --- a/internal/config/prefs_swap.go +++ b/internal/config/prefs_swap.go @@ -234,27 +234,11 @@ func (p *AssetPreferences) normalizeSnapshot(s *Settings, presence map[string]bo } // Restore non-zero nested defaults the overlay zeroed. - if len(s.AssetTypes) == 0 { - s.AssetTypes = def.AssetTypes - } else { - for name, tp := range s.AssetTypes { - if len(tp.FormatOrder) == 0 { - tp.FormatOrder = DefaultFormatOrder(name) - } - if name == TypeMisc && len(tp.FormatOrder) == 1 && tp.FormatOrder[0] == ExtWebP { - tp.FormatOrder = DefaultFormatOrder(name) - } - s.AssetTypes[name] = tp - } - } if s.MusicHosts == nil { s.MusicHosts = def.MusicHosts } else { s.MusicHosts = sanitizeMusicHosts(s.MusicHosts) } - if s.LearnedFormats == nil { - s.LearnedFormats = def.LearnedFormats - } // Bound, drop blank names and ids, and dedupe, so a hand-edited file cannot grow or corrupt the maps. s.SavedStyles = sanitizeStylePresets(s.SavedStyles) s.PanelFontsVal = sanitizePanelFonts(s.PanelFontsVal) diff --git a/internal/config/qol_prefs_test.go b/internal/config/qol_prefs_test.go index 1acc773a..a4396298 100644 --- a/internal/config/qol_prefs_test.go +++ b/internal/config/qol_prefs_test.go @@ -2033,22 +2033,6 @@ func TestWardrobeGenerationBumps(t *testing.T) { } } -// TestClearLearnedType pins that clearing one type's learned formats (the -// desk-policy toggle path) leaves other types alone. -func TestClearLearnedType(t *testing.T) { - p, _ := newTestPrefs(t) - p.RecordLearned("h.example", TypeDeskOverlay, ExtPNG) - p.RecordLearned("h.example", TypeBackground, ExtPNG) - p.ClearLearnedType(TypeDeskOverlay) - snap := p.Load().LearnedSnapshot() - if _, ok := snap[LearnedKey("h.example", TypeDeskOverlay)]; ok { - t.Error("ClearLearnedType(DeskOverlay) must drop desk learned entries") - } - if _, ok := snap[LearnedKey("h.example", TypeBackground)]; !ok { - t.Error("ClearLearnedType(DeskOverlay) must NOT drop other types") - } -} - // TestClampWindowSize pins the shared window-size clamp (the stuck-too-big fix): // an oversize request on a smaller display fits to the usable bounds, a tiny // request floors at the minimum, and an unknown display (0) skips the ceiling. diff --git a/internal/config/settings.go b/internal/config/settings.go index 2294e06c..a06b22b5 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -12,7 +12,6 @@ import ( // Settings is the plain data snapshot of AssetPreferences. type Settings struct { - GlobalFallbacksEnabled bool `json:"globalFallbacksEnabled"` PreferAnimated bool `json:"preferAnimated"` EmoteButtonImages bool `json:"emoteButtonImages"` SmoothScaling bool `json:"smoothScaling"` @@ -124,7 +123,6 @@ type Settings struct { ModcallToast bool `json:"modcallToast"` CallwordSoundFile string `json:"callwordSoundFile"` DebugOverlay bool `json:"debugOverlay"` - AutoDetectFormats bool `json:"formatAutoDetect"` ThemeLayoutOn bool `json:"themeLayout"` ThemeFit int `json:"themeFit"` ThemeFitZoom int `json:"themeFitZoom"` @@ -233,8 +231,6 @@ type Settings struct { TextStayMs int `json:"textStayMs"` ChatRateLimitMs int `json:"chatRateLimitMs"` MasterListURL string `json:"masterListUrl"` - AssetTypes map[string]AssetTypePrefs `json:"assetTypes"` - LearnedFormats map[string][]string `json:"learnedFormats"` Showname string `json:"showname"` ShownamePresets []string `json:"shownamePresets,omitempty"` ShownameKeys map[string]string `json:"shownameKeys,omitempty"` @@ -271,7 +267,6 @@ type Settings struct { BlipRate int `json:"blipRate"` BlipOnSpaces bool `json:"blipOnSpaces"` CallwordsOOC bool `json:"callwordsOOC"` - ExtProfiles map[string]string `json:"extProfiles,omitempty"` LocalAssetsPaths []string `json:"localAssetsPaths"` Favorites []FavoriteServer `json:"favorites"` Wardrobe []string `json:"wardrobe"` diff --git a/internal/config/settings_clone.go b/internal/config/settings_clone.go index b8ba2bb5..d1a439ed 100644 --- a/internal/config/settings_clone.go +++ b/internal/config/settings_clone.go @@ -108,27 +108,6 @@ func (s *Settings) Clone() *Settings { } else { c.ClassicRotations = nil } - if s.AssetTypes != nil { - c.AssetTypes = make(map[string]AssetTypePrefs, len(s.AssetTypes)) - for k20, v21 := range s.AssetTypes { - c.AssetTypes[k20] = snapCloneAssetTypePrefs(v21) - } - } else { - c.AssetTypes = nil - } - if s.LearnedFormats != nil { - c.LearnedFormats = make(map[string][]string, len(s.LearnedFormats)) - for k22, v23 := range s.LearnedFormats { - if v23 != nil { - c.LearnedFormats[k22] = make([]string, len(v23)) - copy(c.LearnedFormats[k22], v23) - } else { - c.LearnedFormats[k22] = nil - } - } - } else { - c.LearnedFormats = nil - } if s.ShownamePresets != nil { c.ShownamePresets = make([]string, len(s.ShownamePresets)) copy(c.ShownamePresets, s.ShownamePresets) @@ -137,16 +116,16 @@ func (s *Settings) Clone() *Settings { } if s.ShownameKeys != nil { c.ShownameKeys = make(map[string]string, len(s.ShownameKeys)) - for k24, v25 := range s.ShownameKeys { - c.ShownameKeys[k24] = v25 + for k20, v21 := range s.ShownameKeys { + c.ShownameKeys[k20] = v21 } } else { c.ShownameKeys = nil } if s.ICPhraseKeys != nil { c.ICPhraseKeys = make(map[string]string, len(s.ICPhraseKeys)) - for k26, v27 := range s.ICPhraseKeys { - c.ICPhraseKeys[k26] = v27 + for k22, v23 := range s.ICPhraseKeys { + c.ICPhraseKeys[k22] = v23 } } else { c.ICPhraseKeys = nil @@ -177,33 +156,25 @@ func (s *Settings) Clone() *Settings { } if s.BlipVols != nil { c.BlipVols = make(map[string]int, len(s.BlipVols)) - for k28, v29 := range s.BlipVols { - c.BlipVols[k28] = v29 + for k24, v25 := range s.BlipVols { + c.BlipVols[k24] = v25 } } else { c.BlipVols = nil } if s.EmoteFavs != nil { c.EmoteFavs = make(map[string][]int, len(s.EmoteFavs)) - for k30, v31 := range s.EmoteFavs { - if v31 != nil { - c.EmoteFavs[k30] = make([]int, len(v31)) - copy(c.EmoteFavs[k30], v31) + for k26, v27 := range s.EmoteFavs { + if v27 != nil { + c.EmoteFavs[k26] = make([]int, len(v27)) + copy(c.EmoteFavs[k26], v27) } else { - c.EmoteFavs[k30] = nil + c.EmoteFavs[k26] = nil } } } else { c.EmoteFavs = nil } - if s.ExtProfiles != nil { - c.ExtProfiles = make(map[string]string, len(s.ExtProfiles)) - for k32, v33 := range s.ExtProfiles { - c.ExtProfiles[k32] = v33 - } - } else { - c.ExtProfiles = nil - } if s.LocalAssetsPaths != nil { c.LocalAssetsPaths = make([]string, len(s.LocalAssetsPaths)) copy(c.LocalAssetsPaths, s.LocalAssetsPaths) @@ -230,8 +201,8 @@ func (s *Settings) Clone() *Settings { } if s.ServerWarm != nil { c.ServerWarm = make(map[string]ServerWarmInfo, len(s.ServerWarm)) - for k34, v35 := range s.ServerWarm { - c.ServerWarm[k34] = snapCloneServerWarmInfo(v35) + for k28, v29 := range s.ServerWarm { + c.ServerWarm[k28] = snapCloneServerWarmInfo(v29) } } else { c.ServerWarm = nil @@ -244,8 +215,8 @@ func (s *Settings) Clone() *Settings { } if s.HotkeyMap != nil { c.HotkeyMap = make(map[string]string, len(s.HotkeyMap)) - for k36, v37 := range s.HotkeyMap { - c.HotkeyMap[k36] = v37 + for k30, v31 := range s.HotkeyMap { + c.HotkeyMap[k30] = v31 } } else { c.HotkeyMap = nil @@ -269,9 +240,6 @@ func (s *Settings) equal(o *Settings) bool { if s == nil || o == nil { return false } - if s.GlobalFallbacksEnabled != o.GlobalFallbacksEnabled { - return false - } if s.PreferAnimated != o.PreferAnimated { return false } @@ -428,8 +396,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.SavedStyles) != len(o.SavedStyles) { return false } - for i38 := range s.SavedStyles { - if s.SavedStyles[i38] != o.SavedStyles[i38] { + for i32 := range s.SavedStyles { + if s.SavedStyles[i32] != o.SavedStyles[i32] { return false } } @@ -466,8 +434,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.PanelFontsVal) != len(o.PanelFontsVal) { return false } - for k39, v40 := range s.PanelFontsVal { - if o.PanelFontsVal[k39] != v40 { + for k33, v34 := range s.PanelFontsVal { + if o.PanelFontsVal[k33] != v34 { return false } } @@ -477,8 +445,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.FontWarnThemes) != len(o.FontWarnThemes) { return false } - for i41 := range s.FontWarnThemes { - if s.FontWarnThemes[i41] != o.FontWarnThemes[i41] { + for i35 := range s.FontWarnThemes { + if s.FontWarnThemes[i35] != o.FontWarnThemes[i35] { return false } } @@ -629,9 +597,6 @@ func (s *Settings) equal(o *Settings) bool { if s.DebugOverlay != o.DebugOverlay { return false } - if s.AutoDetectFormats != o.AutoDetectFormats { - return false - } if s.ThemeLayoutOn != o.ThemeLayoutOn { return false } @@ -779,8 +744,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.OpenTabs) != len(o.OpenTabs) { return false } - for i42 := range s.OpenTabs { - if s.OpenTabs[i42] != o.OpenTabs[i42] { + for i36 := range s.OpenTabs { + if s.OpenTabs[i36] != o.OpenTabs[i36] { return false } } @@ -832,8 +797,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.UserMacros) != len(o.UserMacros) { return false } - for i43 := range s.UserMacros { - if !snapEqualMacroSpec(s.UserMacros[i43], o.UserMacros[i43]) { + for i37 := range s.UserMacros { + if !snapEqualMacroSpec(s.UserMacros[i37], o.UserMacros[i37]) { return false } } @@ -843,19 +808,19 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ThemeRectOv) != len(o.ThemeRectOv) { return false } - for k44, v45 := range s.ThemeRectOv { - ov46, ok47 := o.ThemeRectOv[k44] - if !ok47 { + for k38, v39 := range s.ThemeRectOv { + ov40, ok41 := o.ThemeRectOv[k38] + if !ok41 { return false } - if (v45 == nil) != (ov46 == nil) { + if (v39 == nil) != (ov40 == nil) { return false } - if len(v45) != len(ov46) { + if len(v39) != len(ov40) { return false } - for k48, v49 := range v45 { - if ov46[k48] != v49 { + for k42, v43 := range v39 { + if ov40[k42] != v43 { return false } } @@ -866,19 +831,19 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ThemeRectRotations) != len(o.ThemeRectRotations) { return false } - for k50, v51 := range s.ThemeRectRotations { - ov52, ok53 := o.ThemeRectRotations[k50] - if !ok53 { + for k44, v45 := range s.ThemeRectRotations { + ov46, ok47 := o.ThemeRectRotations[k44] + if !ok47 { return false } - if (v51 == nil) != (ov52 == nil) { + if (v45 == nil) != (ov46 == nil) { return false } - if len(v51) != len(ov52) { + if len(v45) != len(ov46) { return false } - for k54, v55 := range v51 { - if ov52[k54] != v55 { + for k48, v49 := range v45 { + if ov46[k48] != v49 { return false } } @@ -889,8 +854,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ClassicLayout) != len(o.ClassicLayout) { return false } - for k56, v57 := range s.ClassicLayout { - if o.ClassicLayout[k56] != v57 { + for k50, v51 := range s.ClassicLayout { + if o.ClassicLayout[k50] != v51 { return false } } @@ -900,12 +865,12 @@ func (s *Settings) equal(o *Settings) bool { if len(s.LayoutProfiles) != len(o.LayoutProfiles) { return false } - for k58, v59 := range s.LayoutProfiles { - ov60, ok61 := o.LayoutProfiles[k58] - if !ok61 { + for k52, v53 := range s.LayoutProfiles { + ov54, ok55 := o.LayoutProfiles[k52] + if !ok55 { return false } - if !snapEqualLayoutProfile(v59, ov60) { + if !snapEqualLayoutProfile(v53, ov54) { return false } } @@ -918,8 +883,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ClassicAnchors) != len(o.ClassicAnchors) { return false } - for k62, v63 := range s.ClassicAnchors { - if o.ClassicAnchors[k62] != v63 { + for k56, v57 := range s.ClassicAnchors { + if o.ClassicAnchors[k56] != v57 { return false } } @@ -929,8 +894,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ClassicRotations) != len(o.ClassicRotations) { return false } - for k64, v65 := range s.ClassicRotations { - if o.ClassicRotations[k64] != v65 { + for k58, v59 := range s.ClassicRotations { + if o.ClassicRotations[k58] != v59 { return false } } @@ -1045,44 +1010,6 @@ func (s *Settings) equal(o *Settings) bool { if s.MasterListURL != o.MasterListURL { return false } - if (s.AssetTypes == nil) != (o.AssetTypes == nil) { - return false - } - if len(s.AssetTypes) != len(o.AssetTypes) { - return false - } - for k66, v67 := range s.AssetTypes { - ov68, ok69 := o.AssetTypes[k66] - if !ok69 { - return false - } - if !snapEqualAssetTypePrefs(v67, ov68) { - return false - } - } - if (s.LearnedFormats == nil) != (o.LearnedFormats == nil) { - return false - } - if len(s.LearnedFormats) != len(o.LearnedFormats) { - return false - } - for k70, v71 := range s.LearnedFormats { - ov72, ok73 := o.LearnedFormats[k70] - if !ok73 { - return false - } - if (v71 == nil) != (ov72 == nil) { - return false - } - if len(v71) != len(ov72) { - return false - } - for i74 := range v71 { - if v71[i74] != ov72[i74] { - return false - } - } - } if s.Showname != o.Showname { return false } @@ -1092,8 +1019,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ShownamePresets) != len(o.ShownamePresets) { return false } - for i75 := range s.ShownamePresets { - if s.ShownamePresets[i75] != o.ShownamePresets[i75] { + for i60 := range s.ShownamePresets { + if s.ShownamePresets[i60] != o.ShownamePresets[i60] { return false } } @@ -1103,8 +1030,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ShownameKeys) != len(o.ShownameKeys) { return false } - for k76, v77 := range s.ShownameKeys { - if o.ShownameKeys[k76] != v77 { + for k61, v62 := range s.ShownameKeys { + if o.ShownameKeys[k61] != v62 { return false } } @@ -1114,8 +1041,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ICPhraseKeys) != len(o.ICPhraseKeys) { return false } - for k78, v79 := range s.ICPhraseKeys { - if o.ICPhraseKeys[k78] != v79 { + for k63, v64 := range s.ICPhraseKeys { + if o.ICPhraseKeys[k63] != v64 { return false } } @@ -1125,8 +1052,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.MutedSFX) != len(o.MutedSFX) { return false } - for i80 := range s.MutedSFX { - if s.MutedSFX[i80] != o.MutedSFX[i80] { + for i65 := range s.MutedSFX { + if s.MutedSFX[i65] != o.MutedSFX[i65] { return false } } @@ -1136,8 +1063,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.SfxFavorites) != len(o.SfxFavorites) { return false } - for i81 := range s.SfxFavorites { - if s.SfxFavorites[i81] != o.SfxFavorites[i81] { + for i66 := range s.SfxFavorites { + if s.SfxFavorites[i66] != o.SfxFavorites[i66] { return false } } @@ -1147,8 +1074,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ModReasonTemplates) != len(o.ModReasonTemplates) { return false } - for i82 := range s.ModReasonTemplates { - if s.ModReasonTemplates[i82] != o.ModReasonTemplates[i82] { + for i67 := range s.ModReasonTemplates { + if s.ModReasonTemplates[i67] != o.ModReasonTemplates[i67] { return false } } @@ -1158,8 +1085,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ModDurations) != len(o.ModDurations) { return false } - for i83 := range s.ModDurations { - if s.ModDurations[i83] != o.ModDurations[i83] { + for i68 := range s.ModDurations { + if s.ModDurations[i68] != o.ModDurations[i68] { return false } } @@ -1169,8 +1096,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.BlipVols) != len(o.BlipVols) { return false } - for k84, v85 := range s.BlipVols { - if o.BlipVols[k84] != v85 { + for k69, v70 := range s.BlipVols { + if o.BlipVols[k69] != v70 { return false } } @@ -1180,19 +1107,19 @@ func (s *Settings) equal(o *Settings) bool { if len(s.EmoteFavs) != len(o.EmoteFavs) { return false } - for k86, v87 := range s.EmoteFavs { - ov88, ok89 := o.EmoteFavs[k86] - if !ok89 { + for k71, v72 := range s.EmoteFavs { + ov73, ok74 := o.EmoteFavs[k71] + if !ok74 { return false } - if (v87 == nil) != (ov88 == nil) { + if (v72 == nil) != (ov73 == nil) { return false } - if len(v87) != len(ov88) { + if len(v72) != len(ov73) { return false } - for i90 := range v87 { - if v87[i90] != ov88[i90] { + for i75 := range v72 { + if v72[i75] != ov73[i75] { return false } } @@ -1254,25 +1181,14 @@ func (s *Settings) equal(o *Settings) bool { if s.CallwordsOOC != o.CallwordsOOC { return false } - if (s.ExtProfiles == nil) != (o.ExtProfiles == nil) { - return false - } - if len(s.ExtProfiles) != len(o.ExtProfiles) { - return false - } - for k91, v92 := range s.ExtProfiles { - if o.ExtProfiles[k91] != v92 { - return false - } - } if (s.LocalAssetsPaths == nil) != (o.LocalAssetsPaths == nil) { return false } if len(s.LocalAssetsPaths) != len(o.LocalAssetsPaths) { return false } - for i93 := range s.LocalAssetsPaths { - if s.LocalAssetsPaths[i93] != o.LocalAssetsPaths[i93] { + for i76 := range s.LocalAssetsPaths { + if s.LocalAssetsPaths[i76] != o.LocalAssetsPaths[i76] { return false } } @@ -1282,8 +1198,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.Favorites) != len(o.Favorites) { return false } - for i94 := range s.Favorites { - if s.Favorites[i94] != o.Favorites[i94] { + for i77 := range s.Favorites { + if s.Favorites[i77] != o.Favorites[i77] { return false } } @@ -1293,8 +1209,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.Wardrobe) != len(o.Wardrobe) { return false } - for i95 := range s.Wardrobe { - if s.Wardrobe[i95] != o.Wardrobe[i95] { + for i78 := range s.Wardrobe { + if s.Wardrobe[i78] != o.Wardrobe[i78] { return false } } @@ -1310,8 +1226,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.HiddenPanelIDs) != len(o.HiddenPanelIDs) { return false } - for i96 := range s.HiddenPanelIDs { - if s.HiddenPanelIDs[i96] != o.HiddenPanelIDs[i96] { + for i79 := range s.HiddenPanelIDs { + if s.HiddenPanelIDs[i79] != o.HiddenPanelIDs[i79] { return false } } @@ -1321,12 +1237,12 @@ func (s *Settings) equal(o *Settings) bool { if len(s.ServerWarm) != len(o.ServerWarm) { return false } - for k97, v98 := range s.ServerWarm { - ov99, ok100 := o.ServerWarm[k97] - if !ok100 { + for k80, v81 := range s.ServerWarm { + ov82, ok83 := o.ServerWarm[k80] + if !ok83 { return false } - if !snapEqualServerWarmInfo(v98, ov99) { + if !snapEqualServerWarmInfo(v81, ov82) { return false } } @@ -1336,8 +1252,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.CallWordList) != len(o.CallWordList) { return false } - for i101 := range s.CallWordList { - if s.CallWordList[i101] != o.CallWordList[i101] { + for i84 := range s.CallWordList { + if s.CallWordList[i84] != o.CallWordList[i84] { return false } } @@ -1347,8 +1263,8 @@ func (s *Settings) equal(o *Settings) bool { if len(s.HotkeyMap) != len(o.HotkeyMap) { return false } - for k102, v103 := range s.HotkeyMap { - if o.HotkeyMap[k102] != v103 { + for k85, v86 := range s.HotkeyMap { + if o.HotkeyMap[k85] != v86 { return false } } @@ -1499,41 +1415,29 @@ func (s *Settings) equal(o *Settings) bool { if len(s.MusicHosts) != len(o.MusicHosts) { return false } - for i104 := range s.MusicHosts { - if s.MusicHosts[i104] != o.MusicHosts[i104] { + for i87 := range s.MusicHosts { + if s.MusicHosts[i87] != o.MusicHosts[i87] { return false } } return true } -func snapCloneAssetTypePrefs(src AssetTypePrefs) AssetTypePrefs { - var dst AssetTypePrefs - dst = src - if src.FormatOrder != nil { - dst.FormatOrder = make([]string, len(src.FormatOrder)) - copy(dst.FormatOrder, src.FormatOrder) - } else { - dst.FormatOrder = nil - } - return dst -} - func snapCloneLayoutProfile(src LayoutProfile) LayoutProfile { var dst LayoutProfile dst = src if src.Classic != nil { dst.Classic = make(map[string][4]float64, len(src.Classic)) - for k105, v106 := range src.Classic { - dst.Classic[k105] = v106 + for k88, v89 := range src.Classic { + dst.Classic[k88] = v89 } } else { dst.Classic = nil } if src.Anchors != nil { dst.Anchors = make(map[string]ClassicAnchor, len(src.Anchors)) - for k107, v108 := range src.Anchors { - dst.Anchors[k107] = v108 + for k90, v91 := range src.Anchors { + dst.Anchors[k90] = v91 } } else { dst.Anchors = nil @@ -1546,8 +1450,8 @@ func snapCloneLayoutProfile(src LayoutProfile) LayoutProfile { } if src.Rotations != nil { dst.Rotations = make(map[string]uint8, len(src.Rotations)) - for k109, v110 := range src.Rotations { - dst.Rotations[k109] = v110 + for k92, v93 := range src.Rotations { + dst.Rotations[k92] = v93 } } else { dst.Rotations = nil @@ -1584,24 +1488,24 @@ func snapCloneServerWarmInfo(src ServerWarmInfo) ServerWarmInfo { } if src.FavBackgroundFolder != nil { dst.FavBackgroundFolder = make(map[string]string, len(src.FavBackgroundFolder)) - for k111, v112 := range src.FavBackgroundFolder { - dst.FavBackgroundFolder[k111] = v112 + for k94, v95 := range src.FavBackgroundFolder { + dst.FavBackgroundFolder[k94] = v95 } } else { dst.FavBackgroundFolder = nil } if src.CharKeys != nil { dst.CharKeys = make(map[string]string, len(src.CharKeys)) - for k113, v114 := range src.CharKeys { - dst.CharKeys[k113] = v114 + for k96, v97 := range src.CharKeys { + dst.CharKeys[k96] = v97 } } else { dst.CharKeys = nil } if src.WardrobeFolder != nil { dst.WardrobeFolder = make(map[string]string, len(src.WardrobeFolder)) - for k115, v116 := range src.WardrobeFolder { - dst.WardrobeFolder[k115] = v116 + for k98, v99 := range src.WardrobeFolder { + dst.WardrobeFolder[k98] = v99 } } else { dst.WardrobeFolder = nil @@ -1663,24 +1567,6 @@ func snapCloneServerWarmInfo(src ServerWarmInfo) ServerWarmInfo { return dst } -func snapEqualAssetTypePrefs(a, b AssetTypePrefs) bool { - if (a.FormatOrder == nil) != (b.FormatOrder == nil) { - return false - } - if len(a.FormatOrder) != len(b.FormatOrder) { - return false - } - for i117 := range a.FormatOrder { - if a.FormatOrder[i117] != b.FormatOrder[i117] { - return false - } - } - if a.FallbacksEnabled != b.FallbacksEnabled { - return false - } - return true -} - func snapEqualLayoutProfile(a, b LayoutProfile) bool { if (a.Classic == nil) != (b.Classic == nil) { return false @@ -1688,8 +1574,8 @@ func snapEqualLayoutProfile(a, b LayoutProfile) bool { if len(a.Classic) != len(b.Classic) { return false } - for k118, v119 := range a.Classic { - if b.Classic[k118] != v119 { + for k100, v101 := range a.Classic { + if b.Classic[k100] != v101 { return false } } @@ -1699,8 +1585,8 @@ func snapEqualLayoutProfile(a, b LayoutProfile) bool { if len(a.Anchors) != len(b.Anchors) { return false } - for k120, v121 := range a.Anchors { - if b.Anchors[k120] != v121 { + for k102, v103 := range a.Anchors { + if b.Anchors[k102] != v103 { return false } } @@ -1710,8 +1596,8 @@ func snapEqualLayoutProfile(a, b LayoutProfile) bool { if len(a.Hidden) != len(b.Hidden) { return false } - for i122 := range a.Hidden { - if a.Hidden[i122] != b.Hidden[i122] { + for i104 := range a.Hidden { + if a.Hidden[i104] != b.Hidden[i104] { return false } } @@ -1724,8 +1610,8 @@ func snapEqualLayoutProfile(a, b LayoutProfile) bool { if len(a.Rotations) != len(b.Rotations) { return false } - for k123, v124 := range a.Rotations { - if b.Rotations[k123] != v124 { + for k105, v106 := range a.Rotations { + if b.Rotations[k105] != v106 { return false } } @@ -1745,8 +1631,8 @@ func snapEqualMacroSpec(a, b MacroSpec) bool { if len(a.Lines) != len(b.Lines) { return false } - for i125 := range a.Lines { - if a.Lines[i125] != b.Lines[i125] { + for i107 := range a.Lines { + if a.Lines[i107] != b.Lines[i107] { return false } } @@ -1766,8 +1652,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.Wardrobe) != len(b.Wardrobe) { return false } - for i126 := range a.Wardrobe { - if a.Wardrobe[i126] != b.Wardrobe[i126] { + for i108 := range a.Wardrobe { + if a.Wardrobe[i108] != b.Wardrobe[i108] { return false } } @@ -1777,8 +1663,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.FavBackgrounds) != len(b.FavBackgrounds) { return false } - for i127 := range a.FavBackgrounds { - if a.FavBackgrounds[i127] != b.FavBackgrounds[i127] { + for i109 := range a.FavBackgrounds { + if a.FavBackgrounds[i109] != b.FavBackgrounds[i109] { return false } } @@ -1788,8 +1674,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.FavBackgroundFolder) != len(b.FavBackgroundFolder) { return false } - for k128, v129 := range a.FavBackgroundFolder { - if b.FavBackgroundFolder[k128] != v129 { + for k110, v111 := range a.FavBackgroundFolder { + if b.FavBackgroundFolder[k110] != v111 { return false } } @@ -1799,8 +1685,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.CharKeys) != len(b.CharKeys) { return false } - for k130, v131 := range a.CharKeys { - if b.CharKeys[k130] != v131 { + for k112, v113 := range a.CharKeys { + if b.CharKeys[k112] != v113 { return false } } @@ -1810,8 +1696,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.WardrobeFolder) != len(b.WardrobeFolder) { return false } - for k132, v133 := range a.WardrobeFolder { - if b.WardrobeFolder[k132] != v133 { + for k114, v115 := range a.WardrobeFolder { + if b.WardrobeFolder[k114] != v115 { return false } } @@ -1824,8 +1710,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.AssetHosts) != len(b.AssetHosts) { return false } - for i134 := range a.AssetHosts { - if a.AssetHosts[i134] != b.AssetHosts[i134] { + for i116 := range a.AssetHosts { + if a.AssetHosts[i116] != b.AssetHosts[i116] { return false } } @@ -1870,8 +1756,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.Chars) != len(b.Chars) { return false } - for i135 := range a.Chars { - if a.Chars[i135] != b.Chars[i135] { + for i117 := range a.Chars { + if a.Chars[i117] != b.Chars[i117] { return false } } @@ -1881,8 +1767,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.Backgrounds) != len(b.Backgrounds) { return false } - for i136 := range a.Backgrounds { - if a.Backgrounds[i136] != b.Backgrounds[i136] { + for i118 := range a.Backgrounds { + if a.Backgrounds[i118] != b.Backgrounds[i118] { return false } } @@ -1892,8 +1778,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.Friends) != len(b.Friends) { return false } - for i137 := range a.Friends { - if a.Friends[i137] != b.Friends[i137] { + for i119 := range a.Friends { + if a.Friends[i119] != b.Friends[i119] { return false } } @@ -1903,8 +1789,8 @@ func snapEqualServerWarmInfo(a, b ServerWarmInfo) bool { if len(a.Ignored) != len(b.Ignored) { return false } - for i138 := range a.Ignored { - if a.Ignored[i138] != b.Ignored[i138] { + for i120 := range a.Ignored { + if a.Ignored[i120] != b.Ignored[i120] { return false } } diff --git a/internal/config/settings_clone_test.go b/internal/config/settings_clone_test.go index 54de7d23..cf9985d8 100644 --- a/internal/config/settings_clone_test.go +++ b/internal/config/settings_clone_test.go @@ -102,8 +102,6 @@ func filledSettings() *Settings { }, ClassicAnchors: map[string]ClassicAnchor{"e": {Mode: "cc", WinW: 3, WinH: 4}}, ClassicRotations: map[string]uint8{"f": 2}, - AssetTypes: map[string]AssetTypePrefs{"g": {FormatOrder: []string{"png", "webp"}, FallbacksEnabled: true}}, - LearnedFormats: map[string][]string{"h": {"png"}}, ShownamePresets: []string{"s1"}, ShownameKeys: map[string]string{"k1": "v1"}, ICPhraseKeys: map[string]string{"k2": "v2"}, @@ -115,7 +113,6 @@ func filledSettings() *Settings { EmoteFavs: map[string][]int{"e": {1, 2}}, CustomChromeHex: [7]string{"a", "b", "c", "d", "e", "f", "g"}, LayoutPartHex: [4]string{"a", "b", "c", "d"}, - ExtProfiles: map[string]string{"x": "y"}, LocalAssetsPaths: []string{"p1"}, Favorites: []FavoriteServer{{Name: "n", URL: "u", Description: "d"}}, Wardrobe: []string{"w"}, diff --git a/internal/config/testdata/load_golden.json b/internal/config/testdata/load_golden.json index e8fc47f6..44b2f4b6 100644 --- a/internal/config/testdata/load_golden.json +++ b/internal/config/testdata/load_golden.json @@ -418,96 +418,22 @@ "animateEntrances": true, "animatedBudgetMiB": 64, "animatedSpriteCapPx": 240, - "areaHighlightHex": "v832", - "assetCharCase": 1, - "assetOrigin": "v601", - "assetTypes": { - "Background": { - "fallbacksEnabled": false, - "formatOrder": [ - ".webp" - ] - }, - "Blip": { - "fallbacksEnabled": false, - "formatOrder": [ - ".opus" - ] - }, - "CharIcon": { - "fallbacksEnabled": false, - "formatOrder": [ - ".png" - ] - }, - "CharSprite": { - "fallbacksEnabled": false, - "formatOrder": [ - ".webp" - ] - }, - "DeskOverlay": { - "fallbacksEnabled": false, - "formatOrder": [ - ".webp" - ] - }, - "Effect": { - "fallbacksEnabled": false, - "formatOrder": [ - ".webp" - ] - }, - "EmoteButton": { - "fallbacksEnabled": false, - "formatOrder": [ - ".webp" - ] - }, - "Misc": { - "fallbacksEnabled": false, - "formatOrder": [ - ".png", - ".webp" - ] - }, - "Music": { - "fallbacksEnabled": false, - "formatOrder": [ - ".opus" - ] - }, - "SFX": { - "fallbacksEnabled": false, - "formatOrder": [ - ".opus" - ] - }, - "ShoutBubble": { - "fallbacksEnabled": false, - "formatOrder": [ - ".webp" - ] - }, - "v342": { - "fallbacksEnabled": true, - "formatOrder": [ - "v442" - ] - } - }, + "areaHighlightHex": "v232", + "assetCharCase": 2, + "assetOrigin": "v501", + "assetSwitchesMigrated": true, "autoClipModcall": true, "autoConnectOnLaunch": true, "autoLoginToast": true, "autoReconnect": true, "autoReconnectDefaultMigrated": true, "autoStatus": { - "afkWords": "v213", - "busyWords": "v313", - "clearWords": "v113", + "afkWords": "v303", + "busyWords": "v403", + "clearWords": "v203", "enabled": true, - "lfrpWords": "v513", - "writingWords": "v413" + "lfrpWords": "v603", + "writingWords": "v503" }, "bgSlideshow": true, "bgSlideshowSecs": 3, @@ -517,18 +443,19 @@ "blipVolMuted": true, "blipVolume": 1, "blipVolumes": { - "v752": 1 + "v742": 1 }, "boldNamesOff": true, "breathAmp": 2, "breathNoBob": true, "breathNoScale": true, "breathSpeed": 1, + "cacheDir": "v251", "callWords": [ - "v703" + "v892" ], "callwordOSToast": true, - "callwordSoundFile": "v931", + "callwordSoundFile": "v531", "callwordToast": true, "callwordsOOC": true, "casingEnabled": true, @@ -537,7 +464,7 @@ "catchUpLingerMs": 1, "catchUpThreshold": 1, "catchUpWhenBehind": true, - "changelogSeenVersion": "v641", + "changelogSeenVersion": "v241", "charChatbox": true, "chatBoxPercent": 50, "chatRateLimitMs": 2, @@ -545,8 +472,8 @@ "chatboxOpacity": 2, "chatboxTint": true, "chromeShape": "sharp", - "chromeShapeTier": 1, - "chromeTheme": "v613", + "chromeShapeTier": 2, + "chromeTheme": "v703", "classicAnchors": { "cc": { "mode": "cc", @@ -555,7 +482,7 @@ } }, "classicLayout": { - "v881": [ + "v281": [ 0.5, 0.5, 0.5, @@ -563,18 +490,19 @@ ] }, "classicRotations": { - "v212": 2 + "v602": 2 }, "clipSpritesToStage": true, + "cpuRenderer": true, "crossfadeMs": 50, "customChrome": [ - "v362", - "v462", - "v562", - "v662", - "v762", - "v862", - "v962" + "v552", + "v652", + "v752", + "v852", + "v952", + "v062", + "v162" ], "debugOverlay": true, "depthOfField": true, @@ -586,7 +514,7 @@ "disableEffects": true, "disableFrameLimiter": true, "discord": { - "appId": "v013", + "appId": "v103", "enabled": true, "showArea": true, "showChar": true, @@ -603,15 +531,15 @@ "emoteFavOnly": true, "emoteFavStars": true, "emoteFavorites": { - "v952": [ + "v942": [ 1 ] }, - "emoteGridGapPx": 1, + "emoteGridGapPx": 2, "emoteHoverNames": true, "emoteHoverNamesMs": 500, "errorSpriteCustom": true, - "errorSpritePath": "v723", + "errorSpritePath": "v813", "export": { "fps": 6, "heightPx": 240, @@ -619,63 +547,58 @@ "quality": 20, "textScale": 50 }, - "extProfiles": { - "v572": "v672" - }, - "extrasBg": "v332", - "extrasBg2": "v432", - "extrasBorder": "v532", + "extrasBg": "v722", + "extrasBg2": "v822", + "extrasBorder": "v922", "extrasGradient": true, - "extrasText": "v732", - "extrasTitle": "v632", + "extrasText": "v132", + "extrasTitle": "v032", "favEmoteBox": true, "favorites": [ { - "description": "v082", - "name": "v872", - "url": "v972" + "description": "v072", + "name": "v862", + "url": "v962" } ], "followEnabled": true, "fontCensus": true, "fontEverywhere": true, - "fontPaths": "v571", + "fontPaths": "v961", "fontWarnThemes": [ "v411" ], "forceCharNames": true, - "formatAutoDetect": true, "fpsCap": 2, "friendGlowPulse": true, "friendHighlight": true, "friendNotify": true, "friendOSToast": true, "friendSound": true, - "friendSoundFile": "v531", + "friendSoundFile": "v131", "ghostCrawlText": true, - "globalFallbacksEnabled": true, "groupChatButton": true, "groupInviteOSToast": true, "hiddenPanels": [ - "v382" + "v372" ], "hideDesk": true, "hideReactions": true, "hideSpriteStyles": true, - "highlightColor": 1, - "holdClearKey": "v132", + "highlightColor": 2, + "holdClearKey": "v522", "holdClearMs": 300, "holdClearOn": true, "holdDebugTint": true, "holdPrevMaxAgeMs": 100, "hotkeys": { - "v803": "v903" + "v992": "v003" }, "hotkeysEnabled": true, - "icCustomColor": 2, + "icCustomColor": 1, "icLogDepth": 2, "icPhraseKeys": { - "v152": "v252" + "v142": "v242" }, "icQueueCap": 8, "icTimestamps": true, @@ -690,15 +613,15 @@ "lastServerURL": "v31", "layoutGridPx": 2, "layoutPartColors": [ - "v072", - "v172", - "v272", - "v372" + "v262", + "v362", + "v462", + "v562" ], "layoutProfiles": { - "v391": { + "v781": { "classic": { - "v491": [ + "v881": [ 0.5, 0.5, 0.5, @@ -707,50 +630,45 @@ }, "gridPx": 2, "hidden": [ - "v302" + "v791" ], "rotations": { - "v502": 1 + "v991": 1 } } }, - "learnedFormats": { - "v542": [ - "v642" - ] - }, "legacyDevTheme": true, "localAssetsEnabled": true, "localAssetsLayered": true, "localAssetsPaths": [ - "v772" + "v762" ], "logScalePercent": 75, "macros": [ { - "key": "v771", + "key": "v171", "lines": [ - "v871" + "v271" ], - "name": "v671" + "name": "v071" } ], - "masterListUrl": "v242", + "masterListUrl": "v632", "masterVolMuted": true, "masterVolume": 1, "mentionSelf": true, "messageCounter": true, "modBanSFX": true, - "modBanSoundFile": "v631", + "modBanSoundFile": "v231", "modDurations": [ - "v652" + "v642" ], "modKickSFX": true, - "modKickSoundFile": "v731", + "modKickSoundFile": "v331", "modMuteSFX": true, - "modMuteSoundFile": "v831", + "modMuteSoundFile": "v431", "modReasonTemplates": [ - "v552" + "v542" ], "modcallToast": true, "motionRedrawPerEvent": true, @@ -760,36 +678,35 @@ "musicFlags": 1, "musicHistory": true, "musicHosts": [ - "v823" + "v913" ], "musicStreaming": true, "musicVolMode": true, "musicVolMuted": true, "musicVolume": 1, "mutedSFX": [ - "v352" + "v342" ], "mySpriteStyle": { - "b": 1, - "brightness": 1, + "b": 2, + "brightness": 2, "dropShadow": true, "flipH": true, - "g": 2, + "g": 1, "glitch": true, - "glitchAB": 1, - "glitchAG": 2, - "glitchAR": 1, - "glitchBB": 2, - "glitchBG": 1, - "glitchBR": 2, - "glitchMode": 2, + "glitchAB": 2, + "glitchAG": 1, + "glitchAR": 2, + "glitchBB": 1, + "glitchBG": 2, + "glitchBR": 1, + "glitchMode": 1, "glow": true, "grayscale": true, "hueCycle": true, "invert": true, - "motion": 2, + "motion": 1, "motionPath": [ - 1, 2, 1, 2, @@ -804,42 +721,44 @@ 1, 2, 1, - 2 + 2, + 1 ], - "motionPathLen": 1, - "opacity": 2, + "motionPathLen": 2, + "opacity": 1, "outline": true, - "outlineB": 2, - "outlineG": 1, - "outlineR": 2, - "paint2B": 1, - "paint2G": 2, - "paint2R": 1, - "paintSplit": 2, + "outlineB": 1, + "outlineG": 2, + "outlineR": 1, + "paint2B": 2, + "paint2G": 1, + "paint2R": 2, + "paintSplit": 1, "posterize": true, - "r": 1, - "restyle": 1, - "rotation": 1, - "scale": 2, + "r": 2, + "restyle": 2, + "rotation": 2, + "scale": 1, "sepia": true, "spin": true, "tint": true, "wobble": true }, - "nameColorSat": 1, + "nameColorSat": 2, "nameColorVal": 50, "nameColors": true, "notFoundTTLSec": 30, "notifyOnOOC": true, "oocInLogTab": true, - "oocName": "v712", + "oocName": "v112", "oocScalePercent": 75, "openTabs": [ { - "name": "v371", - "url": "v471" + "name": "v761", + "url": "v861" } ], + "packagesOff": true, "panelFonts": { "v111": { "family": "v211" @@ -855,26 +774,28 @@ "postVignette": true, "preanimTimeoutMs": 200, "preferAnimated": true, + "prereleaseTickedFor": "v2", "previewHeightPx": 96, "previewHoverMs": 500, "previewPinned": true, - "previewWinRectH": 1, + "previewWinRectH": 2, "previewWinRectValid": true, - "previewWinRectW": 2, - "previewWinRectX": 2, - "previewWinRectY": 1, + "previewWinRectW": 1, + "previewWinRectX": 1, + "previewWinRectY": 2, "profile": { - "artURL": "v421", - "bio": "v221", + "artURL": "v021", + "bio": "v811", "enabled": true, - "name": "v911", - "pronouns": "v021", + "name": "v511", + "pronouns": "v611", "showOnList": true, - "tag": "v121", - "themeSong": "v321" + "tag": "v711", + "themeSong": "v911" }, - "proxyMode": 2, - "proxyUrl": "v011", + "proxyBypass": "v011", + "proxyMode": 1, + "proxyUrl": "v901", "quitConfirmSkip": true, "rainbowMessages": true, "rainbowPairDesync": true, @@ -894,50 +815,53 @@ "rightClickHideSprite": true, "screenEffects": true, "serverWarm": { - "v482": { - "audioBlip": 2, - "audioMaster": 1, - "audioMusic": 2, + "v472": { + "assetHosts": [ + "v682" + ], + "audioBlip": 1, + "audioMaster": 2, + "audioMusic": 1, "audioOn": true, - "audioSFX": 1, + "audioSFX": 2, "autoLogin": true, - "background": "v682", + "background": "v672", "backgrounds": [ - "v103" + "v292" ], - "char": "v582", + "char": "v572", "charKeys": { - "v192": "v292" + "v182": "v282" }, "chars": [ - "v003" + "v192" ], "favBackgroundFolder": { - "v982": "v092" + "v972": "v082" }, "favBackgrounds": [ - "v882" + "v872" ], "friends": [ - "v203" + "v392" ], "ignored": [ - "v303" + "v492" ], - "loginPass": "v503", - "loginUser": "v403", - "origin": "v592", - "theme": "v603", + "loginPass": "v692", + "loginUser": "v592", + "origin": "v582", + "theme": "v792", "wardrobe": [ - "v782" + "v772" ], "wardrobeFolder": { - "v392": "v492" + "v382": "v482" } } }, "sfxFavorites": [ - "v452" + "v442" ], "sfxOnIdle": true, "sfxVolMuted": true, @@ -950,12 +874,12 @@ "showPairStatus": true, "showRecordButton": true, "showSongURL": true, - "showname": "v742", + "showname": "v732", "shownameKeys": { - "v942": "v052" + "v932": "v042" }, "shownamePresets": [ - "v842" + "v832" ], "smoothLogScroll": true, "smoothScaling": true, @@ -982,31 +906,30 @@ "streamerMode": true, "stylePresets": [ { - "color": 2, - "emote": "v401", - "key": "v501", - "name": "v26", + "color": 1, + "emote": "v301", + "key": "v401", + "name": "v16", "style": { - "b": 2, - "brightness": 2, + "b": 1, + "brightness": 1, "dropShadow": true, "flipH": true, - "g": 1, + "g": 2, "glitch": true, - "glitchAB": 2, - "glitchAG": 1, - "glitchAR": 2, - "glitchBB": 1, - "glitchBG": 2, - "glitchBR": 1, - "glitchMode": 1, + "glitchAB": 1, + "glitchAG": 2, + "glitchAR": 1, + "glitchBB": 2, + "glitchBG": 1, + "glitchBR": 2, + "glitchMode": 2, "glow": true, "grayscale": true, "hueCycle": true, "invert": true, - "motion": 1, + "motion": 2, "motionPath": [ - 2, 1, 2, 1, @@ -1021,23 +944,24 @@ 2, 1, 2, - 1 + 1, + 2 ], - "motionPathLen": 2, - "opacity": 1, + "motionPathLen": 1, + "opacity": 2, "outline": true, - "outlineB": 1, - "outlineG": 2, - "outlineR": 1, - "paint2B": 2, - "paint2G": 1, - "paint2R": 2, - "paintSplit": 1, + "outlineB": 2, + "outlineG": 1, + "outlineR": 2, + "paint2B": 1, + "paint2G": 2, + "paint2R": 1, + "paintSplit": 2, "posterize": true, - "r": 2, - "restyle": 2, - "rotation": 2, - "scale": 1, + "r": 1, + "restyle": 1, + "rotation": 1, + "scale": 2, "sepia": true, "spin": true, "tint": true, @@ -1045,12 +969,12 @@ } } ], - "subtheme": "v612", + "subtheme": "v012", "texBudgetMiB": 32, "texCompression": 1, "textCrawlMs": 5, "textStayMs": 1, - "themeDir": "v512", + "themeDir": "v902", "themeFit": 1, "themeFitDefaultMigrated": true, "themeFitPanX": 1, @@ -1058,10 +982,10 @@ "themeFitZoom": 50, "themeFonts": true, "themeLayout": true, - "themeName": "v412", + "themeName": "v802", "themeRectOverrides": { - "v971": { - "v081": [ + "v371": { + "v471": [ 2, 1, 2, @@ -1070,8 +994,8 @@ } }, "themeRectRotations": { - "v581": { - "v681": 2 + "v971": { + "v081": 2 } }, "timerRepeat": true, @@ -1088,15 +1012,18 @@ "viewportPercent": 40, "volStripOn": true, "wardrobe": [ - "v182" + "v172" ], + "wardrobeAccent": 1, + "wardrobeIconPx": 40, + "wardrobeNameAbove": true, "weatherIntensity": 2, "weatherType": 1, "windowFullscreen": true, "windowHeight": 2, "windowWidth": 1, "wordDelete": true, - "wsOrigin": "v701" + "wsOrigin": "v601" }, "output_delta": { "adaptiveLatMultiple": 2, @@ -1105,26 +1032,18 @@ "animateEntrances": true, "animatedBudgetMiB": 64, "animatedSpriteCapPx": 240, - "areaHighlightHex": "v832", - "assetCharCase": 1, - "assetOrigin": "v601", - "assetTypes": { - "v342": { - "fallbacksEnabled": true, - "formatOrder": [ - "v442" - ] - } - }, + "areaHighlightHex": "v232", + "assetCharCase": 2, + "assetOrigin": "v501", "autoConnectOnLaunch": true, "autoReconnect": true, "autoStatus": { - "afkWords": "v213", - "busyWords": "v313", - "clearWords": "v113", + "afkWords": "v303", + "busyWords": "v403", + "clearWords": "v203", "enabled": true, - "lfrpWords": "v513", - "writingWords": "v413" + "lfrpWords": "v603", + "writingWords": "v503" }, "bgSlideshow": true, "bgSlideshowSecs": 3, @@ -1133,31 +1052,32 @@ "blipVolMuted": true, "blipVolume": 1, "blipVolumes": { - "v752": 1 + "v742": 1 }, "boldNamesOff": true, "breathAmp": 2, "breathNoBob": true, "breathNoScale": true, "breathSpeed": 1, + "cacheDir": "v251", "callWords": [ - "v703" + "v892" ], "callwordOSToast": true, - "callwordSoundFile": "v931", + "callwordSoundFile": "v531", "callwordsOOC": true, "casingEnabled": true, "casingRoles": 1, "catchUpLingerMs": 1, "catchUpWhenBehind": true, - "changelogSeenVersion": "v641", + "changelogSeenVersion": "v241", "chatBoxPercent": 50, "chatRateLimitMs": 2, "chatScalePercent": 50, "chatboxOpacity": 2, "chatboxTint": true, - "chromeShapeTier": 1, - "chromeTheme": "v613", + "chromeShapeTier": 2, + "chromeTheme": "v703", "classicAnchors": { "cc": { "mode": "cc", @@ -1166,7 +1086,7 @@ } }, "classicLayout": { - "v881": [ + "v281": [ 0.5, 0.5, 0.5, @@ -1174,17 +1094,18 @@ ] }, "classicRotations": { - "v212": 2 + "v602": 2 }, + "cpuRenderer": true, "crossfadeMs": 50, "customChrome": [ - "v362", - "v462", - "v562", - "v662", - "v762", - "v862", - "v962" + "v552", + "v652", + "v752", + "v852", + "v952", + "v062", + "v162" ], "debugOverlay": true, "depthOfField": true, @@ -1192,7 +1113,7 @@ "disableEffects": true, "disableFrameLimiter": true, "discord": { - "appId": "v013", + "appId": "v103", "showArea": true }, "diskCacheBudgetMiB": 128, @@ -1203,40 +1124,37 @@ "emoteFavOnly": true, "emoteFavStars": true, "emoteFavorites": { - "v952": [ + "v942": [ 1 ] }, - "emoteGridGapPx": 1, + "emoteGridGapPx": 2, "emoteHoverNamesMs": 500, "errorSpriteCustom": true, - "errorSpritePath": "v723", + "errorSpritePath": "v813", "export": { "fps": 6, "heightPx": 240, "quality": 20, "textScale": 50 }, - "extProfiles": { - "v572": "v672" - }, - "extrasBg": "v332", - "extrasBg2": "v432", - "extrasBorder": "v532", + "extrasBg": "v722", + "extrasBg2": "v822", + "extrasBorder": "v922", "extrasGradient": true, - "extrasText": "v732", - "extrasTitle": "v632", + "extrasText": "v132", + "extrasTitle": "v032", "favEmoteBox": true, "favorites": [ { - "description": "v082", - "name": "v872", - "url": "v972" + "description": "v072", + "name": "v862", + "url": "v962" } ], "followEnabled": true, "fontEverywhere": true, - "fontPaths": "v571", + "fontPaths": "v961", "fontWarnThemes": [ "v411" ], @@ -1247,28 +1165,27 @@ "friendNotify": true, "friendOSToast": true, "friendSound": true, - "friendSoundFile": "v531", - "globalFallbacksEnabled": true, + "friendSoundFile": "v131", "groupInviteOSToast": true, "hiddenPanels": [ - "v382" + "v372" ], "hideDesk": true, "hideReactions": true, "hideSpriteStyles": true, - "highlightColor": 1, - "holdClearKey": "v132", + "highlightColor": 2, + "holdClearKey": "v522", "holdClearMs": 300, "holdDebugTint": true, "holdPrevMaxAgeMs": 100, "hotkeys": { - "v803": "v903" + "v992": "v003" }, "hotkeysEnabled": true, - "icCustomColor": 2, + "icCustomColor": 1, "icLogDepth": 2, "icPhraseKeys": { - "v152": "v252" + "v142": "v242" }, "icQueueCap": 8, "icTimestamps": true, @@ -1283,15 +1200,15 @@ "lastServerURL": "v31", "layoutGridPx": 2, "layoutPartColors": [ - "v072", - "v172", - "v272", - "v372" + "v262", + "v362", + "v462", + "v562" ], "layoutProfiles": { - "v391": { + "v781": { "classic": { - "v491": [ + "v881": [ 0.5, 0.5, 0.5, @@ -1300,49 +1217,44 @@ }, "gridPx": 2, "hidden": [ - "v302" + "v791" ], "rotations": { - "v502": 1 + "v991": 1 } } }, - "learnedFormats": { - "v542": [ - "v642" - ] - }, "legacyDevTheme": true, "localAssetsEnabled": true, "localAssetsLayered": true, "localAssetsPaths": [ - "v772" + "v762" ], "logScalePercent": 75, "macros": [ { - "key": "v771", + "key": "v171", "lines": [ - "v871" + "v271" ], - "name": "v671" + "name": "v071" } ], - "masterListUrl": "v242", + "masterListUrl": "v632", "masterVolMuted": true, "masterVolume": 1, "mentionSelf": true, "modBanSFX": true, - "modBanSoundFile": "v631", + "modBanSoundFile": "v231", "modDurations": [ - "v652" + "v642" ], "modKickSFX": true, - "modKickSoundFile": "v731", + "modKickSoundFile": "v331", "modMuteSFX": true, - "modMuteSoundFile": "v831", + "modMuteSoundFile": "v431", "modReasonTemplates": [ - "v552" + "v542" ], "modcallToast": true, "multiTabCap": 2, @@ -1350,35 +1262,34 @@ "musicDucking": true, "musicFlags": 1, "musicHosts": [ - "v823" + "v913" ], "musicVolMode": true, "musicVolMuted": true, "musicVolume": 1, "mutedSFX": [ - "v352" + "v342" ], "mySpriteStyle": { - "b": 1, - "brightness": 1, + "b": 2, + "brightness": 2, "dropShadow": true, "flipH": true, - "g": 2, + "g": 1, "glitch": true, - "glitchAB": 1, - "glitchAG": 2, - "glitchAR": 1, - "glitchBB": 2, - "glitchBG": 1, - "glitchBR": 2, - "glitchMode": 2, + "glitchAB": 2, + "glitchAG": 1, + "glitchAR": 2, + "glitchBB": 1, + "glitchBG": 2, + "glitchBR": 1, + "glitchMode": 1, "glow": true, "grayscale": true, "hueCycle": true, "invert": true, - "motion": 2, + "motion": 1, "motionPath": [ - 1, 2, 1, 2, @@ -1393,42 +1304,44 @@ 1, 2, 1, - 2 + 2, + 1 ], - "motionPathLen": 1, - "opacity": 2, + "motionPathLen": 2, + "opacity": 1, "outline": true, - "outlineB": 2, - "outlineG": 1, - "outlineR": 2, - "paint2B": 1, - "paint2G": 2, - "paint2R": 1, - "paintSplit": 2, + "outlineB": 1, + "outlineG": 2, + "outlineR": 1, + "paint2B": 2, + "paint2G": 1, + "paint2R": 2, + "paintSplit": 1, "posterize": true, - "r": 1, - "restyle": 1, - "rotation": 1, - "scale": 2, + "r": 2, + "restyle": 2, + "rotation": 2, + "scale": 1, "sepia": true, "spin": true, "tint": true, "wobble": true }, - "nameColorSat": 1, + "nameColorSat": 2, "nameColorVal": 50, "nameColors": true, "notFoundTTLSec": 30, "notifyOnOOC": true, "oocInLogTab": true, - "oocName": "v712", + "oocName": "v112", "oocScalePercent": 75, "openTabs": [ { - "name": "v371", - "url": "v471" + "name": "v761", + "url": "v861" } ], + "packagesOff": true, "panelFonts": { "v111": { "family": "v211" @@ -1442,26 +1355,28 @@ "postScanlines": true, "postVignette": true, "preanimTimeoutMs": 200, + "prereleaseTickedFor": "v2", "previewHeightPx": 96, "previewHoverMs": 500, "previewPinned": true, - "previewWinRectH": 1, + "previewWinRectH": 2, "previewWinRectValid": true, - "previewWinRectW": 2, - "previewWinRectX": 2, - "previewWinRectY": 1, + "previewWinRectW": 1, + "previewWinRectX": 1, + "previewWinRectY": 2, "profile": { - "artURL": "v421", - "bio": "v221", + "artURL": "v021", + "bio": "v811", "enabled": true, - "name": "v911", - "pronouns": "v021", + "name": "v511", + "pronouns": "v611", "showOnList": true, - "tag": "v121", - "themeSong": "v321" + "tag": "v711", + "themeSong": "v911" }, - "proxyMode": 2, - "proxyUrl": "v011", + "proxyBypass": "v011", + "proxyMode": 1, + "proxyUrl": "v901", "quitConfirmSkip": true, "rainbowMessages": true, "rainbowPairDesync": true, @@ -1478,50 +1393,53 @@ "replaySpeed": 25, "restoreTabs": true, "serverWarm": { - "v482": { - "audioBlip": 2, - "audioMaster": 1, - "audioMusic": 2, + "v472": { + "assetHosts": [ + "v682" + ], + "audioBlip": 1, + "audioMaster": 2, + "audioMusic": 1, "audioOn": true, - "audioSFX": 1, + "audioSFX": 2, "autoLogin": true, - "background": "v682", + "background": "v672", "backgrounds": [ - "v103" + "v292" ], - "char": "v582", + "char": "v572", "charKeys": { - "v192": "v292" + "v182": "v282" }, "chars": [ - "v003" + "v192" ], "favBackgroundFolder": { - "v982": "v092" + "v972": "v082" }, "favBackgrounds": [ - "v882" + "v872" ], "friends": [ - "v203" + "v392" ], "ignored": [ - "v303" + "v492" ], - "loginPass": "v503", - "loginUser": "v403", - "origin": "v592", - "theme": "v603", + "loginPass": "v692", + "loginUser": "v592", + "origin": "v582", + "theme": "v792", "wardrobe": [ - "v782" + "v772" ], "wardrobeFolder": { - "v392": "v492" + "v382": "v482" } } }, "sfxFavorites": [ - "v452" + "v442" ], "sfxOnIdle": true, "sfxVolMuted": true, @@ -1531,12 +1449,12 @@ "showPairStatus": true, "showRecordButton": true, "showSongURL": true, - "showname": "v742", + "showname": "v732", "shownameKeys": { - "v942": "v052" + "v932": "v042" }, "shownamePresets": [ - "v842" + "v832" ], "smoothLogScroll": true, "spotlight": true, @@ -1560,31 +1478,30 @@ "streamerMode": true, "stylePresets": [ { - "color": 2, - "emote": "v401", - "key": "v501", - "name": "v26", + "color": 1, + "emote": "v301", + "key": "v401", + "name": "v16", "style": { - "b": 2, - "brightness": 2, + "b": 1, + "brightness": 1, "dropShadow": true, "flipH": true, - "g": 1, + "g": 2, "glitch": true, - "glitchAB": 2, - "glitchAG": 1, - "glitchAR": 2, - "glitchBB": 1, - "glitchBG": 2, - "glitchBR": 1, - "glitchMode": 1, + "glitchAB": 1, + "glitchAG": 2, + "glitchAR": 1, + "glitchBB": 2, + "glitchBG": 1, + "glitchBR": 2, + "glitchMode": 2, "glow": true, "grayscale": true, "hueCycle": true, "invert": true, - "motion": 1, + "motion": 2, "motionPath": [ - 2, 1, 2, 1, @@ -1599,23 +1516,24 @@ 2, 1, 2, - 1 + 1, + 2 ], - "motionPathLen": 2, - "opacity": 1, + "motionPathLen": 1, + "opacity": 2, "outline": true, - "outlineB": 1, - "outlineG": 2, - "outlineR": 1, - "paint2B": 2, - "paint2G": 1, - "paint2R": 2, - "paintSplit": 1, + "outlineB": 2, + "outlineG": 1, + "outlineR": 2, + "paint2B": 1, + "paint2G": 2, + "paint2R": 1, + "paintSplit": 2, "posterize": true, - "r": 2, - "restyle": 2, - "rotation": 2, - "scale": 1, + "r": 1, + "restyle": 1, + "rotation": 1, + "scale": 2, "sepia": true, "spin": true, "tint": true, @@ -1623,20 +1541,20 @@ } } ], - "subtheme": "v612", + "subtheme": "v012", "texBudgetMiB": 32, "texCompression": 1, "textCrawlMs": 5, "textStayMs": 1, - "themeDir": "v512", + "themeDir": "v902", "themeFit": 1, "themeFitPanX": 1, "themeFitPanY": 2, "themeFitZoom": 50, - "themeName": "v412", + "themeName": "v802", "themeRectOverrides": { - "v971": { - "v081": [ + "v371": { + "v471": [ 2, 1, 2, @@ -1645,8 +1563,8 @@ } }, "themeRectRotations": { - "v581": { - "v681": 2 + "v971": { + "v081": 2 } }, "timerRepeat": true, @@ -1661,14 +1579,17 @@ "viewportPercent": 40, "volStripOn": true, "wardrobe": [ - "v182" + "v172" ], + "wardrobeAccent": 1, + "wardrobeIconPx": 40, + "wardrobeNameAbove": true, "weatherIntensity": 2, "weatherType": 1, "windowFullscreen": true, "windowHeight": 2, "windowWidth": 1, - "wsOrigin": "v701" + "wsOrigin": "v601" } } ] \ No newline at end of file diff --git a/internal/config/testdata/prefs_default.json b/internal/config/testdata/prefs_default.json index 799dc6ef..3a194626 100644 --- a/internal/config/testdata/prefs_default.json +++ b/internal/config/testdata/prefs_default.json @@ -1,5 +1,4 @@ { - "globalFallbacksEnabled": false, "preferAnimated": true, "emoteButtonImages": true, "smoothScaling": true, @@ -126,7 +125,6 @@ "modcallToast": false, "callwordSoundFile": "", "debugOverlay": false, - "formatAutoDetect": true, "themeLayout": true, "themeFit": 4, "themeFitZoom": 100, @@ -195,76 +193,6 @@ "textStayMs": 200, "chatRateLimitMs": 0, "masterListUrl": "", - "assetTypes": { - "Background": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "Blip": { - "formatOrder": [ - ".opus" - ], - "fallbacksEnabled": false - }, - "CharIcon": { - "formatOrder": [ - ".png" - ], - "fallbacksEnabled": false - }, - "CharSprite": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "DeskOverlay": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "Effect": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "EmoteButton": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "Misc": { - "formatOrder": [ - ".png", - ".webp" - ], - "fallbacksEnabled": false - }, - "Music": { - "formatOrder": [ - ".opus" - ], - "fallbacksEnabled": false - }, - "SFX": { - "formatOrder": [ - ".opus" - ], - "fallbacksEnabled": false - }, - "ShoutBubble": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - } - }, - "learnedFormats": {}, "showname": "", "emoteFavOnly": false, "emoteFavStars": false, diff --git a/internal/config/testdata/prefs_golden.json b/internal/config/testdata/prefs_golden.json index 762950af..13613b04 100644 --- a/internal/config/testdata/prefs_golden.json +++ b/internal/config/testdata/prefs_golden.json @@ -1,5 +1,4 @@ { - "globalFallbacksEnabled": true, "preferAnimated": true, "emoteButtonImages": true, "smoothScaling": true, @@ -7,10 +6,11 @@ "spriteScalingMigrated": true, "updateCheck": true, "updateExperimental": true, - "highlightColor": 1, - "icCustomColor": 2, + "prereleaseTickedFor": "v2", + "highlightColor": 2, + "icCustomColor": 1, "nameColors": true, - "nameColorSat": 1, + "nameColorSat": 2, "nameColorVal": 50, "bgSlideshow": true, "bgSlideshowSecs": 3, @@ -56,10 +56,10 @@ }, "mySpriteStyle": { "tint": true, - "r": 1, - "g": 2, - "b": 1, - "opacity": 2, + "r": 2, + "g": 1, + "b": 2, + "opacity": 1, "glow": true, "wobble": true, "spin": true, @@ -69,10 +69,9 @@ "grayscale": true, "sepia": true, "posterize": true, - "restyle": 1, - "motion": 2, + "restyle": 2, + "motion": 1, "motionPath": [ - 1, 2, 1, 2, @@ -87,39 +86,40 @@ 1, 2, 1, - 2 + 2, + 1 ], - "motionPathLen": 1, + "motionPathLen": 2, "outline": true, "dropShadow": true, "glitch": true, - "outlineR": 2, - "outlineG": 1, - "outlineB": 2, - "brightness": 1, - "scale": 2, - "rotation": 1, - "paintSplit": 2, - "paint2R": 1, - "paint2G": 2, - "paint2B": 1, - "glitchMode": 2, - "glitchAR": 1, - "glitchAG": 2, - "glitchAB": 1, - "glitchBR": 2, - "glitchBG": 1, - "glitchBB": 2 + "outlineR": 1, + "outlineG": 2, + "outlineB": 1, + "brightness": 2, + "scale": 1, + "rotation": 2, + "paintSplit": 1, + "paint2R": 2, + "paint2G": 1, + "paint2B": 2, + "glitchMode": 1, + "glitchAR": 2, + "glitchAG": 1, + "glitchAB": 2, + "glitchBR": 1, + "glitchBG": 2, + "glitchBB": 1 }, "stylePresets": [ { - "name": "v26", + "name": "v16", "style": { "tint": true, - "r": 2, - "g": 1, - "b": 2, - "opacity": 1, + "r": 1, + "g": 2, + "b": 1, + "opacity": 2, "glow": true, "wobble": true, "spin": true, @@ -129,10 +129,9 @@ "grayscale": true, "sepia": true, "posterize": true, - "restyle": 2, - "motion": 1, + "restyle": 1, + "motion": 2, "motionPath": [ - 2, 1, 2, 1, @@ -147,43 +146,45 @@ 2, 1, 2, - 1 + 1, + 2 ], - "motionPathLen": 2, + "motionPathLen": 1, "outline": true, "dropShadow": true, "glitch": true, - "outlineR": 1, - "outlineG": 2, - "outlineB": 1, - "brightness": 2, - "scale": 1, - "rotation": 2, - "paintSplit": 1, - "paint2R": 2, - "paint2G": 1, - "paint2B": 2, - "glitchMode": 1, - "glitchAR": 2, - "glitchAG": 1, - "glitchAB": 2, - "glitchBR": 1, - "glitchBG": 2, - "glitchBB": 1 + "outlineR": 2, + "outlineG": 1, + "outlineB": 2, + "brightness": 1, + "scale": 2, + "rotation": 1, + "paintSplit": 2, + "paint2R": 1, + "paint2G": 2, + "paint2B": 1, + "glitchMode": 2, + "glitchAR": 1, + "glitchAG": 2, + "glitchAB": 1, + "glitchBR": 2, + "glitchBG": 1, + "glitchBB": 2 }, - "color": 2, - "emote": "v401", - "key": "v501" + "color": 1, + "emote": "v301", + "key": "v401" } ], "hideSpriteStyles": true, "hideReactions": true, "validateTLSCerts": true, - "assetOrigin": "v601", - "wsOrigin": "v701", - "assetCharCase": 1, - "proxyMode": 2, - "proxyUrl": "v011", + "assetOrigin": "v501", + "wsOrigin": "v601", + "assetCharCase": 2, + "proxyMode": 1, + "proxyUrl": "v901", + "proxyBypass": "v011", "panelFonts": { "v111": { "family": "v211" @@ -198,12 +199,12 @@ "profile": { "enabled": true, "showOnList": true, - "name": "v911", - "pronouns": "v021", - "tag": "v121", - "bio": "v221", - "themeSong": "v321", - "artURL": "v421" + "name": "v511", + "pronouns": "v611", + "tag": "v711", + "bio": "v811", + "themeSong": "v911", + "artURL": "v021" }, "chatboxOpacity": 2, "rainbowSpriteVividness": 1, @@ -240,17 +241,16 @@ "callwordOSToast": true, "friendGlowPulse": true, "friendSound": true, - "friendSoundFile": "v531", + "friendSoundFile": "v131", "modBanSFX": true, "modKickSFX": true, "modMuteSFX": true, - "modBanSoundFile": "v631", - "modKickSoundFile": "v731", - "modMuteSoundFile": "v831", + "modBanSoundFile": "v231", + "modKickSoundFile": "v331", + "modMuteSoundFile": "v431", "modcallToast": true, - "callwordSoundFile": "v931", + "callwordSoundFile": "v531", "debugOverlay": true, - "formatAutoDetect": true, "themeLayout": true, "themeFit": 1, "themeFitZoom": 50, @@ -264,7 +264,7 @@ "multiTabCap": 2, "restoreTabs": true, "volStripOn": true, - "changelogSeenVersion": "v641", + "changelogSeenVersion": "v241", "spriteLoadMode": 2, "spriteWaitMs": 50, "spriteWaitPair": true, @@ -279,6 +279,7 @@ "icLogDepth": 2, "catchUpLingerMs": 1, "diskCacheBudgetMiB": 128, + "cacheDir": "v251", "notFoundTTLSec": 30, "adaptiveLatMultiple": 2, "spriteDownscaleOff": true, @@ -299,8 +300,8 @@ "musicFlags": 1, "openTabs": [ { - "name": "v371", - "url": "v471" + "name": "v761", + "url": "v861" } ], "reduceMotion": true, @@ -316,19 +317,19 @@ "autoClipModcall": true, "groupChatButton": true, "charChatbox": true, - "fontPaths": "v571", + "fontPaths": "v961", "macros": [ { - "name": "v671", - "key": "v771", + "name": "v071", + "key": "v171", "lines": [ - "v871" + "v271" ] } ], "themeRectOverrides": { - "v971": { - "v081": [ + "v371": { + "v471": [ 2, 1, 2, @@ -337,12 +338,12 @@ } }, "themeRectRotations": { - "v581": { - "v681": 2 + "v971": { + "v081": 2 } }, "classicLayout": { - "v881": [ + "v281": [ 0.5, 0.5, 0.5, @@ -350,9 +351,9 @@ ] }, "layoutProfiles": { - "v391": { + "v781": { "classic": { - "v491": [ + "v881": [ 0.5, 0.5, 0.5, @@ -360,11 +361,11 @@ ] }, "hidden": [ - "v302" + "v791" ], "gridPx": 2, "rotations": { - "v502": 1 + "v991": 1 } } }, @@ -377,13 +378,13 @@ } }, "classicRotations": { - "v212": 2 + "v602": 2 }, "streamerMode": true, - "themeName": "v412", - "themeDir": "v512", - "subtheme": "v612", - "oocName": "v712", + "themeName": "v802", + "themeDir": "v902", + "subtheme": "v012", + "oocName": "v112", "viewportPercent": 40, "chatScalePercent": 50, "chatBoxPercent": 50, @@ -403,126 +404,46 @@ "sfxVolMuted": true, "blipVolMuted": true, "holdClearOn": true, - "holdClearKey": "v132", + "holdClearKey": "v522", "holdClearMs": 300, - "extrasBg": "v332", - "extrasBg2": "v432", - "extrasBorder": "v532", - "extrasTitle": "v632", - "extrasText": "v732", + "extrasBg": "v722", + "extrasBg2": "v822", + "extrasBorder": "v922", + "extrasTitle": "v032", + "extrasText": "v132", "extrasGradient": true, - "areaHighlightHex": "v832", + "areaHighlightHex": "v232", "textCrawlMs": 5, "textStayMs": 1, "chatRateLimitMs": 2, - "masterListUrl": "v242", - "assetTypes": { - "Background": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "Blip": { - "formatOrder": [ - ".opus" - ], - "fallbacksEnabled": false - }, - "CharIcon": { - "formatOrder": [ - ".png" - ], - "fallbacksEnabled": false - }, - "CharSprite": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "DeskOverlay": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "Effect": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "EmoteButton": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "Misc": { - "formatOrder": [ - ".png", - ".webp" - ], - "fallbacksEnabled": false - }, - "Music": { - "formatOrder": [ - ".opus" - ], - "fallbacksEnabled": false - }, - "SFX": { - "formatOrder": [ - ".opus" - ], - "fallbacksEnabled": false - }, - "ShoutBubble": { - "formatOrder": [ - ".webp" - ], - "fallbacksEnabled": false - }, - "v342": { - "formatOrder": [ - "v442" - ], - "fallbacksEnabled": true - } - }, - "learnedFormats": { - "v542": [ - "v642" - ] - }, - "showname": "v742", + "masterListUrl": "v632", + "showname": "v732", "shownamePresets": [ - "v842" + "v832" ], "shownameKeys": { - "v942": "v052" + "v932": "v042" }, "icPhraseKeys": { - "v152": "v252" + "v142": "v242" }, "mutedSFX": [ - "v352" + "v342" ], "sfxFavorites": [ - "v452" + "v442" ], "modReasonTemplates": [ - "v552" + "v542" ], "modDurations": [ - "v652" + "v642" ], "blipVolumes": { - "v752": 1 + "v742": 1 }, "emoteFavorites": { - "v952": [ + "v942": [ 1 ] }, @@ -530,97 +451,102 @@ "emoteFavStars": true, "localAssetsEnabled": true, "localAssetsLayered": true, + "packagesOff": true, + "cpuRenderer": true, "emoteCaptions": true, "viewportExactW": 256, "oocScalePercent": 75, + "wardrobeIconPx": 40, + "wardrobeNameAbove": true, + "wardrobeAccent": 1, "customChrome": [ - "v362", - "v462", - "v562", - "v662", - "v762", - "v862", - "v962" + "v552", + "v652", + "v752", + "v852", + "v952", + "v062", + "v162" ], "layoutPartColors": [ - "v072", - "v172", - "v272", - "v372" + "v262", + "v362", + "v462", + "v562" ], "boldNamesOff": true, "blipRate": 1, "blipOnSpaces": true, "callwordsOOC": true, - "extProfiles": { - "v572": "v672" - }, "localAssetsPaths": [ - "v772" + "v762" ], "favorites": [ { - "name": "v872", - "url": "v972", - "description": "v082" + "name": "v862", + "url": "v962", + "description": "v072" } ], "wardrobe": [ - "v182" + "v172" ], "casingEnabled": true, "casingRoles": 1, "hiddenPanels": [ - "v382" + "v372" ], "serverWarm": { - "v482": { - "char": "v582", - "background": "v682", + "v472": { + "char": "v572", + "background": "v672", "wardrobe": [ - "v782" + "v772" ], "favBackgrounds": [ - "v882" + "v872" ], "favBackgroundFolder": { - "v982": "v092" + "v972": "v082" }, "charKeys": { - "v192": "v292" + "v182": "v282" }, "wardrobeFolder": { - "v392": "v492" + "v382": "v482" }, - "origin": "v592", + "origin": "v582", + "assetHosts": [ + "v682" + ], "audioOn": true, - "audioMaster": 1, - "audioMusic": 2, - "audioSFX": 1, - "audioBlip": 2, + "audioMaster": 2, + "audioMusic": 1, + "audioSFX": 2, + "audioBlip": 1, "chars": [ - "v003" + "v192" ], "backgrounds": [ - "v103" + "v292" ], "friends": [ - "v203" + "v392" ], "ignored": [ - "v303" + "v492" ], - "loginUser": "v403", - "loginPass": "v503", + "loginUser": "v592", + "loginPass": "v692", "autoLogin": true, - "theme": "v603" + "theme": "v792" } }, "callWords": [ - "v703" + "v892" ], "hotkeys": { - "v803": "v903" + "v992": "v003" }, "discord": { "enabled": true, @@ -628,19 +554,19 @@ "showChar": true, "showName": true, "showArea": true, - "appId": "v013" + "appId": "v103" }, "autoStatus": { "enabled": true, - "clearWords": "v113", - "afkWords": "v213", - "busyWords": "v313", - "writingWords": "v413", - "lfrpWords": "v513" + "clearWords": "v203", + "afkWords": "v303", + "busyWords": "v403", + "writingWords": "v503", + "lfrpWords": "v603" }, - "chromeTheme": "v613", + "chromeTheme": "v703", "chromeShape": "sharp", - "chromeShapeTier": 1, + "chromeShapeTier": 2, "toolboxSeen": true, "spriteMove": true, "deskFollowManifest": true, @@ -649,13 +575,13 @@ "previewHeightPx": 96, "previewPinned": true, "previewWinRectValid": true, - "previewWinRectX": 2, - "previewWinRectY": 1, - "previewWinRectW": 2, - "previewWinRectH": 1, + "previewWinRectX": 1, + "previewWinRectY": 2, + "previewWinRectW": 1, + "previewWinRectH": 2, "emoteHoverNames": true, "emoteHoverNamesMs": 500, - "emoteGridGapPx": 1, + "emoteGridGapPx": 2, "autoLoginToast": true, "callwordToast": true, "messageCounter": true, @@ -682,8 +608,8 @@ "musicAcrossTabs": true, "showMissingPlaceholder": true, "errorSpriteCustom": true, - "errorSpritePath": "v723", + "errorSpritePath": "v813", "musicHosts": [ - "v823" + "v913" ] } \ No newline at end of file diff --git a/internal/courtroom/bgfallback_test.go b/internal/courtroom/bgfallback_test.go index f42ffcc1..0aef859a 100644 --- a/internal/courtroom/bgfallback_test.go +++ b/internal/courtroom/bgfallback_test.go @@ -47,7 +47,7 @@ func newBGRig(t *testing.T) *bgRig { mount := t.TempDir() local := assets.NewLocalFetcher([]string{mount}) mgr := assets.NewManager(assets.ManagerDeps{ - Resolver: assets.NewResolver(prefs), Prefs: prefs, T2: t2, Disk: disk, + Prefs: prefs, T2: t2, Disk: disk, Source: local, Decoder: decoder, }) t.Cleanup(mgr.CloseMedia) diff --git a/internal/courtroom/courtroom_test.go b/internal/courtroom/courtroom_test.go index f897e402..16d8a052 100644 --- a/internal/courtroom/courtroom_test.go +++ b/internal/courtroom/courtroom_test.go @@ -67,7 +67,6 @@ func newCourtroomRig(t testing.TB) (*Courtroom, *Session, *sentRecorder, *audioR t.Fatal(err) } t.Cleanup(func() { _ = prefs.Close() }) - resolver := assets.NewResolver(prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -81,7 +80,7 @@ func newCourtroomRig(t testing.TB) (*Courtroom, *Session, *sentRecorder, *audioR t.Cleanup(decoder.Close) local := assets.NewLocalFetcher([]string{t.TempDir()}) mgr := assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, Prefs: prefs, T2: t2, Disk: disk, + Prefs: prefs, T2: t2, Disk: disk, Source: local, Decoder: decoder, }) t.Cleanup(mgr.CloseMedia) diff --git a/internal/courtroom/messageneeds_test.go b/internal/courtroom/messageneeds_test.go index fcec839e..d327bd65 100644 --- a/internal/courtroom/messageneeds_test.go +++ b/internal/courtroom/messageneeds_test.go @@ -137,7 +137,7 @@ func recordingRoom(t *testing.T) (*Courtroom, *recordingSource) { t.Cleanup(decoder.Close) src := &recordingSource{} mgr := assets.NewManager(assets.ManagerDeps{ - Resolver: assets.NewResolver(prefs), Prefs: prefs, T2: t2, Disk: disk, + Prefs: prefs, T2: t2, Disk: disk, Source: src, Decoder: decoder, }) t.Cleanup(mgr.CloseMedia) diff --git a/internal/media/candidates.go b/internal/media/candidates.go index 9f933f92..f5b80ae3 100644 --- a/internal/media/candidates.go +++ b/internal/media/candidates.go @@ -189,6 +189,24 @@ func (b *CandidateBuilder) Learn(origin string, class Class, ext string) { h.learned[class][ext]++ } +// ForgetLearned drops every learned format; the hosts' own lists stay. +func (b *CandidateBuilder) ForgetLearned() { + for _, h := range b.origins { + clear(h.learned) + } +} + +// LearnedOrigins counts the origins a format was learned for. +func (b *CandidateBuilder) LearnedOrigins() int { + n := 0 + for _, h := range b.origins { + if len(h.learned) > 0 { + n++ + } + } + return n +} + // Allow sets the formats and their order from a host's extensions.json. func (b *CandidateBuilder) Allow(origin string, allowed map[Class][]string) { h := b.hints(origin) diff --git a/internal/media/manifest_fuzz_test.go b/internal/media/manifest_fuzz_test.go new file mode 100644 index 00000000..ba750838 --- /dev/null +++ b/internal/media/manifest_fuzz_test.go @@ -0,0 +1,31 @@ +package media + +import "testing" + +func FuzzParseManifest(f *testing.F) { + seeds := []string{ + `{"charicon_extensions":[".png"],"emote_extensions":[".webp.static",".webp.animated",".webp"]}`, + `{"background_extensions":[".gif",".GIF",".gif",".png",".jpg",".avif",".apng",".png",".bmp"]}`, + `{"emotions_extensions":[" .PNG ",".exe",".webp.static"]}`, + `{}`, `[]`, `null`, `{"emote_extensions":null}`, ``, `{`, + } + for _, s := range seeds { + f.Add([]byte(s)) + } + f.Fuzz(func(t *testing.T, data []byte) { + lists, err := ParseManifest(data) + if err != nil { + return + } + for class, list := range lists { + if len(list) == 0 || len(list) > manifestExtCap { + t.Fatalf("class %d has %d formats: %v", class, len(list), list) + } + for _, ext := range list { + if !knownExt(ext) { + t.Fatalf("class %d kept unknown format %q", class, ext) + } + } + } + }) +} diff --git a/internal/metrics/profiler.go b/internal/metrics/profiler.go index d827920d..c06e2c01 100644 --- a/internal/metrics/profiler.go +++ b/internal/metrics/profiler.go @@ -21,7 +21,6 @@ const ( type StatsSource struct { CacheHits func() (hits, misses int64) NetRequests func() (requests, cached404s int64) - LearnedHits func() (hits, misses int64) } // Sample is one 1 Hz snapshot. diff --git a/internal/render/pump_test.go b/internal/render/pump_test.go index 8ef4867e..ef3bcb5a 100644 --- a/internal/render/pump_test.go +++ b/internal/render/pump_test.go @@ -24,14 +24,13 @@ import ( // buildPumpManager wires a minimal asset manager over the given source — // the same shape the app uses, enough to fetch + decode + emit on Decoded(). // localMode true = a mount-folder source; false = a real network client. -func buildPumpManager(t *testing.T, source assets.Fetcher, localMode bool) (*assets.Manager, *assets.Resolver) { +func buildPumpManager(t *testing.T, source assets.Fetcher, localMode bool) *assets.Manager { t.Helper() prefs, err := config.New(filepath.Join(t.TempDir(), config.PrefsFileName)) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = prefs.Close() }) - resolver := assets.NewResolver(prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -44,14 +43,14 @@ func buildPumpManager(t *testing.T, source assets.Fetcher, localMode bool) (*ass decoder := assets.NewDecoderPool(2) t.Cleanup(decoder.Close) mgr := assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, Prefs: prefs, T2: t2, Disk: disk, + Prefs: prefs, T2: t2, Disk: disk, Source: source, Decoder: decoder, }) t.Cleanup(mgr.CloseMedia) if lf, ok := source.(*assets.LocalFetcher); ok && localMode { mgr.SetFolders(lf.Mounts(), nil) } - return mgr, resolver + return mgr } func writeTestPNG(t *testing.T, path string) { @@ -93,10 +92,10 @@ func TestPumpUploadsPrefetchByBase(t *testing.T) { rel, _ := strings.CutPrefix(base, origin) writeTestPNG(t, filepath.Join(dir, filepath.FromSlash(rel+config.ExtPNG))) - mgr, resolver := buildPumpManager(t, local, true) + mgr := buildPumpManager(t, local, true) // The default probe list is webp-only; this fixture is PNG, so seed the host's // learned format (what a real extensions.json / a prior learned hit provides). - resolver.RecordSuccess(assets.HostOf(base), assets.AssetTypeCharSprite, config.ExtPNG) + mgr.AllowFormats(local.BaseURL(), map[assets.AssetType]string{assets.AssetTypeCharSprite: config.ExtPNG}) store, err := NewTextureStoreBudget(ren, 0) if err != nil { @@ -139,7 +138,7 @@ func TestPumpTransientErrorsDontPin(t *testing.T) { })) defer srvCorrupt.Close() - mgr, _ := buildPumpManager(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false) + mgr := buildPumpManager(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false) store, err := NewTextureStoreBudget(ren, 0) if err != nil { t.Fatal(err) diff --git a/internal/saver/saver_test.go b/internal/saver/saver_test.go index 2443b773..96490cb9 100644 --- a/internal/saver/saver_test.go +++ b/internal/saver/saver_test.go @@ -54,14 +54,15 @@ func TestBurstOfChangesIsOneWriteOfTheLatestValue(t *testing.T) { c.value.Store(int64(i)) s.Changed() } - waitFor(t, func() bool { return c.writes.Load() > 0 }) + want := strconv.Itoa(burst - 1) + waitFor(t, func() bool { + data, err := os.ReadFile(path) + return err == nil && string(data) == want + }) time.Sleep(testDelay * 2) if n := c.writes.Load(); n != 1 { t.Errorf("%d writes, want 1", n) } - if got := readBack(t, path); got != strconv.Itoa(burst-1) { - t.Errorf("file holds %q, want %d", got, burst-1) - } } func TestCloseWritesAndSchedulesNothingAfter(t *testing.T) { diff --git a/internal/ui/app.go b/internal/ui/app.go index 365b8f3f..f38d0080 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -104,9 +104,8 @@ const ( // Deps wires the app to the engine singletons built in main. type Deps struct { - Prefs *config.AssetPreferences - Resolver *assets.Resolver - Manager *assets.Manager + Prefs *config.AssetPreferences + Manager *assets.Manager // Disk is the disk cache tier, which Settings can move to another folder while the client runs. Disk *cache.DiskCache Client *network.Client diff --git a/internal/ui/app_connect.go b/internal/ui/app_connect.go index e9ba75fb..41d3bde9 100644 --- a/internal/ui/app_connect.go +++ b/internal/ui/app_connect.go @@ -1107,19 +1107,6 @@ func (a *App) pickCharacter(idx int) { a.sess.PickCharacter(idx) } -// extProfileFor returns the effective format profile (extensions.json text) for an asset host: a user-set per-server -// profile wins, else the official vanilla server gets the bundled example. "" means fetch the server's own -// extensions.json. -func (a *App) extProfileFor(host string) string { - if p := a.d.Prefs.Load().ExtProfile(host); p != "" { - return p - } - if a.isOfficialVanilla(host) { - return assets.BundledVanillaManifestJSON - } - return "" -} - // isOfficialVanilla matches the AO official vanilla base by asset host, or the official vanilla server by connected // server key, so joining it uses the vanilla format profile. func (a *App) isOfficialVanilla(assetHost string) bool { @@ -1233,43 +1220,32 @@ func charCaseName(c uint8) string { } } -// fetchManifestAsync seeds this host's learned formats from /extensions.json (webAO convention) so the first -// asset of each class costs one probe. Auto-detect (Settings) gates the network fetch; manual orders cover servers -// without a manifest. +// vanillaManifest is the official vanilla server's formats: it publishes no extensions.json, and its art is PNG. +const vanillaManifest = `{ + "charicon_extensions": [".png"], + "emote_extensions": [".apng", ".webp", ".png"], + "emotions_extensions": [".png"], + "background_extensions": [".png"] +}` + +// fetchManifestAsync reads /extensions.json (webAO convention) into the media system, so the first asset of +// each class costs one request. func (a *App) fetchManifestAsync() { origin := a.urls.Origin() - // Settings' re-seed hooks blank manifestFor to force a fresh fetch after a profile or auto-detect change; drop the - // origin from the dedupe set so the guard below re-runs. - if a.manifestFor == "" { - delete(a.manifestSeeded, origin) - } - a.manifestFor = origin if a.originSeeded(origin) || !strings.HasPrefix(origin, "http") { return } a.markOriginSeeded(origin) host := hostOfURL(origin) - // A per-host format profile (user-set, or the built-in official-vanilla example) applies even with auto-detect off; - // it seeds instantly, so the first probe already uses the right formats, and wins over the global default for this - // host. - if profile := a.extProfileFor(host); profile != "" { - if m, err := assets.ParseManifest([]byte(profile)); err == nil { - n := m.SeedLearned(a.d.Prefs, host) - a.d.Resolver.WarmFromPrefs() - a.pushDebug(fmt.Sprintf("format profile: seeded %d classes for %s (instant)", n, host)) - return - } - } - // The network fetch of the server's own extensions.json is gated on auto-detect; the per-server profile above is - // not. - if !a.d.Prefs.Load().AutoDetectFormats { + if a.isOfficialVanilla(host) { + a.d.Manager.AllowManifest(origin, []byte(vanillaManifest)) + a.pushDebug("formats: the vanilla server's built-in list for " + host) return } mgr := a.d.Manager - prefs := a.d.Prefs ch := a.manifestRes go func() { - res := seedOriginFormats(mgr, prefs, origin) + res := seedOriginFormats(mgr, origin) mf := manifestFetch{host: host, seeded: res.seeded, status: res.status, err: res.err} // pollManifest treats a nil err as "seeded". A host with no manifest or an unreadable one is not a seed, so // surface it as an error and let pollManifest log "learn per probe instead". @@ -1310,7 +1286,7 @@ func (a *App) markOriginSeeded(origin string) { type seedStatus int const ( - seedSkipped seedStatus = iota // not attempted (non-http origin, or autodetect off) + seedSkipped seedStatus = iota // not attempted (non-http origin) seedApplied // extensions.json fetched + parsed; N classes seeded seedAbsent // no reachable extensions.json (host publishes none) seedFailed // reachable but unparseable / transport fault @@ -1325,17 +1301,11 @@ type seedResult struct { err error } -// seedOriginFormats is the blocking core shared by the session connect path (fetchManifestAsync) and the diagnostic -// paths (content report, export loader) to seed a host's learned formats from /extensions.json. It runs off the -// render thread (FetchRaw blocks; RecordLearned/SeedLearned take the prefs mutex). The caller republishes the resolver -// table (WarmFromPrefs) on the render thread. absent (a clean 404) is distinct from failed (transport/parse fault) so -// the panel can say which. -func seedOriginFormats(mgr *assets.Manager, prefs *config.AssetPreferences, origin string) seedResult { - if mgr == nil || prefs == nil || !strings.HasPrefix(origin, "http") { - return seedResult{status: seedSkipped} - } - host := hostOfURL(origin) - if host == "" { +// seedOriginFormats reads origin's extensions.json into the media system; it blocks, so the connect path and the +// diagnostic passes (content report, export loader) run it off the render thread. absent (a clean 404) is distinct +// from failed (transport or parse fault) so the panel can say which. +func seedOriginFormats(mgr *assets.Manager, origin string) seedResult { + if mgr == nil || !strings.HasPrefix(origin, "http") || hostOfURL(origin) == "" { return seedResult{status: seedSkipped} } ctx, cancel := context.WithTimeout(context.Background(), smallFetchTimeout) @@ -1347,14 +1317,14 @@ func seedOriginFormats(mgr *assets.Manager, prefs *config.AssetPreferences, orig } return seedResult{status: seedFailed, err: err} } - m, perr := assets.ParseManifest(data) + lists, perr := media.ParseManifest(data) if perr != nil { return seedResult{status: seedFailed, err: perr} } - return seedResult{status: seedApplied, seeded: m.SeedLearned(prefs, host)} + return seedResult{status: seedApplied, seeded: len(lists)} } -// pollManifest lands autodetect results: republish the resolver snapshot with the seeds and report on the debug lane. +// pollManifest reports a finished extensions.json read on the debug lane. func (a *App) pollManifest() { select { case res := <-a.manifestRes: @@ -1363,13 +1333,12 @@ func (a *App) pollManifest() { a.pushDebug("extensions.json: " + res.err.Error() + " — formats learn per probe instead") return } - a.d.Resolver.WarmFromPrefs() - a.pushDebug(fmt.Sprintf("extensions.json: seeded %d format classes for %s", res.seeded, res.host)) + a.pushDebug(fmt.Sprintf("extensions.json: %d format classes for %s", res.seeded, res.host)) default: } } -// noteManifestStatus records whether a host published a usable extensions.json, for Settings -> Formats. Render thread +// noteManifestStatus records whether a host published a usable extensions.json, for Settings -> Assets. Render thread // only (the map is unsynchronized); bounded by the distinct asset hosts visited in a session. func (a *App) noteManifestStatus(host string, st seedStatus) { if host == "" { diff --git a/internal/ui/apptypes.go b/internal/ui/apptypes.go index 500ea591..a09b13da 100644 --- a/internal/ui/apptypes.go +++ b/internal/ui/apptypes.go @@ -161,12 +161,10 @@ type sessionState struct { areaLogs map[string][]icEntry areaLogOrder []string lastICSend time.Time // chat_ratelimit window - // manifestFor: Settings writes "" to force fetchManifestAsync to re-fetch the session origin's extensions.json. - manifestFor string // manifestSeeded holds origins whose extensions.json was already fetched and seeded this session, so each is // seeded once. Bounded by the distinct asset origins visited. manifestSeeded map[string]struct{} - // manifestStatus records per asset host how the extensions.json probe ended; Settings → Formats reads it. + // manifestStatus records per asset host how the extensions.json probe ended; Settings → Assets reads it. // Render thread only, same bound as manifestSeeded. manifestStatus map[string]seedStatus // assetHosts are the connected server's extra asset hosts as last handed to the media system; diff --git a/internal/ui/conclusivemiss_ui_test.go b/internal/ui/conclusivemiss_ui_test.go index 64c225f3..825d394a 100644 --- a/internal/ui/conclusivemiss_ui_test.go +++ b/internal/ui/conclusivemiss_ui_test.go @@ -10,7 +10,6 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/cache" - "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/sdl" ) @@ -42,21 +41,14 @@ func wireEmptyPackManager(t *testing.T, a *App) *assets.LocalFetcher { local := assets.NewLocalFetcher([]string{t.TempDir()}) // empty: nothing resolves a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: assets.NewResolver(a.d.Prefs), - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: local, - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: local, + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) a.d.Manager.SetFolders(local.Mounts(), nil) - // One extension per type keeps the probe chains short and the fixture's - // intent legible; the defaults differ per type and none of that is what - // these gates are about. - for _, typ := range []assets.AssetType{assets.AssetTypeCharIcon, assets.AssetTypeEmoteButton} { - a.d.Prefs.SetFormatOrder(typ.Name(), []string{config.ExtPNG}) - } return local } diff --git a/internal/ui/contentjob.go b/internal/ui/contentjob.go index dee76345..0ba1fdd0 100644 --- a/internal/ui/contentjob.go +++ b/internal/ui/contentjob.go @@ -512,13 +512,10 @@ func (a *App) StartContentReport(rec *sceneRecording, stem string) bool { a.content = j a.contentBusy = true - // Seed first when the origin is a network host and auto-detect is on: fetch /extensions.json and seed - // this - // host's learned formats before probing, as the live connect path does. A .demo's recorded origin is never the - // session origin, so otherwise the probe would try one format against a server that ships .gif/.png. Other - // origins - // skip to probing; probeRef's full-chain fallback still finds assets. Deduped per origin via the shared marker. - if strings.HasPrefix(report.Origin, "http") && a.d.Prefs.Load().AutoDetectFormats && !a.originSeeded(report.Origin) { + // A network origin's extensions.json is read before probing, as the live connect path does: a .demo's recorded + // origin is never the session origin. Other origins skip to probing; probeRef's full walk still finds assets. + // Deduped per origin via the shared marker. + if strings.HasPrefix(report.Origin, "http") && !a.originSeeded(report.Origin) { a.markOriginSeeded(report.Origin) a.startContentSeed(j) a.warnLine = "Checking the server's format manifest…" @@ -582,9 +579,9 @@ func (a *App) startAutoBundle(rec *sceneRecording, stem string) { a.content = j a.contentBusy = true - // Seed first for a network origin with auto-detect on that isn't already seeded; an in-app recording's origin is - // usually the live session origin, seeded on connect. Same condition as StartContentReport. - if strings.HasPrefix(report.Origin, "http") && a.d.Prefs.Load().AutoDetectFormats && !a.originSeeded(report.Origin) { + // Read a network origin's extensions.json first unless it already was; an in-app recording's origin is usually the + // live session origin, read on connect. Same condition as StartContentReport. + if strings.HasPrefix(report.Origin, "http") && !a.originSeeded(report.Origin) { a.markOriginSeeded(report.Origin) a.startContentSeed(j) return @@ -592,7 +589,7 @@ func (a *App) startAutoBundle(rec *sceneRecording, stem string) { a.startProbePhase(j) } -// startContentSeed spawns the one seed goroutine: it fetches /extensions.json and seeds the learned table, +// startContentSeed spawns the one seed goroutine: it reads /extensions.json into the media system, // delivering on the 1-buffered seedDone channel drained by tickContentSeed. A Cancel nils a.content so the send // lands in an unpolled buffer and the goroutine ends. Render thread only. func (a *App) startContentSeed(j *contentJob) { @@ -600,12 +597,11 @@ func (a *App) startContentSeed(j *contentJob) { j.seedDone = make(chan seedResult, contentSeedBuf) done := j.seedDone mgr := j.seedMgr - prefs := a.d.Prefs origin := j.report.Origin j.probeLive.Add(1) go func() { defer j.probeLive.Add(-1) - done <- seedOriginFormats(mgr, prefs, origin) // 1-buffered: always accepts + done <- seedOriginFormats(mgr, origin) // 1-buffered: always accepts }() } @@ -774,17 +770,12 @@ func (a *App) tickContentJob() { } } -// tickContentSeed polls the seed goroutine without blocking; on delivery it republishes the resolver table, notes -// the outcome on the report and starts the probe phase. A Cancel nils a.content, so a stale generation never +// tickContentSeed polls the seed goroutine without blocking; on delivery it notes the outcome on the report and +// starts the probe phase. A Cancel nils a.content, so a stale generation never // reaches here. Render thread only. func (a *App) tickContentSeed(j *contentJob) { select { case res := <-j.seedDone: - // WarmFromPrefs on the render thread: SeedLearned wrote prefs off-thread, and this publishes them into the - // resolver's atomic table before any candidate is built. - if res.status == seedApplied { - a.d.Resolver.WarmFromPrefs() - } j.report.Seed = res.status a.startProbePhase(j) default: diff --git a/internal/ui/contentjob_test.go b/internal/ui/contentjob_test.go index 81b241e9..86730f75 100644 --- a/internal/ui/contentjob_test.go +++ b/internal/ui/contentjob_test.go @@ -1,6 +1,8 @@ package ui import ( + "github.com/SyntaxNyah/AsyncAO/internal/media" + "encoding/json" "fmt" "net/http" @@ -297,7 +299,7 @@ func TestContentProbeWindowBounded(t *testing.T) { // immediately (404 = no manifest) and UNGATED so the seed completes and the // probe phase — the thing under test — actually starts. Only the asset // probes are held on the gate so their concurrency is observable. - if r.URL.Path == "/"+assets.ManifestFileName { + if r.URL.Path == "/"+media.ManifestFile { w.WriteHeader(http.StatusNotFound) return } @@ -651,7 +653,7 @@ func TestCancelMidProbeLeakFree(t *testing.T) { // Answer the pre-probe format-seed's extensions.json UNGATED (404 = no // manifest) so the seed completes and the PROBE phase — the phase this test // cancels mid-flight — actually starts and its workers get held on the gate. - if r.URL.Path == "/"+assets.ManifestFileName { + if r.URL.Path == "/"+media.ManifestFile { w.WriteHeader(http.StatusNotFound) return } @@ -1094,7 +1096,6 @@ func existingAorecs(t *testing.T) map[string]bool { func headlessProbeApp(t *testing.T, source assets.Fetcher, localMode bool) *App { t.Helper() a := testTabApp(t) - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -1106,14 +1107,12 @@ func headlessProbeApp(t *testing.T, source assets.Fetcher, localMode bool) *App t.Cleanup(disk.Close) decoder := assets.NewDecoderPool(2) t.Cleanup(decoder.Close) - a.d.Resolver = resolver a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: source, - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: source, + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) if lf, ok := source.(*assets.LocalFetcher); ok && localMode { @@ -1128,7 +1127,6 @@ func headlessProbeApp(t *testing.T, source assets.Fetcher, localMode bool) *App func localMgr(t *testing.T, mount string) (*assets.Manager, string) { t.Helper() a := testTabApp(t) // reuse its prefs (a real config); we only need the Manager - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -1142,12 +1140,11 @@ func localMgr(t *testing.T, mount string) (*assets.Manager, string) { t.Cleanup(decoder.Close) local := assets.NewLocalFetcher([]string{mount}) mgr := assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: local, - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: local, + Decoder: decoder, }) t.Cleanup(mgr.CloseMedia) t.Cleanup(mgr.CloseMedia) diff --git a/internal/ui/contentseed_test.go b/internal/ui/contentseed_test.go index 8e96bee3..a6cb16ce 100644 --- a/internal/ui/contentseed_test.go +++ b/internal/ui/contentseed_test.go @@ -17,6 +17,8 @@ package ui // through the mounts in the probe path (AO2-parity). import ( + "github.com/SyntaxNyah/AsyncAO/internal/media" + "net/http" "net/http/httptest" "strings" @@ -54,7 +56,7 @@ func TestContentSeedGifManifestResolves(t *testing.T) { var gifHits atomic.Int32 // written in the server goroutine, read in the test → atomic srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { - case r.URL.Path == "/"+assets.ManifestFileName: + case r.URL.Path == "/"+media.ManifestFile: _, _ = w.Write([]byte(manifest)) case r.URL.Path == "/characters/phoenix/(a)normal.gif": gifHits.Add(1) @@ -155,9 +157,8 @@ func TestContentFullChainProbeFindsPNG(t *testing.T) { } // The winner must have been learned so a repeat resolve is single-probe. - host := hostOfURL(rec.Origin) - if ext, ok := a.d.Resolver.Learned(host, assets.AssetTypeCharSprite); !ok || ext != config.ExtPNG { - t.Errorf("Learned(CharSprite) = %q,%v, want %q,true (RecordSuccess should have learned the .png winner)", ext, ok, config.ExtPNG) + if n := a.d.Manager.LearnedHosts(); n == 0 { + t.Error("the .png winner taught no host a format") } // No NON-png candidate for phoenix's base may EVER have been probed on the @@ -273,8 +274,13 @@ func TestContentSeedLocalMountResolves(t *testing.T) { // "seeded before the warm builds candidates"). func TestExportSeedBeforeWarm(t *testing.T) { manifest := `{"emote_extensions": [".gif"], "background_extensions": [".gif"]}` + var mu sync.Mutex + var asked []string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/"+assets.ManifestFileName { + mu.Lock() + asked = append(asked, r.URL.Path) + mu.Unlock() + if r.URL.Path == "/"+media.ManifestFile { _, _ = w.Write([]byte(manifest)) return } @@ -283,26 +289,7 @@ func TestExportSeedBeforeWarm(t *testing.T) { t.Cleanup(srv.Close) a := headlessProbeApp(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false) - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - true - - }) - - // the seed gate respects the same pref the session path does origin := srv.URL + "/" - host := hostOfURL(origin) - - // Pre-seed sanity: nothing learned yet, so the warm's first candidate WOULD be - // the zero-fallback .webp (the bug). - if ext, ok := a.d.Resolver.Learned(host, assets.AssetTypeCharSprite); ok { - t.Fatalf("CharSprite already learned (%q) before seeding — test can't prove the seed did it", ext) - } // Build a seeding-phase export job and fire the seed, exactly as startSceneExport // does after the load lands (no viewport / capture target needed — seeding runs @@ -326,11 +313,15 @@ func TestExportSeedBeforeWarm(t *testing.T) { t.Fatal("seeding phase never completed") } - // The observable: the manifest's .gif is now the learned CharSprite format, so - // the warm's first PrefetchChain candidate is base+".gif" — the manifest- - // declared format, not the .webp default. - if ext, ok := a.d.Resolver.Learned(host, assets.AssetTypeCharSprite); !ok || ext != config.ExtGIF { - t.Errorf("Learned(CharSprite) = %q,%v after export seed, want %q,true (warm would probe the wrong format otherwise)", ext, ok, config.ExtGIF) + // The observable: the manifest's .gif is now the first format asked for a sprite, not the .webp default. + mu.Lock() + asked = nil + mu.Unlock() + a.d.Manager.ResolveRaw(origin+"characters/x/(a)y", assets.AssetTypeCharSprite) + mu.Lock() + defer mu.Unlock() + if len(asked) == 0 || asked[0] != "/characters/x/(a)y"+config.ExtGIF { + t.Errorf("after the export seed the sprite was asked as %v, want .gif first", asked) } } diff --git a/internal/ui/debugpanel.go b/internal/ui/debugpanel.go index 96ab070c..aeda13b0 100644 --- a/internal/ui/debugpanel.go +++ b/internal/ui/debugpanel.go @@ -336,11 +336,8 @@ func (a *App) drawDebugCache(r sdl.Rect) { line(fmt.Sprintf("T3 disk cache — hit %d · miss %d · writes %d · dropped %d · errors %d", d.Hits, d.Misses, d.Writes, d.Dropped, d.WriteErrors), ColText) } - // Resolver — learned per-host formats (the zero-fallback streaming premise). - if a.d.Resolver != nil { - rs := a.d.Resolver.Stats() - line(fmt.Sprintf("Learned formats — hit %d · miss %d (%s)", - rs.LearnedHits, rs.LearnedMisses, hitRatePct(rs.LearnedHits, rs.LearnedMisses)), ColTextDim) + if a.d.Manager != nil { + line(fmt.Sprintf("Learned formats — %d hosts", a.d.Manager.LearnedHosts()), ColTextDim) } // Network client — total probes + cached 404s (never re-probed inside TTL). if a.d.Client != nil { diff --git a/internal/ui/deskmissing_relay_test.go b/internal/ui/deskmissing_relay_test.go index 1a5c30a5..2dae2f2e 100644 --- a/internal/ui/deskmissing_relay_test.go +++ b/internal/ui/deskmissing_relay_test.go @@ -59,9 +59,6 @@ func TestDrainWarningsRelaysDeskMissing(t *testing.T) { dir := t.TempDir() // empty pack: background/gs4/defensedesk exists in no format local, cleanup := wireLocalManager(t, a, dir) defer cleanup() - // The resolver walks the configured formats; point the desk type at - // .png so the probe list is a real (and short) chain over the on-disk root. - a.d.Prefs.SetFormatOrder(assets.AssetTypeDeskOverlay.Name(), []string{config.ExtPNG}) // A real room with a live DeskShow message, so the relay has something to // re-derive (NotifyDeskMissing only touches the scene of the room whose CURRENT @@ -136,7 +133,6 @@ func TestDrainWarningsRelaysBackgroundMissToGate(t *testing.T) { dir := t.TempDir() // empty pack: background/gs4/ exists in no format local, cleanup := wireLocalManager(t, a, dir) defer cleanup() - a.d.Prefs.SetFormatOrder(assets.AssetTypeBackground.Name(), []string{config.ExtPNG}) urls := courtroom.NewURLBuilder(local.BaseURL()) bgBase := urls.PositionScenery("gs4", "wit", nil).Background diff --git a/internal/ui/emotepreviewfollow_test.go b/internal/ui/emotepreviewfollow_test.go index 58e5e024..3da84e55 100644 --- a/internal/ui/emotepreviewfollow_test.go +++ b/internal/ui/emotepreviewfollow_test.go @@ -35,7 +35,6 @@ func emotePreviewFollowTestApp(t *testing.T) *App { t.Helper() a := testTabApp(t) mount := t.TempDir() - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -48,12 +47,11 @@ func emotePreviewFollowTestApp(t *testing.T) *App { decoder := assets.NewDecoderPool(2) t.Cleanup(decoder.Close) a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: assets.NewLocalFetcher([]string{mount}), - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: assets.NewLocalFetcher([]string{mount}), + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) a.d.Manager.SetFolders([]string{mount}, nil) diff --git a/internal/ui/exportstall_test.go b/internal/ui/exportstall_test.go index 8fc8519a..a45d2f6e 100644 --- a/internal/ui/exportstall_test.go +++ b/internal/ui/exportstall_test.go @@ -63,7 +63,6 @@ func newExportStallHarness(t *testing.T) (*App, string) { a.d.Viewport = render.NewViewport(store, false) a.d.Audio = &render.Audio{} // disabled device: a safe no-op AudioSink - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -76,12 +75,11 @@ func newExportStallHarness(t *testing.T) (*App, string) { decoder := assets.NewDecoderPool(2) t.Cleanup(decoder.Close) a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: network.NewClientNotFoundTTL(0, netproxy.Direct()), // stream over HTTP: every request 404s (the all-404 origin) - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: network.NewClientNotFoundTTL(0, netproxy.Direct()), // stream over HTTP: every request 404s (the all-404 origin) + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) a.d.Pump = render.NewPump(store, a.d.Manager, nil) diff --git a/internal/ui/frameharness_test.go b/internal/ui/frameharness_test.go index d7a6eae1..10b0ad3f 100644 --- a/internal/ui/frameharness_test.go +++ b/internal/ui/frameharness_test.go @@ -52,7 +52,6 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/cache" - "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/platform/host" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" @@ -89,7 +88,6 @@ func stageFrameDrivenApp(t testing.TB) (*App, func()) { a, cleanup := stageThemedCourtroom(t) // --- the three dependencies App.Frame dereferences unconditionally --- - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { cleanup() @@ -104,12 +102,11 @@ func stageFrameDrivenApp(t testing.TB) (*App, func()) { decoder := assets.NewDecoderPool(frameHarnessPoolWorkers) t.Cleanup(decoder.Close) a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: assets.NewLocalFetcher([]string{t.TempDir()}), - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: assets.NewLocalFetcher([]string{t.TempDir()}), + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) a.d.Manager.SetFolders([]string{t.TempDir()}, nil) @@ -136,18 +133,6 @@ func stageFrameDrivenApp(t testing.TB) (*App, func()) { // call is guarded, but latching it keeps the frame free of first-frame-only work // so frame 1 and frame 2 are comparable. a.presenceInit = true - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - false - - }) - - // no extensions.json probe interposes // macroBind is the one App field whose ZERO VALUE means "armed" — slot 0 of the // macro key-capture — which is why the real constructor spells it out // (app.go:3322). A hand-built fixture that leaves it at 0 reports diff --git a/internal/ui/gifexport.go b/internal/ui/gifexport.go index abbd4e54..c6c873a6 100644 --- a/internal/ui/gifexport.go +++ b/internal/ui/gifexport.go @@ -481,10 +481,10 @@ func (a *App) startSceneExport(scene *sceneRecording, name string, kind exportKi a.gifExporting = true a.beginExportScaleBracket() // #77: exports render at native (100%) scale, not the live UI scale - // Seed the recording's origin formats before the warm so it probes the manifest-declared format (see the - // seeding-phase field). Same http(s), auto-detect and per-origin dedupe as the session connect path; a non-http - // origin (local:// mount) or auto-detect off skips to warming. tickGifSeed gates the first warm tick on the result. - if strings.HasPrefix(scene.Origin, "http") && a.d.Prefs.Load().AutoDetectFormats && !a.originSeeded(scene.Origin) { + // Read the recording's origin's extensions.json before the warm so it asks the listed format first. Same http(s) + // and per-origin dedupe as the session connect path; a non-http origin (local:// mount) skips to warming. + // tickGifSeed gates the first warm tick on the result. + if strings.HasPrefix(scene.Origin, "http") && !a.originSeeded(scene.Origin) { a.markOriginSeeded(scene.Origin) a.startExportSeed(a.gif, scene.Origin) a.warnLine = "Checking the server's format manifest…" @@ -495,29 +495,22 @@ func (a *App) startSceneExport(scene *sceneRecording, name string, kind exportKi } // startExportSeed spawns the one bounded format-seed goroutine for an export job and enters the seeding phase, which -// tickGifExport gates ahead of the warm. The render thread republishes the resolver table on delivery (tickGifSeed). -// Render thread only. +// tickGifExport gates ahead of the warm. Render thread only. func (a *App) startExportSeed(j *gifExportJob, origin string) { j.seeding = true j.seedOriginTo = origin j.seedDone = make(chan seedResult, gifSeedBuf) done := j.seedDone mgr := a.d.Manager - prefs := a.d.Prefs go func() { - done <- seedOriginFormats(mgr, prefs, origin) // 1-buffered: always accepts + done <- seedOriginFormats(mgr, origin) // 1-buffered: always accepts }() } -// tickGifSeed polls the format-seed goroutine without blocking (render thread). On delivery it republishes the resolver -// table (WarmFromPrefs, as pollManifest does) so the warm's first candidate sees the seeded formats, then enters the -// warm phase. A Cancel that nils a.gif never reaches here (tickGifExport's j==nil guard fires). +// tickGifSeed polls the format-seed goroutine without blocking (render thread); on delivery it enters the warm phase. A Cancel that nils a.gif never reaches here (tickGifExport's j==nil guard fires). func (a *App) tickGifSeed(j *gifExportJob) { select { - case res := <-j.seedDone: - if res.status == seedApplied { - a.d.Resolver.WarmFromPrefs() - } + case <-j.seedDone: j.seeding = false a.warnLine = "Loading scene assets…" a.warnAt = time.Now() diff --git a/internal/ui/gifexport_async_test.go b/internal/ui/gifexport_async_test.go index a1e8de38..d08d6f4b 100644 --- a/internal/ui/gifexport_async_test.go +++ b/internal/ui/gifexport_async_test.go @@ -11,7 +11,6 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/cache" - "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/protocol" "github.com/SyntaxNyah/AsyncAO/internal/render" @@ -230,7 +229,6 @@ func TestTickGifLoadTransitionsToWarming(t *testing.T) { // on the SAME renderer as the capture target: the warm refs simply won't // resolve, which is fine — this test asserts the PHASE transition and that the // refs were QUEUED (not blasted at the pool), not that they load. - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -243,12 +241,11 @@ func TestTickGifLoadTransitionsToWarming(t *testing.T) { decoder := assets.NewDecoderPool(2) t.Cleanup(decoder.Close) a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: assets.NewLocalFetcher([]string{t.TempDir()}), - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: assets.NewLocalFetcher([]string{t.TempDir()}), + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) a.d.Manager.SetFolders([]string{t.TempDir()}, nil) @@ -257,18 +254,6 @@ func TestTickGifLoadTransitionsToWarming(t *testing.T) { // the new pre-warm format-seed phase doesn't interpose (it's covered by // TestExportSeedBeforeWarm). With autodetect off, startSceneExport skips seeding // and the job enters warming directly, exactly as before this phase existed. - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - false - - }) - - // A one-message scene (no StartBg → no audio touched during the transition): // SceneAssets yields this speaker's bg/desk/sprite refs. rec := &sceneRecording{ Version: recordingVersion, @@ -345,7 +330,6 @@ func newWarmHarness(t *testing.T) (*App, *render.TextureStore) { } a.d.Store = store - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -358,12 +342,11 @@ func newWarmHarness(t *testing.T) (*App, *render.TextureStore) { decoder := assets.NewDecoderPool(2) t.Cleanup(decoder.Close) a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: assets.NewLocalFetcher([]string{t.TempDir()}), - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: assets.NewLocalFetcher([]string{t.TempDir()}), + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) a.d.Manager.SetFolders([]string{t.TempDir()}, nil) diff --git a/internal/ui/missingno_noblip_test.go b/internal/ui/missingno_noblip_test.go index ea005f0c..f4fd7d52 100644 --- a/internal/ui/missingno_noblip_test.go +++ b/internal/ui/missingno_noblip_test.go @@ -11,7 +11,6 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/cache" - "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/render" ) @@ -31,7 +30,6 @@ func wireLocalManager(t *testing.T, a *App, dir string) (*assets.LocalFetcher, f } a.d.Store = store - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { cleanup() @@ -48,12 +46,11 @@ func wireLocalManager(t *testing.T, a *App, dir string) (*assets.LocalFetcher, f local := assets.NewLocalFetcher([]string{dir}) a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: local, - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: local, + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) a.d.Manager.SetFolders(local.Mounts(), nil) @@ -119,7 +116,6 @@ func TestSceneWarmNoMissingnoForFolderOnlySprite(t *testing.T) { // The live speaker's idle base is the GLUED spelling (the sprite's identity), // which does not exist on disk — only its folder-form twin does. glued := local.BaseURL() + "characters/hobo/(a)normal" - seedPNGFormat(t, a) a.room = &courtroom.Courtroom{} a.room.Scene.Speaker.Visible = true @@ -167,7 +163,6 @@ func TestHealSpriteLayerFolderOnlySprite(t *testing.T) { defer cleanup() glued := local.BaseURL() + "characters/hobo/(a)normal" - seedPNGFormat(t, a) layer := &courtroom.SpriteLayer{Visible: true, Active: glued} var askBase string @@ -223,7 +218,6 @@ func TestSceneWarmNoMissingnoForBareOnlySprite(t *testing.T) { // Seed the format learn to .png for this host so the folder resolves the bare // PNG (the default probe list is webp-only; a real server would have learned or // the manifest seeded it — see TestResolveRawFromLocalArchive). - seedPNGFormat(t, a) a.room = &courtroom.Courtroom{} a.room.Scene.Speaker.Visible = true @@ -277,7 +271,6 @@ func TestSceneWarmMarksTrulyMissingSprite(t *testing.T) { defer cleanup() prefixed := local.BaseURL() + "characters/ghost/(a)normal" - seedPNGFormat(t, a) a.room = &courtroom.Courtroom{} a.room.Scene.Speaker.Visible = true @@ -308,11 +301,3 @@ func TestSceneWarmMarksTrulyMissingSprite(t *testing.T) { } } } - -// seedPNGFormat forces the char-sprite probe list to .png so the -// resolver finds the on-disk PNG fixtures (the default candidate list is -// webp-only). Mirrors what a real server learns / the archive manifest seeds. -func seedPNGFormat(t *testing.T, a *App) { - t.Helper() - a.d.Prefs.SetFormatOrder(assets.AssetTypeCharSprite.Name(), []string{config.ExtPNG}) -} diff --git a/internal/ui/newroom_test.go b/internal/ui/newroom_test.go index b52c86a3..6d92b7f9 100644 --- a/internal/ui/newroom_test.go +++ b/internal/ui/newroom_test.go @@ -61,7 +61,6 @@ func roomFactoryAppMounted(t *testing.T) (*App, string, func()) { t.Helper() a, cleanup := stageSettledCourtroom(t) mount := t.TempDir() - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { cleanup() @@ -76,27 +75,14 @@ func roomFactoryAppMounted(t *testing.T) (*App, string, func()) { decoder := assets.NewDecoderPool(2) t.Cleanup(decoder.Close) a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: assets.NewLocalFetcher([]string{mount}), - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: assets.NewLocalFetcher([]string{mount}), + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) a.d.Manager.SetFolders([]string{mount}, nil) - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - false - - }) - - // no manifest fetch interposes on the export path return a, mount, cleanup } diff --git a/internal/ui/packcharini_test.go b/internal/ui/packcharini_test.go index 187d32a6..f90826f9 100644 --- a/internal/ui/packcharini_test.go +++ b/internal/ui/packcharini_test.go @@ -44,12 +44,11 @@ func packApp(t *testing.T, files map[string]string) *App { t.Cleanup(decoder.Close) a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: assets.NewResolver(a.d.Prefs), - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: network.NewClientNotFoundTTL(0, netproxy.Direct()), - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: network.NewClientNotFoundTTL(0, netproxy.Direct()), + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) diff --git a/internal/ui/replay.go b/internal/ui/replay.go index 269c7f85..df88e6bb 100644 --- a/internal/ui/replay.go +++ b/internal/ui/replay.go @@ -488,7 +488,7 @@ func (a *App) beginBundledReplay(rec *sceneRecording, dir string) { local := assets.NewLocalFetcher([]string{dir}) rec.Origin = local.BaseURL() a.d.Manager.SetArchiveSource(local) - archive.SeedFormats(a.d.Resolver, rec.Origin, rec.Formats) + archive.SeedFormats(a.d.Manager, rec.Origin, rec.Formats) a.replayBundled = true } diff --git a/internal/ui/replaywarm.go b/internal/ui/replaywarm.go index 87c8328f..5801747f 100644 --- a/internal/ui/replaywarm.go +++ b/internal/ui/replaywarm.go @@ -82,16 +82,15 @@ func (a *App) startReplayWarm(rec *sceneRecording) { musicRefs: musicRefs, created: now, // anchors gifWarmHardCap so a never-settling ref can't hang the phase } - // Seed formats before submitting, under the same auto-detect and per-origin dedupe as the session and export paths. - if a.d.Prefs.Load().AutoDetectFormats && !a.originSeeded(rec.Origin) { + // Read the origin's formats before submitting, under the same per-origin dedupe as the session and export paths. + if strings.HasPrefix(rec.Origin, "http") && !a.originSeeded(rec.Origin) { a.markOriginSeeded(rec.Origin) w.seeding = true w.seedOrigin = rec.Origin w.seedDone = make(chan seedResult, gifSeedBuf) // 1-buffered: leak-free like the export seed done := w.seedDone mgr := a.d.Manager - prefs := a.d.Prefs - go func() { done <- seedOriginFormats(mgr, prefs, rec.Origin) }() + go func() { done <- seedOriginFormats(mgr, rec.Origin) }() } a.replayWarm = w } @@ -111,14 +110,10 @@ func (a *App) tickReplayWarm() { } now := time.Now() - // Hold submission until the format seed lands so the first probe sees the manifest format; republish the resolver - // then. + // Hold submission until the format seed lands so the first probe sees the manifest format. if w.seeding { select { - case res := <-w.seedDone: - if res.status == seedApplied { - a.d.Resolver.WarmFromPrefs() - } + case <-w.seedDone: w.seeding = false default: // Still seeding. The hard cap still applies: a dead origin's seed is bounded only by seedOriginFormats' diff --git a/internal/ui/replaywarm_test.go b/internal/ui/replaywarm_test.go index fb2acd30..70104a44 100644 --- a/internal/ui/replaywarm_test.go +++ b/internal/ui/replaywarm_test.go @@ -6,7 +6,6 @@ import ( "time" "github.com/SyntaxNyah/AsyncAO/internal/assets" - "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/protocol" ) @@ -28,6 +27,9 @@ func replayWarmRec(origin string) *sceneRecording { // TestStartReplayWarmSkipsEmptyOrigin pins that a recording with no streamable // origin (empty or local://) arms NO pre-warm phase — it plays exactly as before, // with the render thread never entering the warm gate (H5's "empty origin skips"). +// warmTestOrigin is the recordings' origin; tests mark it read, as a live session would on connect. +const warmTestOrigin = "http://example.test/" + func TestStartReplayWarmSkipsEmptyOrigin(t *testing.T) { a := testTabApp(t) @@ -47,30 +49,19 @@ func TestStartReplayWarmSkipsEmptyOrigin(t *testing.T) { // TestStartReplayWarmEnumeratesAndSplits pins that an http-origin recording arms the // phase and enumerates the scene once, splitting texture refs (submitted -// incrementally) from music refs (Exact, prefetched once). Format auto-detect is -// turned OFF so no seed goroutine interposes — the split is what's under test. +// incrementally) from music refs (Exact, prefetched once). The origin counts as +// already read, so no seed goroutine interposes — the split is what's under test. func TestStartReplayWarmEnumeratesAndSplits(t *testing.T) { a, _ := newWarmHarness(t) - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - false - - }) + a.markOriginSeeded(warmTestOrigin) - // no seed sub-phase; isolate the enumeration - - a.startReplayWarm(replayWarmRec("http://example.test/")) + a.startReplayWarm(replayWarmRec(warmTestOrigin)) w := a.replayWarm if w == nil { t.Fatal("an http-origin recording must arm the replay pre-warm") } if w.seeding { - t.Error("auto-detect off: the seed sub-phase must not run") + t.Error("an origin already read must not run the seed sub-phase") } if len(w.warmRefs) == 0 { t.Error("no texture refs enumerated — the message's bg/desk/sprite refs are missing") @@ -98,23 +89,12 @@ func TestStartReplayWarmEnumeratesAndSplits(t *testing.T) { // includes-missing path can end this within the tick budget. func TestTickReplayWarmConclusiveMissEndsPromptly(t *testing.T) { a, store := newWarmHarness(t) - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - false - - }) - - // isolate the warm from the seed sub-phase + a.markOriginSeeded(warmTestOrigin) // A big scene: more sprite refs than the in-flight window, so the never-settled // stall shape applies (the first window fills; without the miss release nothing // prunes and the phase would sit until the hard cap). - rec := &sceneRecording{Version: recordingVersion, Origin: "http://example.test/", StartBg: "courtroom"} + rec := &sceneRecording{Version: recordingVersion, Origin: warmTestOrigin, StartBg: "courtroom"} for i := 0; i < warmInFlightWindow+40; i++ { rec.Events = append(rec.Events, recEvent{ Kind: int(courtroom.EventMessage), @@ -158,18 +138,9 @@ func TestTickReplayWarmConclusiveMissEndsPromptly(t *testing.T) { // and one tick must clear the phase. func TestTickReplayWarmHardCapBackstop(t *testing.T) { a, _ := newWarmHarness(t) // never mark anything resident/missing: the never-settled shape - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - false - - }) + a.markOriginSeeded(warmTestOrigin) - rec := &sceneRecording{Version: recordingVersion, Origin: "http://example.test/", StartBg: "courtroom"} + rec := &sceneRecording{Version: recordingVersion, Origin: warmTestOrigin, StartBg: "courtroom"} for i := 0; i < warmInFlightWindow+10; i++ { rec.Events = append(rec.Events, recEvent{ Kind: int(courtroom.EventMessage), @@ -195,18 +166,9 @@ func TestTickReplayWarmHardCapBackstop(t *testing.T) { // PrefetchExact a real (missing) submit; we assert the one-shot latch flips. func TestTickReplayWarmPrefetchesMusicOnce(t *testing.T) { a, _ := newWarmHarness(t) - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - false - - }) + a.markOriginSeeded(warmTestOrigin) - a.startReplayWarm(replayWarmRec("http://example.test/")) + a.startReplayWarm(replayWarmRec(warmTestOrigin)) if a.replayWarm == nil || len(a.replayWarm.musicRefs) == 0 { t.Fatal("warm not armed with music refs") } diff --git a/internal/ui/sendonchange_test.go b/internal/ui/sendonchange_test.go index 95c8c5ab..e746b7ee 100644 --- a/internal/ui/sendonchange_test.go +++ b/internal/ui/sendonchange_test.go @@ -34,7 +34,7 @@ func newRoomForTest(t testing.TB) *courtroom.Courtroom { t.Cleanup(decoder.Close) local := assets.NewLocalFetcher([]string{t.TempDir()}) mgr := assets.NewManager(assets.ManagerDeps{ - Resolver: assets.NewResolver(prefs), Prefs: prefs, T2: t2, Disk: disk, + Prefs: prefs, T2: t2, Disk: disk, Source: local, Decoder: decoder, }) t.Cleanup(mgr.CloseMedia) diff --git a/internal/ui/settings.go b/internal/ui/settings.go index 8e9f65a3..0917ef79 100644 --- a/internal/ui/settings.go +++ b/internal/ui/settings.go @@ -155,17 +155,9 @@ type settingsState struct { cacheStatus string cacheStatusBad bool cacheSizeRes chan cacheSizes - // learnedKeys is the learned-formats map size learnedServers was counted for. - learnedKeys, learnedServers int // ioRes carries one-line results of off-thread file ops back to the status line. ioRes chan string - - // fmtOrderText caches each asset type's probe list, parallel to config.TypeNames (assets.AssetType order). - // Rebuilt only when the format generation moves; fmtOrderOK separates never built from generation 0. - fmtOrderText []string - fmtOrderGen uint64 - fmtOrderOK bool } // themeScan is one result: theme names found, the normalized root, and an auto-pick when the path was a single theme. @@ -197,7 +189,7 @@ var settings = settingsState{ } var settingsTabNames = [numSettingsTabs]string{ - "General", "Theme", "Theme editor", "Assets", "Formats", "Audio", "Chat", "Account", "Hotkeys", "Studio", "Data", "Power user", "Updates", "Reset", + "General", "Theme", "Theme editor", "Assets", "Audio", "Chat", "Account", "Hotkeys", "Studio", "Data", "Power user", "Updates", "Reset", } // Tab indices, in settingsTabNames order. @@ -208,8 +200,6 @@ const ( // It sits right after Theme, which keeps selection, because the two read as a pair in the sidebar. tabThemeEditor tabAssets - // tabFormats owns every control that decides which file type is asked for; beside Assets, where people look. - tabFormats tabAudio tabChat tabAccount @@ -298,20 +288,7 @@ var settingsSearchKeywords = [numSettingsTabs][]string{ "learned format", "learned formats", "learned", "clear learned", "retry missing", "placeholder", "missing sprite", "missingno", "missing character", "error sprite", "custom error sprite", "404", }, - tabFormats: { - // How formats work, This server, Automatic detection, Formats per asset type, Fallbacks. - // Absent because a later tab owns the word: "blip", "volume" (Audio); "ignore", "callword" (Chat); - // "password" (Account); "webp", "gif" (Studio); "export", "import" (Studio, Data); - // "extensions.json" (its ".json" would take Data's "json"). - "image format", "file type", "file types", "extension", "extensions", "manifest", - "format profile", "server format profile", "per-server format", "pin format", - "probe", "probing", "one probe", "probe order", "format order", "which format", - "fallback", "fallbacks", "legacy format", "legacy audio", "audio format", "sound format", - "autodetect", "auto-detect", "detect formats", "desk format", - "png", "apng", "avif", "jpg", "jpeg", "opus", "ogg", "mp3", "wav", - "emotes not loading", "assets not loading", "images not loading", "art not loading", - "stuck images", "repeated images", "same image", "nothing loads", - }, + tabAudio: { // Volume, music ducking, custom music streaming. "audio", "volume", "master volume", "music volume", "sfx volume", "blip volume", "blip", @@ -608,8 +585,6 @@ func (a *App) drawSettingsTabBody(tab int, y, w, h int32) int32 { y = a.drawSettingsThemeEditor(y, w) case tabAssets: y = a.drawSettingsAssets(y, w) - case tabFormats: - y = a.drawSettingsFormats(y, w) case tabAudio: y = a.drawSettingsAudio(y, w) case tabChat: @@ -1787,3 +1762,10 @@ func TextureScaleMode(smooth bool) sdl.ScaleMode { } return sdl.ScaleModeNearest } + +// noteSearchRow registers a button with the settings search; Checkbox does this itself. +func (a *App) noteSearchRow(label string, y int32) { + if a.ctx.onRow != nil { + a.ctx.onRow(label, y) + } +} diff --git a/internal/ui/settings_search_test.go b/internal/ui/settings_search_test.go index ee001922..0fe30f38 100644 --- a/internal/ui/settings_search_test.go +++ b/internal/ui/settings_search_test.go @@ -45,25 +45,7 @@ func TestSettingsSearchMatch(t *testing.T) { {"theme", tabTheme}, {"lobby", tabTheme}, {"audio", tabAudio}, - // Formats now owns every "which file type is asked for" term. These used - // to split between Assets and Power user, which is why nobody found them. - {"format", tabFormats}, - {"image format", tabFormats}, - // "extensions" and not "extensions.json": the literal filename is found by - // the gather-search's ROW-LABEL pass (the auto-detect checkbox says it in - // full), and a keyword carrying the ".json" tail would swallow the Data - // tab's "json" — see TestSettingsSearchKeywordsDoNotShadowLaterTabs. - {"extensions", tabFormats}, - {"manifest", tabFormats}, - {"fallback", tabFormats}, - {"autodetect", tabFormats}, - {"probe", tabFormats}, {"learned", tabAssets}, - {"apng", tabFormats}, - {"opus", tabFormats}, - {"format profile", tabFormats}, - {"stuck images", tabFormats}, - {"emotes not loading", tabFormats}, } for _, c := range cases { if got := settingsSearchMatch(c.q); got != c.tab { diff --git a/internal/ui/settingsasync.go b/internal/ui/settingsasync.go index c0ee08eb..34cff6fe 100644 --- a/internal/ui/settingsasync.go +++ b/internal/ui/settingsasync.go @@ -2,7 +2,6 @@ package ui import ( "errors" - "fmt" "os" "path/filepath" "time" @@ -38,38 +37,6 @@ func applyPresetAsync(d Deps, name string) { }() } -// learnedExportFileName sits next to the executable. -const learnedExportFileName = "learned-formats.json" - -func learnedExportPath() (string, error) { - dir, err := exeDataDir() - if err != nil { - return "", err - } - return filepath.Join(dir, learnedExportFileName), nil -} - -// exportLearnedAsync writes the learned table off-thread (hard rule 2). -func exportLearnedAsync(d Deps) { - go func() { - path, err := learnedExportPath() - if err == nil { - var data []byte - if data, err = d.Prefs.ExportLearnedJSON(); err == nil { - err = os.WriteFile(path, data, 0o644) - } - } - line := "Learned formats exported to " + path - if err != nil { - line = "Export failed: " + err.Error() - } - select { - case settings.ioRes <- line: - default: - } - }() -} - // makePortableAsync copies the config set beside the executable, and themes to /themes, off-thread (hard rule // 2). Themes can fail alone (ErrThemesNotMigrated); that is reported as such because the settings did move. func makePortableAsync(d Deps) { @@ -128,29 +95,3 @@ func importSettingsAsync(d Deps, path string) { } }() } - -// importLearnedAsync merges a learned-formats export and republishes the resolver snapshot (atomic swap, safe -// off-thread). -func importLearnedAsync(d Deps) { - go func() { - var line string - path, err := learnedExportPath() - if err == nil { - var data []byte - if data, err = os.ReadFile(path); err == nil { - var n int - if n, err = d.Prefs.ImportLearnedJSON(data); err == nil { - d.Resolver.WarmFromPrefs() - line = fmt.Sprintf("Imported %d learned entries from %s", n, path) - } - } - } - if err != nil { - line = "Import failed: " + err.Error() + " (expected " + learnedExportFileName + " beside the exe)" - } - select { - case settings.ioRes <- line: - default: - } - }() -} diff --git a/internal/ui/settingscache.go b/internal/ui/settingscache.go index 962f602e..19e8e8c1 100644 --- a/internal/ui/settingscache.go +++ b/internal/ui/settingscache.go @@ -8,7 +8,6 @@ import ( "io/fs" "path/filepath" "strconv" - "strings" "time" "github.com/SyntaxNyah/AsyncAO/internal/config" @@ -115,12 +114,11 @@ func (a *App) drawCacheSettings(y int32) int32 { plural(int(a.d.Manager.Stats().Missing), "asset")+" not found this session", a.drawMissingSettings) if a.drawCacheAction(y, "Clear") { - a.d.Prefs.ClearLearned() - a.d.Resolver.InvalidateAll() + a.d.Manager.ForgetLearned() settings.statusLine = "Learned formats cleared." } y = a.drawCacheRow(y, cacheRowLearned, "Learned formats", - "for "+plural(learnedServerCount(a.d.Prefs.Load().LearnedFormats), "server"), a.drawLearnedSettings) + "for "+plural(a.d.Manager.LearnedHosts(), "server"), a.drawLearnedSettings) return a.settingsDesc(a.formX, y+settDetailGap, "Clear the disk cache if a server updated its art and you still see the old version.", ColTextDim) + settSectionGap @@ -209,17 +207,16 @@ func (a *App) drawMissingSettings(y int32) int32 { return a.settingsDesc(a.formX, y, "Applies after a restart.", ColTextDim) } -// drawLearnedSettings is the learned formats' repair, export and import. +// drawLearnedSettings is the learned formats' repair. func (a *App) drawLearnedSettings(y int32) int32 { c := a.ctx - const fixLabel, exportLabel, importLabel = "Fix stuck images", "Export…", "Import…" + const fixLabel = "Fix stuck images" row := cacheButtonRow{a: a, x: a.formX, y: y} r := row.next(fixLabel) // A server repack or stale CDN needs the learned format and the cached file dropped together; either alone // leaves the other stuck. if c.Button(r, fixLabel) { - a.d.Prefs.ClearLearned() - a.d.Resolver.InvalidateAll() + a.d.Manager.ForgetLearned() settings.statusLine = "Cleared learned formats and the disk cache, so images load fresh." if err := a.d.Manager.ClearDisk(); err != nil { settings.statusLine = "Cleared learned formats, but the disk cache couldn't clear: " + err.Error() @@ -228,16 +225,6 @@ func (a *App) drawLearnedSettings(y int32) int32 { } c.Tooltip(r, "Clears learned formats and the disk cache together, for art that is wrong everywhere.") a.noteSearchRow(fixLabel, r.Y) - r = row.next(exportLabel) - if c.Button(r, exportLabel) { - exportLearnedAsync(a.d) - } - c.Tooltip(r, "Writes learned formats beside the program, to carry to another computer.") - r = row.next(importLabel) - if c.Button(r, importLabel) { - importLearnedAsync(a.d) - } - c.Tooltip(r, "Merges in an exported file, so its servers load right from the first visit.") return row.y + mountCtlH } @@ -317,21 +304,6 @@ func folderSize(root string) (bytes int64, files int) { return bytes, files } -// learnedServerCount counts the servers with learned formats; keys are host, separator, asset type. The count is kept -// for the map's size, so a frame that changed nothing builds no set. -func learnedServerCount(learned map[string][]string) int { - if len(learned) == settings.learnedKeys && settings.learnedKeys > 0 { - return settings.learnedServers - } - hosts := make(map[string]struct{}, len(learned)) - for key := range learned { - host, _, _ := strings.Cut(key, config.LearnedKeySeparator) - hosts[host] = struct{}{} - } - settings.learnedKeys, settings.learnedServers = len(learned), len(hosts) - return len(hosts) -} - // formatBytes shows a byte count in the largest unit that keeps it above one. func formatBytes(n int64) string { switch { diff --git a/internal/ui/settingscache_test.go b/internal/ui/settingscache_test.go index 34b8ca31..fbd54aef 100644 --- a/internal/ui/settingscache_test.go +++ b/internal/ui/settingscache_test.go @@ -6,22 +6,6 @@ import ( "testing" ) -func TestLearnedServerCountCountsHostsNotTypes(t *testing.T) { - t.Cleanup(func() { settings.learnedKeys, settings.learnedServers = 0, 0 }) - const wantServers = 2 - learned := map[string][]string{ - "one.test|charsprite": {".webp"}, - "one.test|background": {".png"}, - "two.test|charsprite": {".gif"}, - } - if got := learnedServerCount(learned); got != wantServers { - t.Errorf("learnedServerCount = %d, want %d", got, wantServers) - } - if got := learnedServerCount(map[string][]string{}); got != 0 { - t.Errorf("an empty table counted %d servers", got) - } -} - func TestFormatBytesPicksTheLargestUnit(t *testing.T) { const half, oneAndHalf = 512, 3 << 29 for _, tc := range []struct { diff --git a/internal/ui/settingsformats.go b/internal/ui/settingsformats.go deleted file mode 100644 index 0bc7d888..00000000 --- a/internal/ui/settingsformats.go +++ /dev/null @@ -1,499 +0,0 @@ -package ui - -import ( - "fmt" - "strings" - - "github.com/SyntaxNyah/AsyncAO/internal/assets" - "github.com/SyntaxNyah/AsyncAO/internal/config" - "github.com/SyntaxNyah/AsyncAO/internal/sdl" -) - -// Settings > Formats: every control that decides which file type is requested from a server. - -// imageTypeNames are the asset classes with a user-tunable image format, in tab order. -var imageTypeNames = []string{ - config.TypeCharIcon, - config.TypeCharSprite, - config.TypeBackground, - config.TypeDeskOverlay, - config.TypeShoutBubble, - config.TypeEmoteButton, - config.TypeMisc, -} - -// audioTypeNames are the asset classes with a user-tunable legacy-audio fallback chain. -var audioTypeNames = []string{config.TypeSFX, config.TypeMusic, config.TypeBlip} - -const ( - // learnedCol* are x offsets from the form origin for the learned table's columns. - learnedColName = 8 - learnedColLearned = 150 - learnedColOrder = 250 - // learnedRowH is one learned-table row's height. - learnedRowH = 20 - // learnedExtGapPx separates extensions when a class has learned more than one. - learnedExtGapPx = 6 - // formatPresetGap separates the per-server "pin one format" preset buttons. - formatPresetGap = 6 -) - -// Row labels are built once at init so the per-frame draw does not allocate. -var ( - // formatPresetLabels / formatPresetTips are display names and hover text, parallel to config.OptionalImageFormats. - formatPresetLabels, formatPresetTips = buildFormatPresets() - // typeRowLabels maps an asset-type name to its ":" row label. - typeRowLabels = buildTypeRowLabels() - // audioFallbackLabels are the legacy-audio checkbox labels, parallel to audioTypeNames. - audioFallbackLabels = buildAudioFallbackLabels() -) - -func buildFormatPresets() (labels, tips []string) { - labels = make([]string, len(config.OptionalImageFormats)) - tips = make([]string, len(config.OptionalImageFormats)) - for i, ext := range config.OptionalImageFormats { - name := strings.ToUpper(strings.TrimPrefix(ext, ".")) - if name == "WEBP" { // the only one whose conventional spelling isn't all-caps - name = "WebP" - } - labels[i] = name - tips[i] = "Ask this server for " + name + " art (character icons, sprites, emote buttons, backgrounds). Applies instantly, and only here." - } - return labels, tips -} - -func buildTypeRowLabels() map[string]string { - out := make(map[string]string, len(config.TypeNames)) - for _, name := range config.TypeNames { - out[name] = name + ":" - } - return out -} - -func buildAudioFallbackLabels() []string { - out := make([]string, len(audioTypeNames)) - for i, name := range audioTypeNames { - out[i] = name + ": also try .ogg / .wav / .mp3 after .opus" - } - return out -} - -// pinnedProfileJSON builds an extensions.json declaring one extension for every manifest class. -// It is a manifest rather than a preference because per-server profiles already persist and re-apply on reconnect. -func pinnedProfileJSON(ext string) string { - return `{"charicon_extensions":["` + ext + `"],` + - `"emote_extensions":["` + ext + `"],` + - `"emotions_extensions":["` + ext + `"],` + - `"background_extensions":["` + ext + `"]}` -} - -// noteSearchRow registers a button with the settings search; Checkbox does this itself. -func (a *App) noteSearchRow(label string, y int32) { - if a.ctx.onRow != nil { - a.ctx.onRow(label, y) - } -} - -// formatsTabPointer draws the jump button to the Formats tab. Returns the next y. -func (a *App) formatsTabPointer(y int32) int32 { - c := a.ctx - pad := a.formX - const label = "Open the Formats tab" - a.noteSearchRow(label, y) - if c.Button(sdl.Rect{X: pad, Y: y, W: 220, H: btnH}, label) { - // Takes effect next frame: drawSettings already took the old tab's scroll pointer. - settings.tab = tabFormats - } - return y + btnH + 8 -} - -// formatOrderText returns each asset type's effective probe list, indexed by assets.AssetType. -// Cached against the format generation so a steady frame allocates nothing. -func formatOrderText(p *config.AssetPreferences) []string { - gen := p.FormatGeneration() - if settings.fmtOrderOK && settings.fmtOrderGen == gen { - return settings.fmtOrderText - } - settings.fmtOrderText = settings.fmtOrderText[:0] - for _, name := range config.TypeNames { - settings.fmtOrderText = append(settings.fmtOrderText, strings.Join(p.Load().FormatList(name), " ")) - } - settings.fmtOrderGen, settings.fmtOrderOK = gen, true - return settings.fmtOrderText -} - -// drawSettingsFormats renders the Formats tab. -func (a *App) drawSettingsFormats(y, _ int32) int32 { - pad := a.formX - w := a.formW2() - - y = a.drawFormatsExplainer(y, w) - y = a.drawFormatsThisServer(y, w) - y = a.drawFormatsAutoDetect(y, w) - y = a.drawFormatsPerType(y, w) - y = a.drawFormatsFallbacks(y, w) - - // Casing is the other cause of a server fetching nothing; its control lives on the Power user tab. - y = a.settingsDesc(pad, y, "Still nothing loading for a server, in any format? The other cause is the character-folder capitalisation in asset URLs — that control is on the Power user tab under \"Character folder casing\".", ColTextDim) - y += 10 - return y -} - -// drawFormatsExplainer explains the one-probe-per-asset model. -func (a *App) drawFormatsExplainer(y, w int32) int32 { - pad := a.formX - y = a.settingsSection(y, w, "How formats work") - y = a.settingsDesc(pad, y, "AO servers don't all ship art in the same file type: one serves .webp sprites, the next .png, an older one .gif or .apng. AsyncAO asks for exactly ONE of them per image — one request, no guessing — because that single request per asset is what makes a room load fast instead of trickling in.", ColTextDim) - y += 6 - y = a.settingsDesc(pad, y, "Most of the time you never think about it. A server that publishes a format list (extensions.json) is read automatically on connect and every request is right first time; and once any asset does load, the format it used is remembered for that server.", ColTextDim) - y += 6 - y = a.settingsDesc(pad, y, "A server that publishes NO list is the case that can bite: AsyncAO asks for its preferred type, and if that server doesn't have it, the image is simply missing — emote buttons and sprites are the usual casualties. That is not a bug to wait out, it's one switch. Set the format for that server below and it's fixed for that server, permanently, without slowing down every other server you play on.", ColTextDim) - y += 6 - y = a.settingsDesc(pad, y, "The trade, stated honestly: one request per asset is the fastest possible cold load but it has no second chance, so a wrong guess shows nothing. Letting AsyncAO try more types (\"fallbacks\", further down) always finds the art but spends an extra request per miss on every asset it applies to — which is why it is off by default and why the per-server fix above it is the better trade.", ColTextDim) - y += 12 - return y -} - -// drawFormatsThisServer draws what decides the current server's formats and the per-server buttons. -func (a *App) drawFormatsThisServer(y, w int32) int32 { - c := a.ctx - pad := a.formX - y = a.settingsSection(y, w, "This server") - - host := hostOfURL(a.urls.Origin()) - if host == "" { - y = a.settingsDesc(pad, y, "Not connected to a server yet. Join one and this section shows what it serves, what AsyncAO learned there, and the one-click fixes for it.", ColTextDim) - y += 10 - return y - } - - c.Label(pad, y, "Asset server:", ColTextDim) - c.LabelClipped(pad+learnedColLearned, y, a.formW-learnedColLearned, host, ColText) - y += 22 - - // Most specific source first: pinned profile, built-in vanilla list, server list, then defaults. - // "Not checked yet" stays apart from "no list" so players aren't sent to a fix they don't need. - hasCustom := a.d.Prefs.Load().ExtProfile(host) != "" - st, known := a.manifestStatus[host] - source, col := "", ColTextDim - switch { - case hasCustom: - source, col = "You have pinned this server's formats. That wins over everything else, on this server only.", ColAccent - case a.extProfileFor(host) != "": - source, col = "Using the built-in official-vanilla format list for this server (it serves classic PNG art).", ColAccent - case !a.d.Prefs.Load().AutoDetectFormats: - source = "Automatic detection is off, so this server's own format list is not being read — the per-type formats below decide everything." - case known && st == seedApplied: - source, col = "This server publishes a format list and AsyncAO read it — nothing here needs touching.", ColAccent - case known && st == seedAbsent: - source = "This server publishes NO format list, so AsyncAO uses the per-type formats below. If art is missing here, pin the type this server actually serves." - case known && st == seedFailed: - source, col = "This server's format list could not be read — formats are being learned per request instead.", ColDanger - default: - source = "AsyncAO hasn't read a format list for this server yet; formats are being learned as art loads." - } - y = a.settingsDesc(pad, y, source, col) - y += 8 - - y = a.drawLearnedTable(y, host) - - y = a.settingsDesc(pad, y, "Art missing on this server? Tell AsyncAO which file type it serves. This applies instantly, to THIS server only, and sticks across reconnects — every other server keeps its own settings and its speed.", ColText) - y += 4 - const pinLabel = "Pin this server's image format" - a.noteSearchRow(pinLabel, y) - c.Label(pad, y+4, pinLabel+":", ColText) - y += 24 - bx, by := pad, y - for i, ext := range config.OptionalImageFormats { - label := formatPresetLabels[i] - bw := c.TextWidth(label) + labelBtnPadX*2 - if bx > pad && bx+bw > pad+a.formW { - bx, by = pad, by+btnH+formatPresetGap - } - r := sdl.Rect{X: bx, Y: by, W: bw, H: btnH} - if c.Button(r, label) { - a.applyServerFormatPin(host, ext, label) - } - c.Tooltip(r, formatPresetTips[i]) - bx += bw + formatPresetGap - } - y = by + btnH + 8 - - const vanillaLabel = "Use the official-vanilla format list" - a.noteSearchRow(vanillaLabel, y) - if c.Button(sdl.Rect{X: pad, Y: y, W: 300, H: btnH}, vanillaLabel) { - a.d.Prefs.SetExtProfile(host, assets.BundledVanillaManifestJSON) - a.manifestFor = "" // allow a re-seed of the connected origin - a.fetchManifestAsync() // apply instantly - settings.statusLine = "Applied the official-vanilla format list to " + host + "." - } - if hasCustom { - if c.Button(sdl.Rect{X: pad + 310, Y: y, W: 200, H: btnH}, "Unpin (back to automatic)") { - a.d.Prefs.SetExtProfile(host, "") - a.manifestFor = "" - a.fetchManifestAsync() - settings.statusLine = "Unpinned " + host + " — back to this server's own format list." - } - } - y += btnH + 6 - - const reprobeLabel = "Forget what AsyncAO learned here" - a.noteSearchRow(reprobeLabel, y) - if c.Button(sdl.Rect{X: pad, Y: y, W: 300, H: btnH}, reprobeLabel) { - n := a.d.Prefs.ClearLearnedHost(host) - // The resolver has no per-host wipe; InvalidateAll would drop every other server's state. - for t := assets.AssetType(0); t < assets.AssetTypeCount; t++ { - a.d.Resolver.Invalidate(host, t) - } - a.manifestFor = "" - a.fetchManifestAsync() - settings.statusLine = fmt.Sprintf("Forgot %d remembered format(s) for %s — they re-derive on the next request.", n, host) - } - y += btnH + 4 - y = a.settingsDesc(pad, y, "Use this if the server repacked its art: it drops only THIS server's remembered formats (every other server keeps its warm state) and re-reads its format list.", ColTextDim) - y += 12 - return y -} - -// applyServerFormatPin pins one image extension for host via the per-server -// profile and re-seeds immediately, so the change is live on the next request. -func (a *App) applyServerFormatPin(host, ext, label string) { - a.d.Prefs.SetExtProfile(host, pinnedProfileJSON(ext)) - // A pin overrides what was learned; clear it so a stale type can't answer first. - a.d.Prefs.ClearLearnedHost(host) - for t := assets.AssetType(0); t < assets.AssetTypeCount; t++ { - a.d.Resolver.Invalidate(host, t) - } - a.manifestFor = "" // allow a re-seed of the connected origin - a.fetchManifestAsync() // seeds from the pinned profile, no network round-trip - settings.statusLine = "Pinned " + label + " for " + host + " — art re-requests in that format." -} - -// drawLearnedTable shows what host has taught AsyncAO per asset class beside the default probe order. -// Allocation-free: LearnedList returns interned strings, drawn as separate labels. -func (a *App) drawLearnedTable(y int32, host string) int32 { - c := a.ctx - pad := a.formX - c.Label(pad+learnedColName, y, "asset", ColTextDim) - c.Label(pad+learnedColLearned, y, "learned here", ColTextDim) - c.Label(pad+learnedColOrder, y, "otherwise asks for", ColTextDim) - y += learnedRowH - orders := formatOrderText(a.d.Prefs) - for t := assets.AssetType(0); t < assets.AssetTypeCount; t++ { - c.Label(pad+learnedColName, y, t.Name(), ColTextDim) - if exts := a.d.Resolver.LearnedList(host, t); len(exts) > 0 { - x := pad + learnedColLearned - for i, ext := range exts { - col := ColAccent // the preferred format — the one actually probed - if i > 0 { - col = ColTextDim // the recovery ladder behind it - } - x += c.Label(x, y, ext, col) + learnedExtGapPx - } - } else { - c.Label(pad+learnedColLearned, y, "—", ColTextDim) - } - if int(t) < len(orders) { - c.LabelClipped(pad+learnedColOrder, y, a.formW-learnedColOrder, orders[t], ColTextDim) - } - y += learnedRowH - } - y += 4 - y = a.settingsDesc(pad, y, "\"Learned here\" is the file type this server actually served for that kind of asset; \"—\" means nothing of that kind has loaded yet. A server can serve more than one — the highlighted type is the one asked for first, the dimmed ones are tried if it isn't there, so a server that mixes (some characters PNG, some WebP) works either way. A dash that never fills in — on emote buttons, say — is the sign that the type being asked for isn't the one the server has.", ColTextDim) - y += 10 - return y -} - -// drawFormatsAutoDetect draws the extensions.json toggle and the desk opt-out. -func (a *App) drawFormatsAutoDetect(y, w int32) int32 { - c := a.ctx - pad := a.formX - y = a.settingsSection(y, w, "Automatic detection") - auto := a.d.Prefs.Load().AutoDetectFormats - if next := c.Checkbox(pad, y, "Read the server's format list (extensions.json) when connecting (recommended, on by default)", auto); next != auto { - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - AutoDetectFormats = - - next - - }) - - if next { - a.manifestFor = "" // re-check the current server right away - a.fetchManifestAsync() - } - } - y += 24 - y = a.settingsDesc(pad, y, "On: AsyncAO reads the list the server publishes and asks for exactly what it ships, so the single request per asset is right first time. Off: the server's list is ignored and the per-type formats below decide everything — turn it off only if you are forcing formats by hand.", ColTextDim) - y += 8 - - deskWebP := !a.d.Prefs.Load().DeskFollowManifest - if next := c.Checkbox(pad, y, "Always use WebP for desks, even when the server's list says otherwise", deskWebP); next != deskWebP { - a.d.Prefs.Update(func( - sn *config. - Settings) { - - sn. - DeskFollowManifest = - - !next - - }) - - a.d.Prefs.ClearLearnedType(config.TypeDeskOverlay) // re-derive on next probe - a.d.Resolver.InvalidateAll() - a.d.Resolver.WarmFromPrefs() - if !next { // now following the list: re-seed from the current server - a.manifestFor = "" - a.fetchManifestAsync() - } - } - y += 24 - y = a.settingsDesc(pad, y, "Off (the default): desks follow the server's list like every other class. On: desks stay pinned to WebP — desks share a manifest class with backgrounds, so this covers servers whose list is right for backgrounds but wrong for desks.", ColTextDim) - y += 12 - return y -} - -// drawFormatsPerType draws the image probe order per asset class and the legacy audio chains. -func (a *App) drawFormatsPerType(y, w int32) int32 { - c := a.ctx - pad := a.formX - y = a.settingsSection(y, w, "Formats per asset type") - auto := a.d.Prefs.Load().AutoDetectFormats - if auto { - y = a.settingsDesc(pad, y, "These are your fallback settings for servers that publish no format list — while automatic detection is on, a server that publishes one overrides them. Defaults: character icons PNG, chatbox skins PNG then WebP, everything else WebP.", ColTextDim) - y += 4 - orders := formatOrderText(a.d.Prefs) - for _, typeName := range imageTypeNames { - if typeName == config.TypeMisc { - // Misc (chatbox skins) is never in extensions.json and mixes formats per pack, so it stays editable. - y = a.drawTypeFormatRow(typeName, y) - continue - } - c.Label(pad, y+2, typeRowLabels[typeName], ColTextDim) - if t, ok := assets.TypeFromName(typeName); ok && int(t) < len(orders) { - c.LabelClipped(pad+110, y+2, a.formW-110, orders[t], ColTextDim) - } - y += 26 - } - y += 4 - y = a.settingsDesc(pad, y, "Chatbox skins (Misc) stay editable above because no server declares them — real servers mix .png and .webp there pack by pack. To edit the rest by hand, turn off automatic detection.", ColTextDim) - y += 10 - } else { - y = a.settingsDesc(pad, y, "Automatic detection is OFF, so these decide every request. Tick only the types your servers actually serve — each extra one is an extra request per asset that misses. With two or more ticked, click a chip in the \"order:\" row to move it earlier.", ColTextDim) - y += 4 - for _, typeName := range imageTypeNames { - y = a.drawTypeFormatRow(typeName, y) - } - y += 10 - } - - y = a.settingsDesc(pad, y, "Sound follows the same rule: AsyncAO asks for .opus first because it is what modern packs ship. Tick a class here to also try the older types when .opus isn't there.", ColTextDim) - y += 4 - for i, typeName := range audioTypeNames { - enabled := a.d.Prefs.Load().TypeFallbacksEnabled(typeName) - if next := c.Checkbox(pad, y, audioFallbackLabels[i], enabled); next != enabled { - a.d.Prefs.SetTypeFallbacks(typeName, next) - a.d.Resolver.InvalidateAll() - a.d.Resolver.WarmFromPrefs() - } - y += 24 - } - y += 12 - return y -} - -// drawTypeFormatRow draws the per-type format checkboxes; the order is the type's default, then extras. -func (a *App) drawTypeFormatRow(typeName string, y int32) int32 { - c := a.ctx - pad := a.formX - c.Label(pad, y+2, typeRowLabels[typeName], ColText) - x := pad + 110 - - current := a.d.Prefs.Load().FormatOrder(typeName) - enabled := map[string]bool{} - for _, ext := range current { - enabled[ext] = true - } - - changed := false - for _, ext := range config.OptionalImageFormats { - on := enabled[ext] - next := c.Checkbox(x, y, ext, on) - if next != on { - enabled[ext] = next - changed = true - } - x += c.TextWidth(ext) + 46 - } - if changed { - def := config.DefaultFormatOrder(typeName) - order := make([]string, 0, len(config.OptionalImageFormats)) - for _, ext := range def { - if enabled[ext] { - order = append(order, ext) - } - } - for _, ext := range config.OptionalImageFormats { - if enabled[ext] && !containsExt(order, ext) { - order = append(order, ext) - } - } - if len(order) == 0 { - order = def // never allow zero probes - } - a.d.Prefs.SetFormatOrder(typeName, order) - a.d.Resolver.InvalidateAll() - a.d.Resolver.WarmFromPrefs() - } - - // Probe-order chips: with 2+ formats ticked, a click moves that chip one place earlier. - if len(current) > 1 && !changed { - c.Label(x+12, y+2, "order:", ColTextDim) - cx := x + 12 + c.TextWidth("order:") + 8 - for i, ext := range current { - bw := c.TextWidth(ext) + 14 - if c.Button(sdl.Rect{X: cx, Y: y, W: bw, H: 22}, ext) && i > 0 { - order := append([]string(nil), current...) - order[i-1], order[i] = order[i], order[i-1] - a.d.Prefs.SetFormatOrder(typeName, order) - a.d.Resolver.InvalidateAll() - a.d.Resolver.WarmFromPrefs() - } - cx += bw + 6 - } - } - return y + 26 -} - -func containsExt(list []string, ext string) bool { - for _, e := range list { - if e == ext { - return true - } - } - return false -} - -// drawFormatsFallbacks draws the global fallback toggle, the only control here that affects every server. -func (a *App) drawFormatsFallbacks(y, w int32) int32 { - c := a.ctx - pad := a.formX - y = a.settingsSection(y, w, "Fallbacks (last resort)") - global := a.d.Prefs.Load().GlobalFallbacksEnabled - if next := c.Checkbox(pad, y, "If the preferred type isn't there, try the older ones too (off by default, affects EVERY server)", global); next != global { - a.d.Prefs.SetGlobalFallbacks(next) - a.d.Resolver.InvalidateAll() - a.d.Resolver.WarmFromPrefs() - } - y += 24 - y = a.settingsDesc(pad, y, "On: a miss is retried down the chain (WebP → APNG → GIF → PNG), so art is found almost whatever a server ships — at the cost of extra requests for every asset that misses, on every server, which is felt most on a cold room load. Off (default): one request per asset, and a miss stays missing.", ColTextDim) - y += 6 - y = a.settingsDesc(pad, y, "Reach for this only when a server's art is inconsistent asset by asset. If it's one server that simply uses a different type, pin that server's format under \"This server\" above — same result, none of the cost.", ColTextDim) - y += 12 - return y -} diff --git a/internal/ui/settingsformats_test.go b/internal/ui/settingsformats_test.go deleted file mode 100644 index 9f003a24..00000000 --- a/internal/ui/settingsformats_test.go +++ /dev/null @@ -1,155 +0,0 @@ -package ui - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/SyntaxNyah/AsyncAO/internal/assets" - "github.com/SyntaxNyah/AsyncAO/internal/config" -) - -func newFormatsTestPrefs(t *testing.T) *config.AssetPreferences { - t.Helper() - p, err := config.New(filepath.Join(t.TempDir(), config.PrefsFileName)) - if err != nil { - t.Fatalf("config.New: %v", err) - } - t.Cleanup(func() { - if err := p.Close(); err != nil { - t.Errorf("Close: %v", err) - } - }) - return p -} - -// TestPinnedProfileSeedsEveryImageClass is the contract behind the Formats -// tab's per-server one-click fix: clicking "PNG" must actually make every kind -// of streamed image ask this server for PNG. The button writes an -// extensions.json document, so the guarantee is only real if that document -// parses AND covers every manifest class — a typo'd key would parse fine and -// silently fix nothing, which is exactly the failure the tab exists to end. -func TestPinnedProfileSeedsEveryImageClass(t *testing.T) { - const host = "example.com" - for _, ext := range config.OptionalImageFormats { - m, err := assets.ParseManifest([]byte(pinnedProfileJSON(ext))) - if err != nil { - t.Fatalf("pinnedProfileJSON(%s) does not parse: %v", ext, err) - } - p := newFormatsTestPrefs(t) - if n := m.SeedLearned(p, host); n == 0 { - t.Fatalf("pinnedProfileJSON(%s) seeded nothing", ext) - } - // Every class a player would notice missing. DeskOverlay is included - // since the 2026-08-08 default flip: desks follow the manifest by default - // like every other class, so a pin covers them too. (A player who ticked - // "Always use WebP for desks" opts desks out of ANY seeding — see - // Manifest.SeedLearned — but that is their explicit choice, not this - // profile's business.) - want := []string{ - config.TypeCharIcon, - config.TypeCharSprite, - config.TypeShoutBubble, - config.TypeEmoteButton, - config.TypeBackground, - config.TypeDeskOverlay, - } - learned := p.Load().LearnedSnapshot() - for _, typeName := range want { - got, ok := learned[config.LearnedKey(host, typeName)] - if !ok { - t.Errorf("pinning %s left %s unpinned — that class would still ask for the wrong type", ext, typeName) - continue - } - if len(got) != 1 || got[0] != ext { - t.Errorf("pinning %s gave %s = %v, want [%s]", ext, typeName, got, ext) - } - } - } -} - -// TestPinnedProfileIsScopedToOneHost pins the "scoped correctly" half of the -// fix: a profile is stored per host, so fixing one server must leave every -// other server exactly as it was. -func TestPinnedProfileIsScopedToOneHost(t *testing.T) { - p := newFormatsTestPrefs(t) - const fixed, other = "needs-png.example.com", "fine.example.com" - p.SetExtProfile(fixed, pinnedProfileJSON(config.ExtPNG)) - if got := p.Load().ExtProfile(fixed); got == "" { - t.Fatal("the pinned host has no profile") - } - if got := p.Load().ExtProfile(other); got != "" { - t.Errorf("an unrelated host picked up a profile: %q", got) - } - p.SetExtProfile(fixed, "") - if got := p.Load().ExtProfile(fixed); got != "" { - t.Errorf("unpinning left %q behind", got) - } -} - -// TestFormatPresetLabelsCoverEveryOfferedFormat guards the two parallel slices -// the tab indexes with one loop variable: a format added to -// config.OptionalImageFormats without a label would draw a blank button, and a -// short slice would panic on the last one. -func TestFormatPresetLabelsCoverEveryOfferedFormat(t *testing.T) { - if len(formatPresetLabels) != len(config.OptionalImageFormats) { - t.Fatalf("labels = %d, offered formats = %d", len(formatPresetLabels), len(config.OptionalImageFormats)) - } - if len(formatPresetTips) != len(config.OptionalImageFormats) { - t.Fatalf("tips = %d, offered formats = %d", len(formatPresetTips), len(config.OptionalImageFormats)) - } - for i, ext := range config.OptionalImageFormats { - if formatPresetLabels[i] == "" { - t.Errorf("%s has no button label", ext) - } - if !strings.Contains(formatPresetTips[i], formatPresetLabels[i]) { - t.Errorf("%s tip %q does not name its own format", ext, formatPresetTips[i]) - } - } - for _, name := range config.TypeNames { - if typeRowLabels[name] != name+":" { - t.Errorf("typeRowLabels[%s] = %q, want %q", name, typeRowLabels[name], name+":") - } - } - if len(audioFallbackLabels) != len(audioTypeNames) { - t.Fatalf("audio labels = %d, audio types = %d", len(audioFallbackLabels), len(audioTypeNames)) - } -} - -// TestFormatOrderTextTracksGeneration pins the Formats tab's per-frame budget. -// The settings screen has NO allocation gate, so nothing else would catch this -// cache going stale (wrong text forever) or never caching (string building on -// every frame the tab is open). Both directions are asserted here. -func TestFormatOrderTextTracksGeneration(t *testing.T) { - p := newFormatsTestPrefs(t) - settings.fmtOrderOK, settings.fmtOrderGen, settings.fmtOrderText = false, 0, nil - t.Cleanup(func() { settings.fmtOrderOK, settings.fmtOrderGen, settings.fmtOrderText = false, 0, nil }) - - first := formatOrderText(p) - if len(first) != len(config.TypeNames) { - t.Fatalf("formatOrderText returned %d rows, want %d (one per asset type)", len(first), len(config.TypeNames)) - } - // Indexed by assets.AssetType, so the sprite row must describe sprites. - spriteRow := first[assets.AssetTypeCharSprite] - if !strings.Contains(spriteRow, config.ExtWebP) { - t.Errorf("CharSprite row = %q, want it to mention %s (the shipped default)", spriteRow, config.ExtWebP) - } - gen := settings.fmtOrderGen - - // No preference change: the cache must answer without rebuilding. - if second := formatOrderText(p); settings.fmtOrderGen != gen { - t.Errorf("generation moved from %d to %d without a preference change (rebuilt every call)", gen, settings.fmtOrderGen) - } else if len(second) != len(first) { - t.Fatalf("cached read returned %d rows, want %d", len(second), len(first)) - } - - // A real change must invalidate it, or the tab would show stale formats. - p.SetFormatOrder(config.TypeCharSprite, []string{config.ExtPNG}) - after := formatOrderText(p) - if settings.fmtOrderGen == gen { - t.Error("the format generation did not move after SetFormatOrder — the cache would go stale") - } - if got := after[assets.AssetTypeCharSprite]; !strings.Contains(got, config.ExtPNG) { - t.Errorf("CharSprite row = %q after pinning %s, want it to mention it", got, config.ExtPNG) - } -} diff --git a/internal/ui/settingspower.go b/internal/ui/settingspower.go index b43f0b4c..d649a6a0 100644 --- a/internal/ui/settingspower.go +++ b/internal/ui/settingspower.go @@ -543,13 +543,6 @@ func (a *App) drawSettingsPowerUser(y, _ int32) int32 { y += 10 y = a.drawProxySettings(y, w) - - // Image formats have their own tab, not here: art failing to render is a first-week problem. The pointer stays - // because the casing control above is the other reason a server's art fetches nothing. - y = a.settingsSection(y, w, "Image & audio formats") - y = a.settingsDesc(pad, y, "Which file types AsyncAO asks a server for — and the one-click fix for a server whose art isn't loading — live on their own tab now.", ColTextDim) - y += 6 - y = a.formatsTabPointer(y) return y } diff --git a/internal/ui/settingstabs.go b/internal/ui/settingstabs.go index 2203446e..9c28593b 100644 --- a/internal/ui/settingstabs.go +++ b/internal/ui/settingstabs.go @@ -898,7 +898,7 @@ func (a *App) applyFactoryReset(wipeAll bool) { if wipeAll { a.d.Prefs.ResetAll() _ = a.d.Manager.ClearDisk() - a.d.Resolver.InvalidateAll() + a.d.Manager.ForgetLearned() if a.juke != nil { a.juke.Clear() // the jukebox library lives in its own file — wipe it too } diff --git a/internal/ui/themeeditorpreview_test.go b/internal/ui/themeeditorpreview_test.go index d75dd649..d39602d0 100644 --- a/internal/ui/themeeditorpreview_test.go +++ b/internal/ui/themeeditorpreview_test.go @@ -318,7 +318,6 @@ func TestPreviewRestoresARehearsalSessionsOfflineGate(t *testing.T) { func stageCountingFetcher(t *testing.T, a *App) *countingFetcher { t.Helper() canary := &countingFetcher{} - resolver := assets.NewResolver(a.d.Prefs) t2, err := cache.NewByteBudgetLRU[string, []byte](cache.DefaultMaxEntries, cache.DefaultT2BudgetBytes, nil) if err != nil { t.Fatal(err) @@ -334,12 +333,11 @@ func stageCountingFetcher(t *testing.T, a *App) *countingFetcher { // (no folders), because that is the mode a real install runs in and the mode // whose egress the offline gate stands in front of. a.d.Manager = assets.NewManager(assets.ManagerDeps{ - Resolver: resolver, - Prefs: a.d.Prefs, - T2: t2, - Disk: disk, - Source: canary, - Decoder: decoder, + Prefs: a.d.Prefs, + T2: t2, + Disk: disk, + Source: canary, + Decoder: decoder, }) t.Cleanup(a.d.Manager.CloseMedia) return canary From 9b0fad8ecb9d4481f0b994111e4733e80476b307 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:05:53 +0100 Subject: [PATCH 20/43] docs: remove BENCHMARKS.md Its numbers came from another machine and Go version and had drifted, including rows for benchmarks that no longer exist. The gates it described are enforced by tests; a change is measured by running the benchmarks on the commit before it and after it, side by side. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- README.md | 1 - docs/BENCHMARKS.md | 90 -------------------------------------- docs/RESTRUCTURING_PLAN.md | 4 +- 4 files changed, 3 insertions(+), 94 deletions(-) delete mode 100644 docs/BENCHMARKS.md diff --git a/CLAUDE.md b/CLAUDE.md index 01c0cf54..37011dd3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -117,7 +117,7 @@ Then set `CGO_ENABLED=1`, ```bash go test -race -count=1 ./... # full gate -go test -run=NONE -bench=. -benchmem ./... # alloc gates (see docs/BENCHMARKS.md) +go test -run=NONE -bench=. -benchmem ./... # compare against the previous commit, run side by side gofmt -w . && go vet ./... # before every commit ``` diff --git a/README.md b/README.md index 927ded5c..d1ff3685 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,6 @@ asyncao -debug # pprof on localhost:6060 | [BUILDING.md](BUILDING.md) | Step-by-step build guide (Windows/Linux/macOS) | | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Thread model, cache tiers, pipelines | | [docs/PERFORMANCE.md](docs/PERFORMANCE.md) | Tuning, PGO capture, profiling | -| [docs/BENCHMARKS.md](docs/BENCHMARKS.md) | Recorded numbers for every gate | | [docs/adr/0001-zero-fallback-by-default.md](docs/adr/0001-zero-fallback-by-default.md) | Why zero fallbacks | | [docs/PROTOCOL.md](docs/PROTOCOL.md) | The AO2 wire protocol as implemented | | [docs/DISCORD.md](docs/DISCORD.md) | Discord Rich Presence: setup, privacy, building without it | diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md deleted file mode 100644 index ab9f36a3..00000000 --- a/docs/BENCHMARKS.md +++ /dev/null @@ -1,90 +0,0 @@ -# Benchmarks - -Recorded gates (spec §1/§15). Reference machine: Intel i7-7700K, -Windows 11, Go 1.24.4, MSYS2 UCRT64 gcc 16.1, libwebp 1.6.0. Re-run with: - -```bash -go test -run=NONE -bench=. -benchmem ./... -go test -race -count=1 ./... # the assertion-style gates live in tests -``` - -| Gate (budget) | Measured | Where | -|---|---|---| -| Resolver fast path < 100 ns, ≤ 1 alloc | **76.5 ns/op, 1 alloc (64 B)** | `BenchmarkBuildCandidates_Learned` | -| Resolver MISS path (unlearned) | **72.5 ns/op, 1 alloc** — generation-cached format lists make the cold path as cheap as the learned one | `BenchmarkBuildCandidates_Miss` | -| Resolve 200 assets < 1 ms | **14.6 µs** | `BenchmarkResolveAssets` | -| T1 cache hit, 0 allocs | **41.2 ns/op, 0 allocs** | `BenchmarkCacheHit_T1` | -| T2 cache hit, 0 allocs | **41.2 ns/op, 0 allocs** | `BenchmarkCacheHit_T2` | -| WebP 256×192 decode < 3 ms | **0.179 ms/op** | `BenchmarkDecodeWebP_256x192` | -| Render frame < 16 ms, 0 allocs | **2.34 ms/op (software renderer), 0 allocs** — generation-cached texture pages, zero LRU ops per steady frame | `BenchmarkRenderFrame` + `TestRenderFrameZeroAllocs` | -| UI emote-grid counter, 0 allocs | **0 allocs/op steady state** — the "page x/y · N emotes" label is memoized; the `fmt.Sprintf` runs only when page/total change | `TestEmotePageCounterMemoized` | -| UI HP-bar key, 0 allocs | **0 allocs/op** — `defensebar`/`prosecutionbar` keys are a precomputed table, not a per-frame string concat (ran ≤ 4×/frame) | `TestHPBarStemNoAlloc` | -| UI tab-chip label, 0 allocs | **0 allocs/op** steady state — the "name (N)" strip label is memoized per tab; the strip asks ~3×/tab/frame and now hits the cache until name/state/unread change | `TestTabChipLabelMemoized` | -| UI Tab-chain reorder, 0 allocs | **0 allocs/op** — the AO2 chat chain (showname → IC → OOC → OOC name) is re-seated with a fixed stack scratch + one `copy`, on the Tab press only, never per frame | `TestOrderTabChainNoAlloc` | -| UI server-clock chips, 0 allocs | **0 allocs/op** for a stable/paused clock — labels memoized per displayed second into a reused scratch slice (was a slice + `fmt.Sprintf`/visible-timer every frame); a running clock rebuilds ≤ 1×/sec | `TestTimerChipLabelsMemoized` | -| UI whole-screen courtroom draw, 0 allocs | **0 allocs/op** steady state — a settled headless courtroom scene (real font-loaded Ctx over a software renderer, every stage base resident, room settled) exercises `drawICControls`, the hover toolbox, and the pushClip conversions; guards the whole-screen composite instead of one widget | `TestDrawCourtroomZeroAlloc` | -| UI whole-screen lobby draw, 0 allocs | **0 allocs/op** steady state — the lobby composite (`screens.go` `drawLobby`) held to the same whole-screen gate | `TestDrawLobbyZeroAlloc` | -| UI whole-screen **themed** courtroom draw, 0 allocs | **0 allocs/op** steady state — the theme-driven composite (`theme_layout.go` `drawCourtroomThemed`) had no gate and could not have had one: three rects escaped to the heap through cgo every frame, plus per-frame string building for theme button stems, the list header counter and the extras tooltip. All converted to the `c.cgoRect` idiom / memoized first | `TestDrawCourtroomThemedZeroAlloc` | -| UI themed draw with divergent panel zooms, 0 allocs | **0 allocs/op** steady state — the sibling gate for a user who has zoomed one panel away from another (one scroll reaches it). It caught a real defect: the log, music, area and music-name surfaces shared one font set, so divergent zoom rebuilt it twice per frame and tore down the text atlas — 42 allocs/frame. Each element now draws from its own set | `TestDrawCourtroomThemedDivergentZoomZeroAlloc` | -| Cold probes ≤ 1/asset, ≤ 450 total | **285 probes / 285 assets** (200-char session) | `TestProbeBudget200CharServer` | -| Paired cold ≈ single (±20%) | **parallel: 0.17 s with 150 ms/request latency** (serial would be ≥ 0.30 s) | `TestPairedPrefetchResolvesConcurrently` | -| Steady-state probes (learned warm start) | **N probes for N assets, all first-try** | `TestManagerLearnedWarmStart` | -| 404 never re-probed in TTL | **1 upstream hit for 11 fetches** | `TestNotFoundCachedWithinTTL` | -| Singleflight | **32 concurrent fetches → 1 upstream request** | `TestSingleflightCollapsesConcurrentFetches` | -| Prefs deadlock regression | **mutators complete instantly** | `TestSetFormatOrderCompletes` | -| UI label blit at fractional scale, 0 allocs | **0 allocs/op** steady state, **~2.0-2.4 µs/op** (device-exact) vs **~4.0 µs/op pre-fix** (software renderer) — `blitLabel`'s device-exact bracket (`blitLabelExact`) is *cheaper* than the ambient-scale resample it replaces here, because a scaled `Ren.Copy` costs a per-pixel bilinear resample the extra `SetScale`/`SetClipRect` calls don't approach; identity scale (100%) is unaffected (~1.5-1.8 µs/op either way, noise-level) since `uiDeviceExactAt` excludes it | `BenchmarkLabelAtFractionalScale` / `BenchmarkLabelAtIdentityScale` + `TestLabelAllocFreeAtFractionalScale` | -| Popped-out preview: closed = free, main loop's new per-pass call | **4.6 ns/op, 0 allocs/op** (closed) vs **236.8 ns/op, 0 allocs/op** (open + animating, clock swept across the loop) — `AdvanceDetachedPreview` is the call `cmd/asyncao`'s minimized/`SkipFrame` branches now make on EVERY pass regardless of whether the preview was ever opened | `BenchmarkAdvanceDetachedPreviewClosed` / `BenchmarkAdvanceDetachedPreviewOpenAnimating` + `TestAdvanceDetachedPreviewClosedIsZeroAlloc` (software renderer) | -| Popped-out preview: animation cache hit vs miss | **19.3 ns/op, 0 allocs/op** (cache hit — a looping animation past its first pass) vs **350668 ns/op, 5 allocs/op (311529 B)** (cache miss — a fresh readback+upload) | `BenchmarkPreviewWindowShowAnimFrameCacheHit` / `...CacheMiss` + `TestPreviewWindowShowAnimFrameCachesAfterFirstPass` (software renderer) | -| Courtroom message start, plain | **5.5 µs/op, 107 allocs** | `BenchmarkMessageBeginPlain` | -| Courtroom message start, with chat extras | **10.6 µs/op, 140 allocs** | `BenchmarkMessageBeginMarked` | -| Chat extras decode, per message | **3.9 µs/op, 27 allocs** | `BenchmarkDecodeMarkers` | -| Courtroom update, idle / talking, per frame | **5.9 ns/op, 0 allocs / ~0.9 µs/op, 1 alloc** | `BenchmarkUpdateIdle`, `BenchmarkUpdateTalking` | -| char.ini parse, 60 emotes | **424 µs/op, 1,406 allocs** | `BenchmarkParseCharINI` | -| Whole idle frame, headless | **~297 µs/op, 0 allocs** | `BenchmarkFrameIdle` | -| Background pass, idle | **220 ns/op, 0 allocs** | `BenchmarkBackgroundIdle` | -| `Conn.Send`, time the caller waits | **~2.4 µs/op, 2 allocs** (queues the packet; ~48 µs and 8 allocs when the caller wrote to the socket itself) | `BenchmarkConnSend` | -| Wait gate, one tick holding a message under strict sequencing | **~17 ns/op, 0 allocs** (~6 µs and 174 allocs on a tick that rebuilds the list) | `BenchmarkWaitGateHeld` | -| Race detector | **clean across all packages** | CI `go test -race ./...` | - -Notes: - -- `BenchmarkRenderFrame` runs on SDL's *software* renderer (headless CI); - the accelerated path in real use is significantly faster. The 16 ms budget - holds even in the worst case. -- The resolver's single allocation is the joined URL string itself — the - theoretical floor without `unsafe.String` tricks, which the 68 ns reading - says we don't need. -- The viewport's steady-state texture lookups are generation-cached - (`animState.resolve`): zero LRU operations per frame until an upload, - eviction, or purge bumps `TextureStore.Generation` (re-measured above). -- GIF/APNG composition canvases and DisposalPrevious snapshots come from the - pixel pool: animated decodes now allocate only their output frames. -- `BenchmarkLabelAtFractionalScale`'s software-renderer win is a property of - *this* backend (a scaled bilinear resample is expensive to interpret in - software); it is not a claim that the accelerated (D3D/OpenGL) backend sees - the same delta — there the extra `SetScale`/`SetClipRect` cgo calls have to - compete against a cheap GPU-side scale instead of an expensive CPU one. Not - measured on an accelerated renderer; the alloc gate (`TestLabelAllocFreeAtFractionalScale`) - is backend-independent and is the one that must hold everywhere. -- **Character select is the one whole-screen draw with no gate yet.** Its themed - geometry is alloc-free (`charSelectGridPlan`, `cellAt`, `charHoverID` and the - cached heading are all covered), but `drawCharCell` still rebuilds each visible - character's icon URL every frame, and that URL depends on the session's asset - origin — so caching it means a second invalidation source, not a one-liner. - Tracked in `docs/ROADMAP.md`; do not add a gate that only passes by shrinking - the staged roster. -- The two popped-out-preview rows above are measured on the SDL *software* - renderer only (the same backend every headless test gets, per this repo's - standing convention) — not re-verified against an accelerated D3D/GL - renderer. `BenchmarkAdvanceDetachedPreviewClosed`'s near-zero cost is - backend-independent (it never reaches a single SDL call); the animated - numbers could differ on an accelerated backend and are not claimed to - match one. -- Both preview rows are zero-alloc because the display slot is handed the - frame size it already knows instead of asking `sdl.Texture.Query` for it. - That call crosses cgo with four out-parameters, all of which escape: - measured at 4 allocs / 16 B per call, and it ran on every frame tick. - Removing it is what took the cache hit from 216 ns / 4 allocs to - 19 ns / 0 allocs. Same trap as `Ren.GetScale` (CLAUDE.md) — assume any - cgo call with pointer out-params allocates until a benchmark says otherwise. -- Keep this file current: update measurements when touching any gated path. diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index cf41c058..05b0ba82 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -82,8 +82,8 @@ in **Status**. Update Status in the same commit that completes a step. starts from a benchmark and is measured again after it; a cheap rewrite or optimisation found on the way is welcome. Moving work to a goroutine needs a measured cost or a blocking call, and work that applies in message order stays in order. `Scene` and the message state machine stay on the game thread - - [x] baseline benchmarks: `internal/courtroom/bench_test.go`, `internal/ui/framebench_test.go`, recorded in - `docs/BENCHMARKS.md` + - [x] baseline benchmarks: `internal/courtroom/bench_test.go`, `internal/ui/framebench_test.go`; a move is measured + by running them on the commit before it and after it, side by side - [x] one loop mode: the classic loop and its setting are gone (decided 2026-11-01) - [x] writer goroutine for `Conn.Send`, which proves the worker shape (one shape for background jobs, replacing the separate goroutine, channel and poll of each `ui` job). A full queue of 64 or a failed write ends the connection and From 5b6f52ccbd303087676c6f78cf93a46fa642af6d Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:18:40 +0100 Subject: [PATCH 21/43] media: compact, gzip'd learned.json; build and parse it off the media goroutine At the cap (16,384 winners) learned.json was 3.3 MB: every winner wrote its whole key with field names and its host's URL twice. Version 2 groups formats and winners by host, writes each winner as one line with the path relative to its host and the file as just its extension when the key's own name won, and gzips the JSON: about 148 KB at the cap. A binary encoding of the old layout measured only 34% smaller, and of the new one 4% smaller than JSON, so the layout carries the saving. Decompression stops at 64 MB. Version 1 files are ignored. Remember now only copies the two tables (about 0.3 ms on the media goroutine at the cap, from 0.6 ms); Memory.Learned builds the lines and EncodeLearned gzips on the saver's goroutine. Loading mirrors it: DecodeLearned and Learned.Memory parse on a disk worker, and Recall takes the parsed winners whole when the session has none yet. Co-Authored-By: Claude Opus 5.5 --- internal/assets/mediabridge.go | 20 ++- internal/media/candidates.go | 9 +- internal/media/learned.go | 283 ++++++++++++++++++++++++++++----- internal/media/learned_test.go | 98 +++++++++--- 4 files changed, 339 insertions(+), 71 deletions(-) diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index d79eb45f..8946c225 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -2,7 +2,6 @@ package assets import ( "context" - "encoding/json" "errors" "os" "slices" @@ -159,15 +158,14 @@ func (b *mediaBridge) recallLearned() { path := b.m.learnedPath b.media.Run(b.diskP, media.Later, func() any { var l media.Learned - if path == "" { - return l - } - if data, err := os.ReadFile(path); err == nil { - _ = json.Unmarshal(data, &l) // a damaged file is a fresh start + if path != "" { + if data, err := os.ReadFile(path); err == nil { + l, _ = media.DecodeLearned(data) // a damaged file is a fresh start + } } - return l + return l.Memory() }, func(v any) { - media.Recall(b.media, b.builder, v.(media.Learned)) + media.Recall(b.media, b.builder, v.(media.Memory)) b.recalled = true b.learnedHosts.Store(int64(b.builder.LearnedOrigins())) if b.foundEarly { @@ -178,14 +176,14 @@ func (b *mediaBridge) recallLearned() { // encodeLearned snapshots the learned formats and winners on the Manager's goroutine for the saver. func (b *mediaBridge) encodeLearned() ([]byte, error) { - var l media.Learned + var mem media.Memory var err error ran := b.media.Call(func() { if !b.recalled { err = errLearnedNotRecalled return } - l = media.Remember(b.media, b.builder) + mem = media.Remember(b.media, b.builder) }) if !ran { return nil, errMediaStopped @@ -193,7 +191,7 @@ func (b *mediaBridge) encodeLearned() ([]byte, error) { if err != nil { return nil, err } - return json.Marshal(l) + return media.EncodeLearned(mem.Learned()) } // scanDisk fills the disk index; until it lands, a cached file is fetched again, which is only slower. diff --git a/internal/media/candidates.go b/internal/media/candidates.go index f5b80ae3..b775ab7c 100644 --- a/internal/media/candidates.go +++ b/internal/media/candidates.go @@ -4,6 +4,8 @@ import ( "encoding/json" "errors" "fmt" + "iter" + "maps" "slices" "strings" @@ -131,11 +133,16 @@ func defaultOrder(class Class) []string { // originOf is the key's own origin, or for a key holding a whole URL, the longest origin known to contain it, then its host. func (b *CandidateBuilder) originOf(key Key) string { + return originAmong(key, maps.Keys(b.origins)) +} + +// originAmong is originOf over a list of known origins. +func originAmong(key Key, origins iter.Seq[string]) string { if key.Origin != "" { return key.Origin } best := "" - for origin := range b.origins { + for origin := range origins { if len(origin) > len(best) && strings.HasPrefix(key.Path, origin) { best = origin } diff --git a/internal/media/learned.go b/internal/media/learned.go index 1bed84be..bd6010bd 100644 --- a/internal/media/learned.go +++ b/internal/media/learned.go @@ -1,35 +1,86 @@ package media import ( + "bytes" + "compress/gzip" + "encoding/json" + "errors" + "fmt" + "io" "maps" + "math" "slices" + "strconv" + "strings" ) const ( - // LearnedVersion changes whenever Key, Class or Place change meaning; a saved file of another version is ignored. - LearnedVersion = 1 - // learnedOriginsCap bounds the origins kept between sessions; the ones with the fewest finds go first. + // LearnedVersion changes whenever the saved layout or Key, Class or Place change meaning; another version is + // ignored. + LearnedVersion = 2 + // learnedOriginsCap bounds the hosts whose formats are kept between sessions; the ones with the fewest finds go + // first. learnedOriginsCap = 256 + // learnedMaxBytes bounds a decompressed file, so a damaged or hostile one can't fill memory (hard rule 4). + learnedMaxBytes = 64 << 20 ) -// Learned is what searches taught a Manager and its CandidateBuilder, kept between sessions. +// A winner line is its key's numbers, how its path is stored, the path and the file, separated by tabs. +const ( + fieldPlace = iota + fieldKind + fieldClass + fieldSize + fieldTag + fieldHow + fieldPath + fieldFile + winnerFields +) + +const ( + winnerSep = "\t" + // pathUnder: the path is stored after its host's prefix; pathOfOrigin: the key's Origin is the host, path as is; + // pathWhole: stored whole. + pathUnder = "0" + pathOfOrigin = "1" + pathWhole = "2" + // fileAfterPath marks a file that is the key's own name plus a suffix (its extension); fileUnderHost one stored + // after the host's prefix. Anything else is a whole URL. + fileAfterPath = "+" + fileUnderHost = "~" +) + +// Learned is what searches taught a Manager and its CandidateBuilder, as kept between sessions: per host, the +// formats found there and the files keys were last found as. type Learned struct { - Version int `json:"version"` - // Formats counts, per origin and class, how often each format was found. - Formats map[string]map[Class]map[string]int `json:"formats"` - Winners []Winner `json:"winners"` + Version int `json:"v"` + Hosts map[string]*LearnedHost `json:"h"` } -// Winner is the file a key was last found as. -type Winner struct { - Key Key `json:"key"` - File File `json:"file"` +// LearnedHost is one host's part of Learned. +type LearnedHost struct { + // Formats counts how often each format was found, per class. + Formats map[Class]map[string]int `json:"f,omitempty"` + // Winners are one line per key; see winnerLine. + Winners []string `json:"w,omitempty"` +} + +var errLearnedTooLarge = errors.New("media: learned file too large") + +// Memory is a copy of what a Manager and its CandidateBuilder learned; Learned builds the saved form from it on any +// goroutine, so the Manager's is held only for the copy. +type Memory struct { + origins []string + formats map[string]map[Class]map[string]int + winners map[Key]File } // Remember copies what m and b have learned; call it on the Manager's goroutine (Do or Call). -func Remember(m *Manager, b *CandidateBuilder) Learned { - l := Learned{Version: LearnedVersion, Formats: map[string]map[Class]map[string]int{}} +func Remember(m *Manager, b *CandidateBuilder) Memory { + mem := Memory{formats: map[string]map[Class]map[string]int{}, winners: maps.Clone(m.winners)} for origin, h := range b.origins { + mem.origins = append(mem.origins, origin) if len(h.learned) == 0 { continue } @@ -37,24 +88,40 @@ func Remember(m *Manager, b *CandidateBuilder) Learned { for class, counts := range h.learned { classes[class] = maps.Clone(counts) } - l.Formats[origin] = classes - } - if len(l.Formats) > learnedOriginsCap { - origins := slices.SortedFunc(maps.Keys(l.Formats), func(x, y string) int { - return finds(l.Formats[y]) - finds(l.Formats[x]) - }) - for _, origin := range origins[learnedOriginsCap:] { - delete(l.Formats, origin) + mem.formats[origin] = classes + } + return mem +} + +// Learned is the saved form: hosts with the most finds first, up to learnedOriginsCap, and every winner under the +// host it belongs to. +func (mem Memory) Learned() Learned { + l := Learned{Version: LearnedVersion, Hosts: map[string]*LearnedHost{}} + host := func(origin string) *LearnedHost { + h := l.Hosts[origin] + if h == nil { + h = &LearnedHost{} + l.Hosts[origin] = h } + return h } - l.Winners = make([]Winner, 0, len(m.winners)) - for k, f := range m.winners { - l.Winners = append(l.Winners, Winner{Key: k, File: f}) + origins := slices.SortedFunc(maps.Keys(mem.formats), func(x, y string) int { + return finds(mem.formats[y]) - finds(mem.formats[x]) + }) + for _, origin := range origins[:min(len(origins), learnedOriginsCap)] { + host(origin).Formats = mem.formats[origin] + } + for k, f := range mem.winners { + group := originAmong(k, slices.Values(mem.origins)) + if line, ok := winnerLine(group, k, f); ok { + h := host(group) + h.Winners = append(h.Winners, line) + } } return l } -// finds totals one origin's counts. +// finds totals one host's counts. func finds(classes map[Class]map[string]int) int { n := 0 for _, counts := range classes { @@ -65,14 +132,85 @@ func finds(classes map[Class]map[string]int) int { return n } -// Recall adds a saved Learned to what m and b know; call it on the Manager's goroutine. Saved counts are halved, so a -// host that changed its formats is relearned in a few sessions, and what this session already learned stays. -func Recall(m *Manager, b *CandidateBuilder, l Learned) { +// winnerLine writes one winner relative to its host; false for a path or file a line can't hold. +func winnerLine(group string, k Key, f File) (string, bool) { + how, path := pathWhole, k.Path + switch { + case k.Origin != "": + how = pathOfOrigin // originOf made the key's own origin its group + case strings.HasPrefix(k.Path, group): + how, path = pathUnder, strings.TrimPrefix(k.Path, group) + } + file := string(f) + if rest, ok := strings.CutPrefix(file, k.Origin+k.Path); ok { + file = fileAfterPath + rest + } else if rest, ok := strings.CutPrefix(file, group); ok { + file = fileUnderHost + rest + } + if strings.ContainsAny(path, winnerSep+"\n") || strings.ContainsAny(file, winnerSep+"\n") { + return "", false + } + return strings.Join([]string{ + strconv.Itoa(int(k.Place)), strconv.Itoa(int(k.Kind)), strconv.Itoa(int(k.Class)), strconv.Itoa(k.Size), + strconv.Itoa(int(k.Tag)), how, path, file, + }, winnerSep), true +} + +// readWinner rebuilds one winner line; false for a damaged one. +func readWinner(group, line string) (Key, File, bool) { + parts := strings.Split(line, winnerSep) + if len(parts) != winnerFields { + return Key{}, "", false + } + var nums [fieldHow]int + for i := range nums { + n, err := strconv.Atoi(parts[i]) + if err != nil || n < 0 { + return Key{}, "", false + } + nums[i] = n + } + if nums[fieldPlace] > math.MaxUint8 || nums[fieldKind] > math.MaxUint8 || nums[fieldClass] > int(ClassBlips) || + nums[fieldTag] > math.MaxUint8 { + return Key{}, "", false + } + k := Key{Place: Place(nums[fieldPlace]), Kind: Kind(nums[fieldKind]), Class: Class(nums[fieldClass]), + Size: nums[fieldSize], Tag: uint8(nums[fieldTag])} + path, file := parts[fieldPath], parts[fieldFile] + switch parts[fieldHow] { + case pathUnder: + k.Path = group + path + case pathOfOrigin: + k.Origin, k.Path = group, path + case pathWhole: + k.Path = path + default: + return Key{}, "", false + } + if rest, ok := strings.CutPrefix(file, fileAfterPath); ok { + file = k.Origin + k.Path + rest + } else if rest, ok := strings.CutPrefix(file, fileUnderHost); ok { + file = group + rest + } + if k.Path == "" || file == "" { + return Key{}, "", false + } + return k, File(file), true +} + +// Memory reads the saved form back, leaving out what another version, an unknown class or format, or a damaged line +// would get wrong; any goroutine. Saved counts are halved, so a host that changed its formats is relearned in a few +// sessions. +func (l Learned) Memory() Memory { + mem := Memory{formats: map[string]map[Class]map[string]int{}, winners: map[Key]File{}} if l.Version != LearnedVersion { - return + return mem } - for origin, classes := range l.Formats { - for class, counts := range classes { + for origin, h := range l.Hosts { + if h == nil { + continue + } + for class, counts := range h.Formats { if class == ClassExact || class > ClassBlips { continue } @@ -80,24 +218,91 @@ func Recall(m *Manager, b *CandidateBuilder, l Learned) { if c <= 0 || !knownExt(ext) { continue } - h := b.hints(origin) - if h.learned[class] == nil { - h.learned[class] = map[string]int{} + if mem.formats[origin] == nil { + mem.formats[origin] = map[Class]map[string]int{} } - h.learned[class][ext] += (c + 1) / 2 + if mem.formats[origin][class] == nil { + mem.formats[origin][class] = map[string]int{} + } + mem.formats[origin][class][ext] = (c + 1) / 2 + } + } + for _, line := range h.Winners { + if len(mem.winners) >= winnersCap { + break + } + if k, f, ok := readWinner(origin, line); ok { + mem.winners[k] = f } } } - for _, w := range l.Winners { + return mem +} + +// Recall adds mem to what m and b know, keeping what this session already learned; call it on the Manager's +// goroutine. m may keep mem's maps, so mem is not used again. +func Recall(m *Manager, b *CandidateBuilder, mem Memory) { + for origin, classes := range mem.formats { + hints := b.hints(origin) + for class, counts := range classes { + if hints.learned[class] == nil { + hints.learned[class] = map[string]int{} + } + for ext, c := range counts { + hints.learned[class][ext] += c + } + } + } + if len(m.winners) == 0 && mem.winners != nil { + m.winners = mem.winners // the usual case at start; Memory caps it at winnersCap + return + } + for k, f := range mem.winners { if len(m.winners) >= winnersCap { break } - if _, ok := m.winners[w.Key]; !ok && w.Key.Path != "" && w.File != "" { - m.winners[w.Key] = w.File + if _, known := m.winners[k]; !known { + m.winners[k] = f } } } +// EncodeLearned is the saved form of l: JSON, gzip'd. +func EncodeLearned(l Learned) ([]byte, error) { + var buf bytes.Buffer + zw, err := gzip.NewWriterLevel(&buf, gzip.BestSpeed) + if err != nil { + return nil, err + } + if err := json.NewEncoder(zw).Encode(l); err != nil { + return nil, err + } + if err := zw.Close(); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// DecodeLearned reads what EncodeLearned wrote. +func DecodeLearned(data []byte) (Learned, error) { + var l Learned + zr, err := gzip.NewReader(bytes.NewReader(data)) + if err != nil { + return l, fmt.Errorf("media: reading learned file: %w", err) + } + raw, err := io.ReadAll(io.LimitReader(zr, learnedMaxBytes+1)) + if err != nil { + return l, fmt.Errorf("media: reading learned file: %w", err) + } + if len(raw) > learnedMaxBytes { + return l, errLearnedTooLarge + } + if err := json.Unmarshal(raw, &l); err != nil { + return l, fmt.Errorf("media: reading learned file: %w", err) + } + return l, nil +} + // knownExt reports whether ext is a format some decoder reads. func knownExt(ext string) bool { return slices.Contains(defaultImageOrder, ext) || slices.Contains(defaultAudioOrder, ext) diff --git a/internal/media/learned_test.go b/internal/media/learned_test.go index b6795a58..d4407e5b 100644 --- a/internal/media/learned_test.go +++ b/internal/media/learned_test.go @@ -1,34 +1,37 @@ package media import ( - "encoding/json" + "bytes" + "compress/gzip" + "maps" "testing" "github.com/SyntaxNyah/AsyncAO/internal/config" ) -// rememberJSON is what a session would write to learned.json. -func rememberJSON(t *testing.T, r *remoteRig) []byte { +// rememberFile is what a session would write to learned.json. +func rememberFile(t *testing.T, m *Manager, b *CandidateBuilder) []byte { t.Helper() - var l Learned - if !r.m.Call(func() { l = Remember(r.m, r.builder) }) { + var mem Memory + if !m.Call(func() { mem = Remember(m, b) }) { t.Fatal("manager stopped") } - data, err := json.Marshal(l) + data, err := EncodeLearned(mem.Learned()) if err != nil { t.Fatal(err) } return data } -// recallJSON is what the next session does with it. -func recallJSON(t *testing.T, r *remoteRig, data []byte) { +// recallFile is what the next session does with it. +func recallFile(t *testing.T, m *Manager, b *CandidateBuilder, data []byte) { t.Helper() - var l Learned - if err := json.Unmarshal(data, &l); err != nil { + l, err := DecodeLearned(data) + if err != nil { t.Fatal(err) } - r.m.Call(func() { Recall(r.m, r.builder, l) }) + mem := l.Memory() + m.Call(func() { Recall(m, b, mem) }) } func TestNextSessionAsksTheLearnedFormatAndWinnerFirst(t *testing.T) { @@ -38,10 +41,10 @@ func TestNextSessionAsksTheLearnedFormatAndWinnerFirst(t *testing.T) { } first := newRemoteRig(t, files) waitFinal(t, first.m.Get(sprite("a"), Now, 0)) - saved := rememberJSON(t, first) + saved := rememberFile(t, first.m, first.builder) next := newRemoteRig(t, files) - recallJSON(t, next, saved) + recallFile(t, next.m, next.builder, saved) waitFinal(t, next.m.Get(sprite("a"), Now, 0)) waitFinal(t, next.m.Get(sprite("b"), Now, 0)) want := []string{testOrigin + "a" + config.ExtPNG, testOrigin + "b" + config.ExtPNG} @@ -50,14 +53,69 @@ func TestNextSessionAsksTheLearnedFormatAndWinnerFirst(t *testing.T) { } } -func TestRecallIgnoresAnotherVersionAndUnknownFormats(t *testing.T) { +func TestEveryWinnerShapeSurvivesTheFile(t *testing.T) { + const mirror = "https://mirror.test/base/" + under := Key{Place: PlaceServer, Path: testOrigin + "characters/c/(a)e", Kind: KindImage, Class: ClassEmote, Tag: 3} + own := Key{Place: PlaceServer, Origin: testOrigin, Path: "characters/c/(b)e", Kind: KindImage, Class: ClassEmote} + sized := Key{Place: PlaceServer, Path: testOrigin + "characters/c/char_icon", Kind: KindImage, + Class: ClassCharIcon, Size: 64} + tabbed := Key{Place: PlaceServer, Path: testOrigin + "characters/c/a\tb", Kind: KindImage, Class: ClassEmote} + saved := map[Key]File{ + under: File(testOrigin + "characters/c/e.webp"), // the bare spelling won + own: File(testOrigin + "characters/c/(b)e.png"), // the key's own name won + sized: File(mirror + "characters/c/char_icon.png"), // found on an extra host + tabbed: File(testOrigin + "characters/c/a\tb.png"), + } + r := newRemoteRig(t, nil) + r.m.Call(func() { + r.builder.Allow(testOrigin, map[Class][]string{ClassEmote: {config.ExtWebP}}) + maps.Copy(r.m.winners, saved) + }) + data := rememberFile(t, r.m, r.builder) + + next := newRemoteRig(t, nil) + next.m.Call(func() { next.builder.Allow(testOrigin, map[Class][]string{ClassEmote: {config.ExtWebP}}) }) + recallFile(t, next.m, next.builder, data) + var got map[Key]File + next.m.Call(func() { got = maps.Clone(next.m.winners) }) + delete(saved, tabbed) // a line can't hold a tab, so that one is left out + if !maps.Equal(got, saved) { + t.Fatalf("recalled %v\nwant %v", got, saved) + } +} + +func TestRecallIgnoresAnotherVersionAndDamage(t *testing.T) { r := newRemoteRig(t, nil) - recallJSON(t, r, []byte(`{"version":999,"formats":{"`+testOrigin+`":{"2":{".png":50}}}}`)) - recallJSON(t, r, []byte(`{"version":1,"formats":{"`+testOrigin+`":{"2":{".exe":50}}}}`)) - var l Learned - r.m.Call(func() { l = Remember(r.m, r.builder) }) - if len(l.Formats) != 0 { - t.Fatalf("recalled %v", l.Formats) + formats := map[Class]map[string]int{ClassEmote: {config.ExtPNG: 1, ".exe": 1}, ClassExact: {config.ExtPNG: 1}} + r.m.Call(func() { + Recall(r.m, r.builder, Learned{Version: LearnedVersion + 1, Hosts: map[string]*LearnedHost{ + testOrigin: {Formats: formats, Winners: []string{"0\t0\t2\t0\t0\t0\ta\t+.png"}}, + }}.Memory()) + Recall(r.m, r.builder, Learned{Version: LearnedVersion, Hosts: map[string]*LearnedHost{ + testOrigin: {Formats: map[Class]map[string]int{ClassEmote: {".exe": 1}}, + Winners: []string{"short", "0\t0\t99\t0\t0\t0\ta\t+.png", "0\t0\t2\t0\t0\t9\ta\t+.png"}}, + "nil.test": nil, + }}.Memory()) + }) + var mem Memory + r.m.Call(func() { mem = Remember(r.m, r.builder) }) + if l := mem.Learned(); len(l.Hosts) != 0 { + t.Fatalf("recalled %+v", l.Hosts[testOrigin]) + } +} + +func TestDecodeRefusesDamagedAndOversizedFiles(t *testing.T) { + if _, err := DecodeLearned([]byte("{}")); err == nil { + t.Error("a file that isn't gzip decoded") + } + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + if _, err := zw.Write(make([]byte, learnedMaxBytes+1)); err != nil { + t.Fatal(err) + } + _ = zw.Close() + if _, err := DecodeLearned(buf.Bytes()); err == nil { + t.Error("a file past the size cap decoded") } } From e9e72e1cc89726aabf7ca548f964c64105a6268a Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:31:43 +0100 Subject: [PATCH 22/43] courtroom, ui: OOC names coloured by sender; no hanging indent in OOC (#68, #53) #68: CT's third field marks a line the server itself sent ("1"); AO2 colours that sender's name with server_chatlog_sender_color and a player's with ms_chatlog_sender_color (courtroom.cpp:1921). EventOOC now carries the flag from aolib's IsFromServer or the legacy wire, each OOC entry keeps it beside its speaker, and a server line's name draws in the theme's server colour on its canvas, else the accent. A player's name takes the theme's player colour when per-speaker colours are off. Unknown values count as a player rather than AO2's black. Both theme colours go through the same contrast guard as other theme inks, measured against the OOC log's backdrop. A logNameInk value replaces the nameOn/sat/val arguments at every log row. #53: OOC rows no longer hang under their first row. AO2's server log is plain text laid out as the server wrote it; the indent suited the IC log only. The OOC wrap uses the full width and oocWrapCont is gone. Co-Authored-By: Claude Opus 5.5 --- internal/courtroom/ctfromserver_test.go | 28 ++++++++++ internal/courtroom/session.go | 13 +++-- internal/ui/app.go | 1 - internal/ui/app_connect.go | 18 +++---- internal/ui/app_ic.go | 5 +- internal/ui/apptypes.go | 1 + internal/ui/court_extras.go | 2 +- internal/ui/logbottomrow_test.go | 2 +- internal/ui/logselect_wire.go | 43 ++++++++++++--- internal/ui/logwrap_test.go | 37 +++++-------- internal/ui/ooclinks_test.go | 10 ++-- internal/ui/oocsender_test.go | 54 +++++++++++++++++++ internal/ui/qol.go | 21 +++----- internal/ui/rosterpoll_test.go | 4 +- internal/ui/screensemote.go | 2 +- internal/ui/screensooc.go | 69 +++++++++++++------------ internal/ui/sessioncarry.go | 35 +++++++------ internal/ui/tabs.go | 3 ++ internal/ui/themefonts.go | 19 +++++++ internal/ui/themeink.go | 11 ++++ internal/ui/translogooc_test.go | 8 +-- internal/ui/ui_test.go | 4 +- internal/ui/wholescreenalloc_test.go | 4 +- 23 files changed, 267 insertions(+), 127 deletions(-) create mode 100644 internal/courtroom/ctfromserver_test.go create mode 100644 internal/ui/oocsender_test.go diff --git a/internal/courtroom/ctfromserver_test.go b/internal/courtroom/ctfromserver_test.go new file mode 100644 index 00000000..b87b82f2 --- /dev/null +++ b/internal/courtroom/ctfromserver_test.go @@ -0,0 +1,28 @@ +package courtroom + +import ( + "testing" + + aolib "github.com/AO-Underground/aolib/go/v2" + + "github.com/SyntaxNyah/AsyncAO/internal/protocol" +) + +// Issue #68: CT's third field says whether the server itself sent the line; only "1" means it did. +func TestOOCLineCarriesWhetherTheServerSentIt(t *testing.T) { + s := NewSession((&sentRecorder{}).send, "h") + for raw, want := range map[string]bool{ + "CT#Server#welcome#1#%": true, + "CT#Bob#hi#0#%": false, + "CT#Bob#hi#%": false, + "CT#Bob#hi#7#%": false, + } { + if ev := feed(t, s, raw); len(ev) != 1 || ev[0].Kind != EventOOC || ev[0].FromServer != want { + t.Errorf("%s → %+v, want FromServer=%v", raw, ev, want) + } + } + typed := s.HandlePacket(protocol.NewTypedPacket(&aolib.CTToClient{Name: "Server", Message: "hi", IsFromServer: true})) + if len(typed) != 1 || !typed[0].FromServer { + t.Errorf("typed CT from the server → %+v", typed) + } +} diff --git a/internal/courtroom/session.go b/internal/courtroom/session.go index bdd3e4c6..63d783c2 100644 --- a/internal/courtroom/session.go +++ b/internal/courtroom/session.go @@ -15,6 +15,9 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/protocol" ) +// ctFromServer is CT's third field on a line the server itself sent; any other value is a player (packet_distribution.cpp:86). +const ctFromServer = "1" + // Handshake phases, as AO2-Client 2.11: decryptor→HI, ID→ID, PN→askchaa, SI→RC, SC→RM, SM→RD, DONE. // askchaa is what makes the server send SI; without it every server waits forever. type SessionPhase int @@ -193,6 +196,8 @@ type Event struct { // Loop and MusicEffects carry MC looping (field 3) and MUSIC_EFFECT flags (field 5); only EventMusic sets them. Loop bool MusicEffects int + // FromServer is CT's third field, "1" for the server's own line (courtroom.cpp:1921); only EventOOC sets it. + FromServer bool // Wipe is set_background's display parameter (packet_distribution.cpp:352, courtroom.cpp:1427): a BN with a pos. // Only the reducer sets it; client-made EventBackgrounds must leave it false or they erase what they re-seed. Wipe bool @@ -518,11 +523,11 @@ func (s *Session) handleTyped(t aolib.Outgoing) (ev []Event, ok bool) { if !s.Features.Has(protocol.FeatureAuthPacket) && v.Message == "Logged in as a moderator." { s.ModGranted = true return []Event{ - {Kind: EventOOC, Name: v.Name, Text: v.Message}, + {Kind: EventOOC, Name: v.Name, Text: v.Message, FromServer: v.IsFromServer}, {Kind: EventAuth, Int: 1}, }, true } - return []Event{{Kind: EventOOC, Name: v.Name, Text: v.Message}}, true + return []Event{{Kind: EventOOC, Name: v.Name, Text: v.Message, FromServer: v.IsFromServer}}, true case *aolib.KK: return []Event{{Kind: EventDisconnect, Text: "Kicked: " + capServerText(v.Reason)}}, true @@ -859,11 +864,11 @@ func (s *Session) HandlePacket(p protocol.Packet) []Event { if !s.Features.Has(protocol.FeatureAuthPacket) && p.Field(1) == "Logged in as a moderator." { s.ModGranted = true return []Event{ - {Kind: EventOOC, Name: p.Field(0), Text: p.Field(1)}, + {Kind: EventOOC, Name: p.Field(0), Text: p.Field(1), FromServer: p.Field(2) == ctFromServer}, {Kind: EventAuth, Int: 1}, } } - return []Event{{Kind: EventOOC, Name: p.Field(0), Text: p.Field(1)}} + return []Event{{Kind: EventOOC, Name: p.Field(0), Text: p.Field(1), FromServer: p.Field(2) == ctFromServer}} // Removal reasons are attacker-controlled, capped ahead of every consumer; cap the field (see capServerText). case "KK": diff --git a/internal/ui/app.go b/internal/ui/app.go index f38d0080..78a9c784 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -303,7 +303,6 @@ type App struct { // OOC wrapped-lines cache, also keyed by logViewEpoch: rebuilt only when the log, width or font scale moved. oocWrap []string oocWrapName []string // parallel to oocWrap: speaker to tint on each entry's FIRST display line ("" otherwise) - oocWrapCont []bool // parallel to oocWrap: true = a wrap continuation row (hanging indent); a paragraph's own newline starts a fresh row, not a continuation oocWrapSrc []int // parallel to oocWrap: the source oocLog entry index of each display line (mirrors icWrapLine.entry) // Every URL in a paragraph is separately hoverable. oocWrapLink is the flat table in row order; // oocWrapLinkAt has len(rows)+1 entries, so row r's spans are oocWrapLink[oocWrapLinkAt[r]:oocWrapLinkAt[r+1]]. diff --git a/internal/ui/app_connect.go b/internal/ui/app_connect.go index 41d3bde9..5ecec742 100644 --- a/internal/ui/app_connect.go +++ b/internal/ui/app_connect.go @@ -714,7 +714,7 @@ func (a *App) handleSessionEvents(events []courtroom.Event) { if uid, sender, ok := courtroom.ParsePMSender(ev.Name); ok { a.routeIncomingPM(uid, sender, ev.Text) } - a.pushOOC(ev.Name+": "+ev.Text, ev.Name) + a.pushOOC(ev.Name+": "+ev.Text, ev.Name, ev.FromServer) if a.d.Prefs.Load().CallwordsOOC && !looksLikeAreaList(ev.Text) { // OOC callwords opt-in (default OFF); /ga roster never self-pings names := a.mentionNames() a.checkCallwords(ev.Text, names, isSelfName(ev.Name, names)) @@ -783,7 +783,7 @@ func (a *App) handleSessionEvents(events []courtroom.Event) { case courtroom.EventWTCE: a.handleWTCE(ev.Text, ev.Int) case courtroom.EventModcall: - a.pushOOC("[MOD CALL] "+ev.Text, "") + a.pushOOC("[MOD CALL] "+ev.Text, "", false) // AO2's ui_guard silences only the modcall alert (courtroom.cpp:4997-5001: sound and window flash); the OOC // line and auto-clip still land, so a guarded mod loses the interruption, never the report. if !a.modcallGuard { @@ -796,21 +796,21 @@ func (a *App) handleSessionEvents(events []courtroom.Event) { // AO2 surfaces auth transitions as CLIENT lines in the OOC log (on_authentication_state_received). switch { case ev.Int >= 1: - a.pushOOC("CLIENT: Logged in as a moderator.", "") + a.pushOOC("CLIENT: Logged in as a moderator.", "", false) // Mod now: re-pull /getarea so IPIDs (mod-only, absent from PR/PU) reach the roster; the first // auto-pull can fire before this auto-login lands. if a.sess != nil { a.fetchRoster() } case ev.Int == 0: - a.pushOOC("CLIENT: Login unsuccessful.", "") + a.pushOOC("CLIENT: Login unsuccessful.", "", false) default: - a.pushOOC("CLIENT: You were logged out.", "") + a.pushOOC("CLIENT: You were logged out.", "", false) } case courtroom.EventSetPos: a.sidePref = ev.Text // SP: the server moved us case courtroom.EventCase: - a.pushOOC("[CASE] "+ev.Text, "") + a.pushOOC("[CASE] "+ev.Text, "", false) if enabled, roles := a.d.Prefs.Load().Casing(); enabled && ev.Int&roles != 0 { a.playThemeSFX("case_call") a.ctx.FlashWindow() @@ -819,7 +819,7 @@ func (a *App) handleSessionEvents(events []courtroom.Event) { // BB is AO2's call_notice, shown in a modal (courtroom.cpp). Do both: the OOC log keeps it searchable, the // box makes it copyable and unmissable. serverNoticeInfo, so dismissing touches nothing; the connection is // fine. - a.pushOOC("[SERVER] "+ev.Text, "") + a.pushOOC("[SERVER] "+ev.Text, "", false) if strings.TrimSpace(ev.Text) != "" { a.openServerNotice(serverNoticeInfo, serverNoticeInfoTitle, a.serverName, ev.Text) } @@ -828,9 +828,9 @@ func (a *App) handleSessionEvents(events []courtroom.Event) { // The server (un)muted us: log it and flash the window; the IC input shows a muted chip and refuses sends // while Session.Muted is set (AO2 set_mute disables ui_ic_chat_message). if ev.Int == 1 { - a.pushOOC("[SERVER] You have been muted — you can't speak in-character.", "") + a.pushOOC("[SERVER] You have been muted — you can't speak in-character.", "", false) } else { - a.pushOOC("[SERVER] You have been unmuted.", "") + a.pushOOC("[SERVER] You have been unmuted.", "", false) } a.ctx.FlashWindow() case courtroom.EventEvidence: diff --git a/internal/ui/app_ic.go b/internal/ui/app_ic.go index 29238294..28d0fe28 100644 --- a/internal/ui/app_ic.go +++ b/internal/ui/app_ic.go @@ -1143,7 +1143,7 @@ const oocLineCap = 16384 // pushOOC appends an OOC line; speaker is "" for system lines, // and the slices stay parallel so display needn't re-parse. -func (a *App) pushOOC(line, speaker string) { +func (a *App) pushOOC(line, speaker string, fromServer bool) { // OOC carries AsyncAO's DMs raw, so markers arrive here; the control frame was already decoded by routeIncomingPM. // The head is preserved, keeping the "speaker: " trim working and oocSpeakers a substring of oocLog. line = stripDisplayTail(line, speaker) @@ -1173,13 +1173,14 @@ func (a *App) pushOOC(line, speaker string) { } a.oocLog = appendCapped(a.oocLog, line, icLogCap) a.oocSpeakers = appendCapped(a.oocSpeakers, speaker, icLogCap) + a.oocFromServer = appendCapped(a.oocFromServer, fromServer, icLogCap) a.oocSeq++ // invalidate the wrapped-lines cache // Every active-tab OOC event funnels through here, like AO2's append_server_chatmessage, // so the transcript logs what's shown. a.logDetailedOOC(a.serverName, a.logSession, line) // detailed transcript (opt-in), this tab's own file } -func appendCapped(list []string, line string, cap int) []string { +func appendCapped[T any](list []T, line T, cap int) []T { list = append(list, line) if len(list) > cap { copy(list, list[len(list)-cap:]) diff --git a/internal/ui/apptypes.go b/internal/ui/apptypes.go index a09b13da..a909f8bf 100644 --- a/internal/ui/apptypes.go +++ b/internal/ui/apptypes.go @@ -446,6 +446,7 @@ type sessionState struct { oocSeq uint64 oocLog []string oocSpeakers []string // parallel to oocLog: speaker per line ("" = system line); for name colours + oocFromServer []bool // parallel to oocLog: CT's server flag, which colours the speaker as the server oocScroll int32 musicScroll int32 // Music-list search: the query plus a memoized filter. musicFiltered holds matching indices into a.sess.Music. diff --git a/internal/ui/court_extras.go b/internal/ui/court_extras.go index 6ea9e446..85c97ae8 100644 --- a/internal/ui/court_extras.go +++ b/internal/ui/court_extras.go @@ -1549,7 +1549,7 @@ func (a *App) drawModcallPanel(w, h int32, pressed *bool) { a.modReason, _ = c.TextField("modreason", sdl.Rect{X: r.X + pad, Y: r.Y + floatTitleH + 32, W: r.W - 2*pad, H: fieldH}, a.modReason, "What needs attention?") if c.Button(sdl.Rect{X: r.X + pad, Y: r.Y + r.H - btnH - 12, W: 110, H: btnH}, "Call mod") { a.sess.CallMod(strings.TrimSpace(a.modReason)) - a.pushOOC("CLIENT: Moderator called.", "") + a.pushOOC("CLIENT: Moderator called.", "", false) a.showModcall, a.modReason = false, "" } } diff --git a/internal/ui/logbottomrow_test.go b/internal/ui/logbottomrow_test.go index ed6d2bf6..48de55a3 100644 --- a/internal/ui/logbottomrow_test.go +++ b/internal/ui/logbottomrow_test.go @@ -33,7 +33,7 @@ func TestOOCLogDrawsHalfVisibleBottomRow(t *testing.T) { a.ctx = ctx a.oocPct = DefaultScalePct for range lineCount { - a.pushOOC("MMMMMMMMMMMMMMMM", "") + a.pushOOC("MMMMMMMMMMMMMMMM", "", false) } lineH := int32(a.elemFont(elemServerChatlog, a.oocPct).Height()) + logRowGapPx list := sdl.Rect{X: listX, Y: listY, W: listW, H: visibleRows*lineH + lineH/2} diff --git a/internal/ui/logselect_wire.go b/internal/ui/logselect_wire.go index 7c212168..3ba2ace5 100644 --- a/internal/ui/logselect_wire.go +++ b/internal/ui/logselect_wire.go @@ -57,8 +57,9 @@ func (c *Ctx) logRowSplit(font, emojiFont *ttf.Font, line, speaker string, nameO // drawLogLineNamed draws one wrapped log line, tinting the speaker's name prefix in its per-speaker colour when // name colours are on and speaker != "" (the caller passes "" for non-first rows and system lines). The rest draws // in col; otherwise a plain draw. Shared by the IC and OOC log paths. -func (a *App) drawLogLineNamed(font, emojiFont *ttf.Font, x, y, wrapW int32, line, speaker string, col sdl.Color, nameOn bool, sat, val float64, bold bool) { +func (a *App) drawLogLineNamed(font, emojiFont *ttf.Font, x, y, wrapW int32, line, speaker string, col sdl.Color, ink logNameInk, bold bool) { c := a.ctx + nameOn := ink.tints() // logRowSplit proves both segments will measure before anything is drawn, so there is no partial-draw state to // fall into the plain-weight fallback below. if nameStart, boldEnd, ok := c.logRowSplit(font, emojiFont, line, speaker, nameOn, bold); ok { @@ -75,11 +76,7 @@ func (a *App) drawLogLineNamed(font, emojiFont *ttf.Font, x, y, wrapW int32, lin used += pw } nw, _ := c.fontTextWidthWeight(font, speaker, bold) // logRowSplit already proved this succeeds - nameCol := col - if nameOn { - nameCol = nameColor(speaker, sat, val) - } - c.LabelClippedFontWeight(font, px, y, wrapW-used, speaker, nameCol, bold) + c.LabelClippedFontWeight(font, px, y, wrapW-used, speaker, ink.of(speaker, col), bold) used += nw c.LabelClippedFont(font, px+nw, y, wrapW-used, line[boldEnd:], col) return @@ -88,6 +85,40 @@ func (a *App) drawLogLineNamed(font, emojiFont *ttf.Font, x, y, wrapW int32, lin a.labelEmoji(font, emojiFont, x, y, wrapW, line, col) } +// logNameInk is how a log row colours its speaker's name: a fixed ink, a colour per speaker, or the line's own. +type logNameInk struct { + perSpeaker bool + sat, val float64 + fixed sdl.Color + fixedSet bool +} + +// namePctScale turns the saturation and value prefs, in percent, into 0..1. +const namePctScale = 100 + +// logNameInkPref is the player's name-colour setting as a logNameInk; read it once per frame. +func (a *App) logNameInkPref() logNameInk { + s := a.d.Prefs.Load() + if !s.NameColors { + return logNameInk{} + } + return logNameInk{perSpeaker: true, sat: float64(s.NameSat) / namePctScale, val: float64(s.NameVal) / namePctScale} +} + +// tints reports whether the name draws in a colour of its own. +func (n logNameInk) tints() bool { return n.fixedSet || n.perSpeaker } + +// of is the name's colour on a line drawn in line. +func (n logNameInk) of(speaker string, line sdl.Color) sdl.Color { + switch { + case n.fixedSet: + return n.fixed + case n.perSpeaker: + return nameColor(speaker, n.sat, n.val) + } + return line +} + const ( logSelNone = iota logSelIC diff --git a/internal/ui/logwrap_test.go b/internal/ui/logwrap_test.go index b780507f..b2d6c828 100644 --- a/internal/ui/logwrap_test.go +++ b/internal/ui/logwrap_test.go @@ -47,8 +47,7 @@ func TestLogHangingIndent(t *testing.T) { t.Errorf("IC continuation indent = %d, want %d", got, logWrapIndentPx) } - // OOC: a wrapping paragraph THEN an explicit newline — the wrap's rows are - // continuations, the newline's row starts a fresh unindented paragraph. + // OOC (#53): no row hangs, wrapped or not, as AO2's server log draws the text as the server wrote it. a.oocLog = append(a.oocLog, "a long first paragraph that will wrap across rows\nsecond para") a.oocSpeakers = append(a.oocSpeakers, "MOTD") a.oocSeq++ @@ -56,23 +55,13 @@ func TestLogHangingIndent(t *testing.T) { if len(lines) < 3 { t.Fatalf("OOC fixture must wrap, got %d rows", len(lines)) } - if len(a.oocWrapCont) != len(lines) { - t.Fatalf("cont flags = %d, rows = %d — must stay parallel", len(a.oocWrapCont), len(lines)) - } if len(a.oocWrapSrc) != len(lines) { t.Fatalf("src indices = %d, rows = %d — must stay parallel (both append sites)", len(a.oocWrapSrc), len(lines)) } - if a.oocWrapCont[0] { - t.Error("a paragraph's first row must not be a continuation") - } - if !a.oocWrapCont[1] { - t.Error("a wrapped row must be a continuation") - } - if last := len(lines) - 1; a.oocWrapCont[last] { - t.Error("a newline-started paragraph must not be a continuation") - } - if got := a.logRowIndent(logSelOOC, 1); got != logWrapIndentPx { - t.Errorf("OOC continuation indent = %d, want %d", got, logWrapIndentPx) + for li := range lines { + if got := a.logRowIndent(logSelOOC, li); got != 0 { + t.Errorf("OOC row %d indent = %d, want 0", li, got) + } } } @@ -255,10 +244,10 @@ func TestOOCWrapLongHelpNoLoss(t *testing.T) { } // Parallel slices stay in lockstep at the new budget (the link index carries // one extra entry by construction — it holds each row's span START). - if len(a.oocWrapName) != len(rows) || len(a.oocWrapCont) != len(rows) || + if len(a.oocWrapName) != len(rows) || len(a.oocWrapSrc) != len(rows) || len(a.oocWrapLinkAt) != len(rows)+1 { - t.Fatalf("parallel slices desynced: out=%d name=%d cont=%d src=%d linkAt=%d", - len(rows), len(a.oocWrapName), len(a.oocWrapCont), len(a.oocWrapSrc), len(a.oocWrapLinkAt)) + t.Fatalf("parallel slices desynced: out=%d name=%d src=%d linkAt=%d", + len(rows), len(a.oocWrapName), len(a.oocWrapSrc), len(a.oocWrapLinkAt)) } if got, want := stripSpaces(strings.Join(rows, "")), stripSpaces(help); got != want { t.Fatalf("text lost in wrap: reassembled %d chars, original %d", len(got), len(want)) @@ -283,7 +272,7 @@ const oocWrapMaxLinesPerEntryOld = 24 func TestPushOOCStoreCapIntact(t *testing.T) { a := testTabApp(t) huge := strings.Repeat("x", oocLineCap+500) // comfortably over the cap - a.pushOOC(huge, "") + a.pushOOC(huge, "", false) if len(a.oocLog) != 1 { t.Fatalf("expected one stored entry, got %d", len(a.oocLog)) } @@ -297,7 +286,7 @@ func TestPushOOCStoreCapIntact(t *testing.T) { // A legitimately long /help UNDER the cap is stored whole (not clipped). a2 := testTabApp(t) fits := strings.Repeat("y", oocLineCap-1) - a2.pushOOC(fits, "") + a2.pushOOC(fits, "", false) if len(a2.oocLog) != 1 || a2.oocLog[0] != fits { t.Fatal("an under-cap entry must be stored verbatim") } @@ -331,10 +320,10 @@ func TestOOCWrapPathologicalMarker(t *testing.T) { t.Fatalf("row count %d exceeds budget+marker (%d)", len(rows), oocWrapMaxLinesPerEntry+1) } // Parallel slices include the marker row. - if len(a.oocWrapName) != len(rows) || len(a.oocWrapCont) != len(rows) || + if len(a.oocWrapName) != len(rows) || len(a.oocWrapSrc) != len(rows) || len(a.oocWrapLinkAt) != len(rows)+1 { - t.Fatalf("marker desynced parallel slices: out=%d name=%d cont=%d src=%d linkAt=%d", - len(rows), len(a.oocWrapName), len(a.oocWrapCont), len(a.oocWrapSrc), len(a.oocWrapLinkAt)) + t.Fatalf("marker desynced parallel slices: out=%d name=%d src=%d linkAt=%d", + len(rows), len(a.oocWrapName), len(a.oocWrapSrc), len(a.oocWrapLinkAt)) } // A NORMAL width never trips the marker for the same content. a.oocSeq++ // force a cache rebuild at the new width diff --git a/internal/ui/ooclinks_test.go b/internal/ui/ooclinks_test.go index eee35da5..3cfd0aa3 100644 --- a/internal/ui/ooclinks_test.go +++ b/internal/ui/ooclinks_test.go @@ -38,7 +38,7 @@ func TestOOCLinkSpansMultiplePerParagraph(t *testing.T) { const u2 = "www.bbb.example.org" const u3 = "http://ccc.example.net/three" line := "Links: " + u1 + " and " + u2 + " plus " + u3 + "." - a.pushOOC(line, "") + a.pushOOC(line, "", false) rows := a.oocWrapped(int32(len(line)+8) * wrapFallbackCharPx) // wide enough for one row if len(rows) != 1 { @@ -108,7 +108,7 @@ func TestOOCLinkSpansMultiplePerParagraph(t *testing.T) { func TestOOCLinkSpansNoURL(t *testing.T) { a := testTabApp(t) a.oocPct = DefaultScalePct - a.pushOOC("Nyah: no links here, just a colon: and a dot.", "Nyah") + a.pushOOC("Nyah: no links here, just a colon: and a dot.", "Nyah", false) rows := a.oocWrapped(2000) if len(a.oocWrapLink) != 0 { @@ -132,7 +132,7 @@ func TestOOCLinkSpansWrapContiguous(t *testing.T) { a := testTabApp(t) a.oocPct = DefaultScalePct const url = "https://example.com/a/very/long/path/that/cannot/fit/one/row/at/all.zip" - a.pushOOC("see "+url+" ok", "") + a.pushOOC("see "+url+" ok", "", false) rows := a.oocWrapped(20 * wrapFallbackCharPx) // ~20 chars/row → the URL must split if len(rows) < 3 { @@ -186,7 +186,7 @@ func TestOOCLinkSpansStreamerMasked(t *testing.T) { a.oocPct = DefaultScalePct const url = "https://example.com/x" a.d.Prefs.Update(func(sn *config.Settings) { sn.StreamerModeOn = true }) - a.pushOOC("Nyah: grab "+url+" now", "Nyah") + a.pushOOC("Nyah: grab "+url+" now", "Nyah", false) rows := a.oocWrapped(2000) if len(rows) != 1 { @@ -217,7 +217,7 @@ func TestOOCLinkSpansStreamerMasked(t *testing.T) { func TestOOCRowLinksNoAlloc(t *testing.T) { a := testTabApp(t) a.oocPct = DefaultScalePct - a.pushOOC("Nyah: see https://example.com/one and https://example.com/two", "Nyah") + a.pushOOC("Nyah: see https://example.com/one and https://example.com/two", "Nyah", false) rows := a.oocWrapped(2000) if len(a.oocWrapLink) != 2 { t.Fatalf("fixture must produce 2 spans, got %d", len(a.oocWrapLink)) diff --git a/internal/ui/oocsender_test.go b/internal/ui/oocsender_test.go new file mode 100644 index 00000000..f4547f4e --- /dev/null +++ b/internal/ui/oocsender_test.go @@ -0,0 +1,54 @@ +package ui + +import ( + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/sdl" +) + +// Issue #68: the OOC log colours a sender's name by who sent the line, as AO2's append_server_chatmessage does. +func TestOOCSenderNameInk(t *testing.T) { + const wide = 1000 + serverInk := sdl.Color{R: 250, G: 200, B: 40, A: 255} + playerInk := sdl.Color{R: 90, G: 220, B: 250, A: 255} + a := testTabApp(t) + a.oocPct = DefaultScalePct + a.pushOOC("Server: welcome", "Server", true) + a.pushOOC("Bob: hi", "Bob", false) + a.oocWrapped(wide) + const serverRow, playerRow = 0, 1 + plain := logNameInk{} + perSpeaker := logNameInk{perSpeaker: true} + + if ink := a.oocRowNameInk(serverRow, plain, true); !ink.fixedSet || ink.fixed != ColAccent { + t.Errorf("server line without a theme colour: %+v, want the accent", ink) + } + if ink := a.oocRowNameInk(playerRow, plain, true); ink.tints() { + t.Errorf("player line without a theme colour tints its name: %+v", ink) + } + + a.themeFonts.senderInk[oocFromServer], a.themeFonts.senderInkSet[oocFromServer] = serverInk, true + a.themeFonts.senderInk[oocFromPlayer], a.themeFonts.senderInkSet[oocFromPlayer] = playerInk, true + if ink := a.oocRowNameInk(serverRow, perSpeaker, true); ink.of("Server", ColText) != serverInk { + t.Errorf("server line on the theme's canvas: %+v, want server_chatlog_sender_color", ink) + } + if ink := a.oocRowNameInk(playerRow, plain, true); ink.of("Bob", ColText) != playerInk { + t.Errorf("player line on the theme's canvas: %+v, want ms_chatlog_sender_color", ink) + } + if ink := a.oocRowNameInk(playerRow, perSpeaker, true); ink.fixedSet { + t.Errorf("per-speaker colours were turned on, yet the theme's player colour won: %+v", ink) + } + if ink := a.oocRowNameInk(serverRow, plain, false); ink.fixed != ColAccent { + t.Errorf("off the theme's canvas the server line took the theme colour: %+v", ink) + } +} + +// A theme sender colour that can't be read on the log's backdrop is dropped like any other theme ink. +func TestUnreadableSenderInkIsDropped(t *testing.T) { + tbl := themeFontTable{} + tbl.senderInk[oocFromServer], tbl.senderInkSet[oocFromServer] = ColPanel, true + guardThemeInk(&themeApply{}, &tbl) + if tbl.senderInkSet[oocFromServer] { + t.Error("a sender colour equal to the panel was kept") + } +} diff --git a/internal/ui/qol.go b/internal/ui/qol.go index 46f30823..9e991e44 100644 --- a/internal/ui/qol.go +++ b/internal/ui/qol.go @@ -1243,7 +1243,6 @@ func (a *App) oocWrapped(width int32) []string { } out := a.oocWrap[:0] name := a.oocWrapName[:0] // parallel to out: speaker on each entry's first display line - cont := a.oocWrapCont[:0] // parallel to out: wrap continuation rows (hanging indent) src := a.oocWrapSrc[:0] // parallel to out: source oocLog entry index links := a.oocWrapLink[:0] // NOT parallel: the flat link-span table, rows index it via linkAt below var nextLinkID int32 // link ids are unique across the whole rebuild, so a span identifies its link alone @@ -1292,16 +1291,14 @@ func (a *App) oocWrapped(width int32) []string { if len(lines) == 0 { out = append(out, "") // blank MOTD spacer lines survive name = append(name, "") - cont = append(cont, false) src = append(src, i) remaining-- // a spacer row spends budget too, so the count stays bounded continue } rowBase := len(out) // where this paragraph's rows land — the spans index into the WRAP, not into lines - for row, ln := range lines { + for _, ln := range lines { out = append(out, ln) - cont = append(cont, row > 0) // rows the WRAP made are continuations (hanging indent); the paragraph's own newline isn't - src = append(src, i) // all rows of this entry carry its oocLog index + src = append(src, i) // all rows of this entry carry its oocLog index if entryFirst { name = append(name, sp) entryFirst = false @@ -1319,10 +1316,9 @@ func (a *App) oocWrapped(width int32) []string { } } if truncated { - // One marker row for the whole entry, parallel slices in step; cont=true hangs it under the entry. + // One marker row for the whole entry, parallel slices in step. out = append(out, "…") name = append(name, "") - cont = append(cont, true) src = append(src, i) } } @@ -1337,7 +1333,7 @@ func (a *App) oocWrapped(width int32) []string { } linkAt = append(linkAt, int32(k)) } - a.oocWrap, a.oocWrapName, a.oocWrapCont, a.oocWrapSrc = out, name, cont, src + a.oocWrap, a.oocWrapName, a.oocWrapSrc = out, name, src a.oocWrapLink, a.oocWrapLinkAt = links, linkAt a.oocWrapSeq, a.oocWrapW, a.oocWrapPct, a.oocWrapMask = a.oocSeq, width, pct, streamer a.oocWrapEpoch = a.logViewEpoch @@ -1367,14 +1363,9 @@ func (a *App) icRowIsEntryStart(li int) bool { } // logRowIndent is row li's draw indent in log which; selection hit-testing uses the same offset. +// OOC rows never hang: AO2's server log is plain text, laid out as the server wrote it (#53). func (a *App) logRowIndent(which, li int) int32 { - if which == logSelIC { - if !a.icRowIsEntryStart(li) { - return logWrapIndentPx - } - return 0 - } - if li >= 0 && li < len(a.oocWrapCont) && a.oocWrapCont[li] { + if which == logSelIC && !a.icRowIsEntryStart(li) { return logWrapIndentPx } return 0 diff --git a/internal/ui/rosterpoll_test.go b/internal/ui/rosterpoll_test.go index 51040a38..5c563939 100644 --- a/internal/ui/rosterpoll_test.go +++ b/internal/ui/rosterpoll_test.go @@ -81,7 +81,7 @@ func TestAManualRosterFetchStillWorksAndShowsItsReply(t *testing.T) { // The reply burst it asked for is parsed but suppressed (areaEchoSuppressWindow). before := len(a.oocLog) - a.pushOOC("Server: [0] Phoenix Wright (1001) [Def]", "Server") // a real roster row (looksLikeAreaList) + a.pushOOC("Server: [0] Phoenix Wright (1001) [Def]", "Server", false) // a real roster row (looksLikeAreaList) if len(a.oocLog) != before { t.Error("the roster body we asked for must stay out of the OOC log") } @@ -89,7 +89,7 @@ func TestAManualRosterFetchStillWorksAndShowsItsReply(t *testing.T) { // A refusal is NOT suppressed any more: it is the answer to a press, it can only // appear once per press, and hiding it makes the control look broken. before = len(a.oocLog) - a.pushOOC("Server: You cannot see players in all areas in this hub!", "Server") + a.pushOOC("Server: You cannot see players in all areas in this hub!", "Server", false) if len(a.oocLog) == before { t.Error("a server's refusal must reach the OOC log now that nothing sends the command on its own") } diff --git a/internal/ui/screensemote.go b/internal/ui/screensemote.go index 1fbe2649..2d777207 100644 --- a/internal/ui/screensemote.go +++ b/internal/ui/screensemote.go @@ -976,7 +976,7 @@ func (a *App) sendIC() { } // Muted (AO2 set_mute; on_chat_return_pressed returns early): refuse but keep the line, as no echo will clear it. if a.sess.Muted { - a.pushOOC("[SERVER] You're muted — that message wasn't sent.", "") + a.pushOOC("[SERVER] You're muted — that message wasn't sent.", "", false) return } // AO2-Client chat_ratelimit parity: drop sends inside the window. diff --git a/internal/ui/screensooc.go b/internal/ui/screensooc.go index 32344df7..854aab7f 100644 --- a/internal/ui/screensooc.go +++ b/internal/ui/screensooc.go @@ -143,13 +143,8 @@ func (a *App) drawICLogList(list sdl.Rect, canvasInk bool) { pinChord := c.hotkey != 0 && strings.EqualFold(sdl.GetKeyName(c.hotkey), a.hotkeyFor(hotkeyPinNote)) friendsOn := a.d.Prefs.Load().FriendHighlight // gates the per-line friend glow (read once) // Per-speaker name colours, read once: tint the name prefix on an entry's first wrapped row. - nameColorsOn := a.d.Prefs.Load().NameColors + nameInk := a.logNameInkPref() boldNames := a.logRowBoldPref(logSelIC) // read once per frame, passed per line (#39: ic_chatlog_bold) - var nameSat, nameVal float64 - if nameColorsOn { - nameSat = float64(a.d.Prefs.Load().NameSat) / 100 - nameVal = float64(a.d.Prefs.Load().NameVal) / 100 - } // Glow alpha, computed once per frame: static, or a slow breathe with FriendGlowPulse (off under reduce-motion). friendAlpha := friendTintColor.A pulseOn := friendsOn && a.d.Prefs.Load().FriendGlowPulse && !a.d.Prefs.Load().ReduceMotionOn @@ -225,7 +220,7 @@ func (a *App) drawICLogList(list sdl.Rect, canvasInk bool) { // Per-speaker name colour on an entry's first wrapped row (the helper falls back to a plain draw for // system/evidence lines or when a long name wrapped off this row). lineSpeaker := "" - if nameColorsOn && a.icRowIsEntryStart(ri) { + if nameInk.perSpeaker && a.icRowIsEntryStart(ri) { lineSpeaker = a.icLog[row.entry].speaker } // Not said yet -> faint. After the link-hover override so a hovered unspoken link stays faint; @@ -243,7 +238,7 @@ func (a *App) drawICLogList(list sdl.Rect, canvasInk bool) { spans := inlineSpanAt(styles, row.headRunes, row.bodyOff, bodyLen, col) a.drawColoredLogRow(font, c.EmojiFont(icPct), list.X+indent, y, wrapW-indent, row.text, spans) } else { - a.drawLogLineNamed(font, c.EmojiFont(icPct), list.X+indent, y, wrapW-indent, row.text, lineSpeaker, col, nameColorsOn, nameSat, nameVal, boldNames) + a.drawLogLineNamed(font, c.EmojiFont(icPct), list.X+indent, y, wrapW-indent, row.text, lineSpeaker, col, nameInk, boldNames) } if u := a.icLog[row.entry].url; u != "" { if c.hovering(rowRect) { @@ -311,15 +306,9 @@ func (a *App) drawOOCLogList(list sdl.Rect, canvasInk bool) { font := a.elemFont(elemServerChatlog, a.oocPct) lineH := int32(font.Height()) + logRowGapPx wrapW := list.W - scrollBarW - scrollBarGap - // Wrap against the indented width so continuation rows (drawn at +logWrapIndentPx) cannot overflow. - lines := a.oocWrapped(wrapW - logWrapIndentPx) // MOTDs wrap — never truncate - nameColorsOn := a.d.Prefs.Load().NameColors // per-speaker OOC name colours (read once) - boldNames := a.logRowBoldPref(logSelOOC) // read once per frame, passed per line - var nameSat, nameVal float64 - if nameColorsOn { - nameSat = float64(a.d.Prefs.Load().NameSat) / 100 - nameVal = float64(a.d.Prefs.Load().NameVal) / 100 - } + lines := a.oocWrapped(wrapW) // MOTDs wrap — never truncate + nameInk := a.logNameInkPref() // per-speaker OOC name colours (read once) + boldNames := a.logRowBoldPref(logSelOOC) // read once per frame, passed per line contentH := int32(len(lines)) * lineH track := sdl.Rect{X: list.X + list.W - scrollBarW, Y: list.Y, W: scrollBarW, H: list.H} // Ctrl+wheel (fine) or wheel-button-held (fast) zooms the OOC text (independent of the IC log). @@ -364,7 +353,7 @@ func (a *App) drawOOCLogList(list sdl.Rect, canvasInk bool) { // OOC links open on click and copy on right-click; the URL is resolved at wrap time. rowRect := sdl.Rect{X: list.X, Y: y, W: wrapW, H: lineH} a.oocRowLinkActions(hoverSpan, li, rowRect, list.X+indent, y, lineH) - a.drawOOCLogRow(list, li, font, list.X+indent, y, wrapW-indent, line, sp, hoverID, nameColorsOn, nameSat, nameVal, boldNames, oocInk) + a.drawOOCLogRow(list, li, font, list.X+indent, y, wrapW-indent, line, sp, hoverID, a.oocRowNameInk(li, nameInk, canvasInk), boldNames, oocInk) } y += lineH } @@ -409,16 +398,38 @@ func (a *App) oocRowLinkActions(hoverSpan, li int, rowRect sdl.Rect, textX, y, l a.oocLinkActions(rowRect, sdl.Rect{X: textX + s.x0, Y: y, W: s.x1 - s.x0, H: lineH}, s.url) } +// oocRowNameInk is display row li's name ink: the server's on a line CT marked as the server's, else the theme's player +// ink while per-speaker colours are off. canvasInk is elemInk's. +func (a *App) oocRowNameInk(li int, base logNameInk, canvasInk bool) logNameInk { + sender := oocFromPlayer + if li < len(a.oocWrapSrc) { + if e := a.oocWrapSrc[li]; e < len(a.oocFromServer) && a.oocFromServer[e] { + sender = oocFromServer + } + } + ink, set := a.themeFonts.senderInk[sender], a.themeFonts.senderInkSet[sender] && canvasInk + switch { + case sender == oocFromServer: + base.fixed, base.fixedSet = ColAccent, true + if set { + base.fixed = ink + } + case !base.perSpeaker && set: + base.fixed, base.fixedSet = ink, true + } + return base +} + // drawOOCLogRow draws one wrapped OOC row, tinting only the hovered link (hoverID < 0 = none). // The row is drawn whole per pass and the clip picks the slice, so tinted and plain parts share one glyph layout. // The clip keeps the list's vertical bounds so a partly scrolled row still cuts at the rect edge. // base is the plain-text colour: server_chatlog_color on the canvas panel, ColText in the chrome OOC box. -func (a *App) drawOOCLogRow(list sdl.Rect, li int, font *ttf.Font, x, y, textW int32, line, sp string, hoverID int32, nameOn bool, sat, val float64, bold bool, base sdl.Color) { +func (a *App) drawOOCLogRow(list sdl.Rect, li int, font *ttf.Font, x, y, textW int32, line, sp string, hoverID int32, ink logNameInk, bold bool, base sdl.Color) { c := a.ctx ef := a.elemEmoji(elemServerChatlog, a.oocPct) // #39: baseline must match the row's resolved text scale spans := a.oocRowLinks(li) if hoverID < 0 || len(spans) == 0 { - a.drawLogLineNamed(font, ef, x, y, textW, line, sp, base, nameOn, sat, val, bold) + a.drawLogLineNamed(font, ef, x, y, textW, line, sp, base, ink, bold) return } seg := func(lo, hi int32, col sdl.Color) { @@ -426,7 +437,7 @@ func (a *App) drawOOCLogRow(list sdl.Rect, li int, font *ttf.Font, x, y, textW i return } prev, had := c.pushClip(sdl.Rect{X: x + lo, Y: list.Y, W: hi - lo, H: list.H}) - a.drawLogLineNamed(font, ef, x, y, textW, line, sp, col, nameOn, sat, val, bold) + a.drawLogLineNamed(font, ef, x, y, textW, line, sp, col, ink, bold) c.popClip(prev, had) } drawn := int32(0) @@ -439,7 +450,7 @@ func (a *App) drawOOCLogRow(list sdl.Rect, li int, font *ttf.Font, x, y, textW i drawn = spans[k].x1 } if drawn == 0 { // the hovered link isn't on this row after all - a.drawLogLineNamed(font, ef, x, y, textW, line, sp, base, nameOn, sat, val, bold) + a.drawLogLineNamed(font, ef, x, y, textW, line, sp, base, ink, bold) return } seg(drawn, textW, base) // the remainder of the row @@ -499,15 +510,9 @@ func (a *App) drawOOCPanel(r sdl.Rect, withInput bool) { font := a.elemFont(elemServerChatlog, a.oocPct) lineH := int32(font.Height()) + logRowGapPx wrapW := list.W - scrollBarW - scrollBarGap - // Wrap against the indented width so continuation rows (drawn at +logWrapIndentPx) cannot overflow. - lines := a.oocWrapped(wrapW - logWrapIndentPx) // MOTDs wrap — never truncate - nameColorsOn := a.d.Prefs.Load().NameColors // per-speaker OOC name colours (read once) - boldNames := a.logRowBoldPref(logSelOOC) // read once per frame, passed per line - var nameSat, nameVal float64 - if nameColorsOn { - nameSat = float64(a.d.Prefs.Load().NameSat) / 100 - nameVal = float64(a.d.Prefs.Load().NameVal) / 100 - } + lines := a.oocWrapped(wrapW) // MOTDs wrap — never truncate + nameInk := a.logNameInkPref() // per-speaker OOC name colours (read once) + boldNames := a.logRowBoldPref(logSelOOC) // read once per frame, passed per line contentH := int32(len(lines)) * lineH track := sdl.Rect{X: list.X + list.W - scrollBarW, Y: list.Y, W: scrollBarW, H: list.H} // Ctrl+wheel / wheel-button zooms the OOC text, independent of the IC log. As a docked tab the right-column @@ -552,7 +557,7 @@ func (a *App) drawOOCPanel(r sdl.Rect, withInput bool) { rowRect := sdl.Rect{X: list.X, Y: y, W: wrapW, H: lineH} a.oocRowLinkActions(hoverSpan, li, rowRect, list.X+indent, y, lineH) // ColText, not server_chatlog_color: this box is chrome outside any theme canvas, on its own ColPanel. - a.drawOOCLogRow(list, li, font, list.X+indent, y, wrapW-indent, line, sp, hoverID, nameColorsOn, nameSat, nameVal, boldNames, ColText) + a.drawOOCLogRow(list, li, font, list.X+indent, y, wrapW-indent, line, sp, hoverID, a.oocRowNameInk(li, nameInk, false), boldNames, ColText) } y += lineH } diff --git a/internal/ui/sessioncarry.go b/internal/ui/sessioncarry.go index 83980ab6..dcc6d487 100644 --- a/internal/ui/sessioncarry.go +++ b/internal/ui/sessioncarry.go @@ -3,14 +3,15 @@ package ui // sessionCarry is the one-shot snapshot of the logs a resumed session should see again; every other sessionState // field is connection-scoped and comes back fresh. This file is the only place that field list may appear. type sessionCarry struct { - icLog []icEntry - icLogSeq uint64 - icReadMark int - oocLog []string - oocSpeakers []string - oocSeq uint64 - areaLogs map[string][]icEntry - areaLogOrder []string + icLog []icEntry + icLogSeq uint64 + icReadMark int + oocLog []string + oocSpeakers []string + oocFromServer []bool + oocSeq uint64 + areaLogs map[string][]icEntry + areaLogOrder []string } // snapshotSessionCarry copies the log fields into the carry, keyed by a.serverKey (the dialled address, not the name). @@ -18,14 +19,15 @@ type sessionCarry struct { // A second call overwrites; the contents are already capped by icLogCap/oocLineCap. func (a *App) snapshotSessionCarry() { a.pendingSessionCarry = &sessionCarry{ - icLog: a.icLog, - icLogSeq: a.icLogSeq, - icReadMark: a.icReadMark, - oocLog: a.oocLog, - oocSpeakers: a.oocSpeakers, - oocSeq: a.oocSeq, - areaLogs: a.areaLogs, - areaLogOrder: a.areaLogOrder, + icLog: a.icLog, + icLogSeq: a.icLogSeq, + icReadMark: a.icReadMark, + oocLog: a.oocLog, + oocSpeakers: a.oocSpeakers, + oocFromServer: a.oocFromServer, + oocSeq: a.oocSeq, + areaLogs: a.areaLogs, + areaLogOrder: a.areaLogOrder, } a.pendingSessionCarryKey = a.serverKey } @@ -43,6 +45,7 @@ func (a *App) applySessionCarryIfPending(wsURL string) { a.icReadMark = carry.icReadMark a.oocLog = carry.oocLog a.oocSpeakers = carry.oocSpeakers + a.oocFromServer = carry.oocFromServer a.oocSeq = carry.oocSeq a.areaLogs = carry.areaLogs a.areaLogOrder = carry.areaLogOrder diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index 8dcc08e0..132fed92 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -451,6 +451,7 @@ func (a *App) routeBackgroundEvent(t *courtTab, ev courtroom.Event) { } s.oocLog = appendCapped(s.oocLog, line, icLogCap) s.oocSpeakers = appendCapped(s.oocSpeakers, ev.Name, icLogCap) // parallel: for name colours + s.oocFromServer = appendCapped(s.oocFromServer, ev.FromServer, icLogCap) s.oocSeq++ a.logDetailedOOC(s.serverName, s.logSession, line) // detailed transcript (opt-in), the PARKED tab's own file // OOC doesn't bump unread by default because servers post auto-messages there. Opt in through Settings. @@ -466,6 +467,7 @@ func (a *App) routeBackgroundEvent(t *courtTab, ev courtroom.Event) { modcallLine := "[MOD CALL] " + ev.Text s.oocLog = appendCapped(s.oocLog, modcallLine, icLogCap) s.oocSpeakers = appendCapped(s.oocSpeakers, "", icLogCap) // system line — no name tint + s.oocFromServer = appendCapped(s.oocFromServer, false, icLogCap) s.oocSeq++ a.logDetailedOOC(s.serverName, s.logSession, modcallLine) // detailed transcript (opt-in), the PARKED tab's own file t.unread++ @@ -494,6 +496,7 @@ func (a *App) routeBackgroundEvent(t *courtTab, ev courtroom.Event) { disconnectLine := "SERVER: disconnected: " + ev.Text s.oocLog = appendCapped(s.oocLog, disconnectLine, icLogCap) s.oocSpeakers = appendCapped(s.oocSpeakers, "", icLogCap) // system line + s.oocFromServer = appendCapped(s.oocFromServer, false, icLogCap) s.oocSeq++ a.logDetailedOOC(s.serverName, s.logSession, disconnectLine) // detailed transcript (opt-in), the PARKED tab's own file } diff --git a/internal/ui/themefonts.go b/internal/ui/themefonts.go index 271f1a1f..0955e7dc 100644 --- a/internal/ui/themefonts.go +++ b/internal/ui/themefonts.go @@ -79,8 +79,24 @@ func (f themeElemFont) faceIdx() int { return f.face - 1 } // time. type themeFontTable struct { e [themeFontElemCount]themeElemFont + // senderInk is the OOC log's name ink per sender, from oocSenderKeys; senderInkSet false keeps the client's. + senderInk [oocSenderCount]sdl.Color + senderInkSet [oocSenderCount]bool } +// oocSender is who sent an OOC line, as CT's third field says. +type oocSender uint8 + +const ( + oocFromPlayer oocSender = iota + oocFromServer + oocSenderCount +) + +// oocSenderKeys are the courtroom_fonts.ini keys, less "_color", AO2 colours each sender's name with +// (courtroom.cpp:1921-1932). +var oocSenderKeys = [oocSenderCount]string{oocFromPlayer: "ms_chatlog_sender", oocFromServer: "server_chatlog_sender"} + // themeFaceCap bounds the distinct theme-declared face files held at once. Real themes reuse one or two families, so 4 // (matching fontChainCap) is enough; past it an element keeps the client font (hard rule 4). const themeFaceCap = 4 @@ -260,6 +276,9 @@ func (res *themeApply) buildThemeFontTable(t *theme.Theme, sysDirs []string) { slot.color, slot.colorSet = declaredFontInk(spec) } } + for s, key := range oocSenderKeys { + res.fontTable.senderInk[s], res.fontTable.senderInkSet[s] = declaredFontInk(t.Font(key)) + } } // themeSidecarFontDir is where a native theme's own font files live, relative to the theme folder: AO2's fonts/ diff --git a/internal/ui/themeink.go b/internal/ui/themeink.go index f7b64794..38e34d46 100644 --- a/internal/ui/themeink.go +++ b/internal/ui/themeink.go @@ -108,6 +108,17 @@ func guardThemeInk(res *themeApply, tbl *themeFontTable) { f.colorSet = false dropped = append(dropped, fmt.Sprintf("%s (on luma %d)", theme.FontElements[el], back)) } + // The sender names draw on the OOC log, so they are measured against its backdrop. + back := colLuma(ColPanel) + if res.backdropSampled[elemServerChatlog] { + back = res.backdropLuma[elemServerChatlog] + } + for s, set := range tbl.senderInkSet { + if set && absInt(colLuma(tbl.senderInk[s])-back) < minInkSkinContrast { + tbl.senderInkSet[s] = false + dropped = append(dropped, fmt.Sprintf("%s (on luma %d)", oocSenderKeys[s], back)) + } + } if len(dropped) == 0 { return } diff --git a/internal/ui/translogooc_test.go b/internal/ui/translogooc_test.go index 6ffc8ed8..2765929c 100644 --- a/internal/ui/translogooc_test.go +++ b/internal/ui/translogooc_test.go @@ -33,7 +33,7 @@ func TestOOCLogRespectsDetailedLogPref(t *testing.T) { }) a.serverName = "Skrapegropen-ooc-pref-off" - a.pushOOC("Nyah: should not be logged", "Nyah") + a.pushOOC("Nyah: should not be logged", "Nyah", false) if n := len(a.translogs); n != 0 { t.Errorf("pushOOC opened %d transcript writer(s) with detailed logging OFF — it must stay a no-op", n) @@ -104,7 +104,7 @@ func TestPushOOCSuppressedRosterBurstNeverReachesDisk(t *testing.T) { } beforeOOC := len(a.oocLog) - a.pushOOC("5 players online", "") // looksLikeAreaList == true + a.pushOOC("5 players online", "", false) // looksLikeAreaList == true if len(a.oocLog) != beforeOOC { t.Fatal("setup broken: the roster burst reached the on-screen OOC log, so it wasn't actually suppressed") } @@ -158,7 +158,7 @@ func TestTwoTabsOOCLogsGoToSeparateFiles(t *testing.T) { t.Fatal("opening tab one's transcript writer created no new file") } - a.pushOOC("Nyah: hello from tab one", "Nyah") + a.pushOOC("Nyah: hello from tab one", "Nyah", false) // Park tab one, bring up tab two on the SAME server. a.tabs = append(a.tabs, &courtTab{}) @@ -178,7 +178,7 @@ func TestTwoTabsOOCLogsGoToSeparateFiles(t *testing.T) { t.Fatalf("both tabs resolved to the SAME file %q — this is the reported defect", tab1File) } - a.pushOOC("Nyah: hello from tab two", "Nyah") + a.pushOOC("Nyah: hello from tab two", "Nyah", false) // The exact bug class reported: tab one, now BACKGROUNDED, logs OOC of its own. // It must land in tab1File (its own log), not tab2File (the now-active tab's). diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index 679fd8b3..d645ff7f 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -527,7 +527,7 @@ func TestWrapToWidthMOTD(t *testing.T) { func TestOOCWrapURLFullLink(t *testing.T) { a := testTabApp(t) const url = "https://cdn.discordapp.com/attachments/151/151/asyncao-windows-x86_64.zip?ex=6a31e0a4&is=6a308f24&hm=335a54ec&" - a.pushOOC("Nyah: "+url, "Nyah") + a.pushOOC("Nyah: "+url, "Nyah", false) // A narrow column (15 chars at the 8 px/char headless metric) forces the // URL to hard-split across several display rows. @@ -574,7 +574,7 @@ func TestOOCWrapURLPerParagraph(t *testing.T) { a := testTabApp(t) const u1 = "https://github.com/SyntaxNyah/Nyathena" const u2 = "https://github.com/MangosArentLiterature/Athena" - a.pushOOC("Server: Fork:\n"+u1+"\nUpstream:\n"+u2, "Server") + a.pushOOC("Server: Fork:\n"+u1+"\nUpstream:\n"+u2, "Server", false) lines := a.oocWrapped(800) // wide enough that each URL fits one row if len(a.oocWrapLinkAt) != len(lines)+1 { diff --git a/internal/ui/wholescreenalloc_test.go b/internal/ui/wholescreenalloc_test.go index 6f703d3f..921f095a 100644 --- a/internal/ui/wholescreenalloc_test.go +++ b/internal/ui/wholescreenalloc_test.go @@ -130,8 +130,8 @@ func stageSettledCourtroom(t testing.TB) (*App, func()) { // for a fresh install — but with an empty OOC log its per-line raster loop // never runs and the gate would silently stop measuring the panel that just // became default. ASCII only, same reasoning as the IC lines above. - a.pushOOC("Judge: welcome to the courtroom", "Judge") - a.pushOOC("Witch: an ooc line for the raster", "Witch") + a.pushOOC("Judge: welcome to the courtroom", "Judge", false) + a.pushOOC("Witch: an ooc line for the raster", "Witch", false) return a, func() { store.Purge() From d5472a29442d3aca35299ab886342fde1affa392 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:31:43 +0100 Subject: [PATCH 23/43] ui: hide the emote page arrows where they can't move (#61) AO2 hides emote_left on the first page and emote_right on the last (emotes.cpp:110-147). Both the themed grid and the classic "<"/">" drew them always, as buttons that did nothing at the ends. Co-Authored-By: Claude Opus 5.5 --- internal/ui/emotearrows_test.go | 71 +++++++++++++++++++++++++++++++++ internal/ui/screensemote.go | 7 ++-- internal/ui/theme_layout.go | 11 ++--- 3 files changed, 81 insertions(+), 8 deletions(-) create mode 100644 internal/ui/emotearrows_test.go diff --git a/internal/ui/emotearrows_test.go b/internal/ui/emotearrows_test.go new file mode 100644 index 00000000..9e79a91f --- /dev/null +++ b/internal/ui/emotearrows_test.go @@ -0,0 +1,71 @@ +package ui + +import ( + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/config" + "github.com/SyntaxNyah/AsyncAO/internal/courtroom" + "github.com/SyntaxNyah/AsyncAO/internal/render" + "github.com/SyntaxNyah/AsyncAO/internal/sdl" +) + +// Issue #61: the page arrows show only where they can move, as AO2's emote_left and emote_right (emotes.cpp:110-147). +func TestEmotePageArrowsHideAtTheEnds(t *testing.T) { + const ( + targetW, targetH = int32(480), int32(240) + emoteCount = 60 + nextArrowX = int32(34) + inset = int32(3) + // gapX is between ">" (ending at 64) and the page counter (from 72), where nothing draws. + gapX = int32(67) + ) + ren, cleanup := newCaptureHarness(t) + defer cleanup() + ctx, err := NewCtx(ren) + if err != nil { + t.Skipf("Ctx unavailable: %v", err) + } + ct, err := render.NewCaptureTarget(ren, targetW, targetH) + if err != nil { + t.Skipf("capture target unavailable: %v", err) + } + defer ct.Close() + + a := testTabApp(t) + a.ctx = ctx + a.d.Prefs.Update(func(sn *config.Settings) { sn.EmoteButtonImages = false }) // text cells need no texture store + a.emotes = make([]courtroom.Emote, emoteCount) + for i := range a.emotes { + a.emotes[i].Comment = "emote" + } + ctx.mouseX, ctx.mouseY = -targetW, -targetH + grid := sdl.Rect{W: targetW, H: targetH} + arrowY := grid.Y + grid.H - btnH + + drawn := func(x int32) bool { + frame, err := ct.Capture(ren, func(sdl.Rect) { a.drawEmoteRow(grid, grid) }) + if err != nil { + t.Skipf("offscreen capture unavailable headlessly: %v", err) + } + return frame.RGBAAt(int(x+inset), int(arrowY+inset)) != frame.RGBAAt(int(grid.X+gapX), int(arrowY+inset)) + } + if !a.emoteGridScrolls() { + _ = drawn(0) // the first draw stamps the grid metrics + } + if !a.emoteGridScrolls() { + t.Fatal("fixture must need more than one page") + } + if drawn(grid.X) { + t.Error("\"<\" shows on the first page, where it can't move") + } + if !drawn(grid.X + nextArrowX) { + t.Error("\">\" is missing on the first page") + } + a.scrollEmoteRows(emoteCount) + if !drawn(grid.X) { + t.Error("\"<\" is missing on the last page") + } + if drawn(grid.X + nextArrowX) { + t.Error("\">\" shows on the last page, where it can't move") + } +} diff --git a/internal/ui/screensemote.go b/internal/ui/screensemote.go index 2d777207..e5cf7346 100644 --- a/internal/ui/screensemote.go +++ b/internal/ui/screensemote.go @@ -161,13 +161,14 @@ func (a *App) drawEmoteRow(r sdl.Rect, vp sdl.Rect) { c.Label(r.X, r.Y+4, "No favourite emotes yet — turn off ★ Favs, then click the ★ on an emote.", ColTextDim) } - // "<" and ">" move a whole page; the per-row step belongs to the wheel. + // "<" and ">" move a whole page, and show only where they can, as AO2's emote arrows (emotes.cpp:110-147); the per-row + // step belongs to the wheel. if a.emoteGridScrolls() { cy := r.Y + r.H - btnH - if c.Button(sdl.Rect{X: r.X, Y: cy, W: 30, H: btnH}, "<") && a.emoteCanScrollUp() { + if a.emoteCanScrollUp() && c.Button(sdl.Rect{X: r.X, Y: cy, W: 30, H: btnH}, "<") { a.scrollEmotePages(-1) } - if c.Button(sdl.Rect{X: r.X + 34, Y: cy, W: 30, H: btnH}, ">") && a.emoteCanScrollDown() { + if a.emoteCanScrollDown() && c.Button(sdl.Rect{X: r.X + 34, Y: cy, W: 30, H: btnH}, ">") { a.scrollEmotePages(1) } c.Label(r.X+72, cy+6, a.emotePageCounter(a.emotePageShown(), a.emotePagesShown(), len(vis)), ColTextDim) diff --git a/internal/ui/theme_layout.go b/internal/ui/theme_layout.go index 78bd17b4..e173f75e 100644 --- a/internal/ui/theme_layout.go +++ b/internal/ui/theme_layout.go @@ -1313,15 +1313,16 @@ func (a *App) drawEmoteGridThemed(r sdl.Rect, lay *themeLayoutCache, vp sdl.Rect c.Label(r.X, r.Y+4, "No favourite emotes — turn off \"favourites only\" in Settings, then click an emote's ★.", ColTextDim) } - // AO2's emote_left / emote_right step pages (courtroom.cpp on_emote_left_clicked); only the wheel is per-row. + // AO2's emote_left / emote_right step pages (courtroom.cpp on_emote_left_clicked) and are hidden where they can't + // (emotes.cpp:110-147); only the wheel is per-row. if a.emoteGridScrolls() { - if lr, ok := lay.rect("emote_left"); ok { - if a.drawThemeButton("emote_left", "<", lr) && a.emoteCanScrollUp() { + if lr, ok := lay.rect("emote_left"); ok && a.emoteCanScrollUp() { + if a.drawThemeButton("emote_left", "<", lr) { a.scrollEmotePages(-1) } } - if rr, ok := lay.rect("emote_right"); ok { - if a.drawThemeButton("emote_right", ">", rr) && a.emoteCanScrollDown() { + if rr, ok := lay.rect("emote_right"); ok && a.emoteCanScrollDown() { + if a.drawThemeButton("emote_right", ">", rr) { a.scrollEmotePages(1) } } From e80cb6fcf53244995c7ff959aa71502301647ee5 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:47:22 +0100 Subject: [PATCH 24/43] media: parse learned.json's byte fields at 8 bits readWinner read every number with strconv.Atoi and range-checked the byte-sized ones through an array before converting them to uint8, which CodeQL can't follow (go/incorrect-integer-conversion, 4 alerts on PR #146). Place, Kind, Class and Tag now parse with strconv.ParseUint at 8 bits, so a value past 255 fails the parse and the line is skipped. A negative size or an out-of-range tag joins the damaged-line test. Co-Authored-By: Claude Opus 5.5 --- internal/media/learned.go | 24 ++++++++++++++---------- internal/media/learned_test.go | 3 ++- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/internal/media/learned.go b/internal/media/learned.go index bd6010bd..d58e2df0 100644 --- a/internal/media/learned.go +++ b/internal/media/learned.go @@ -8,7 +8,6 @@ import ( "fmt" "io" "maps" - "math" "slices" "strconv" "strings" @@ -40,6 +39,9 @@ const ( const ( winnerSep = "\t" + // decimal and byteBits parse a line's byte-sized numbers. + decimal = 10 + byteBits = 8 // pathUnder: the path is stored after its host's prefix; pathOfOrigin: the key's Origin is the host, path as is; // pathWhole: stored whole. pathUnder = "0" @@ -162,20 +164,22 @@ func readWinner(group, line string) (Key, File, bool) { if len(parts) != winnerFields { return Key{}, "", false } - var nums [fieldHow]int - for i := range nums { - n, err := strconv.Atoi(parts[i]) - if err != nil || n < 0 { + // The byte fields parse at 8 bits, so a value past 255 fails here rather than wrapping in a conversion. + var small [fieldSize]uint8 + for _, i := range []int{fieldPlace, fieldKind, fieldClass} { + n, err := strconv.ParseUint(parts[i], decimal, byteBits) + if err != nil { return Key{}, "", false } - nums[i] = n + small[i] = uint8(n) } - if nums[fieldPlace] > math.MaxUint8 || nums[fieldKind] > math.MaxUint8 || nums[fieldClass] > int(ClassBlips) || - nums[fieldTag] > math.MaxUint8 { + tag, err := strconv.ParseUint(parts[fieldTag], decimal, byteBits) + size, sizeErr := strconv.Atoi(parts[fieldSize]) + if err != nil || sizeErr != nil || size < 0 || Class(small[fieldClass]) > ClassBlips { return Key{}, "", false } - k := Key{Place: Place(nums[fieldPlace]), Kind: Kind(nums[fieldKind]), Class: Class(nums[fieldClass]), - Size: nums[fieldSize], Tag: uint8(nums[fieldTag])} + k := Key{Place: Place(small[fieldPlace]), Kind: Kind(small[fieldKind]), Class: Class(small[fieldClass]), + Size: size, Tag: uint8(tag)} path, file := parts[fieldPath], parts[fieldFile] switch parts[fieldHow] { case pathUnder: diff --git a/internal/media/learned_test.go b/internal/media/learned_test.go index d4407e5b..29d8feb3 100644 --- a/internal/media/learned_test.go +++ b/internal/media/learned_test.go @@ -93,7 +93,8 @@ func TestRecallIgnoresAnotherVersionAndDamage(t *testing.T) { }}.Memory()) Recall(r.m, r.builder, Learned{Version: LearnedVersion, Hosts: map[string]*LearnedHost{ testOrigin: {Formats: map[Class]map[string]int{ClassEmote: {".exe": 1}}, - Winners: []string{"short", "0\t0\t99\t0\t0\t0\ta\t+.png", "0\t0\t2\t0\t0\t9\ta\t+.png"}}, + Winners: []string{"short", "0\t0\t99\t0\t0\t0\ta\t+.png", "0\t0\t2\t0\t0\t9\ta\t+.png", + "0\t0\t2\t0\t256\t0\ta\t+.png", "0\t0\t2\t-1\t0\t0\ta\t+.png"}}, "nil.test": nil, }}.Memory()) }) From 4622c6bbf9d6b78e6b481c05ed207d2baf058fde Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:49:29 +0100 Subject: [PATCH 25/43] ci: drop the alloc gate for the removed resolver benchmark BenchmarkBuildCandidates_Learned went with the old resolver (9efae11f), so check-bench.sh failed on "no result" in the Linux tests job. The cache-hit and render-frame gates stay. Co-Authored-By: Claude Opus 5.5 --- scripts/check-bench.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/check-bench.sh b/scripts/check-bench.sh index 5d7460bd..cb586c0f 100644 --- a/scripts/check-bench.sh +++ b/scripts/check-bench.sh @@ -18,7 +18,6 @@ check() { # benchmark max-allocs fi } -check BenchmarkBuildCandidates_Learned 1 check BenchmarkCacheHit_T1 0 check BenchmarkCacheHit_T2 0 check BenchmarkRenderFrame 0 From e9cadd97ad37fe56b4c4d1427e5d9080f823a4cb Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:08:38 +0100 Subject: [PATCH 26/43] media: one folder-listing parser, which knows a listing from an index page The background and evidence pickers parsed host folder listings in ui; the parser moves to media for character mapping, and the pickers use it from there. ParseListing also reports whether the page is a listing at all: it must link to its parent folder ("../" on nginx and Caddy, "Parent Directory" on Apache), so an index page or a soft 404 never reads as an empty folder. Co-Authored-By: Claude Opus 5.5 --- internal/media/listing.go | 69 +++++++++++++++++++++++++++++++++ internal/media/listing_test.go | 53 +++++++++++++++++++++++++ internal/ui/bgpicker.go | 66 ++----------------------------- internal/ui/evidserverpicker.go | 7 ++-- internal/ui/ui_test.go | 32 +-------------- 5 files changed, 131 insertions(+), 96 deletions(-) create mode 100644 internal/media/listing.go create mode 100644 internal/media/listing_test.go diff --git a/internal/media/listing.go b/internal/media/listing.go new file mode 100644 index 00000000..128d487a --- /dev/null +++ b/internal/media/listing.go @@ -0,0 +1,69 @@ +package media + +import ( + "net/url" + "regexp" + "strings" +) + +// ListingEntry is one link in a host's HTML folder listing (Apache, nginx or Caddy autoindex). +type ListingEntry struct { + // Href is the link as written, still escaped; a folder keeps its trailing slash. + Href string + // Name is the decoded file or folder name. + Name string + Dir bool +} + +// listingHref captures href targets; [^"?#] drops Apache's ?C=N;O=A sort links. +var listingHref = regexp.MustCompile(`(?i)href="([^"?#]+)"`) + +// listingParent finds the link to the parent folder every autoindex page has: "../" on nginx and Caddy, "Parent +// Directory" on Apache, whose href is absolute. +var listingParent = regexp.MustCompile(`(?i)href="(\./)?\.\./?"|>\s*Parent Directory\s*<`) + +// ParseListing returns up to limit unique entries one level below the folder, and whether data is a folder listing at +// all: an index page or a soft 404 has no parent link, and must never read as an empty folder. +func ParseListing(data []byte, limit int) (entries []ListingEntry, ok bool) { + if !listingParent.Match(data) { + return nil, false + } + seen := make(map[string]struct{}) + for _, m := range listingHref.FindAllSubmatch(data, -1) { + e, ok := cleanListingEntry(string(m[1])) + if !ok { + continue + } + key := strings.ToLower(e.Name) + if e.Dir { + key += "/" + } + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + entries = append(entries, e) + if len(entries) >= limit { + break + } + } + return entries, true +} + +// cleanListingEntry normalizes one href and reports whether it is one level deep and stays in the folder. It is the +// listing's security boundary: ../, ./, /x, x://, a/b and any raw or percent-encoded ".." are refused. +func cleanListingEntry(raw string) (ListingEntry, bool) { + if raw == "" || strings.HasPrefix(raw, "/") || strings.Contains(raw, "://") { + return ListingEntry{}, false + } + dir := strings.HasSuffix(raw, "/") + name := strings.TrimSuffix(raw, "/") + if dec, err := url.PathUnescape(name); err == nil { + name = dec + } + name = strings.TrimSpace(name) + if name == "" || name == "." || name == ".." || strings.Contains(name, "..") || strings.ContainsAny(name, `/\`) { + return ListingEntry{}, false + } + return ListingEntry{Href: raw, Name: name, Dir: dir}, true +} diff --git a/internal/media/listing_test.go b/internal/media/listing_test.go new file mode 100644 index 00000000..f0c410f1 --- /dev/null +++ b/internal/media/listing_test.go @@ -0,0 +1,53 @@ +package media + +import "testing" + +// cleanListingEntry is the listing's security boundary: parent, self, absolute, external, nested and ".." links, raw or +// percent-encoded, are all refused. +func TestCleanListingEntry(t *testing.T) { + reject := []string{ + "../", "./", "..", "%2e%2e/", "%2e%2e%2f", "a/..%2f", + "/abs/", "/etc/passwd", + "https://evil.example/x/", "http://x/y", + "a/b", "a/b/", `a\b`, + "", "%2e%2e", + } + for _, raw := range reject { + if e, ok := cleanListingEntry(raw); ok { + t.Errorf("cleanListingEntry(%q) accepted as %+v", raw, e) + } + } + accept := map[string]ListingEntry{ + "maya/": {Href: "maya/", Name: "maya", Dir: true}, + "char_icon.png": {Href: "char_icon.png", Name: "char_icon.png"}, + "my%20court/": {Href: "my%20court/", Name: "my court", Dir: true}, + } + for raw, want := range accept { + if got, ok := cleanListingEntry(raw); !ok || got != want { + t.Errorf("cleanListingEntry(%q) = %+v, %v; want %+v", raw, got, ok, want) + } + } +} + +// Only a page that links to its parent folder is a listing, so an index page or soft 404 never reads as empty. +func TestParseListingNeedsAParentLink(t *testing.T) { + const limit = 10 + for name, page := range map[string]string{ + "nginx": `
../normal.png
`, + "apache": `Parent Directory normal.png`, + "caddy": `Upnormal.pngx`, + } { + if _, ok := ParseListing([]byte(page), limit); !ok { + t.Errorf("%s listing not recognised", name) + } + } + for name, page := range map[string]string{ + "index page": `normal.png`, + "error page": `

403 Forbidden

`, + "empty": ``, + } { + if entries, ok := ParseListing([]byte(page), limit); ok { + t.Errorf("%s read as a listing: %+v", name, entries) + } + } +} diff --git a/internal/ui/bgpicker.go b/internal/ui/bgpicker.go index 3332f00b..02ca8894 100644 --- a/internal/ui/bgpicker.go +++ b/internal/ui/bgpicker.go @@ -7,14 +7,13 @@ package ui import ( "context" "fmt" - "net/url" - "regexp" "sort" "strings" "time" "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/network" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" @@ -385,70 +384,13 @@ func (a *App) drawBgCell(idx int, cell sdl.Rect, budget *int64) { } } -// autoindexEntry is one parsed directory-listing link. -type autoindexEntry struct { - href string // raw URL segment from the listing (already escaped; dirs keep the trailing /) - name string // decoded display / filesystem name - dir bool // trailing slash in the listing -} - -// autoindexHref captures href targets from an HTML directory listing; [^"?#] drops Apache's ?C=N;O=A sort links. -var autoindexHref = regexp.MustCompile(`(?i)href="([^"?#]+)"`) - -// cleanAutoindexEntry normalizes one raw href into an entry and reports whether it is usable, one level deep and -// non-escaping. It is the security boundary for the listing: ../, ./, /x, x://, a/b and any raw or percent-encoded -// ".." are rejected. -func cleanAutoindexEntry(raw string) (autoindexEntry, bool) { - if raw == "" || strings.HasPrefix(raw, "/") || strings.Contains(raw, "://") { - return autoindexEntry{}, false - } - dir := strings.HasSuffix(raw, "/") - name := strings.TrimSuffix(raw, "/") - if dec, err := url.PathUnescape(name); err == nil { - name = dec - } - name = strings.TrimSpace(name) - if name == "" || name == "." || name == ".." || strings.Contains(name, "..") { - return autoindexEntry{}, false - } - if strings.ContainsAny(name, `/\`) { // one level deep only - return autoindexEntry{}, false - } - return autoindexEntry{href: raw, name: name, dir: dir}, true -} - -// parseAutoindexEntries returns up to limit unique files and dirs; a non-autoindex response yields nothing. -func parseAutoindexEntries(data []byte, limit int) []autoindexEntry { - out := make([]autoindexEntry, 0) - seen := make(map[string]struct{}) - for _, m := range autoindexHref.FindAllSubmatch(data, -1) { - e, ok := cleanAutoindexEntry(string(m[1])) - if !ok { - continue - } - key := strings.ToLower(e.name) - if e.dir { - key += "/" - } - if _, dup := seen[key]; dup { - continue - } - seen[key] = struct{}{} - out = append(out, e) - if len(out) >= limit { - break - } - } - return out -} - // parseAutoindexDirs is the picker's discovery list: sorted, de-duplicated folder names from a listing. func parseAutoindexDirs(data []byte) []string { - entries := parseAutoindexEntries(data, bgListCap) + entries, _ := media.ParseListing(data, bgListCap) names := make([]string, 0, len(entries)) for _, e := range entries { - if e.dir { - names = append(names, e.name) + if e.Dir { + names = append(names, e.Name) } } sort.SliceStable(names, func(i, j int) bool { diff --git a/internal/ui/evidserverpicker.go b/internal/ui/evidserverpicker.go index 74ebc646..34711e88 100644 --- a/internal/ui/evidserverpicker.go +++ b/internal/ui/evidserverpicker.go @@ -11,6 +11,7 @@ import ( "time" "github.com/SyntaxNyah/AsyncAO/internal/assets" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/network" "github.com/SyntaxNyah/AsyncAO/internal/sdl" ) @@ -68,13 +69,13 @@ func (a *App) fetchServerEvidenceIndex() { a.evidServerRes <- nil return } - entries := parseAutoindexEntries(data, evidServerCap) + entries, _ := media.ParseListing(data, evidServerCap) var out []string for _, e := range entries { - if e.dir { + if e.Dir { continue // only image files, not nested folders } - out = append(out, e.name) + out = append(out, e.Name) } sort.SliceStable(out, func(i, j int) bool { return strings.ToLower(out[i]) < strings.ToLower(out[j]) }) a.evidServerRes <- out diff --git a/internal/ui/ui_test.go b/internal/ui/ui_test.go index d645ff7f..6a32dd83 100644 --- a/internal/ui/ui_test.go +++ b/internal/ui/ui_test.go @@ -85,7 +85,7 @@ func TestParseAutoindexDirs(t *testing.T) { } // Cap holds against a hostile listing. - var huge []byte + huge := []byte(`../`) for i := 0; i < bgListCap+500; i++ { huge = append(huge, []byte(fmt.Sprintf(`x`+"\n", i))...) } @@ -94,36 +94,6 @@ func TestParseAutoindexDirs(t *testing.T) { } } -// TestCleanAutoindexEntry pins the autoindex listing's security boundary: parent, -// self, absolute, external, nested and ".." links (raw OR percent-encoded) -// are all rejected, so a hostile listing can never write outside the dest. -func TestCleanAutoindexEntry(t *testing.T) { - reject := []string{ - "../", "./", "..", "%2e%2e/", "%2e%2e%2f", "a/..%2f", // traversal - "/abs/", "/etc/passwd", // absolute - "https://evil.example/x/", "http://x/y", // external - "a/b", "a/b/", `a\b`, // nested / separators - "", "%2e%2e", // empty / bare encoded .. - } - for _, raw := range reject { - if e, ok := cleanAutoindexEntry(raw); ok { - t.Errorf("cleanAutoindexEntry(%q) accepted as %+v, want rejected", raw, e) - } - } - - accept := map[string]autoindexEntry{ - "maya/": {href: "maya/", name: "maya", dir: true}, - "char_icon.png": {href: "char_icon.png", name: "char_icon.png", dir: false}, - "my%20court/": {href: "my%20court/", name: "my court", dir: true}, - } - for raw, want := range accept { - got, ok := cleanAutoindexEntry(raw) - if !ok || got != want { - t.Errorf("cleanAutoindexEntry(%q) = %+v, %v; want %+v, true", raw, got, ok, want) - } - } -} - // TestSelectAllChordArms pins Ctrl+A semantics: the chord arms a pending // select-all that survives BeginFrame until a field consumes it (typing // replaces the whole value, backspace clears it — handled in TextField). From 63dc7f4288ba33ca5d17b022394e6af050c1aec8 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:08:38 +0100 Subject: [PATCH 27/43] media, assets: map a character's folders so missing files cost no request On a host without extensions.json most cold requests were misses: every bare-named sprite was first asked as "(a)X" in all six formats. The first sprite or emote button asked of a character now lists its folder in the background, five deep and at most 128 listings, on its origin and each extra host. RemoteSource answers a file its folder's listing leaves out, or a folder its parent's listing leaves out, as absent with no request; names match whatever their case, as a case-insensitive host serves any. Only a real listing is trusted. A 404 folder proves nothing; a 403, or a page with no parent link, keeps the host on the per-file search for the session. Character-select icons never trigger a walk, so a roster isn't mapped. Maps are kept in learned.json (512 most recent, folder listings shared rather than copied on the media goroutine) and walked again on use after seven days; Retry missing drops them. Measured on the headless scenario (60 sprites, half bare-named, 30 ms a request): a cold session went from 241 requests in 7.4 s to 121 plus 20 listings in 3.7 s, and new characters on a known host likewise. Co-Authored-By: Claude Opus 5.5 --- docs/RESTRUCTURING_PLAN.md | 11 +- internal/assets/charmap_test.go | 44 +++++ internal/assets/manager_test.go | 7 +- internal/assets/mediabridge.go | 16 +- internal/media/charmap.go | 294 ++++++++++++++++++++++++++++++++ internal/media/charmap_test.go | 218 +++++++++++++++++++++++ internal/media/learned.go | 34 +++- internal/media/learned_test.go | 22 +-- internal/media/sources.go | 16 +- 9 files changed, 636 insertions(+), 26 deletions(-) create mode 100644 internal/assets/charmap_test.go create mode 100644 internal/media/charmap.go create mode 100644 internal/media/charmap_test.go diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index 05b0ba82..8b51f847 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -101,7 +101,12 @@ in **Status**. Update Status in the same commit that completes a step. `internal/saver`; the disk index is not saved, and the disk is asked until its startup scan lands; 404s are never saved. The old resolver, `prefs.LearnedFormats`, the Formats tab and every format override setting are gone; archive, export and replay use the media table - - [ ] sources still to build: character mapping + - [x] character mapping (2026-11-15): the first sprite asked of a character lists its folder, five deep, on the + origin and each extra host, so a file the listings leave out is answered absent with no request. Only a real + listing (one with a parent link) is trusted; a host that gives none keeps the per-file search for the + session. Maps are kept in `learned.json` and walked again after seven days or on Retry missing. Measured on a + host with no `extensions.json`, half the sprites bare-named: a cold session went from 241 requests to 121 + plus 20 listings, 7.4 s to 3.7 s at 30 ms a request - [x] extra asset hosts per server: the user adds them in a fixed order with no speed ranking, the ASS packet's host is always first; Settings → Assets edits them. Raw fetch paths not on the media system yet don't ask them - [x] the client runs on it: `assets.Manager`'s requests go through `internal/media`, so callers and `Pump` are unchanged, and @@ -127,8 +132,8 @@ in **Status**. Update Status in the same commit that completes a step. Settings → Check folders now end every folder check's trust. The old pipeline (network pool, mount index and layer, conclusive-miss set, Local-only mode in the Manager) and `-old-media` are deleted, and with them the wait gate's refusal re-ask: high-priority requests are never refused - - [ ] known problems from the benchmark: on a host with no `extensions.json`, 200 missing sprites cost 2,400 requests against the - old 1,600 until character mapping exists; peak heap with files asked for every frame is 384-617 MiB, unexplained + - [ ] known problem from the benchmark: peak heap with files asked for every frame is 384-617 MiB, unexplained (the + request count on hosts with no `extensions.json` is answered by character mapping above) - [ ] move callers: courtroom, then screens, theme and audio; `Pump` on `TakeResults`; music streaming - [ ] off-thread texture preparation: waits for the renderer overhaul (decided 2026-11-02). See below - [x] a sprite sometimes shows its old animation for a frame before the right one (reported 2026-11-01): the wait gate diff --git a/internal/assets/charmap_test.go b/internal/assets/charmap_test.go new file mode 100644 index 00000000..db894f83 --- /dev/null +++ b/internal/assets/charmap_test.go @@ -0,0 +1,44 @@ +package assets + +import ( + "image/color" + "testing" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/media" + "github.com/SyntaxNyah/AsyncAO/internal/netproxy" + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +// Once a character's folder is mapped, a sprite named only "X" costs one request, not the misses for "(a)X". +func TestMappedCharacterSkipsMissingSpellings(t *testing.T) { + const side = 4 + png := encodePNG(t, side, side, color.White) + cs := newCountingServer(t, map[string][]byte{ + "/characters/c/": []byte(`
../xx
`), + "/characters/c/first.png": png, + "/characters/c/second.png": png, + }) + rig := newRig(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false) + ask := func(name string) { + t.Helper() + base := cs.srv.URL + "/characters/c/" + rig.manager.PrefetchChain(base+"(a)"+name, []string{base + name}, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + waitDecoded(t, rig.manager).Asset.Release() + } + ask("first") + root := media.File(cs.srv.URL + "/characters/c/") + deadline := time.Now().Add(managerWait) + for mapped := false; !mapped; { + rig.manager.bridge.media.Call(func() { mapped = rig.manager.bridge.remote.Mapped(root) }) + if time.Now().After(deadline) { + t.Fatal("the character was never mapped") + } + time.Sleep(time.Millisecond) + } + before := cs.total() + ask("second") + if n := cs.total() - before; n != 1 { + t.Errorf("a mapped character's bare-named sprite cost %d requests, want 1", n) + } +} diff --git a/internal/assets/manager_test.go b/internal/assets/manager_test.go index 59b2387a..fcc27c85 100644 --- a/internal/assets/manager_test.go +++ b/internal/assets/manager_test.go @@ -147,12 +147,15 @@ func newCountingServer(t *testing.T, payloads map[string][]byte) *countingServer return cs } +// total counts requests for files; a character folder's listing is mapping's, not a probe for an asset. func (cs *countingServer) total() int { cs.mu.Lock() defer cs.mu.Unlock() n := 0 - for _, c := range cs.requests { - n += c + for path, c := range cs.requests { + if !strings.HasSuffix(path, "/") { + n += c + } } return n } diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index 8946c225..b466c655 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -165,7 +165,7 @@ func (b *mediaBridge) recallLearned() { } return l.Memory() }, func(v any) { - media.Recall(b.media, b.builder, v.(media.Memory)) + media.Recall(b.media, b.builder, b.remote, v.(media.Memory)) b.recalled = true b.learnedHosts.Store(int64(b.builder.LearnedOrigins())) if b.foundEarly { @@ -183,7 +183,7 @@ func (b *mediaBridge) encodeLearned() ([]byte, error) { err = errLearnedNotRecalled return } - mem = media.Remember(b.media, b.builder) + mem = media.Remember(b.media, b.builder, b.remote) }) if !ran { return nil, errMediaStopped @@ -264,9 +264,21 @@ func (b *mediaBridge) askChain(base string, alts []string, t AssetType, p networ b.m.t1Hits.Add(1) return } + b.mapCharacterOf(base, t) b.ask(chainKey(base, t), flagsOf(false, sticky), p, alts...) } +// mapCharacterOf maps the folder of a character whose sprites are asked for, so everyone who appears is mapped and a +// roster of icons is not. +func (b *mediaBridge) mapCharacterOf(base string, t AssetType) { + if t != AssetTypeCharSprite && t != AssetTypeEmoteButton || !strings.HasPrefix(base, "http") { + return + } + if root := media.CharacterRoot(base); root != "" { + b.media.Do(func() { media.MapCharacter(b.media, b.network, b.remote, b.builder, root) }) + } +} + func (b *mediaBridge) askExact(url string, t AssetType, p network.Priority) { if b.m.t1Contains != nil && b.m.t1Contains(url) { b.m.t1Hits.Add(1) diff --git a/internal/media/charmap.go b/internal/media/charmap.go new file mode 100644 index 00000000..d7211981 --- /dev/null +++ b/internal/media/charmap.go @@ -0,0 +1,294 @@ +package media + +import ( + "errors" + "net/url" + "slices" + "strings" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +// Character mapping: a character's folders are listed once, in the background, so a file the listings leave out is +// answered absent with no request. Only folders that answered with a real listing are trusted; anything else keeps the +// per-file search. + +const ( + // mapDepth bounds how far below a character's folder a walk lists (costumes, emotions, (a)/ and (b)/ nest). + mapDepth = 5 + // mapListingsCap bounds one character's listings; the largest folder measured needed 98. + mapListingsCap = 128 + // listingEntriesCap bounds the entries read from one listing. + listingEntriesCap = 4096 + // listedCap and walksCap bound the session's tables; past them a table starts over, which only costs requests. + listedCap = 1 << 15 + walksCap = 1 << 10 + // MapMaxAge is how old a character's map may be before its next use walks it again in the background. + MapMaxAge = 7 * 24 * time.Hour + // charactersDir is the folder every character lives in. + charactersDir = "/characters/" +) + +// listedFolder is what one folder's listing showed, by lowercased name, as a case-insensitive host serves any case. +type listedFolder struct { + files map[string]struct{} + dirs map[string]struct{} +} + +// walk is one character's mapping: when it finished, and what is still out. +type walk struct { + at time.Time + listings int + open int +} + +// listingResult is one listing request's answer, carried from a Network worker to the Manager's goroutine. +type listingResult struct { + data []byte + err error +} + +// folderKey is a folder or file URL decoded, so a listing's names and a request's escapes compare alike. +func folderKey(s string) string { + if dec, err := url.PathUnescape(s); err == nil { + return dec + } + return s +} + +// splitLast cuts a decoded path into its folder (with the slash) and the last name. +func splitLast(path string) (string, string) { + i := strings.LastIndexByte(path, '/') + return path[:i+1], path[i+1:] +} + +// mapAbsent reports whether a listing proves f isn't there: its folder listed without it, or its folder missing from a +// listed parent. +func (s *RemoteSource) mapAbsent(f File) bool { + dir, name := splitLast(folderKey(string(f))) + if lf := s.listed[dir]; lf != nil { + _, ok := lf.files[strings.ToLower(name)] + return !ok + } + parent, sub := splitLast(strings.TrimSuffix(dir, "/")) + if pf := s.listed[parent]; pf != nil && sub != "" { + _, ok := pf.dirs[strings.ToLower(sub)] + return !ok + } + return false +} + +// CharacterRoot is the character folder a sprite URL lives in, or "" for a URL outside characters/. +func CharacterRoot(u string) File { + i := strings.Index(u, charactersDir) + if i < 0 { + return "" + } + start := i + len(charactersDir) + end := strings.IndexByte(u[start:], '/') + if end <= 0 { + return "" + } + return File(u[:start+end+1]) +} + +// MapCharacter maps the character folder root on its origin and each extra host, unless a fresh map or a walk in +// progress already covers it; call it on the Manager's goroutine. +func MapCharacter(m *Manager, pool *Pool, s *RemoteSource, b *CandidateBuilder, root File) { + origin := b.originOf(Key{Path: string(root)}) + mapFolder(m, pool, s, root) + rel, ok := strings.CutPrefix(string(root), origin) + if !ok { + return + } + for _, host := range b.extras[origin] { + mapFolder(m, pool, s, File(host+rel)) + } +} + +// mapFolder starts root's walk; a host that answered a folder with anything but a listing is not asked again. +func mapFolder(m *Manager, pool *Pool, s *RemoteSource, root File) { + key := folderKey(string(root)) + if s.refused[hostOf(root)] { + return + } + if w := s.walks[key]; w != nil && (w.open > 0 || s.clock().Sub(w.at) < MapMaxAge) { + return + } + if len(s.walks) >= walksCap { + clear(s.walks) + } + w := &walk{} + s.walks[key] = w + s.list(m, pool, w, root, key, 0) +} + +// list asks for one folder's listing and, when it lands, lists the folders it shows. +func (s *RemoteSource) list(m *Manager, pool *Pool, w *walk, folder File, key string, depth int) { + w.listings++ + w.open++ + m.Run(pool, Later, func() any { + data, err := s.fetch.Fetch(s.ctx, string(folder)) + return listingResult{data, err} + }, func(v any) { + w.open-- + // Every path ends the walk once nothing is out, a failed listing too, or it would walk again on every use. + defer func() { + if w.open == 0 { + w.at = s.clock() + } + }() + res := v.(listingResult) + host := hostOf(folder) + switch { + case res.err == nil: + s.answered[host] = true + case errors.Is(res.err, network.ErrAssetNotFound): + s.answered[host] = true + return // no such folder: nothing is proven, so the search stays as it was + case errors.Is(res.err, network.ErrUnexpectedStatus): + s.answered[host] = true + s.refused[host] = true // 403 and the like: this host doesn't list folders + return + default: + return + } + entries, ok := ParseListing(res.data, listingEntriesCap) + if !ok { + s.refused[host] = true // an index page or soft 404 where a listing should be + return + } + lf := &listedFolder{files: map[string]struct{}{}, dirs: map[string]struct{}{}} + for _, e := range entries { + name := strings.ToLower(e.Name) + if !e.Dir { + lf.files[name] = struct{}{} + continue + } + lf.dirs[name] = struct{}{} + if depth+1 < mapDepth && w.listings < mapListingsCap { + s.list(m, pool, w, folder+File(e.Href), key+e.Name+"/", depth+1) + } + } + if len(s.listed) >= listedCap { + clear(s.listed) + } + s.listed[key] = lf + }) +} + +// Mapped reports whether root's walk has finished; call it on the Manager's goroutine. +func (s *RemoteSource) Mapped(root File) bool { + w := s.walks[folderKey(string(root))] + return w != nil && w.open == 0 && !w.at.IsZero() +} + +// forgetMaps drops the maps and listings under a decoded prefix, so the next use walks them again. +func (s *RemoteSource) forgetMaps(prefix string) { + for k := range s.listed { + if strings.HasPrefix(k, prefix) { + delete(s.listed, k) + } + } + for k := range s.walks { + if strings.HasPrefix(k, prefix) { + delete(s.walks, k) + } + } +} + +// learnedMapsCap bounds the character maps kept between sessions; the most recently walked stay. +const learnedMapsCap = 512 + +// savedMap is one character's finished map, as kept between sessions. Its folders are shared, not copied: a listing is +// never changed once recorded, only replaced. +type savedMap struct { + at time.Time + folders map[string]*listedFolder +} + +// LearnedMap is one character's map in learned.json: when it was walked, and each folder below its root (relative, +// "" for the root) with its names, a folder's ending in "/". +type LearnedMap struct { + At int64 `json:"t"` + Folders map[string][]string `json:"f"` +} + +// rememberMaps copies the finished maps; on the Manager's goroutine, and only pointers, so it is cheap. +func (s *RemoteSource) rememberMaps() map[string]savedMap { + out := map[string]savedMap{} + for key, lf := range s.listed { + root := string(CharacterRoot(key)) + w := s.walks[root] + if root == "" || w == nil || w.open > 0 || w.at.IsZero() { + continue + } + sm, ok := out[root] + if !ok { + sm = savedMap{at: w.at, folders: map[string]*listedFolder{}} + out[root] = sm + } + sm.folders[key] = lf + } + return out +} + +// recallMaps adds saved maps the session hasn't walked itself; an old one still answers until its next use walks it. +func (s *RemoteSource) recallMaps(saved map[string]savedMap) { + for root, sm := range saved { + if _, walked := s.walks[root]; walked || len(s.walks) >= walksCap { + continue + } + s.walks[root] = &walk{at: sm.at} + for key, lf := range sm.folders { + if _, ok := s.listed[key]; !ok && len(s.listed) < listedCap { + s.listed[key] = lf + } + } + } +} + +// learnedMap writes one map with its folders relative to root. +func learnedMap(root string, sm savedMap) *LearnedMap { + lm := &LearnedMap{At: sm.at.Unix(), Folders: make(map[string][]string, len(sm.folders))} + for key, lf := range sm.folders { + names := make([]string, 0, len(lf.files)+len(lf.dirs)) + for n := range lf.files { + names = append(names, n) + } + for n := range lf.dirs { + names = append(names, n+"/") + } + slices.Sort(names) + lm.Folders[strings.TrimPrefix(key, root)] = names + } + return lm +} + +// readMap rebuilds a saved map under root; false when root isn't a character folder. +func readMap(root string, lm *LearnedMap) (savedMap, bool) { + if lm == nil || CharacterRoot(root) != File(root) { + return savedMap{}, false + } + sm := savedMap{at: time.Unix(lm.At, 0), folders: map[string]*listedFolder{}} + for rel, names := range lm.Folders { + if rel != "" && !strings.HasSuffix(rel, "/") || strings.Contains(rel, "..") || len(names) > listingEntriesCap { + continue + } + lf := &listedFolder{files: map[string]struct{}{}, dirs: map[string]struct{}{}} + for _, n := range names { + name, dir := strings.CutSuffix(n, "/") + if name == "" || strings.ContainsAny(name, `/\`) || strings.Contains(name, "..") { + continue + } + if dir { + lf.dirs[strings.ToLower(name)] = struct{}{} + } else { + lf.files[strings.ToLower(name)] = struct{}{} + } + } + sm.folders[root+rel] = lf + } + return sm, true +} diff --git a/internal/media/charmap_test.go b/internal/media/charmap_test.go new file mode 100644 index 00000000..19cd8e86 --- /dev/null +++ b/internal/media/charmap_test.go @@ -0,0 +1,218 @@ +package media + +import ( + "fmt" + "slices" + "strings" + "testing" + + "github.com/SyntaxNyah/AsyncAO/internal/config" + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +const charRoot = testOrigin + "characters/c/" + +// listing is an nginx-style folder page linking each name; a name ending in "/" is a folder. +func listing(names ...string) []byte { + var b strings.Builder + b.WriteString(`
../`)
+	for _, n := range names {
+		fmt.Fprintf(&b, `%s`, n, n)
+	}
+	b.WriteString(`
`) + return []byte(b.String()) +} + +// mapAndWait maps root and waits until its walk has nothing out. +func mapAndWait(t *testing.T, r *remoteRig, root File) { + t.Helper() + r.m.Call(func() { MapCharacter(r.m, r.network, r.remote, r.builder, root) }) + waitUntil(t, func() bool { + done := false + r.m.Call(func() { done = r.remote.Mapped(root) }) + return done + }) +} + +// askedSince is what the host was asked after the first n requests. +func askedSince(r *remoteRig, n int) []string { return r.fetch.askedFor()[n:] } + +func TestMappedFolderAnswersMissingFilesWithoutRequests(t *testing.T) { + r := newRemoteRig(t, map[string][]byte{ + charRoot: listing("e.png", "emotions/"), + charRoot + "emotions/": listing("button1_off.png"), + charRoot + "e" + config.ExtPNG: []byte("x"), + }) + mapAndWait(t, r, charRoot) + before := len(r.fetch.askedFor()) + + a := r.m.Get(sprite("characters/c/(a)e"), Now, 0, "characters/c/e") + waitFinal(t, a) + if !a.Ready() { + t.Fatalf("state %d err %v", a.State(), a.Err()) + } + if got := askedSince(r, before); !slices.Equal(got, []string{charRoot + "e" + config.ExtPNG}) { + t.Errorf("asked %v, want only the listed spelling and format", got) + } + + before = len(r.fetch.askedFor()) + b := r.m.Get(sprite("characters/c/(a)/e"), Now, 0) + waitFinal(t, b) + if b.State() != Missing || len(askedSince(r, before)) != 0 { + t.Errorf("a file in a folder the listing doesn't show: state %d, asked %v", b.State(), askedSince(r, before)) + } +} + +// A case-insensitive host serves "normal.png" for a listed "Normal.PNG", so that file must still be asked for. +func TestListedNamesMatchWhateverTheirCase(t *testing.T) { + r := newRemoteRig(t, map[string][]byte{ + charRoot: listing("Normal.PNG"), + charRoot + "normal" + config.ExtPNG: []byte("x"), + }) + mapAndWait(t, r, charRoot) + before := len(r.fetch.askedFor()) + a := r.m.Get(sprite("characters/c/normal"), Now, 0) + waitFinal(t, a) + if !a.Ready() || !slices.Equal(askedSince(r, before), []string{charRoot + "normal" + config.ExtPNG}) { + t.Errorf("state %d, asked %v", a.State(), askedSince(r, before)) + } +} + +// A folder answered with an index page or a 403 proves nothing: the host keeps the per-file search for the session. +func TestHostWithoutListingsKeepsSearching(t *testing.T) { + for name, serve := range map[string]func(*remoteRig){ + "index page": func(r *remoteRig) { r.fetch.add(charRoot, []byte(`e.png`)) }, + "403": func(r *remoteRig) { r.fetch.setBroken(fmt.Errorf("%w: 403", network.ErrUnexpectedStatus)) }, + } { + t.Run(name, func(t *testing.T) { + r := newRemoteRig(t, map[string][]byte{charRoot + "e" + config.ExtPNG: []byte("x")}) + serve(r) + mapAndWait(t, r, charRoot) + r.fetch.setBroken(nil) + a := r.m.Get(sprite("characters/c/e"), Now, 0) + waitFinal(t, a) + if !a.Ready() { + t.Fatalf("state %d: an unproven folder blocked a real file", a.State()) + } + other := File(testOrigin + "characters/d/") + started := false + r.m.Call(func() { + MapCharacter(r.m, r.network, r.remote, r.builder, other) + _, started = r.remote.walks[folderKey(string(other))] + }) + if started { + t.Error("another walk started on a host that showed it gives no listings") + } + }) + } +} + +// A folder that 404s proves nothing and is not walked again until the map is old. +func TestMissingFolderIsWalkedAgainOnlyWhenOld(t *testing.T) { + r := newRemoteRig(t, map[string][]byte{}) + mapAndWait(t, r, charRoot) + current := func() *walk { + var w *walk + r.m.Call(func() { + MapCharacter(r.m, r.network, r.remote, r.builder, charRoot) + w = r.remote.walks[folderKey(charRoot)] + }) + return w + } + first := current() + if current() != first { + t.Fatal("a fresh walk was repeated") + } + r.clock.add(MapMaxAge) + if current() == first { + t.Error("an old walk was not repeated") + } +} + +// Retry missing drops the maps under its prefix, so a sprite added to the server since is found. +func TestForgetMissingDropsTheMap(t *testing.T) { + r := newRemoteRig(t, map[string][]byte{charRoot: listing("e.png")}) + mapAndWait(t, r, charRoot) + r.fetch.add(charRoot+"new"+config.ExtPNG, []byte("x")) + r.m.Call(func() { r.remote.ForgetMissing(testOrigin) }) + a := r.m.Get(sprite("characters/c/new"), Now, 0) + waitFinal(t, a) + if !a.Ready() { + t.Errorf("state %d: the dropped map still answered", a.State()) + } +} + +func TestExtraHostsAreMappedToo(t *testing.T) { + const mirror = "http://mirror.test/base/" + r := newRemoteRig(t, map[string][]byte{charRoot: listing("e.png")}) + r.m.Call(func() { r.builder.SetHosts(testOrigin, []string{mirror}) }) + mapAndWait(t, r, charRoot) + mapAndWait(t, r, File(mirror+"characters/c/")) + if !slices.Contains(r.fetch.askedFor(), mirror+"characters/c/") { + t.Errorf("asked %v, want the mirror's folder listed", r.fetch.askedFor()) + } +} + +func TestWalkStopsAtItsDepth(t *testing.T) { + files := map[string][]byte{} + folder := charRoot + for range mapDepth + 2 { + files[folder] = listing("d/") + folder += "d/" + } + r := newRemoteRig(t, files) + mapAndWait(t, r, charRoot) + if n := len(r.fetch.askedFor()); n != mapDepth { + t.Errorf("listed %d folders, want %d", n, mapDepth) + } +} + +func TestCharacterRoot(t *testing.T) { + for in, want := range map[string]File{ + testOrigin + "characters/Phoenix/(a)normal": testOrigin + "characters/Phoenix/", + testOrigin + "characters/Phoenix/(a)/normal": testOrigin + "characters/Phoenix/", + testOrigin + "background/court/defenseempty": "", + testOrigin + "characters/": "", + } { + if got := CharacterRoot(in); got != want { + t.Errorf("CharacterRoot(%q) = %q, want %q", in, got, want) + } + } +} + +// A map kept in learned.json answers in the next session without a listing, and an old one is walked again. +func TestMapOutlivesTheSession(t *testing.T) { + files := map[string][]byte{ + charRoot: listing("e.png", "emotions/"), + charRoot + "emotions/": listing("button1_off.png"), + charRoot + "e" + config.ExtPNG: []byte("x"), + } + first := newRemoteRig(t, files) + mapAndWait(t, first, charRoot) + saved := rememberFile(t, first) + + next := newRemoteRig(t, files) + recallFile(t, next, saved) + mapped := false + next.m.Call(func() { mapped = next.remote.Mapped(charRoot) }) + if !mapped { + t.Fatal("the saved map was not recalled") + } + a := next.m.Get(sprite("characters/c/(a)e"), Now, 0, "characters/c/e") + waitFinal(t, a) + if got := next.fetch.askedFor(); !a.Ready() || !slices.Equal(got, []string{charRoot + "e" + config.ExtPNG}) { + t.Errorf("state %d, asked %v: the recalled map should answer every other spelling", a.State(), got) + } + + var before *walk + next.m.Call(func() { before = next.remote.walks[folderKey(charRoot)] }) + next.clock.add(MapMaxAge) + var after *walk + next.m.Call(func() { + MapCharacter(next.m, next.network, next.remote, next.builder, charRoot) + after = next.remote.walks[folderKey(charRoot)] + }) + if after == before { + t.Error("an old saved map was not walked again on use") + } +} diff --git a/internal/media/learned.go b/internal/media/learned.go index d58e2df0..79a68986 100644 --- a/internal/media/learned.go +++ b/internal/media/learned.go @@ -66,6 +66,8 @@ type LearnedHost struct { Formats map[Class]map[string]int `json:"f,omitempty"` // Winners are one line per key; see winnerLine. Winners []string `json:"w,omitempty"` + // Maps are the character maps, by root relative to the host (whole when outside it). + Maps map[string]*LearnedMap `json:"m,omitempty"` } var errLearnedTooLarge = errors.New("media: learned file too large") @@ -76,11 +78,12 @@ type Memory struct { origins []string formats map[string]map[Class]map[string]int winners map[Key]File + maps map[string]savedMap } -// Remember copies what m and b have learned; call it on the Manager's goroutine (Do or Call). -func Remember(m *Manager, b *CandidateBuilder) Memory { - mem := Memory{formats: map[string]map[Class]map[string]int{}, winners: maps.Clone(m.winners)} +// Remember copies what m, b and s have learned; call it on the Manager's goroutine (Do or Call). +func Remember(m *Manager, b *CandidateBuilder, s *RemoteSource) Memory { + mem := Memory{formats: map[string]map[Class]map[string]int{}, winners: maps.Clone(m.winners), maps: s.rememberMaps()} for origin, h := range b.origins { mem.origins = append(mem.origins, origin) if len(h.learned) == 0 { @@ -120,6 +123,17 @@ func (mem Memory) Learned() Learned { h.Winners = append(h.Winners, line) } } + roots := slices.SortedFunc(maps.Keys(mem.maps), func(x, y string) int { + return mem.maps[y].at.Compare(mem.maps[x].at) + }) + for _, root := range roots[:min(len(roots), learnedMapsCap)] { + group := originAmong(Key{Path: root}, slices.Values(mem.origins)) + h := host(group) + if h.Maps == nil { + h.Maps = map[string]*LearnedMap{} + } + h.Maps[strings.TrimPrefix(root, group)] = learnedMap(root, mem.maps[root]) + } return l } @@ -206,7 +220,7 @@ func readWinner(group, line string) (Key, File, bool) { // would get wrong; any goroutine. Saved counts are halved, so a host that changed its formats is relearned in a few // sessions. func (l Learned) Memory() Memory { - mem := Memory{formats: map[string]map[Class]map[string]int{}, winners: map[Key]File{}} + mem := Memory{formats: map[string]map[Class]map[string]int{}, winners: map[Key]File{}, maps: map[string]savedMap{}} if l.Version != LearnedVersion { return mem } @@ -239,13 +253,23 @@ func (l Learned) Memory() Memory { mem.winners[k] = f } } + for rel, lm := range h.Maps { + root := rel + if !strings.Contains(rel, "://") { + root = origin + rel + } + if sm, ok := readMap(root, lm); ok && len(mem.maps) < learnedMapsCap { + mem.maps[root] = sm + } + } } return mem } // Recall adds mem to what m and b know, keeping what this session already learned; call it on the Manager's // goroutine. m may keep mem's maps, so mem is not used again. -func Recall(m *Manager, b *CandidateBuilder, mem Memory) { +func Recall(m *Manager, b *CandidateBuilder, s *RemoteSource, mem Memory) { + s.recallMaps(mem.maps) for origin, classes := range mem.formats { hints := b.hints(origin) for class, counts := range classes { diff --git a/internal/media/learned_test.go b/internal/media/learned_test.go index 29d8feb3..ae75adb5 100644 --- a/internal/media/learned_test.go +++ b/internal/media/learned_test.go @@ -10,10 +10,10 @@ import ( ) // rememberFile is what a session would write to learned.json. -func rememberFile(t *testing.T, m *Manager, b *CandidateBuilder) []byte { +func rememberFile(t *testing.T, r *remoteRig) []byte { t.Helper() var mem Memory - if !m.Call(func() { mem = Remember(m, b) }) { + if !r.m.Call(func() { mem = Remember(r.m, r.builder, r.remote) }) { t.Fatal("manager stopped") } data, err := EncodeLearned(mem.Learned()) @@ -24,14 +24,14 @@ func rememberFile(t *testing.T, m *Manager, b *CandidateBuilder) []byte { } // recallFile is what the next session does with it. -func recallFile(t *testing.T, m *Manager, b *CandidateBuilder, data []byte) { +func recallFile(t *testing.T, r *remoteRig, data []byte) { t.Helper() l, err := DecodeLearned(data) if err != nil { t.Fatal(err) } mem := l.Memory() - m.Call(func() { Recall(m, b, mem) }) + r.m.Call(func() { Recall(r.m, r.builder, r.remote, mem) }) } func TestNextSessionAsksTheLearnedFormatAndWinnerFirst(t *testing.T) { @@ -41,10 +41,10 @@ func TestNextSessionAsksTheLearnedFormatAndWinnerFirst(t *testing.T) { } first := newRemoteRig(t, files) waitFinal(t, first.m.Get(sprite("a"), Now, 0)) - saved := rememberFile(t, first.m, first.builder) + saved := rememberFile(t, first) next := newRemoteRig(t, files) - recallFile(t, next.m, next.builder, saved) + recallFile(t, next, saved) waitFinal(t, next.m.Get(sprite("a"), Now, 0)) waitFinal(t, next.m.Get(sprite("b"), Now, 0)) want := []string{testOrigin + "a" + config.ExtPNG, testOrigin + "b" + config.ExtPNG} @@ -71,11 +71,11 @@ func TestEveryWinnerShapeSurvivesTheFile(t *testing.T) { r.builder.Allow(testOrigin, map[Class][]string{ClassEmote: {config.ExtWebP}}) maps.Copy(r.m.winners, saved) }) - data := rememberFile(t, r.m, r.builder) + data := rememberFile(t, r) next := newRemoteRig(t, nil) next.m.Call(func() { next.builder.Allow(testOrigin, map[Class][]string{ClassEmote: {config.ExtWebP}}) }) - recallFile(t, next.m, next.builder, data) + recallFile(t, next, data) var got map[Key]File next.m.Call(func() { got = maps.Clone(next.m.winners) }) delete(saved, tabbed) // a line can't hold a tab, so that one is left out @@ -88,10 +88,10 @@ func TestRecallIgnoresAnotherVersionAndDamage(t *testing.T) { r := newRemoteRig(t, nil) formats := map[Class]map[string]int{ClassEmote: {config.ExtPNG: 1, ".exe": 1}, ClassExact: {config.ExtPNG: 1}} r.m.Call(func() { - Recall(r.m, r.builder, Learned{Version: LearnedVersion + 1, Hosts: map[string]*LearnedHost{ + Recall(r.m, r.builder, r.remote, Learned{Version: LearnedVersion + 1, Hosts: map[string]*LearnedHost{ testOrigin: {Formats: formats, Winners: []string{"0\t0\t2\t0\t0\t0\ta\t+.png"}}, }}.Memory()) - Recall(r.m, r.builder, Learned{Version: LearnedVersion, Hosts: map[string]*LearnedHost{ + Recall(r.m, r.builder, r.remote, Learned{Version: LearnedVersion, Hosts: map[string]*LearnedHost{ testOrigin: {Formats: map[Class]map[string]int{ClassEmote: {".exe": 1}}, Winners: []string{"short", "0\t0\t99\t0\t0\t0\ta\t+.png", "0\t0\t2\t0\t0\t9\ta\t+.png", "0\t0\t2\t0\t256\t0\ta\t+.png", "0\t0\t2\t-1\t0\t0\ta\t+.png"}}, @@ -99,7 +99,7 @@ func TestRecallIgnoresAnotherVersionAndDamage(t *testing.T) { }}.Memory()) }) var mem Memory - r.m.Call(func() { mem = Remember(r.m, r.builder) }) + r.m.Call(func() { mem = Remember(r.m, r.builder, r.remote) }) if l := mem.Learned(); len(l.Hosts) != 0 { t.Fatalf("recalled %+v", l.Hosts[testOrigin]) } diff --git a/internal/media/sources.go b/internal/media/sources.go index a595c749..c9c75c7b 100644 --- a/internal/media/sources.go +++ b/internal/media/sources.go @@ -124,15 +124,21 @@ type RemoteSource struct { exists map[File]struct{} missing map[File]time.Time answered map[string]bool + // listed, walks and refused are character mapping's (charmap.go): folders by decoded URL, character walks by + // decoded root, and hosts that answered a folder with no listing this session. + listed map[string]*listedFolder + walks map[string]*walk + refused map[string]bool } // NewRemoteSource asks through fetch. func NewRemoteSource(ctx context.Context, fetch Fetcher, missingTTL time.Duration, clock func() time.Time) *RemoteSource { return &RemoteSource{fetch: fetch, ctx: ctx, clock: clock, missingTTL: missingTTL, - exists: map[File]struct{}{}, missing: map[File]time.Time{}, answered: map[string]bool{}} + exists: map[File]struct{}{}, missing: map[File]time.Time{}, answered: map[string]bool{}, + listed: map[string]*listedFolder{}, walks: map[string]*walk{}, refused: map[string]bool{}} } -// Has answers from the tables; a file never asked about is Unknown, and only that costs a request. +// Has answers from the tables and the character maps; a file neither proves is Unknown, and only that costs a request. func (s *RemoteSource) Has(f File) Answer { if _, ok := s.exists[f]; ok { return Yes @@ -143,6 +149,9 @@ func (s *RemoteSource) Has(f File) Answer { } delete(s.missing, f) } + if s.mapAbsent(f) { + return No + } return Unknown } @@ -181,8 +190,9 @@ func (s *RemoteSource) Observe(f File, _ []byte, err error) { } } -// ForgetMissing drops known-missing answers for files under prefix, so they are asked about again. +// ForgetMissing drops known-missing answers and the character maps under prefix, so they are asked about again. func (s *RemoteSource) ForgetMissing(prefix string) { + s.forgetMaps(folderKey(prefix)) for f := range s.missing { if strings.HasPrefix(string(f), prefix) { delete(s.missing, f) From 11ec81a61c4522b37be1fadc11eba125f757c286 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:34:15 +0100 Subject: [PATCH 28/43] media, assets, render: decoded images reach the pump through TakeResults The bridge's image format handed the bytes to the decoder's own goroutines and held a Compute worker waiting for them, and decoded pages went to the render thread through a 64-slot channel outside the media system, which saw the request as ready the moment the decode was handed off. Images now decode on the Compute worker that holds the request and need the main thread: the pump takes them with TakeResults and finishes each request after its upload. A request can deliver several results: Format.Decode gets a page callback, so an animation's opening frames and streamed chunks reach the pump as early pages of the same request, in order, and TakeResults says which result is final. A Delivered hook wakes the frame loop after each result is queued. The decoder is no longer a pool (DecoderPool becomes Decoder): no goroutines, no job queue, no Close; its crash guard moved into Decode. A fetch that fails at the network stage is counted in ManagerStats.Failed instead of travelling to the pump as a transient decode error. Co-Authored-By: Claude Opus 5.5 --- cmd/asyncao/main.go | 3 +- docs/RESTRUCTURING_PLAN.md | 12 ++- internal/archive/archive_test.go | 3 +- internal/assets/charmap_test.go | 2 +- internal/assets/decoder.go | 108 +++++------------------- internal/assets/decoder_test.go | 106 +++++------------------ internal/assets/dxt.go | 2 +- internal/assets/folders_test.go | 2 +- internal/assets/learned_test.go | 4 +- internal/assets/manager.go | 68 +++++++++------ internal/assets/manager_test.go | 74 +++++++++------- internal/assets/mediabridge.go | 36 ++++---- internal/assets/mediabridge_test.go | 58 +++++++------ internal/assets/notify_test.go | 13 ++- internal/assets/scenerypin_test.go | 2 +- internal/assets/webp_cgo_test.go | 45 +++------- internal/courtroom/bgfallback_test.go | 27 ++++-- internal/courtroom/courtroom_test.go | 3 +- internal/courtroom/messageneeds_test.go | 3 +- internal/media/manager.go | 34 +++++--- internal/media/manager_test.go | 59 ++++++++++++- internal/media/types.go | 4 +- internal/render/pump.go | 45 ++++------ internal/render/pump_test.go | 13 ++- internal/ui/conclusivemiss_ui_test.go | 28 ++++-- internal/ui/contentjob_test.go | 6 +- internal/ui/debugpanel.go | 6 +- internal/ui/deskmissing_relay_test.go | 30 ++----- internal/ui/emotebuttonart_test.go | 16 ++-- internal/ui/emotepreviewfollow_test.go | 3 +- internal/ui/exportstall_test.go | 3 +- internal/ui/frameharness_test.go | 6 +- internal/ui/gifexport_async_test.go | 12 +-- internal/ui/missingno_noblip_test.go | 43 +++------- internal/ui/newroom_test.go | 3 +- internal/ui/packcharini_test.go | 3 +- internal/ui/sendonchange_test.go | 3 +- internal/ui/themeeditorpreview_test.go | 3 +- 38 files changed, 392 insertions(+), 499 deletions(-) diff --git a/cmd/asyncao/main.go b/cmd/asyncao/main.go index 70c07f0f..08bff58f 100644 --- a/cmd/asyncao/main.go +++ b/cmd/asyncao/main.go @@ -141,8 +141,7 @@ func run(rt *host.Runtime, serverURL, masterURL string, gpuOpts host.GraphicsOpt client := network.NewClientNotFoundTTL(time.Duration(prefs.Load().NotFoundTTLSecVal)*time.Second, sockets) client.SetAssetOrigin(prefs.Load().AssetOrigin) // power-user Origin/CORS override for asset streaming client.SetAdaptiveLatencyMultiple(prefs.Load().AdaptiveLatMultipleVal) - decoder := assets.NewDecoderPool(assets.DecodeWorkers()) - defer decoder.Close() + decoder := assets.NewDecoder() decoder.SetAnimatedBudgetMiB(prefs.Load().AnimatedBudgetMiB()) decoder.SetAnimatedDecodeConcurrency(prefs.Load().AnimDecodeConcurrency()) diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index 8b51f847..ce6be494 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -133,8 +133,16 @@ in **Status**. Update Status in the same commit that completes a step. layer, conclusive-miss set, Local-only mode in the Manager) and `-old-media` are deleted, and with them the wait gate's refusal re-ask: high-priority requests are never refused - [ ] known problem from the benchmark: peak heap with files asked for every frame is 384-617 MiB, unexplained (the - request count on hosts with no `extensions.json` is answered by character mapping above) - - [ ] move callers: courtroom, then screens, theme and audio; `Pump` on `TakeResults`; music streaming + request count on hosts with no `extensions.json` is answered by character mapping above). Lead: images declare + no memory claim and the bridge sets no `ClaimLimit`, so decoded pages are bounded by nothing + - [ ] move callers (decided 2026-11-15): callers call `media.Manager` directly with keys from small assets helpers, + and the bridge goes at the end. Order: `Pump` on `TakeResults`, then courtroom, screens, theme and audio; + music streaming after them + - [x] `Pump` on `TakeResults`: images decode on the Compute worker holding the request, and an animation's opening + frames reach the pump as early pages of the same request (`Format.Decode`'s `page`). The decoder's own + goroutines and the 64-slot hand-off channel are gone + - [ ] courtroom, then screens, theme and audio + - [ ] music streaming - [ ] off-thread texture preparation: waits for the renderer overhaul (decided 2026-11-02). See below - [x] a sprite sometimes shows its old animation for a frame before the right one (reported 2026-11-01): the wait gate released on a first frame or a reduced page. The speaker's sprites now wait for every frame; a pair partner's still diff --git a/internal/archive/archive_test.go b/internal/archive/archive_test.go index d65131cb..ab3c236b 100644 --- a/internal/archive/archive_test.go +++ b/internal/archive/archive_test.go @@ -30,8 +30,7 @@ func buildManager(t *testing.T, source assets.Fetcher, localMode bool) *assets.M t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() mgr := assets.NewManager(assets.ManagerDeps{ Prefs: prefs, T2: t2, Disk: disk, Source: source, Decoder: decoder, diff --git a/internal/assets/charmap_test.go b/internal/assets/charmap_test.go index db894f83..ae8ad8a2 100644 --- a/internal/assets/charmap_test.go +++ b/internal/assets/charmap_test.go @@ -24,7 +24,7 @@ func TestMappedCharacterSkipsMissingSpellings(t *testing.T) { t.Helper() base := cs.srv.URL + "/characters/c/" rig.manager.PrefetchChain(base+"(a)"+name, []string{base + name}, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - waitDecoded(t, rig.manager).Asset.Release() + waitDecoded(t, rig).Asset.Release() } ask("first") root := media.File(cs.srv.URL + "/characters/c/") diff --git a/internal/assets/decoder.go b/internal/assets/decoder.go index 1b16361a..093df835 100644 --- a/internal/assets/decoder.go +++ b/internal/assets/decoder.go @@ -24,8 +24,6 @@ import ( ) const ( - // decodeQueueCap bounds the decode job queue; Submit blocks briefly when full, since decode work is never shed. - decodeQueueCap = 64 // minDecodeWorkers is the floor of the worker count, max(2, NumCPU/2). minDecodeWorkers = 2 @@ -378,17 +376,13 @@ type DecodeRequest struct { Type AssetType // PlayAnimations decodes all frames when true, only the first when false. PlayAnimations bool - // OnDone runs on a decoder goroutine: it must be cheap and must not touch SDL (hard rule 1). + // OnDone runs on the decoding goroutine, once per page: it must be cheap and must not touch SDL (hard rule 1). OnDone func(url string, d *Decoded, err error) } -// DecoderPool decodes image payloads into plain RGBA with no SDL calls; upload happens on the render thread. -type DecoderPool struct { - jobs chan DecodeRequest - stop chan struct{} - wg sync.WaitGroup - closeOnce sync.Once - +// Decoder decodes image payloads into plain RGBA with no SDL calls, on the caller's goroutine; upload happens on the +// render thread. +type Decoder struct { decoded atomic.Int64 failed atomic.Int64 @@ -407,7 +401,6 @@ type DecoderPool struct { // decodeNsEWMA tracks decode+fit wall time. decodeNsEWMA atomic.Int64 - workers int // running lists the decodes in progress, for diagnostics. running *network.ActiveWork } @@ -466,27 +459,13 @@ func heapSysMiB() uint64 { return ms.Sys >> 20 } -// NewDecoderPool starts workers decode goroutines (DecodeWorkers() when workers <= 0). -func NewDecoderPool(workers int) *DecoderPool { - if workers <= 0 { - workers = DecodeWorkers() - } - p := &DecoderPool{ - jobs: make(chan DecodeRequest, decodeQueueCap), - stop: make(chan struct{}), - animGate: newAnimGate(defaultAnimatedDecodeConcurrency), - workers: workers, - running: network.NewActiveWork(workers), - } - p.wg.Add(workers) - for i := 0; i < workers; i++ { - go p.worker() - } - return p +// NewDecoder makes a decoder; the media system's Compute workers run its decodes. +func NewDecoder() *Decoder { + return &Decoder{animGate: newAnimGate(defaultAnimatedDecodeConcurrency), running: network.NewActiveWork(DecodeWorkers())} } // SetSpriteCap sets the height ceiling for full-size assets; 0 disables it. -func (p *DecoderPool) SetSpriteCap(px int) { +func (p *Decoder) SetSpriteCap(px int) { if px < 0 { px = 0 } @@ -494,7 +473,7 @@ func (p *DecoderPool) SetSpriteCap(px int) { } // SetAnimatedSpriteCap sets the animated-only height cap; 0 disables it. -func (p *DecoderPool) SetAnimatedSpriteCap(px int) { +func (p *Decoder) SetAnimatedSpriteCap(px int) { if px < 0 { px = 0 } @@ -502,17 +481,17 @@ func (p *DecoderPool) SetAnimatedSpriteCap(px int) { } // SetAnimatedBudgetMiB sets the per-animated-asset frame budget; <= 0 resets to the default. -func (p *DecoderPool) SetAnimatedBudgetMiB(mib int) { +func (p *Decoder) SetAnimatedBudgetMiB(mib int) { SetAnimatedDecodedAssetBytes(int64(mib) << 20) } // SetAnimatedDecodeConcurrency sets the concurrent animated decode bound. -func (p *DecoderPool) SetAnimatedDecodeConcurrency(n int) { +func (p *Decoder) SetAnimatedDecodeConcurrency(n int) { p.animGate.SetLimit(n) } // SetTextureCompression sets the compression mode (CompressOff, CompressDXT5, CompressDXT1) for new decodes. -func (p *DecoderPool) SetTextureCompression(mode int) { +func (p *Decoder) SetTextureCompression(mode int) { switch mode { case CompressDXT5: p.texCompress.Store(DXT5FourCC) @@ -525,7 +504,7 @@ func (p *DecoderPool) SetTextureCompression(mode int) { // prepareForUpload marks fully opaque frames, then compresses in place when a DXT mode is active and the canvas is // 4-aligned; idempotent, as compressing releases the frames the opaque check reads. -func (p *DecoderPool) prepareForUpload(d *Decoded) { +func (p *Decoder) prepareForUpload(d *Decoded) { if d == nil { return } @@ -558,7 +537,7 @@ func framesOpaque(frames []*image.RGBA) bool { } // fit downscales to the ceiling: fixed-cell types to a square, others to the sprite cap or the animated cap when set. -func (p *DecoderPool) fit(t AssetType, d *Decoded) *Decoded { +func (p *Decoder) fit(t AssetType, d *Decoded) *Decoded { if d == nil { return d } @@ -578,51 +557,16 @@ func (p *DecoderPool) fit(t AssetType, d *Decoded) *Decoded { } // fullSizeMaxH is the decode-time height cap for a full-size asset, 0 for fixed-cell types, which downscale in fit. -func (p *DecoderPool) fullSizeMaxH(t AssetType) int { +func (p *Decoder) fullSizeMaxH(t AssetType) int { if decodeTargetPx(t) > 0 { return 0 } return int(p.spriteCap.Load()) } -// Submit queues a decode; a closed pool returns false and calls OnDone inline, so callers always hear back. -func (p *DecoderPool) Submit(req DecodeRequest) bool { - if req.OnDone == nil { - return false - } - select { - case <-p.stop: - req.OnDone(req.URL, nil, fmt.Errorf("assets: decoder pool closed")) - return false - default: - } - select { - case p.jobs <- req: - return true - case <-p.stop: - req.OnDone(req.URL, nil, fmt.Errorf("assets: decoder pool closed")) - return false - } -} - -// Close stops the workers and fails queued jobs so nobody waits forever. -func (p *DecoderPool) Close() { - p.closeOnce.Do(func() { - close(p.stop) - p.wg.Wait() - for { - select { - case req := <-p.jobs: - req.OnDone(req.URL, nil, fmt.Errorf("assets: decoder pool closed")) - default: - return - } - } - }) -} - -func (p *DecoderPool) worker() { - defer p.wg.Done() +// Decode decodes one payload on the calling goroutine; an animated payload hands OnDone frame 0 first, then the full set +// replaces it at upload. +func (p *Decoder) Decode(req DecodeRequest) { // The render thread's crash guard cannot see this goroutine: log any panic to disk, then re-panic. defer func() { if r := recover(); r != nil { @@ -630,18 +574,6 @@ func (p *DecoderPool) worker() { panic(r) } }() - for { - select { - case req := <-p.jobs: - p.runJob(req) - case <-p.stop: - return - } - } -} - -// runJob decodes one payload; animated payloads deliver frame 0 first, then the full set replaces it at upload. -func (p *DecoderPool) runJob(req DecodeRequest) { defer p.running.End(p.running.Begin(req.Type.Name(), req.URL)) done := req.OnDone req.OnDone = func(url string, d *Decoded, err error) { @@ -771,7 +703,7 @@ func fitEstablishingPrefix(first *Decoded, data []byte, maxH int) *Decoded { } // streamAnimated appends each remaining WebP/AVIF frame; if decimation is needed it falls back to a full decode. -func (p *DecoderPool) streamAnimated(req DecodeRequest) { +func (p *Decoder) streamAnimated(req DecodeRequest) { format := Sniff(req.Data) maxH := p.fullSizeMaxH(req.Type) start := time.Now() @@ -841,7 +773,7 @@ type DecoderStats struct { } // Stats snapshots the pool's counters. -func (p *DecoderPool) Stats() DecoderStats { +func (p *Decoder) Stats() DecoderStats { return DecoderStats{ Decoded: p.decoded.Load(), Failed: p.failed.Load(), diff --git a/internal/assets/decoder_test.go b/internal/assets/decoder_test.go index 2fceabe0..bfbbf99e 100644 --- a/internal/assets/decoder_test.go +++ b/internal/assets/decoder_test.go @@ -225,72 +225,28 @@ func TestDecodeRejectsJunk(t *testing.T) { } } -// --- decoder pool --------------------------------------------------------------- +// --- decoder --------------------------------------------------------------------- -func TestDecoderPoolDeliversResults(t *testing.T) { - p := NewDecoderPool(2) - defer p.Close() - - results := make(chan *Decoded, 4) - errs := make(chan error, 4) +func TestDecoderDeliversResults(t *testing.T) { + const decodes = 4 + p := NewDecoder() payload := encodePNG(t, 8, 8, color.White) - for i := 0; i < 4; i++ { - ok := p.Submit(DecodeRequest{ - URL: "http://example.com/a.png", - Data: payload, - Type: AssetTypeCharSprite, - PlayAnimations: true, + for range decodes { + p.Decode(DecodeRequest{ + URL: "http://example.com/a.png", Data: payload, Type: AssetTypeCharSprite, PlayAnimations: true, OnDone: func(_ string, d *Decoded, err error) { if err != nil { - errs <- err - return + t.Fatalf("decode error: %v", err) } - results <- d + d.Release() }, }) - if !ok { - t.Fatal("Submit refused while pool open") - } - } - for i := 0; i < 4; i++ { - select { - case d := <-results: - d.Release() - case err := <-errs: - t.Fatalf("decode error: %v", err) - case <-time.After(5 * time.Second): - t.Fatal("decoder pool never delivered") - } } - if s := p.Stats(); s.Decoded != 4 || s.Failed != 0 { + if s := p.Stats(); s.Decoded != decodes || s.Failed != 0 { t.Errorf("Stats = %+v", s) } } -func TestDecoderPoolCloseFailsQueuedJobs(t *testing.T) { - p := NewDecoderPool(1) - p.Close() - heard := make(chan error, 1) - ok := p.Submit(DecodeRequest{ - URL: "x", - Data: nil, - OnDone: func(_ string, _ *Decoded, err error) { - heard <- err - }, - }) - if ok { - t.Error("Submit accepted after Close") - } - select { - case err := <-heard: - if err == nil { - t.Error("expected error for post-Close submit") - } - case <-time.After(2 * time.Second): - t.Fatal("post-Close submit never heard back") - } -} - func TestPixPoolRoundTrip(t *testing.T) { buf, token := getPixBuf(1024) if len(buf) != 1024 { @@ -620,31 +576,20 @@ func TestFrameKeepIndexMapping(t *testing.T) { // cell size inside the decode pool, so a 500×500 pack icon costs ~16 KB of // T1 instead of ~1 MB; every other type keeps its native size. func TestDecoderThumbnailsFixedCellTypes(t *testing.T) { - pool := NewDecoderPool(1) - defer pool.Close() - + pool := NewDecoder() decode := func(data []byte, typ AssetType) *Decoded { t.Helper() - done := make(chan *Decoded, 1) - ok := pool.Submit(DecodeRequest{ + var out *Decoded + pool.Decode(DecodeRequest{ URL: "x", Data: data, Type: typ, PlayAnimations: true, OnDone: func(_ string, d *Decoded, err error) { if err != nil { t.Errorf("decode failed: %v", err) } - done <- d + out = d }, }) - if !ok { - t.Fatal("submit refused") - } - select { - case d := <-done: - return d - case <-time.After(managerWait): - t.Fatal("decode timed out") - return nil - } + return out } big := encodePNG(t, 256, 256, color.RGBA{R: 9, G: 99, B: 199, A: 255}) @@ -755,27 +700,18 @@ func TestDecoderMarksOpaqueFrames(t *testing.T) { solid = 255 faint = 254 ) - pool := NewDecoderPool(1) - defer pool.Close() + pool := NewDecoder() decode := func(data []byte) *Decoded { t.Helper() - done := make(chan *Decoded, 1) - if !pool.Submit(DecodeRequest{URL: "x", Data: data, Type: AssetTypeBackground, + var out *Decoded + pool.Decode(DecodeRequest{URL: "x", Data: data, Type: AssetTypeBackground, OnDone: func(_ string, d *Decoded, err error) { if err != nil { t.Errorf("decode failed: %v", err) } - done <- d - }}) { - t.Fatal("submit refused") - } - select { - case d := <-done: - return d - case <-time.After(managerWait): - t.Fatal("decode timed out") - return nil - } + out = d + }}) + return out } opaque := decode(encodePNG(t, side, side, color.RGBA{R: 1, G: 2, B: 3, A: solid})) diff --git a/internal/assets/dxt.go b/internal/assets/dxt.go index 43cb5c30..89cd8117 100644 --- a/internal/assets/dxt.go +++ b/internal/assets/dxt.go @@ -266,7 +266,7 @@ func nearestColor(r, g, b uint8, pal [4][3]uint8, colors int) uint8 { return best } -// Texture-compression modes for DecoderPool.SetTextureCompression. +// Texture-compression modes for Decoder.SetTextureCompression. const ( CompressOff = 0 // raw RGBA (the default) CompressDXT5 = 1 // DXT5/BC3, 8 bpp, smooth alpha diff --git a/internal/assets/folders_test.go b/internal/assets/folders_test.go index 04ca8de7..8c43d429 100644 --- a/internal/assets/folders_test.go +++ b/internal/assets/folders_test.go @@ -275,7 +275,7 @@ func TestFolderSpriteIsFoundInAFormatTheServerDoesNotList(t *testing.T) { } base := pr.base("characters/witch/normal") pr.rig.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - if d := nextDecoded(t, pr.rig.manager, base); d.Err != nil { + if d := nextDecoded(t, pr.rig, base); d.Err != nil { t.Fatalf("the folder's .png was not used: %v", d.Err) } for _, ext := range []string{".webp", ".png"} { diff --git a/internal/assets/learned_test.go b/internal/assets/learned_test.go index e58ebb92..8fe12b06 100644 --- a/internal/assets/learned_test.go +++ b/internal/assets/learned_test.go @@ -41,7 +41,7 @@ func TestLearnedFormatOutlivesTheSession(t *testing.T) { first := newRigAt(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false, learned) waitRecalled(t, first.manager) first.manager.Prefetch(cs.srv.URL+"/characters/a/(a)x", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - waitDecoded(t, first.manager).Asset.Release() + waitDecoded(t, first).Asset.Release() first.manager.CloseMedia() if _, err := os.Stat(learned); err != nil { t.Fatalf("learned.json not written: %v", err) @@ -51,7 +51,7 @@ func TestLearnedFormatOutlivesTheSession(t *testing.T) { waitRecalled(t, next.manager) before := cs.total() next.manager.Prefetch(cs.srv.URL+"/characters/a/(a)y", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - waitDecoded(t, next.manager).Asset.Release() + waitDecoded(t, next).Asset.Release() if n := cs.total() - before; n != 1 { t.Errorf("the next session needed %d requests, want 1", n) } diff --git a/internal/assets/manager.go b/internal/assets/manager.go index f66c3571..fc03de9a 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -14,8 +14,6 @@ import ( ) const ( - // decodedChanCap bounds the render-thread handoff; when full, workers block, so results never drop. - decodedChanCap = 64 // audioChanCap bounds the raw-audio handoff to the audio system. audioChanCap = 64 // warningChanCap bounds missing-asset warnings; these may be dropped, results may not. @@ -31,8 +29,6 @@ type DecodedAsset struct { Type AssetType Asset *Decoded Err error - // Transient marks a network failure: bytes were never seen, so keep it out of the negative cache. - Transient bool // FromPack marks bytes from the player's folders; Base is still the server's URL, so never MarkFailed(Base) on // them, or a corrupt local file takes the server's good copy offline. FromPack bool @@ -74,7 +70,7 @@ type Manager struct { t2 *cache.ByteBudgetLRU[string, []byte] disk *cache.DiskCache client Fetcher - decoder *DecoderPool + decoder *Decoder // learnedPath is where the media system's learned formats and winners are kept between sessions. learnedPath string @@ -83,7 +79,6 @@ type Manager struct { // t1Failed reports a recent decode failure of base, so one bad asset cannot storm the network. t1Failed func(base string) bool - decodedCh chan DecodedAsset audioCh chan AudioAsset warningCh chan Warning musicFailCh chan MusicFailure @@ -107,6 +102,8 @@ type Manager struct { missing atomic.Int64 mountFetches atomic.Int64 packQuarantined atomic.Int64 + // failed counts requests that ended in a fetch failure rather than a missing file. + failed atomic.Int64 } // SetOffline opens or closes the network block. @@ -196,7 +193,7 @@ type ManagerDeps struct { Disk *cache.DiskCache // Source is the network client, or a fake in tests. Source Fetcher - Decoder *DecoderPool + Decoder *Decoder T1Contains func(url string) bool T1Failed func(base string) bool // LearnedPath is the learned.json the media system's learned formats and winners are kept in; "" keeps none. @@ -214,7 +211,6 @@ func NewManager(deps ManagerDeps) *Manager { t1Contains: deps.T1Contains, t1Failed: deps.T1Failed, learnedPath: deps.LearnedPath, - decodedCh: make(chan DecodedAsset, decodedChanCap), audioCh: make(chan AudioAsset, audioChanCap), warningCh: make(chan Warning, warningChanCap), musicFailCh: make(chan MusicFailure, musicFailChanCap), @@ -225,23 +221,17 @@ func NewManager(deps ManagerDeps) *Manager { // WorkStats shows what the decoders and handoffs hold, for diagnostics. type WorkStats struct { - Refused int64 - DecodeQueued, DecodeCap int - DecodeWorkers int - DecodedQueued, DecodedCap int - AudioQueued, AudioCap int - Decoding []network.WorkItem + Refused int64 + DecodeWorkers int + AudioQueued, AudioCap int + Decoding []network.WorkItem } // WorkStats snapshots the decoders and handoffs; it allocates, so call it only while the debug panel shows it. func (m *Manager) WorkStats() WorkStats { return WorkStats{ Refused: m.refused.Load(), - DecodeQueued: len(m.decoder.jobs), - DecodeCap: cap(m.decoder.jobs), - DecodeWorkers: m.decoder.workers, - DecodedQueued: len(m.decodedCh), - DecodedCap: cap(m.decodedCh), + DecodeWorkers: DecodeWorkers(), AudioQueued: len(m.audioCh), AudioCap: cap(m.audioCh), Decoding: m.decoder.running.Snapshot(), @@ -264,8 +254,35 @@ func (m *Manager) NotifyDelivery() { } } -// Decoded returns the channel the render thread drains for texture uploads. -func (m *Manager) Decoded() <-chan DecodedAsset { return m.decodedCh } +// Delivery is one decoded page for the render thread, and the request it belongs to. +type Delivery struct { + DecodedAsset + asset *media.Asset + final bool +} + +// TakeDeliveries hands the render thread every decoded page waiting, in order; it calls Done on each once through. +func (m *Manager) TakeDeliveries(use func(Delivery)) { + m.bridge.media.TakeResults(func(a *media.Asset, v any, final bool) { + d, ok := v.(DecodedAsset) + if !ok { + // Only images need the render thread; anything else is finished here so its claim is freed. + m.Done(Delivery{asset: a, final: final}) + return + } + use(Delivery{DecodedAsset: d, asset: a, final: final}) + }) +} + +// Done tells the media system the render thread is through with d: the final page finishes its request and forgets it, +// so an evicted texture can ask again. +func (m *Manager) Done(d Delivery) { + if !d.final { + return + } + m.bridge.media.Finish(d.asset, nil) + m.bridge.media.ForgetAsset(d.asset) +} // Audio returns the channel the audio system drains for SDL_mixer loads. func (m *Manager) Audio() <-chan AudioAsset { return m.audioCh } @@ -472,12 +489,6 @@ func (m *Manager) resolveIn(base string, t AssetType, urls []string) (url string return "", nil, false, false } -// onDecoded hands one decoded page to the render thread. -func (m *Manager) onDecoded(url, base string, t AssetType, fromPack bool, d *Decoded, err error) { - m.decodedCh <- DecodedAsset{URL: url, Base: base, Type: t, Asset: d, Err: err, FromPack: fromPack} - m.NotifyDelivery() -} - // PurgeCorrupt evicts url from memory and the disk cache so the next demand refetches; url is the full fetch URL. func (m *Manager) PurgeCorrupt(url string) { if url == "" { @@ -564,6 +575,8 @@ type ManagerStats struct { MountFetches int64 // PackQuarantined counts folder files withdrawn after a decode failure. PackQuarantined int64 + // Failed counts requests that ended in a fetch failure rather than a missing file. + Failed int64 } // Stats snapshots the manager's counters. @@ -576,5 +589,6 @@ func (m *Manager) Stats() ManagerStats { Missing: m.missing.Load(), MountFetches: m.mountFetches.Load(), PackQuarantined: m.packQuarantined.Load(), + Failed: m.failed.Load(), } } diff --git a/internal/assets/manager_test.go b/internal/assets/manager_test.go index fcc27c85..edb01c0a 100644 --- a/internal/assets/manager_test.go +++ b/internal/assets/manager_test.go @@ -24,9 +24,11 @@ const managerWait = 5 * time.Second type testRig struct { prefs *config.AssetPreferences manager *Manager - decoder *DecoderPool + decoder *Decoder disk *cache.DiskCache t2 *cache.ByteBudgetLRU[string, []byte] + // pending holds pages taken from the media system but not yet read, as TakeDeliveries hands over all at once. + pending []DecodedAsset } // newRig builds a Manager on source; localMode mounts a LocalFetcher source's folders, as "only use my folders" does. @@ -58,8 +60,7 @@ func newRigAt(tb testing.TB, source Fetcher, localMode bool, learnedPath string) tb.Fatal(err) } tb.Cleanup(disk.Close) - decoder := NewDecoderPool(2) - tb.Cleanup(decoder.Close) + decoder := NewDecoder() m := NewManager(ManagerDeps{ Prefs: prefs, @@ -160,15 +161,35 @@ func (cs *countingServer) total() int { return n } -func waitDecoded(t *testing.T, m *Manager) DecodedAsset { +// takeDecoded returns the next page delivered within wait, finishing it as the upload pump does. +func (r *testRig) takeDecoded(wait time.Duration) (DecodedAsset, bool) { + deadline := time.Now().Add(wait) + for { + if len(r.pending) > 0 { + d := r.pending[0] + r.pending = r.pending[1:] + return d, true + } + r.manager.TakeDeliveries(func(d Delivery) { + r.pending = append(r.pending, d.DecodedAsset) + r.manager.Done(d) + }) + if len(r.pending) == 0 { + if !time.Now().Before(deadline) { + return DecodedAsset{}, false + } + time.Sleep(time.Millisecond) + } + } +} + +func waitDecoded(t *testing.T, r *testRig) DecodedAsset { t.Helper() - select { - case d := <-m.Decoded(): - return d - case <-time.After(managerWait): + d, ok := r.takeDecoded(managerWait) + if !ok { t.Fatal("no decoded asset delivered") - return DecodedAsset{} } + return d } func waitWarning(t *testing.T, m *Manager) Warning { @@ -207,7 +228,7 @@ func TestManagerWebPOnlyServerOneProbePerAsset(t *testing.T) { rig.manager.Prefetch(b.base, b.typ, network.PriorityHigh) // AssetType: mixed (test) } for range bases { - d := waitDecoded(t, rig.manager) + d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("decode error: %v", d.Err) } @@ -239,7 +260,7 @@ func TestManagerT1ShortCircuitUsesBaseKey(t *testing.T) { rig.manager.t1Contains = func(key string) bool { return resident[key] } rig.manager.Prefetch(base, AssetTypeCharIcon, network.PriorityHigh) // AssetType: CharIcon - d := waitDecoded(t, rig.manager) + d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("decode error: %v", d.Err) } @@ -265,10 +286,8 @@ func TestManagerT1ShortCircuitUsesBaseKey(t *testing.T) { if got := cs.total(); got != firstLoad { t.Errorf("requests after the T1 hit = %d, want still %d (no re-fetch)", got, firstLoad) } - select { - case d := <-rig.manager.Decoded(): + if d, ok := rig.takeDecoded(0); ok { t.Errorf("unexpected re-decode of resident asset: %+v", d) - default: } } @@ -291,7 +310,7 @@ func TestManagerUnprefixedSpriteFallback(t *testing.T) { rig.manager.t1Contains = func(key string) bool { return resident[key] } rig.manager.PrefetchChain(primary, []string{bare}, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - d := waitDecoded(t, rig.manager) + d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("decode error: %v", d.Err) } @@ -338,7 +357,7 @@ func TestManagerPrefetchChain(t *testing.T) { } rig.manager.PrefetchChain(identity, alts, AssetTypeMisc, network.PriorityHigh) // AssetType: Misc (test chain) - d := waitDecoded(t, rig.manager) + d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("decode error: %v", d.Err) } @@ -408,7 +427,7 @@ func TestManagerLocalMounts(t *testing.T) { origin := local.BaseURL() rig.manager.Prefetch(origin+"characters/phoenix/(a)normal", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - d := waitDecoded(t, rig.manager) + d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("local decode error: %v", d.Err) } @@ -418,7 +437,7 @@ func TestManagerLocalMounts(t *testing.T) { d.Asset.Release() rig.manager.Prefetch(origin+"characters/phoenix/(b)normal", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - d = waitDecoded(t, rig.manager) + d = waitDecoded(t, rig) if d.Err != nil { t.Fatalf("local decode error: %v", d.Err) } @@ -456,21 +475,17 @@ func TestManagerInflightDedup(t *testing.T) { for i := 0; i < 4; i++ { rig.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite } - d := waitDecoded(t, rig.manager) + d := waitDecoded(t, rig) if d.Err != nil { t.Fatal(d.Err) } d.Asset.Release() // No further deliveries expected; give stragglers a moment to misbehave. - select { - case extra := <-rig.manager.Decoded(): - // A second delivery is acceptable only if it was a T2 hit decode - // (same bytes); more than one upstream probe is not. - if extra.Err == nil && extra.Asset != nil { - extra.Asset.Release() - } - case <-time.After(200 * time.Millisecond): + // A second delivery is acceptable only if it was a T2 hit decode (same bytes); more than one upstream probe is not. + const stragglerWait = 200 * time.Millisecond + if extra, ok := rig.takeDecoded(stragglerWait); ok && extra.Err == nil && extra.Asset != nil { + extra.Asset.Release() } if got := cs.total(); got != 1 { t.Errorf("upstream probes = %d, want 1 (inflight dedup + singleflight)", got) @@ -527,13 +542,10 @@ func TestPurgeCorruptEvictsTiers(t *testing.T) { wantURL := base + ".webp" // the format probed first — the T2/T3 key rig.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - d := waitDecoded(t, rig.manager) + d := waitDecoded(t, rig) if d.Err == nil { t.Fatal("corrupt payload decoded without error") } - if d.Transient { - t.Fatal("corrupt-decode failure tagged transient — it would never be purged") - } if d.URL != wantURL { t.Fatalf("delivered URL = %q, want the fetched %q (the T2/T3 key)", d.URL, wantURL) } diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index b466c655..b6109d9a 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -73,7 +73,7 @@ func newMediaBridge(m *Manager) *mediaBridge { b.folders = newBridgeFolders(m) b.learned = saver.New(m.learnedPath, learnedSaveDelay, b.encodeLearned) cfg := media.Config{Candidates: b.builder.Build, AllFormats: media.EveryFormat, Found: b.found, - Finished: b.finished, Compute: b.compute} + Finished: b.finished, Delivered: m.NotifyDelivery, Compute: b.compute} b.remote = media.NewRemoteSource(ctx, bridgeFetcher{m}, media.DefaultMissingTTL, time.Now) cfg.Chains = map[media.Place]*media.Chain{media.PlaceServer: media.NewChain( media.Entry{Source: bridgeMemory{m.t2, b.pin, m}}, @@ -355,12 +355,8 @@ func (b *mediaBridge) finished(a *media.Asset) { if t == AssetTypeMusic { b.m.reportMusicFailure(k.Path, err) } - // Tagged transient so it never enters the decode negative cache. - b.media.Run(b.compute, media.Later, func() any { - b.m.decodedCh <- DecodedAsset{URL: k.Path, Base: k.Path, Type: t, Err: err, Transient: true} - b.m.NotifyDelivery() - return nil - }, func(any) {}) + // Counted, never shown as a broken asset: the bytes were never seen, so the next ask tries again. + b.m.failed.Add(1) default: // Delivered: from here T1 answers, and an evicted texture has to be able to ask again. b.media.ForgetAsset(a) @@ -570,32 +566,32 @@ func (b *mediaBridge) hitOf(hit media.Hit) (string, bool) { return string(hit.File), hit.Source == media.Source(b.folders) } -// bridgeImage decodes through DecoderPool, holding a Compute worker until the last frame, so Now work keeps its place. +// bridgeImage decodes on the Compute worker that holds the request; an animation's opening frames go to the render +// thread as early pages, and the last page is the result. type bridgeImage struct{ b *mediaBridge } -func (f bridgeImage) OnMainThread() bool { return false } +func (f bridgeImage) OnMainThread() bool { return true } -func (f bridgeImage) Decode(k media.Key, hit media.Hit, data []byte) (any, error) { +func (f bridgeImage) Decode(k media.Key, hit media.Hit, data []byte, page func(any)) (any, error) { url, fromPack := f.b.hitOf(hit) t := AssetType(k.Tag) m := f.b.m - finished := make(chan struct{}) - accepted := m.decoder.Submit(DecodeRequest{ + var last DecodedAsset + m.decoder.Decode(DecodeRequest{ URL: url, Data: data, Type: t, PlayAnimations: m.prefs.Load().PreferAnimated, OnDone: func(doneURL string, d *Decoded, err error) { - m.onDecoded(doneURL, k.Path, t, fromPack, d, err) - if d == nil || !d.Partial { - close(finished) + decoded := DecodedAsset{URL: doneURL, Base: k.Path, Type: t, Asset: d, Err: err, FromPack: fromPack} + if d != nil && d.Partial { + page(decoded) + return } + last = decoded }, }) - if accepted { - <-finished - } - return nil, nil + return last, nil } // bridgeSound hands the bytes to the audio side, which decodes them itself. @@ -603,7 +599,7 @@ type bridgeSound struct{ b *mediaBridge } func (f bridgeSound) OnMainThread() bool { return false } -func (f bridgeSound) Decode(k media.Key, hit media.Hit, data []byte) (any, error) { +func (f bridgeSound) Decode(k media.Key, hit media.Hit, data []byte, _ func(any)) (any, error) { url, fromPack := f.b.hitOf(hit) f.b.m.audioCh <- AudioAsset{URL: url, Base: k.Path, Type: AssetType(k.Tag), Data: data, FromPack: fromPack} f.b.m.NotifyDelivery() diff --git a/internal/assets/mediabridge_test.go b/internal/assets/mediabridge_test.go index 0e4f6e8a..8390e10f 100644 --- a/internal/assets/mediabridge_test.go +++ b/internal/assets/mediabridge_test.go @@ -73,31 +73,29 @@ func newBridgeRig(t *testing.T, host *bridgeFakeHost) *testRig { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := NewDecoderPool(bridgeTestWorkers) - t.Cleanup(decoder.Close) + decoder := NewDecoder() m := NewManager(ManagerDeps{Prefs: prefs, T2: t2, Disk: disk, Source: host, Decoder: decoder}) t.Cleanup(m.CloseMedia) return &testRig{prefs: prefs, manager: m, decoder: decoder, disk: disk, t2: t2} } // nextDecoded waits for the final page of base, releasing partial ones as the upload pump does. -func nextDecoded(t *testing.T, m *Manager, base string) DecodedAsset { +func nextDecoded(t *testing.T, rig *testRig, base string) DecodedAsset { t.Helper() - deadline := time.After(bridgeTestTimeout) + deadline := time.Now().Add(bridgeTestTimeout) for { - select { - case d := <-m.Decoded(): - if d.Base != base { - continue - } - if d.Asset != nil && d.Asset.Partial { - d.Asset.Release() - continue - } - return d - case <-deadline: + d, ok := rig.takeDecoded(time.Until(deadline)) + if !ok { t.Fatalf("%s was never delivered", base) } + if d.Base != base { + continue + } + if d.Asset != nil && d.Asset.Partial { + d.Asset.Release() + continue + } + return d } } @@ -107,7 +105,7 @@ func TestBridgeDeliversAndLearns(t *testing.T) { r := newBridgeRig(t, host) base := bridgeTestOrigin + "c/(a)e" r.manager.PrefetchChain(base, []string{bridgeTestOrigin + "c/e"}, AssetTypeCharSprite, network.PriorityHigh) - d := nextDecoded(t, r.manager, base) + d := nextDecoded(t, r, base) if d.Err != nil || d.Asset == nil || d.URL != base+".webp" { t.Fatalf("url %q err %v", d.URL, d.Err) } @@ -119,12 +117,12 @@ func TestBridgeAsksAgainAfterDelivery(t *testing.T) { r := newBridgeRig(t, host) base := bridgeTestOrigin + "e" r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) - nextDecoded(t, r.manager, base) + nextDecoded(t, r, base) deadline := time.Now().Add(bridgeTestTimeout) // An evicted texture asks again and comes back from memory, with no second request. var d DecodedAsset got := make(chan DecodedAsset, 1) - go func() { got <- nextDecoded(t, r.manager, base) }() + go func() { got <- nextDecoded(t, r, base) }() for time.Now().Before(deadline) { r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) select { @@ -174,14 +172,24 @@ func TestBridgeMissingWarnsAndDoesNotAskAgain(t *testing.T) { } } +// A host that can't be reached is counted as a failed fetch, never shown as a broken or missing asset. func TestBridgeTransportFailureIsTransient(t *testing.T) { host := &bridgeFakeHost{files: map[string][]byte{}, broken: errors.New("refused")} r := newBridgeRig(t, host) base := bridgeTestOrigin + "e" r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) - d := nextDecoded(t, r.manager, base) - if d.Err == nil || !d.Transient { - t.Fatalf("err %v transient %v", d.Err, d.Transient) + deadline := time.Now().Add(bridgeTestTimeout) + for r.manager.Stats().Failed == 0 { + if time.Now().After(deadline) { + t.Fatal("the failed fetch was never counted") + } + time.Sleep(time.Millisecond) + } + if r.manager.IsMissing(base, AssetTypeCharSprite) { + t.Error("a failed fetch was remembered as missing") + } + if d, ok := r.takeDecoded(0); ok { + t.Errorf("a failed fetch reached the render thread: %+v", d) } } @@ -196,7 +204,7 @@ func TestBridgeHungHostDoesNotBlockOtherWork(t *testing.T) { } base := bridgeTestOrigin + "e" r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) - if d := nextDecoded(t, r.manager, base); d.Err != nil { + if d := nextDecoded(t, r, base); d.Err != nil { t.Fatal(d.Err) } } @@ -237,7 +245,7 @@ func TestBridgeManifestSetsOrderAndIsFetchedFresh(t *testing.T) { } base := bridgeTestOrigin + "e" r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) - nextDecoded(t, r.manager, base) + nextDecoded(t, r, base) want := []string{bridgeTestOrigin + media.ManifestFile, bridgeTestOrigin + media.ManifestFile, base + ".png", base + ".webp"} if asked := host.askedFor(); !slices.Equal(asked, want) { t.Fatalf("asked %v, want %v", asked, want) @@ -262,7 +270,7 @@ func TestBridgeOfflineRecordsNothing(t *testing.T) { time.Sleep(bridgeSettle) r.manager.SetOffline(false) r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) - if d := nextDecoded(t, r.manager, base); d.Err != nil { + if d := nextDecoded(t, r, base); d.Err != nil { t.Fatalf("a file offline said nothing about was not fetched: %v", d.Err) } } @@ -282,7 +290,7 @@ func TestBridgeExtraHostServesWhatTheServerLacks(t *testing.T) { r.manager.SetAssetHosts(bridgeTestOrigin, []string{mirror}) waitUntil(t, "the miss to be forgotten", func() bool { return !r.manager.IsMissing(base, AssetTypeCharSprite) }) r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) - d := nextDecoded(t, r.manager, base) + d := nextDecoded(t, r, base) if d.Err != nil || d.Asset == nil || d.URL != mirror+"c/e.webp" { t.Fatalf("url %q err %v", d.URL, d.Err) } diff --git a/internal/assets/notify_test.go b/internal/assets/notify_test.go index 4226cfe3..be1959bf 100644 --- a/internal/assets/notify_test.go +++ b/internal/assets/notify_test.go @@ -45,13 +45,12 @@ func TestManagerDeliveryNotify(t *testing.T) { case <-deadline: t.Fatal("no delivery wake after the decode landed") } - select { - case d := <-rig.manager.Decoded(): - if d.Err != nil || d.Asset == nil { - t.Fatalf("decode delivery broken: %+v", d) - } - d.Asset.Release() - case <-time.After(managerWait): + d, ok := rig.takeDecoded(managerWait) + if !ok { t.Fatal("the decode itself never delivered") } + if d.Err != nil || d.Asset == nil { + t.Fatalf("decode delivery broken: %+v", d) + } + d.Asset.Release() } diff --git a/internal/assets/scenerypin_test.go b/internal/assets/scenerypin_test.go index be92383b..cef24534 100644 --- a/internal/assets/scenerypin_test.go +++ b/internal/assets/scenerypin_test.go @@ -54,7 +54,7 @@ func TestAFetchedBackgroundIsServedFromThePinAfterTheSharedCacheDropsIt(t *testi r := newBridgeRig(t, host) r.manager.PinScenery(bridgeTestOrigin + "background/court/") r.manager.PrefetchChain(base, nil, AssetTypeBackground, network.PriorityHigh) // AssetType: Background - nextDecoded(t, r.manager, base) + nextDecoded(t, r, base) r.t2.Purge() if (bridgeMemory{r.t2, r.manager.bridge.pin, r.manager}).Has(media.File(base+".webp")) != media.Yes { t.Fatal("the room's background left memory with the shared cache") diff --git a/internal/assets/webp_cgo_test.go b/internal/assets/webp_cgo_test.go index ec817ddd..1498e5de 100644 --- a/internal/assets/webp_cgo_test.go +++ b/internal/assets/webp_cgo_test.go @@ -86,8 +86,7 @@ func TestDecodeWebPAnimatedFirstFrameOnly(t *testing.T) { // frame-by-frame instead of being replaced by a full set. Statics deliver // exactly once. func TestProgressiveAnimatedDecode(t *testing.T) { - pool := NewDecoderPool(1) - defer pool.Close() + pool := NewDecoder() type result struct { frames int @@ -97,29 +96,18 @@ func TestProgressiveAnimatedDecode(t *testing.T) { source int } deliver := func(data []byte) []result { - out := make(chan result, 8) - done := make(chan struct{}) - pool.Submit(DecodeRequest{ + var rs []result + pool.Decode(DecodeRequest{ URL: "x", Data: data, Type: AssetTypeCharSprite, PlayAnimations: true, OnDone: func(_ string, d *Decoded, err error) { if err != nil { t.Errorf("decode: %v", err) - close(done) return } - out <- result{frames: len(d.Frames), partial: d.Partial, stream: d.Stream, offset: d.FrameOffset, source: d.SourceFrames} - if !d.Partial { - close(done) // the finalize is always the last delivery - } + rs = append(rs, result{frames: len(d.Frames), partial: d.Partial, stream: d.Stream, offset: d.FrameOffset, source: d.SourceFrames}) d.Release() }, }) - <-done - close(out) - var rs []result - for r := range out { - rs = append(rs, r) - } return rs } @@ -253,33 +241,20 @@ func TestAOneFrameAnimationDecodesToItsFrame(t *testing.T) { if Sniff(data) != FormatWebPAnim { t.Fatalf("built %v, want an animated webp", Sniff(data)) } - const wait = 5 * time.Second - pool := NewDecoderPool(1) - defer pool.Close() - got := make(chan *Decoded, 4) - pool.Submit(DecodeRequest{ + var frames int + var final *Decoded + NewDecoder().Decode(DecodeRequest{ URL: "x", Data: data, Type: AssetTypeCharSprite, PlayAnimations: true, OnDone: func(_ string, d *Decoded, err error) { if err != nil { - t.Errorf("decode: %v", err) - d = &Decoded{} + t.Fatalf("decode: %v", err) } - got <- d - }, - }) - var frames int - var final *Decoded - for final == nil { - select { - case d := <-got: frames += len(d.Frames) if !d.Partial { final = d } - case <-time.After(wait): - t.Fatalf("no final page after %d frames", frames) - } - } + }, + }) if final == nil || frames != 1 || final.Width != w || final.Height != h { t.Fatalf("delivered %d frames, final %+v; want one %dx%d frame and a final page", frames, final, w, h) } diff --git a/internal/courtroom/bgfallback_test.go b/internal/courtroom/bgfallback_test.go index 0aef859a..75e821ec 100644 --- a/internal/courtroom/bgfallback_test.go +++ b/internal/courtroom/bgfallback_test.go @@ -41,8 +41,7 @@ func newBGRig(t *testing.T) *bgRig { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() mount := t.TempDir() local := assets.NewLocalFetcher([]string{mount}) @@ -85,11 +84,18 @@ func awaitDelivery(t *testing.T, mgr *assets.Manager, want string) string { t.Helper() deadline := time.After(5 * time.Second) for { - select { - case d := <-mgr.Decoded(): - if d.Base == want { - return d.URL + answered := "" + mgr.TakeDeliveries(func(d assets.Delivery) { + if d.Base == want && answered == "" { + answered = d.URL } + mgr.Done(d) + }) + if answered != "" { + return answered + } + select { + case <-time.After(time.Millisecond): case w := <-mgr.Warnings(): if w.Base == want { t.Fatalf("the background chain reported %q missing instead of falling back (tried %v)", w.Base, w.Tried) @@ -256,11 +262,14 @@ func TestTheDeskKeepsItsNoFallbackContract(t *testing.T) { } deadline := time.After(5 * time.Second) for { - select { - case d := <-r.mgr.Decoded(): + r.mgr.TakeDeliveries(func(d assets.Delivery) { if d.Base == deskBase { - t.Fatalf("the desk must NOT fall back; it was served %q", d.URL) + t.Errorf("the desk must NOT fall back; it was served %q", d.URL) } + r.mgr.Done(d) + }) + select { + case <-time.After(time.Millisecond): case w := <-r.mgr.Warnings(): if w.Base == deskBase { return // conclusively missing → DeskDrawn hides the layer. Correct. diff --git a/internal/courtroom/courtroom_test.go b/internal/courtroom/courtroom_test.go index 16d8a052..d5e5022b 100644 --- a/internal/courtroom/courtroom_test.go +++ b/internal/courtroom/courtroom_test.go @@ -76,8 +76,7 @@ func newCourtroomRig(t testing.TB) (*Courtroom, *Session, *sentRecorder, *audioR t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() local := assets.NewLocalFetcher([]string{t.TempDir()}) mgr := assets.NewManager(assets.ManagerDeps{ Prefs: prefs, T2: t2, Disk: disk, diff --git a/internal/courtroom/messageneeds_test.go b/internal/courtroom/messageneeds_test.go index d327bd65..0e2fbc3b 100644 --- a/internal/courtroom/messageneeds_test.go +++ b/internal/courtroom/messageneeds_test.go @@ -133,8 +133,7 @@ func recordingRoom(t *testing.T) (*Courtroom, *recordingSource) { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(1) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() src := &recordingSource{} mgr := assets.NewManager(assets.ManagerDeps{ Prefs: prefs, T2: t2, Disk: disk, diff --git a/internal/media/manager.go b/internal/media/manager.go index e017bb0d..75b989be 100644 --- a/internal/media/manager.go +++ b/internal/media/manager.go @@ -32,6 +32,8 @@ type Config struct { Found func(Key, File) // Finished runs on the Manager's goroutine when a request ends, and must not block. Finished func(*Asset) + // Delivered runs after a result is waiting for TakeResults, on any goroutine, to wake the main thread's loop. + Delivered func() // ClaimLimit is the memory decodes may claim at once; Now work may pass it, so a message can't wait on memory. ClaimLimit int64 MaxAssets int @@ -87,10 +89,12 @@ type request struct { lastErr error queued bool dead bool - pool *Pool - work func() any - done func(any) - next *request + // page marks an early part of a result, which the main thread uses without finishing the Asset. + page bool + pool *Pool + work func() any + done func(any) + next *request } // pipe is a lock-free list many threads push to and one thread takes whole. @@ -341,10 +345,19 @@ func (m *Manager) Run(pool *Pool, urgency Urgency, work func() any, done func(an m.post(&request{event: eventWork, pool: pool, urgency: urgency, work: work, done: done, step: stepWork}) } -// TakeResults hands the main thread every result that needs it, once per frame, with one atomic swap. -func (m *Manager) TakeResults(use func(*Asset, any)) { +// TakeResults hands the main thread every result that needs it, in order, once per frame, with one atomic swap. final is +// false for an early page; only the final result is Finished. +func (m *Manager) TakeResults(use func(a *Asset, result any, final bool)) { for r := m.results.take(); r != nil; r = r.next { - use(r.asset, r.result) + use(r.asset, r.result, !r.page) + } +} + +// deliver queues a result for TakeResults and wakes the main thread; any goroutine. +func (m *Manager) deliver(r *request) { + m.results.push(r) + if m.cfg.Delivered != nil { + m.cfg.Delivered() } } @@ -631,7 +644,7 @@ func (m *Manager) decodeDone(r *request) { } if m.cfg.Formats[r.asset.key.Kind].OnMainThread() { delete(m.active, r.asset.key) - m.results.push(r) + m.deliver(r) return } m.end(r, Ready, r.result, nil) @@ -710,10 +723,11 @@ func (m *Manager) start(p *Pool, r *request) { m.claimed += r.claim r.asset.claim.Store(r.claim) format := m.cfg.Formats[r.asset.key.Kind] - key, data := r.asset.key, r.bytes + key, data, asset := r.asset.key, r.bytes, r.asset hit := Hit{File: r.file, Source: m.cfg.Chains[key.Place].entries[r.entry].Source} + page := func(v any) { m.deliver(&request{asset: asset, result: v, page: true}) } p.jobs <- func() { - r.result, r.err = format.Decode(key, hit, data) + r.result, r.err = format.Decode(key, hit, data, page) m.report(r) } } diff --git a/internal/media/manager_test.go b/internal/media/manager_test.go index 2a9b7aba..2f9094a5 100644 --- a/internal/media/manager_test.go +++ b/internal/media/manager_test.go @@ -3,6 +3,7 @@ package media import ( "context" "errors" + "slices" "sync" "sync/atomic" "testing" @@ -106,7 +107,7 @@ type fakeFormat struct { measured int64 } -func (f *fakeFormat) Decode(_ Key, _ Hit, b []byte) (any, error) { +func (f *fakeFormat) Decode(_ Key, _ Hit, b []byte, _ func(any)) (any, error) { f.started.Add(1) if f.hold != nil { <-f.hold @@ -385,7 +386,7 @@ func TestMainThreadResultsWaitForFinish(t *testing.T) { var got any deadline := time.Now().Add(testTimeout) for got == nil && time.Now().Before(deadline) { - m.TakeResults(func(_ *Asset, r any) { got = r }) + m.TakeResults(func(_ *Asset, r any, _ bool) { got = r }) time.Sleep(time.Millisecond) } if got != "pixels" { @@ -516,3 +517,57 @@ func TestEveryRequestEnds(t *testing.T) { } } } + +// pagingFormat hands two early pages to the main thread, then returns the last one. +type pagingFormat struct{} + +func (pagingFormat) Decode(_ Key, _ Hit, b []byte, page func(any)) (any, error) { + page("first") + page("second") + return string(b), nil +} + +func (pagingFormat) OnMainThread() bool { return true } + +// A result can arrive in pages: early ones in order, then the final one, each waking the main thread. +func TestResultPagesArriveInOrderBeforeTheFinal(t *testing.T) { + src := newFakeSource("memory") + src.put("a", []byte("last")) + compute := NewPool("compute", testWorkers, 1) + t.Cleanup(compute.Close) + var woken atomic.Int64 + m := NewManager(Config{ + Chains: map[Place]*Chain{PlaceServer: NewChain(Entry{Source: src})}, + Formats: map[Kind]Format{KindImage: pagingFormat{}}, + Candidates: oneFile, + Compute: compute, + Delivered: func() { woken.Add(1) }, + }) + t.Cleanup(m.Close) + + a := m.Get(image("a"), Now, 0) + type got struct { + result any + final bool + } + var all []got + deadline := time.Now().Add(testTimeout) + for (len(all) == 0 || !all[len(all)-1].final) && time.Now().Before(deadline) { + m.TakeResults(func(_ *Asset, r any, final bool) { all = append(all, got{r, final}) }) + time.Sleep(time.Millisecond) + } + want := []got{{"first", false}, {"second", false}, {"last", true}} + if !slices.Equal(all, want) { + t.Fatalf("results %v, want %v", all, want) + } + if n := woken.Load(); n != int64(len(want)) { + t.Errorf("the main thread was woken %d times, want %d", n, len(want)) + } + if a.Ready() { + t.Fatal("a page finished the Asset") + } + m.Finish(a, "texture") + if !a.Ready() { + t.Fatal("Finish after the final page didn't finish the Asset") + } +} diff --git a/internal/media/types.go b/internal/media/types.go index 0580bbd3..850227df 100644 --- a/internal/media/types.go +++ b/internal/media/types.go @@ -124,7 +124,9 @@ type Hit struct { // Format turns bytes into a result on a Compute worker, and holds no shared state. type Format interface { - Decode(key Key, hit Hit, data []byte) (any, error) + // Decode returns the result; page hands the main thread an earlier part of it first, such as the opening frames of + // a long animation, for a format whose results need the main thread. + Decode(key Key, hit Hit, data []byte, page func(any)) (any, error) // OnMainThread reports whether a result needs the main thread, such as a texture upload, before it is ready. OnMainThread() bool } diff --git a/internal/render/pump.go b/internal/render/pump.go index c774b11b..b6ef20e6 100644 --- a/internal/render/pump.go +++ b/internal/render/pump.go @@ -11,28 +11,23 @@ import ( type Pump struct { store *TextureStore mgr *assets.Manager - // carry holds budget-deferred uploads, bounded by the manager's decoded channel capacity plus its backlog. - carry []assets.DecodedAsset + // carry holds budget-deferred uploads; each still holds its request, so the media system's claim limit bounds it. + carry []assets.Delivery // IsLive reports whether a base belongs to the message on screen, which bypasses the budget. IsLive func(base string) bool - // uploadErrs and transientErrs are debug counters; atomic so the panel read can't race. - uploadErrs atomic.Int64 - transientErrs atomic.Int64 + // uploadErrs is a debug counter; atomic so the panel read can't race. + uploadErrs atomic.Int64 } // PumpStats is a snapshot of the pump's debug counters. type PumpStats struct { - UploadErrs int64 // GPU texture-upload failures (over-budget canvas, OOM) - TransientErrs int64 // network-stage failures that reached the pump (not cached) + UploadErrs int64 // GPU texture-upload failures (over-budget canvas, OOM) } // Stats snapshots the error counters using atomic loads, so it never blocks Frame. func (p *Pump) Stats() PumpStats { - return PumpStats{ - UploadErrs: p.uploadErrs.Load(), - TransientErrs: p.transientErrs.Load(), - } + return PumpStats{UploadErrs: p.uploadErrs.Load()} } func NewPump(store *TextureStore, mgr *assets.Manager, isLive func(base string) bool) *Pump { @@ -47,20 +42,17 @@ func (p *Pump) Frame() { uploadedTextures := 0 uploadedBytes := int64(0) - withinBudget := func(d *assets.DecodedAsset) bool { + withinBudget := func(d *assets.Delivery) bool { if p.IsLive(d.Base) { return true // live-message uploads are never deferred } return uploadedTextures < speculativeUploadMaxTextures && uploadedBytes < speculativeUploadMaxBytes } - upload := func(d assets.DecodedAsset) { + upload := func(delivery assets.Delivery) { + defer p.mgr.Done(delivery) + d := delivery.DecodedAsset if d.Err != nil || d.Asset == nil { - // Network-stage failures skip the negative cache: the bytes were never seen, so the next demand must retry. - if d.Err != nil && d.Transient { - p.transientErrs.Add(1) - return - } // Bad cached bytes: purge T2/T3 by d.URL (their key, never d.Base), or the same blob re-promotes forever. if d.Err != nil { p.mgr.PurgeCorrupt(d.URL) @@ -123,16 +115,11 @@ func (p *Pump) Frame() { } p.carry = kept - for { - select { - case d := <-p.mgr.Decoded(): - if withinBudget(&d) { - upload(d) - } else { - p.carry = append(p.carry, d) - } - default: - return + p.mgr.TakeDeliveries(func(d assets.Delivery) { + if withinBudget(&d) { + upload(d) + } else { + p.carry = append(p.carry, d) } - } + }) } diff --git a/internal/render/pump_test.go b/internal/render/pump_test.go index ef3bcb5a..26dd854c 100644 --- a/internal/render/pump_test.go +++ b/internal/render/pump_test.go @@ -40,8 +40,7 @@ func buildPumpManager(t *testing.T, source assets.Fetcher, localMode bool) *asse t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() mgr := assets.NewManager(assets.ManagerDeps{ Prefs: prefs, T2: t2, Disk: disk, Source: source, Decoder: decoder, @@ -107,7 +106,7 @@ func TestPumpUploadsPrefetchByBase(t *testing.T) { mgr.Prefetch(base, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (warm-gate prefetch) // Pump every "frame" until the async decode lands in T1 — the same loop the - // export's warm phase runs (Pump.Frame() drains Manager.Decoded() each frame). + // export's warm phase runs (Pump.Frame() takes the waiting deliveries each frame). deadline := time.Now().Add(3 * time.Second) for !store.Contains(base) && time.Now().Before(deadline) { pump.Frame() @@ -147,16 +146,16 @@ func TestPumpTransientErrorsDontPin(t *testing.T) { pump := NewPump(store, mgr, nil) // Sick origin: the fetch (with its bounded retry) fails at the network - // stage → transient → counted, NOT pinned. + // stage → counted as a failed fetch, NOT pinned. sick := srvSick.URL + "/characters/witch/(a)sick" mgr.Prefetch(sick, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (test) deadline := time.Now().Add(5 * time.Second) - for pump.Stats().TransientErrs == 0 && time.Now().Before(deadline) { + for mgr.Stats().Failed == 0 && time.Now().Before(deadline) { pump.Frame() time.Sleep(5 * time.Millisecond) } - if pump.Stats().TransientErrs == 0 { - t.Fatal("the network failure never reached the pump as transient") + if mgr.Stats().Failed == 0 { + t.Fatal("the network failure was never counted") } if store.FailedRecently(sick) { t.Error("a transient network failure entered the decode negative cache — the asset would stay blank for decodeFailTTL after the origin recovers") diff --git a/internal/ui/conclusivemiss_ui_test.go b/internal/ui/conclusivemiss_ui_test.go index 825d394a..ddf523a8 100644 --- a/internal/ui/conclusivemiss_ui_test.go +++ b/internal/ui/conclusivemiss_ui_test.go @@ -36,8 +36,7 @@ func wireEmptyPackManager(t *testing.T, a *App) *assets.LocalFetcher { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() local := assets.NewLocalFetcher([]string{t.TempDir()}) // empty: nothing resolves a.d.Manager = assets.NewManager(assets.ManagerDeps{ @@ -52,16 +51,11 @@ func wireEmptyPackManager(t *testing.T, a *App) *assets.LocalFetcher { return local } -// drainManager empties the manager's result channels so the pipeline keeps -// moving while a gate polls. Results are never dropped by the manager (rule -// §17.7), so a gate that ignores them stalls the pool once the buffers fill. +// drainManager finishes the decoded pages and empties the warnings, so the pipeline keeps moving while a gate polls. func drainManager(a *App) { + releaseDeliveries(a) for { select { - case d := <-a.d.Manager.Decoded(): - if d.Asset != nil { - d.Asset.Release() - } case <-a.d.Manager.Warnings(): default: return @@ -69,6 +63,22 @@ func drainManager(a *App) { } } +// releaseDeliveries finishes every decoded page waiting, as the upload pump would, without uploading it. +func releaseDeliveries(a *App) { deliveredBase(a, "") } + +// deliveredBase finishes every decoded page waiting and reports whether base arrived without an error. +func deliveredBase(a *App, base string) bool { + got := false + a.d.Manager.TakeDeliveries(func(d assets.Delivery) { + got = got || base != "" && d.Base == base && d.Err == nil + if d.Asset != nil { + d.Asset.Release() + } + a.d.Manager.Done(d) + }) + return got +} + // settleMissUI waits until the manager has established that base is absent. func settleMissUI(t *testing.T, a *App, base string, typ assets.AssetType) { t.Helper() diff --git a/internal/ui/contentjob_test.go b/internal/ui/contentjob_test.go index 86730f75..a156d100 100644 --- a/internal/ui/contentjob_test.go +++ b/internal/ui/contentjob_test.go @@ -1105,8 +1105,7 @@ func headlessProbeApp(t *testing.T, source assets.Fetcher, localMode bool) *App t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() a.d.Manager = assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, T2: t2, @@ -1136,8 +1135,7 @@ func localMgr(t *testing.T, mount string) (*assets.Manager, string) { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(1) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() local := assets.NewLocalFetcher([]string{mount}) mgr := assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, diff --git a/internal/ui/debugpanel.go b/internal/ui/debugpanel.go index aeda13b0..0dd72ec5 100644 --- a/internal/ui/debugpanel.go +++ b/internal/ui/debugpanel.go @@ -242,7 +242,7 @@ func (a *App) drawDebugPerf(r sdl.Rect) { if ps.UploadErrs > 0 { col = ColTierYellow } - c.LabelClipped(r.X, y, r.W, fmt.Sprintf("Pump: %d upload errors · %d transient (network) errors", ps.UploadErrs, ps.TransientErrs), col) + c.LabelClipped(r.X, y, r.W, fmt.Sprintf("Pump: %d upload errors · %d failed fetches", ps.UploadErrs, a.d.Manager.Stats().Failed), col) y += debugLineH } @@ -361,8 +361,8 @@ func (a *App) drawDebugWorkers(r sdl.Rect) { y += debugLineH } s := a.d.Manager.WorkStats() - line(fmt.Sprintf("Decode: %d/%d busy · queue %d/%d", len(s.Decoding), s.DecodeWorkers, s.DecodeQueued, s.DecodeCap), ColText) - line(fmt.Sprintf("Waiting for the frame loop: images %d/%d · audio %d/%d", s.DecodedQueued, s.DecodedCap, s.AudioQueued, s.AudioCap), ColText) + line(fmt.Sprintf("Decode: %d/%d busy", len(s.Decoding), s.DecodeWorkers), ColText) + line(fmt.Sprintf("Waiting for the frame loop: audio %d/%d", s.AudioQueued, s.AudioCap), ColText) col := ColText if s.Refused > 0 { col = ColDanger diff --git a/internal/ui/deskmissing_relay_test.go b/internal/ui/deskmissing_relay_test.go index 2dae2f2e..9c3880e2 100644 --- a/internal/ui/deskmissing_relay_test.go +++ b/internal/ui/deskmissing_relay_test.go @@ -87,14 +87,8 @@ func TestDrainWarningsRelaysDeskMissing(t *testing.T) { t.Fatalf("desk miss never relayed: ShowDesk=%v IsMissing=%v", room.Scene.ShowDesk, a.d.Store.IsMissing(deskBase)) } a.drainWarnings() - select { - case d := <-a.d.Manager.Decoded(): - if d.Asset != nil { - d.Asset.Release() - } - default: - time.Sleep(2 * time.Millisecond) - } + releaseDeliveries(a) + time.Sleep(2 * time.Millisecond) } // Positive control on the type gate: a BACKGROUND miss must not be relayed as a @@ -107,14 +101,8 @@ func TestDrainWarningsRelaysDeskMissing(t *testing.T) { ctrl := time.Now().Add(500 * time.Millisecond) for time.Now().Before(ctrl) { a.drainWarnings() - select { - case d := <-a.d.Manager.Decoded(): - if d.Asset != nil { - d.Asset.Release() - } - default: - time.Sleep(2 * time.Millisecond) - } + releaseDeliveries(a) + time.Sleep(2 * time.Millisecond) } if a.d.Store.IsMissing(bgBase) { t.Error("a missing BACKGROUND must not be marked missing — the background arm of set_scene has a fallback, the desk arm does not") @@ -162,14 +150,8 @@ func TestDrainWarningsRelaysBackgroundMissToGate(t *testing.T) { } a.drainWarnings() room.Update(16 * time.Millisecond) - select { - case d := <-a.d.Manager.Decoded(): - if d.Asset != nil { - d.Asset.Release() - } - default: - time.Sleep(2 * time.Millisecond) - } + releaseDeliveries(a) + time.Sleep(2 * time.Millisecond) } // The split stays honest: the background was relayed to the courtroom gate but diff --git a/internal/ui/emotebuttonart_test.go b/internal/ui/emotebuttonart_test.go index 05d68c8e..36c9d84a 100644 --- a/internal/ui/emotebuttonart_test.go +++ b/internal/ui/emotebuttonart_test.go @@ -28,21 +28,15 @@ func TestSelectedEmoteButtonWithoutOnArtLoadsItsOffArt(t *testing.T) { for time.Now().Before(deadline) { a.iconAskBudget = charIconAskPerFrame a.drawEmoteImageButton(btn, me, 0, true, "normal") - for { + if deliveredBase(a, off) { + return + } + for drained := false; !drained; { select { - case d := <-a.d.Manager.Decoded(): - if d.Asset != nil { - d.Asset.Release() - } - if d.Base == off && d.Err == nil { - return - } - continue case <-a.d.Manager.Warnings(): - continue default: + drained = true } - break } time.Sleep(missGatePollStep) } diff --git a/internal/ui/emotepreviewfollow_test.go b/internal/ui/emotepreviewfollow_test.go index 3da84e55..9513bc3b 100644 --- a/internal/ui/emotepreviewfollow_test.go +++ b/internal/ui/emotepreviewfollow_test.go @@ -44,8 +44,7 @@ func emotePreviewFollowTestApp(t *testing.T) *App { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() a.d.Manager = assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, T2: t2, diff --git a/internal/ui/exportstall_test.go b/internal/ui/exportstall_test.go index a45d2f6e..a35260b8 100644 --- a/internal/ui/exportstall_test.go +++ b/internal/ui/exportstall_test.go @@ -72,8 +72,7 @@ func newExportStallHarness(t *testing.T) (*App, string) { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() a.d.Manager = assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, T2: t2, diff --git a/internal/ui/frameharness_test.go b/internal/ui/frameharness_test.go index 10b0ad3f..ae704e76 100644 --- a/internal/ui/frameharness_test.go +++ b/internal/ui/frameharness_test.go @@ -67,9 +67,6 @@ const ( // frameHarnessDt is the per-frame delta handed to App.Frame — one 60 Hz tick. // FIXED rather than wall-clock so a slow machine cannot change what a gate sees. frameHarnessDt = 16 * time.Millisecond - // frameHarnessPoolWorkers is the harness Manager's decode workers; no gate here fetches anything (a t.TempDir - // folder, autodetect off). - frameHarnessPoolWorkers = 2 // frameHarnessApplyFrames bounds how many frames driveUntilThemeApplied spends // waiting for an apply goroutine. At 16 ms of simulated time each this is a // generous real-time budget with a hard stop, so a stuck apply fails the gate @@ -99,8 +96,7 @@ func stageFrameDrivenApp(t testing.TB) (*App, func()) { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(frameHarnessPoolWorkers) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() a.d.Manager = assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, T2: t2, diff --git a/internal/ui/gifexport_async_test.go b/internal/ui/gifexport_async_test.go index d08d6f4b..18d97e61 100644 --- a/internal/ui/gifexport_async_test.go +++ b/internal/ui/gifexport_async_test.go @@ -238,8 +238,7 @@ func TestTickGifLoadTransitionsToWarming(t *testing.T) { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() a.d.Manager = assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, T2: t2, @@ -339,8 +338,7 @@ func newWarmHarness(t *testing.T) (*App, *render.TextureStore) { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() a.d.Manager = assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, T2: t2, @@ -356,15 +354,13 @@ func newWarmHarness(t *testing.T) (*App, *render.TextureStore) { // residency it seeds itself; these deliveries are irrelevant to it. go func() { for { + releaseDeliveries(a) select { - case d := <-a.d.Manager.Decoded(): - if d.Asset != nil { - d.Asset.Release() - } case <-a.d.Manager.Audio(): case <-a.d.Manager.Warnings(): case <-stopDrain: return + case <-time.After(time.Millisecond): } } }() diff --git a/internal/ui/missingno_noblip_test.go b/internal/ui/missingno_noblip_test.go index f4fd7d52..fd76e287 100644 --- a/internal/ui/missingno_noblip_test.go +++ b/internal/ui/missingno_noblip_test.go @@ -41,8 +41,7 @@ func wireLocalManager(t *testing.T, a *App, dir string) (*assets.LocalFetcher, f t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() local := assets.NewLocalFetcher([]string{dir}) a.d.Manager = assets.NewManager(assets.ManagerDeps{ @@ -128,14 +127,10 @@ func TestSceneWarmNoMissingnoForFolderOnlySprite(t *testing.T) { settleDeadline := time.Now().Add(5 * time.Second) gotDecode := false for !gotDecode && time.Now().Before(settleDeadline) { + if deliveredBase(a, glued) { + gotDecode = true + } select { - case d := <-a.d.Manager.Decoded(): - if d.Err == nil && d.Base == glued { - gotDecode = true - } - if d.Asset != nil { - d.Asset.Release() - } case w := <-a.d.Manager.Warnings(): t.Fatalf("a folder-only sprite must NOT report missing (no-blip guarantee); got Warning for %q", w.Base) default: @@ -172,14 +167,10 @@ func TestHealSpriteLayerFolderOnlySprite(t *testing.T) { settleDeadline := time.Now().Add(5 * time.Second) gotDecode := false for !gotDecode && time.Now().Before(settleDeadline) { + if deliveredBase(a, glued) { + gotDecode = true + } select { - case d := <-a.d.Manager.Decoded(): - if d.Err == nil && d.Base == glued { - gotDecode = true - } - if d.Asset != nil { - d.Asset.Release() - } case w := <-a.d.Manager.Warnings(): t.Fatalf("a folder-only sprite must NOT report missing via healSpriteLayer; got Warning for %q", w.Base) default: @@ -233,14 +224,10 @@ func TestSceneWarmNoMissingnoForBareOnlySprite(t *testing.T) { settleDeadline := time.Now().Add(5 * time.Second) gotDecode := false for !gotDecode && time.Now().Before(settleDeadline) { + if deliveredBase(a, prefixed) { + gotDecode = true + } select { - case d := <-a.d.Manager.Decoded(): - if d.Err == nil && d.Base == prefixed { - gotDecode = true - } - if d.Asset != nil { - d.Asset.Release() - } case w := <-a.d.Manager.Warnings(): t.Fatalf("a bare-only sprite must NOT report missing (no-blip guarantee); got Warning for %q", w.Base) default: @@ -291,13 +278,7 @@ func TestSceneWarmMarksTrulyMissingSprite(t *testing.T) { break } // Drain any transient decode results so the pipeline keeps moving. - select { - case d := <-a.d.Manager.Decoded(): - if d.Asset != nil { - d.Asset.Release() - } - default: - time.Sleep(2 * time.Millisecond) - } + releaseDeliveries(a) + time.Sleep(2 * time.Millisecond) } } diff --git a/internal/ui/newroom_test.go b/internal/ui/newroom_test.go index 6d92b7f9..3be0299f 100644 --- a/internal/ui/newroom_test.go +++ b/internal/ui/newroom_test.go @@ -72,8 +72,7 @@ func roomFactoryAppMounted(t *testing.T) (*App, string, func()) { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() a.d.Manager = assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, T2: t2, diff --git a/internal/ui/packcharini_test.go b/internal/ui/packcharini_test.go index f90826f9..816a4823 100644 --- a/internal/ui/packcharini_test.go +++ b/internal/ui/packcharini_test.go @@ -40,8 +40,7 @@ func packApp(t *testing.T, files map[string]string) *App { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() a.d.Manager = assets.NewManager(assets.ManagerDeps{ Prefs: a.d.Prefs, diff --git a/internal/ui/sendonchange_test.go b/internal/ui/sendonchange_test.go index e746b7ee..5d138efa 100644 --- a/internal/ui/sendonchange_test.go +++ b/internal/ui/sendonchange_test.go @@ -30,8 +30,7 @@ func newRoomForTest(t testing.TB) *courtroom.Courtroom { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(2) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() local := assets.NewLocalFetcher([]string{t.TempDir()}) mgr := assets.NewManager(assets.ManagerDeps{ Prefs: prefs, T2: t2, Disk: disk, diff --git a/internal/ui/themeeditorpreview_test.go b/internal/ui/themeeditorpreview_test.go index d39602d0..3d521950 100644 --- a/internal/ui/themeeditorpreview_test.go +++ b/internal/ui/themeeditorpreview_test.go @@ -327,8 +327,7 @@ func stageCountingFetcher(t *testing.T, a *App) *countingFetcher { t.Fatal(err) } t.Cleanup(disk.Close) - decoder := assets.NewDecoderPool(frameHarnessPoolWorkers) - t.Cleanup(decoder.Close) + decoder := assets.NewDecoder() // The production constructor with ONE substituted collaborator. Streaming mode // (no folders), because that is the mode a real install runs in and the mode // whose egress the offline gate stands in front of. From 781196ab992589b45604c014d03950b6d2584285 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 01:53:38 +0100 Subject: [PATCH 29/43] assets: let animated decodes through the gate in arrival order At most two animated decodes run at once. The gate woke every waiter with a broadcast and let them race for its lock, so arrival order was lost and a short blink loop could wait behind a 331-frame animation that came later. Waiters now queue, and each freed slot goes to the longest waiter; a raised limit still lets waiters in at once. Measured with 14 official-server APNGs asked for at once (5 runs, 60 Hz frame loop): median first frame 49 ms in the previous client (8 decoder threads), 65-82 ms after decodes moved onto the Compute pool (45c41073), and 16-17 ms with the ordered gate. At 3 or 9 sprites at once all builds were already one frame. Co-Authored-By: Claude Opus 5.5 --- internal/assets/animgate_test.go | 31 ++++++++++++++++++ internal/assets/decoder.go | 54 +++++++++++++++++++------------- 2 files changed, 64 insertions(+), 21 deletions(-) diff --git a/internal/assets/animgate_test.go b/internal/assets/animgate_test.go index c1161fed..94fa91fe 100644 --- a/internal/assets/animgate_test.go +++ b/internal/assets/animgate_test.go @@ -79,3 +79,34 @@ func TestSetAnimatedDecodedAssetBytes(t *testing.T) { t.Fatalf("reset budget = %d, want default %d", got, defaultMaxAnimatedDecodedAssetBytes) } } + +// Waiters go in by arrival order, so a small loop that came first isn't left behind a long animation that came later. +func TestAnimGateAdmitsWaitersInArrivalOrder(t *testing.T) { + const waiters = 8 + g := newAnimGate(1) + g.acquire() + order := make(chan int, waiters) + for i := range waiters { + go func() { + g.acquire() + order <- i + g.release() + }() + for queued := false; !queued; time.Sleep(time.Millisecond) { + g.mu.Lock() + queued = len(g.waiting) == i+1 + g.mu.Unlock() + } + } + g.release() + for want := range waiters { + select { + case got := <-order: + if got != want { + t.Fatalf("waiter %d went in at turn %d", got, want) + } + case <-time.After(time.Second): + t.Fatalf("waiter %d never went in", want) + } + } +} diff --git a/internal/assets/decoder.go b/internal/assets/decoder.go index 093df835..39335330 100644 --- a/internal/assets/decoder.go +++ b/internal/assets/decoder.go @@ -327,46 +327,58 @@ func DecodeWorkers() int { // defaultAnimatedDecodeConcurrency bounds full animated decodes, since their per-frame RGBA is the memory spike. const defaultAnimatedDecodeConcurrency = 2 -// animGate is a resizable semaphore: a buffered channel cannot resize, so waiters re-check an atomic limit. +// animGate bounds concurrent animated decodes and lets waiters in by arrival order, so a small loop that came first is +// not left behind a long animation that came later; the limit can change live, and 0 means no bound. At most one +// waiter per Compute worker, so the queue is bounded by the pool. type animGate struct { - mu sync.Mutex - cond *sync.Cond - limit atomic.Int64 - active atomic.Int64 + mu sync.Mutex + limit int + active int + waiting []chan struct{} } -func newAnimGate(limit int) *animGate { - g := &animGate{} - g.cond = sync.NewCond(&g.mu) - g.limit.Store(int64(limit)) - return g -} +func newAnimGate(limit int) *animGate { return &animGate{limit: limit} } -// SetLimit changes the bound live; a raised limit wakes waiters. +// SetLimit changes the bound live; a raised limit lets the longest waiters in. func (g *animGate) SetLimit(n int) { g.mu.Lock() - g.limit.Store(int64(n)) - g.cond.Broadcast() + g.limit = n + g.admitLocked() g.mu.Unlock() } -// acquire blocks until an animated decode may start. +// acquire blocks until an animated decode may start, behind everyone already waiting. func (g *animGate) acquire() { g.mu.Lock() - defer g.mu.Unlock() - for g.limit.Load() > 0 && g.active.Load() >= g.limit.Load() { - g.cond.Wait() + if len(g.waiting) == 0 && g.roomLocked() { + g.active++ + g.mu.Unlock() + return } - g.active.Add(1) + turn := make(chan struct{}) + g.waiting = append(g.waiting, turn) + g.mu.Unlock() + <-turn } func (g *animGate) release() { g.mu.Lock() - g.active.Add(-1) - g.cond.Broadcast() + g.active-- + g.admitLocked() g.mu.Unlock() } +func (g *animGate) roomLocked() bool { return g.limit <= 0 || g.active < g.limit } + +// admitLocked lets the longest waiters in while there is room; the caller holds g.mu. +func (g *animGate) admitLocked() { + for len(g.waiting) > 0 && g.roomLocked() { + g.active++ + close(g.waiting[0]) + g.waiting = g.waiting[1:] + } +} + // DecodeRequest is one decode job. type DecodeRequest struct { URL string From d9e54572bfe8435914f91e4b914181e477e59439 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:03:33 +0100 Subject: [PATCH 30/43] courtroom, media, assets: the courtroom asks the media system directly The courtroom holds a *media.Manager and asks for ChainKey(base, type) with its alternate names; scenery pinning goes through a one-method interface. The per-request work the bridge did around each ask moves into media hooks: Skip (a texture already uploaded or a key that failed), Asked (start character mapping), MissingAgain (warn on a repeat ask while missing), and a Refused() counter. assets exports ChainKey and ExactKey for callers. Co-Authored-By: Claude Opus 5.5 --- docs/RESTRUCTURING_PLAN.md | 5 +- internal/assets/manager.go | 19 +++--- internal/assets/mediabridge.go | 80 ++++++++++++++----------- internal/courtroom/bgfallback_test.go | 2 +- internal/courtroom/courtroom.go | 59 +++++++++++------- internal/courtroom/courtroom_test.go | 2 +- internal/courtroom/messageneeds.go | 3 +- internal/courtroom/messageneeds_test.go | 10 ++-- internal/media/manager.go | 30 +++++++++- internal/ui/deskmissing_relay_test.go | 4 +- internal/ui/disconnectdialog_test.go | 4 +- internal/ui/newroom.go | 2 +- internal/ui/reconnect_decision_test.go | 2 +- internal/ui/sendonchange_test.go | 2 +- internal/ui/tabs_test.go | 4 +- internal/ui/webaohold_test.go | 2 +- 16 files changed, 141 insertions(+), 89 deletions(-) diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index ce6be494..2d84ddbc 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -141,7 +141,10 @@ in **Status**. Update Status in the same commit that completes a step. - [x] `Pump` on `TakeResults`: images decode on the Compute worker holding the request, and an animation's opening frames reach the pump as early pages of the same request (`Format.Decode`'s `page`). The decoder's own goroutines and the 64-slot hand-off channel are gone - - [ ] courtroom, then screens, theme and audio + - [x] courtroom: asks `media.Get(assets.ChainKey(base, t), …)`. What the bridge did per request (skip a texture + already uploaded, start character mapping, warn on a repeat ask while missing, count refusals) is media's + `Skip`/`Asked`/`MissingAgain` hooks and `Refused()` + - [ ] screens, theme and audio - [ ] music streaming - [ ] off-thread texture preparation: waits for the renderer overhaul (decided 2026-11-02). See below - [x] a sprite sometimes shows its old animation for a frame before the right one (reported 2026-11-01): the wait gate diff --git a/internal/assets/manager.go b/internal/assets/manager.go index fc03de9a..2902e222 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -86,9 +86,6 @@ type Manager struct { // deliveryNotify wakes the event-driven render loop; on workers, so cheap, non-blocking and SDL-free. deliveryNotify atomic.Pointer[func()] - // refused counts requests the media system turned away at its cap. - refused atomic.Int64 - // offline blocks every network fetch; caches and folders still read, and misses learn no 404s. offline atomic.Bool @@ -230,7 +227,7 @@ type WorkStats struct { // WorkStats snapshots the decoders and handoffs; it allocates, so call it only while the debug panel shows it. func (m *Manager) WorkStats() WorkStats { return WorkStats{ - Refused: m.refused.Load(), + Refused: m.bridge.media.Refused(), DecodeWorkers: DecodeWorkers(), AudioQueued: len(m.audioCh), AudioCap: cap(m.audioCh), @@ -254,6 +251,14 @@ func (m *Manager) NotifyDelivery() { } } +// Media is the media system callers ask directly, with keys from ChainKey and ExactKey. +func (m *Manager) Media() *media.Manager { + if m == nil { + return nil + } + return m.bridge.media +} + // Delivery is one decoded page for the render thread, and the request it belongs to. type Delivery struct { DecodedAsset @@ -313,9 +318,6 @@ func (m *Manager) PrefetchChain(base string, alts []string, t AssetType, prio ne if base == "" || !t.Valid() { return } - if m.t1Failed != nil && m.t1Failed(base) { - return // recently failed to decode — back off (the negative cache absorbs retries) - } m.bridge.askChain(base, alts, t, prio, false) } @@ -332,9 +334,6 @@ func (m *Manager) PrefetchExact(url string, t AssetType, prio network.Priority) if url == "" || !t.Valid() { return } - if m.t1Failed != nil && m.t1Failed(url) { - return // recently failed to decode — back off - } m.bridge.askExact(url, t, prio) } diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index b6109d9a..d61da357 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -73,7 +73,8 @@ func newMediaBridge(m *Manager) *mediaBridge { b.folders = newBridgeFolders(m) b.learned = saver.New(m.learnedPath, learnedSaveDelay, b.encodeLearned) cfg := media.Config{Candidates: b.builder.Build, AllFormats: media.EveryFormat, Found: b.found, - Finished: b.finished, Delivered: m.NotifyDelivery, Compute: b.compute} + Finished: b.finished, Delivered: m.NotifyDelivery, Skip: b.skip, Asked: b.asked, MissingAgain: b.missingAgain, + Compute: b.compute} b.remote = media.NewRemoteSource(ctx, bridgeFetcher{m}, media.DefaultMissingTTL, time.Now) cfg.Chains = map[media.Place]*media.Chain{media.PlaceServer: media.NewChain( media.Entry{Source: bridgeMemory{m.t2, b.pin, m}}, @@ -100,13 +101,13 @@ func (b *mediaBridge) found(k media.Key, f media.File) { // learn is found for a raw walk on a worker: url turned up for base. func (b *mediaBridge) learn(base string, t AssetType, url string) { - b.media.Do(func() { b.found(chainKey(base, t), media.File(url)) }) + b.media.Do(func() { b.found(ChainKey(base, t), media.File(url)) }) } // candidates lists the URLs base may be, in the order the live chain asks; for workers, as it waits on the Manager. func (b *mediaBridge) candidates(base string, t AssetType) []string { var files []media.File - b.media.Call(func() { files = b.builder.Build(chainKey(base, t), base) }) + b.media.Call(func() { files = b.builder.Build(ChainKey(base, t), base) }) urls := make([]string, len(files)) for i, f := range files { urls[i] = string(f) @@ -244,10 +245,18 @@ func kindOf(t AssetType) media.Kind { return media.KindImage } -func chainKey(base string, t AssetType) media.Key { +// ChainKey is the key a base is asked under; its formats and spellings are the media system's to find. +func ChainKey(base string, t AssetType) media.Key { return media.Key{Place: media.PlaceServer, Path: base, Kind: kindOf(t), Class: classOf(t), Tag: uint8(t)} } +// ExactKey is the key for a complete URL, such as a music track: one file, no formats to try. +func ExactKey(url string, t AssetType) media.Key { + k := ChainKey(url, t) + k.Class = media.ClassExact + return k +} + func flagsOf(quiet, sticky bool) media.Flags { var f media.Flags if quiet { @@ -260,52 +269,51 @@ func flagsOf(quiet, sticky bool) media.Flags { } func (b *mediaBridge) askChain(base string, alts []string, t AssetType, p network.Priority, sticky bool) { - if b.m.t1Contains != nil && b.m.t1Contains(base) { - b.m.t1Hits.Add(1) - return - } - b.mapCharacterOf(base, t) - b.ask(chainKey(base, t), flagsOf(false, sticky), p, alts...) + b.media.Get(ChainKey(base, t), urgencyOf(p), flagsOf(false, sticky), alts...) } -// mapCharacterOf maps the folder of a character whose sprites are asked for, so everyone who appears is mapped and a -// roster of icons is not. -func (b *mediaBridge) mapCharacterOf(base string, t AssetType) { - if t != AssetTypeCharSprite && t != AssetTypeEmoteButton || !strings.HasPrefix(base, "http") { - return - } - if root := media.CharacterRoot(base); root != "" { - b.media.Do(func() { media.MapCharacter(b.media, b.network, b.remote, b.builder, root) }) - } +func (b *mediaBridge) askExact(url string, t AssetType, p network.Priority) { + b.media.Get(ExactKey(url, t), urgencyOf(p), 0) } -func (b *mediaBridge) askExact(url string, t AssetType, p network.Priority) { - if b.m.t1Contains != nil && b.m.t1Contains(url) { +func (b *mediaBridge) askRaw(url string, p network.Priority) { + b.media.Get(media.Key{Place: media.PlaceServer, Path: url, Kind: media.KindRaw, Class: media.ClassExact}, urgencyOf(p), media.Quiet) +} + +// skip is Config.Skip: an uploaded texture is held already, and one that failed to decode lately is left alone. +func (b *mediaBridge) skip(k media.Key) bool { + if k.Kind == media.KindRaw { + return false + } + if b.m.t1Contains != nil && b.m.t1Contains(k.Path) { b.m.t1Hits.Add(1) - return + return true } - k := chainKey(url, t) - k.Class = media.ClassExact - b.ask(k, 0, p) + return b.m.t1Failed != nil && b.m.t1Failed(k.Path) } -func (b *mediaBridge) askRaw(url string, p network.Priority) { - b.media.Get(media.Key{Place: media.PlaceServer, Path: url, Kind: media.KindRaw, Class: media.ClassExact}, urgencyOf(p), media.Quiet) +// asked is Config.Asked: a character's first sprite or emote button maps its folder, so everyone who appears is mapped +// and a roster of icons is not. +func (b *mediaBridge) asked(k media.Key) { + t := AssetType(k.Tag) + if k.Kind == media.KindRaw || t != AssetTypeCharSprite && t != AssetTypeEmoteButton || !strings.HasPrefix(k.Path, "http") { + return + } + if root := media.CharacterRoot(k.Path); root != "" { + media.MapCharacter(b.media, b.network, b.remote, b.builder, root) + } } -func (b *mediaBridge) ask(k media.Key, f media.Flags, p network.Priority, alts ...string) { - a := b.media.Get(k, urgencyOf(p), f, alts...) - switch a.State() { - case media.Missing: - // Asked again inside the file's missing time: no request, and the warning still fires. - b.m.skipExhausted(k.Path, AssetType(k.Tag), f&media.Quiet != 0) - case media.Refused: - b.m.refused.Add(1) +// missingAgain is Config.MissingAgain: asked again inside its missing time costs no request, and the warning still +// fires. +func (b *mediaBridge) missingAgain(a *media.Asset) { + if k := a.Key(); k.Kind != media.KindRaw { + b.m.skipExhausted(k.Path, AssetType(k.Tag), a.Quiet()) } } func (b *mediaBridge) isMissing(base string, t AssetType) bool { - a := b.media.Peek(chainKey(base, t)) + a := b.media.Peek(ChainKey(base, t)) return a != nil && a.State() == media.Missing } diff --git a/internal/courtroom/bgfallback_test.go b/internal/courtroom/bgfallback_test.go index 75e821ec..c88f284e 100644 --- a/internal/courtroom/bgfallback_test.go +++ b/internal/courtroom/bgfallback_test.go @@ -53,7 +53,7 @@ func newBGRig(t *testing.T) *bgRig { mgr.SetFolders(local.Mounts(), nil) sess := NewSession(func(protocol.Packet) error { return nil }, "test-hdid") sess.Background = "court" - room := NewCourtroom(NewURLBuilder(local.BaseURL()), mgr, sess, nil) + room := NewCourtroom(NewURLBuilder(local.BaseURL()), mgr.Media(), mgr, sess, nil) return &bgRig{room: room, sess: sess, mgr: mgr, mount: mount} } diff --git a/internal/courtroom/courtroom.go b/internal/courtroom/courtroom.go index 62eba6f8..8058ebba 100644 --- a/internal/courtroom/courtroom.go +++ b/internal/courtroom/courtroom.go @@ -8,7 +8,7 @@ import ( "unicode/utf8" "github.com/SyntaxNyah/AsyncAO/internal/assets" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/protocol" "github.com/SyntaxNyah/AsyncAO/internal/theme" ) @@ -246,7 +246,8 @@ type EnvResolver interface { type Courtroom struct { urls URLBuilder - mgr *assets.Manager + media *media.Manager + pin ScenePinner sess *Session audio AudioSink @@ -405,14 +406,27 @@ type Courtroom struct { RealizationSFX string } -// NewCourtroom wires the state machine. audio may be nil (NopAudio). -func NewCourtroom(urls URLBuilder, mgr *assets.Manager, sess *Session, audio AudioSink) *Courtroom { +// ask asks the media system for base, then each alt while earlier names miss, as CharLayer::load_image does; an empty +// base or no media system asks nothing. +func (c *Courtroom) ask(base string, alts []string, t assets.AssetType) { + if base == "" || c.media == nil || !t.Valid() { + return + } + c.media.Get(assets.ChainKey(base, t), media.Now, 0, alts...) +} + +// ScenePinner keeps a room's background folder in memory while it is on screen. +type ScenePinner interface{ PinScenery(folder string) } + +// NewCourtroom wires the state machine. m and pin may be nil, asking for nothing; audio may be nil (NopAudio). +func NewCourtroom(urls URLBuilder, m *media.Manager, pin ScenePinner, sess *Session, audio AudioSink) *Courtroom { if audio == nil { audio = NopAudio{} } c := &Courtroom{ urls: urls, - mgr: mgr, + media: m, + pin: pin, sess: sess, audio: audio, Typewriter: NewTypewriter(), @@ -485,9 +499,11 @@ func (c *Courtroom) setScenery(bg, pos string) { s := c.urls.PositionScenery(bg, pos, c.design) c.Scene.BackgroundBase, c.Scene.BackgroundAlts, c.Scene.DeskBase = s.Background, s.Alts, s.Desk c.placeScenery(fileStem(s.Background)) - c.mgr.PinScenery(s.Background[:strings.LastIndexByte(s.Background, '/')+1]) - c.mgr.PrefetchChain(s.Background, s.Alts, assets.AssetTypeBackground, network.PriorityHigh) // AssetType: Background - c.mgr.Prefetch(s.Desk, assets.AssetTypeDeskOverlay, network.PriorityHigh) // AssetType: DeskOverlay + if c.pin != nil { + c.pin.PinScenery(s.Background[:strings.LastIndexByte(s.Background, '/')+1]) + } + c.ask(s.Background, s.Alts, assets.AssetTypeBackground) // AssetType: Background + c.ask(s.Desk, nil, assets.AssetTypeDeskOverlay) // AssetType: DeskOverlay c.followBackground() } @@ -884,21 +900,21 @@ func (c *Courtroom) begin(msg *protocol.ChatMessage) { // Prefetch fan-out, all HIGH. Sprites walk "(a)X", bare, "(a)/X" (animationlayer.cpp:422-444). idle := c.urls.Emote(speakerName, msg.Emote, EmoteIdle) talk := c.urls.Emote(speakerName, msg.Emote, EmoteTalk) - c.mgr.PrefetchChain(idle, c.spriteAlts(speakerName, msg.Emote, EmoteIdle), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite - c.mgr.PrefetchChain(talk, c.spriteAlts(speakerName, msg.Emote, EmoteTalk), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + c.ask(idle, c.spriteAlts(speakerName, msg.Emote, EmoteIdle), assets.AssetTypeCharSprite) // AssetType: CharSprite + c.ask(talk, c.spriteAlts(speakerName, msg.Emote, EmoteTalk), assets.AssetTypeCharSprite) // AssetType: CharSprite pre := "" if hasPreanim(msg) { pre = c.urls.Emote(speakerName, msg.PreEmote, EmotePreanim) if !c.restoring { // settled form never plays the preanim — don't probe for it - c.mgr.Prefetch(pre, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + c.ask(pre, nil, assets.AssetTypeCharSprite) // AssetType: CharSprite } } pairIdle := "" if msg.Pair.Active() { pairIdle = c.urls.Emote(msg.Pair.Name, msg.Pair.Emote, EmoteIdle) - c.mgr.PrefetchChain(pairIdle, c.spriteAlts(msg.Pair.Name, msg.Pair.Emote, EmoteIdle), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (pair partner) + c.ask(pairIdle, c.spriteAlts(msg.Pair.Name, msg.Pair.Emote, EmoteIdle), assets.AssetTypeCharSprite) // AssetType: CharSprite (pair partner) } if msg.IsShout() { @@ -907,9 +923,9 @@ func (c *Courtroom) begin(msg *protocol.ChatMessage) { c.ShoutDefaultBase = defaultBase if !c.restoring { // settled form never shows the bubble — don't probe for it if defaultBase != "" { - c.mgr.Prefetch(defaultBase, assets.AssetTypeShoutBubble, network.PriorityHigh) // AssetType: ShoutBubble + c.ask(defaultBase, nil, assets.AssetTypeShoutBubble) // AssetType: ShoutBubble } - c.mgr.Prefetch(charBase, assets.AssetTypeShoutBubble, network.PriorityHigh) // AssetType: ShoutBubble + c.ask(charBase, nil, assets.AssetTypeShoutBubble) // AssetType: ShoutBubble } c.audio.PlayShout(shoutSFX) // AssetType: SFX } @@ -928,7 +944,7 @@ func (c *Courtroom) begin(msg *protocol.ChatMessage) { if misc := c.Chars.ChatSkinFor(speakerName); misc != "" { cands := c.urls.MiscChatboxCandidates(misc) c.Scene.ChatSkinBase = cands[0] - c.mgr.PrefetchChain(cands[0], cands[1:], assets.AssetTypeMisc, network.PriorityHigh) // AssetType: Misc (chatbox skin) + c.ask(cands[0], cands[1:], assets.AssetTypeMisc) // AssetType: Misc (chatbox skin) } } // The speaker's chatbox colours (misc//courtroom_fonts.ini, get_chat), falling back to the theme. @@ -984,8 +1000,7 @@ func (c *Courtroom) begin(msg *protocol.ChatMessage) { if msg.EmoteMod == protocol.EmoteModZoom || msg.EmoteMod == protocol.EmoteModPreanimZoom { c.Scene.SpeedlinesSide = ZoomSide(msg.Side) c.Scene.SpeedlinesChain = c.urls.SpeedlinesCandidates(speakerName, msg.Side) - c.mgr.PrefetchChain(c.Scene.SpeedlinesChain[0], c.Scene.SpeedlinesChain[1:], - assets.AssetTypeMisc, network.PriorityHigh) // AssetType: Misc (zoom speedlines) + c.ask(c.Scene.SpeedlinesChain[0], c.Scene.SpeedlinesChain[1:], assets.AssetTypeMisc) // AssetType: Misc (zoom speedlines) } // Parse FRAME_* once here, never per frame, after the Speaker bases so NotifyFrameShown can bind the group. @@ -1020,7 +1035,7 @@ func (c *Courtroom) begin(msg *protocol.ChatMessage) { continue // the speaker is already on the Speaker layer } base := c.urls.Emote(m.Name, m.Emote, EmoteIdle) - c.mgr.PrefetchChain(base, c.spriteAlts(m.Name, m.Emote, EmoteIdle), assets.AssetTypeCharSprite, network.PriorityHigh) + c.ask(base, c.spriteAlts(m.Name, m.Emote, EmoteIdle), assets.AssetTypeCharSprite) c.Scene.Group = append(c.Scene.Group, SpriteLayer{ Name: m.Name, IdleBase: base, @@ -1071,7 +1086,7 @@ func (c *Courtroom) resolveBlip() { return } c.blipRef = ref - c.mgr.PrefetchChain(ref.Base, ref.Alts, ref.Type, network.PriorityHigh) + c.ask(ref.Base, ref.Alts, ref.Type) } // blipRefFor builds the chain for the wait gate; pending means char.ini is in flight, so skip the blip, don't hold. @@ -1277,8 +1292,8 @@ func (c *Courtroom) armSFXDelay(msg *protocol.ChatMessage) { return // nothing to schedule } // Warm now so a first play adds no fetch latency on top of SFX_DELAY. - if base != "" && c.mgr != nil { - c.mgr.Prefetch(base, assets.AssetTypeSFX, network.PriorityHigh) // AssetType: SFX + if base != "" && c.media != nil { + c.ask(base, nil, assets.AssetTypeSFX) // AssetType: SFX } c.sfxArmed = true c.sfxLeft = time.Duration(msg.SFXDelay) * sfxDelayUnit @@ -1728,7 +1743,7 @@ func (c *Courtroom) followBackground() { return } c.Scene.DeskBase = desk - c.mgr.Prefetch(desk, assets.AssetTypeDeskOverlay, network.PriorityHigh) // AssetType: DeskOverlay + c.ask(desk, nil, assets.AssetTypeDeskOverlay) // AssetType: DeskOverlay if c.current != nil { c.applyDeskMods(c.phase == PhasePreanim) } diff --git a/internal/courtroom/courtroom_test.go b/internal/courtroom/courtroom_test.go index d5e5022b..743bd499 100644 --- a/internal/courtroom/courtroom_test.go +++ b/internal/courtroom/courtroom_test.go @@ -88,7 +88,7 @@ func newCourtroomRig(t testing.TB) (*Courtroom, *Session, *sentRecorder, *audioR rec := &sentRecorder{} sess := NewSession(rec.send, "test-hdid") audio := &audioRecorder{} - room := NewCourtroom(NewURLBuilder(local.BaseURL()), mgr, sess, audio) + room := NewCourtroom(NewURLBuilder(local.BaseURL()), mgr.Media(), mgr, sess, audio) return room, sess, rec, audio } diff --git a/internal/courtroom/messageneeds.go b/internal/courtroom/messageneeds.go index 95fe1c0d..465a5f10 100644 --- a/internal/courtroom/messageneeds.go +++ b/internal/courtroom/messageneeds.go @@ -2,7 +2,6 @@ package courtroom import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" - "github.com/SyntaxNyah/AsyncAO/internal/network" "github.com/SyntaxNyah/AsyncAO/internal/protocol" ) @@ -177,7 +176,7 @@ func (c *Courtroom) firstUnsettled(needs []messageNeed) (messageNeed, bool) { func (c *Courtroom) requestNeeds(needs []messageNeed) { for _, n := range needs { if n.gate != gateOverlay && !c.needSettled(n) { - c.mgr.PrefetchChain(n.base, n.alts, n.typ, network.PriorityHigh) // AssetType: from the need + c.ask(n.base, n.alts, n.typ) // AssetType: from the need } } } diff --git a/internal/courtroom/messageneeds_test.go b/internal/courtroom/messageneeds_test.go index 0e2fbc3b..3c7b501a 100644 --- a/internal/courtroom/messageneeds_test.go +++ b/internal/courtroom/messageneeds_test.go @@ -117,7 +117,7 @@ func (s *recordingSource) askedFor(base string) bool { return found } -func recordingRoom(t *testing.T) (*Courtroom, *recordingSource) { +func recordingRoom(t *testing.T) (*Courtroom, *recordingSource, *assets.Manager) { t.Helper() prefs, err := config.New(filepath.Join(t.TempDir(), config.PrefsFileName)) if err != nil { @@ -141,14 +141,14 @@ func recordingRoom(t *testing.T) (*Courtroom, *recordingSource) { }) t.Cleanup(mgr.CloseMedia) sess := NewSession((&sentRecorder{}).send, "test-hdid") - return NewCourtroom(NewURLBuilder("https://h.example/"), mgr, sess, &audioRecorder{}), src + return NewCourtroom(NewURLBuilder("https://h.example/"), mgr.Media(), mgr, sess, &audioRecorder{}), src, mgr } // TestWaitGateRequestsANeedThatJoinsLater: the chat skin is known only once char.ini lands, often after the gate armed, // and nothing else asks for it until the message plays, so the gate must ask or it holds for the whole limit. func TestWaitGateRequestsANeedThatJoinsLater(t *testing.T) { const tick = 16 * time.Millisecond - room, src := recordingRoom(t) + room, src, _ := recordingRoom(t) room.SequentialWait = true ready := map[string]bool{} room.Assets = assetFake{sprite: func(base string) bool { return ready[base] }} @@ -217,7 +217,7 @@ func TestWaitGateAsksAgainWhileItHolds(t *testing.T) { tick = 16 * time.Millisecond wait = 5 * time.Second ) - room, _ := recordingRoom(t) + room, _, mgr := recordingRoom(t) room.SequentialWait = true room.Assets = assetFake{sprite: func(string) bool { return false }} idle := room.urls.Emote("Phoenix", "normal", EmoteIdle) @@ -225,7 +225,7 @@ func TestWaitGateAsksAgainWhileItHolds(t *testing.T) { deadline := time.After(wait) for { select { - case w := <-room.mgr.Warnings(): + case w := <-mgr.Warnings(): if w.Base == idle { return true } diff --git a/internal/media/manager.go b/internal/media/manager.go index 75b989be..3ec48a28 100644 --- a/internal/media/manager.go +++ b/internal/media/manager.go @@ -34,6 +34,14 @@ type Config struct { Finished func(*Asset) // Delivered runs after a result is waiting for TakeResults, on any goroutine, to wake the main thread's loop. Delivered func() + // Skip runs in Get on the caller's thread: true means nothing is asked, as the caller already holds key, such as an + // uploaded texture. It must be cheap; Get then returns Skipped. + Skip func(Key) bool + // Asked runs on the Manager's goroutine when a new request starts, such as to map the folder it lives in. + Asked func(Key) + // MissingAgain runs in Get on the caller's thread when key is asked again while known missing, which costs no + // request, so the caller can still warn. + MissingAgain func(*Asset) // ClaimLimit is the memory decodes may claim at once; Now work may pass it, so a message can't wait on memory. ClaimLimit int64 MaxAssets int @@ -198,6 +206,10 @@ type Manager struct { claimed int64 // winners maps a key to the file it was last found as, tried first next time, as AO2's asset_lookup_cache is. winners map[Key]File + // refused counts Gets turned away at MaxAssets. + refused atomic.Int64 + // skipped is what Get returns when Config.Skip says the caller holds the key already. + skipped *Asset } // NewManager starts a Manager's goroutine. @@ -213,6 +225,8 @@ func NewManager(cfg Config) *Manager { } m := &Manager{cfg: cfg, wake: make(chan struct{}, 1), stop: make(chan struct{}), stopped: make(chan struct{}), active: map[Key]*request{}, queues: map[*Pool]*poolQueue{}, hostBusy: map[string]int{}, winners: map[Key]File{}} + m.skipped = newAsset(Key{}, Later, 0, nil) + m.skipped.finish(Ready, nil, nil, cfg.Clock()) go m.run() return m } @@ -223,9 +237,13 @@ func (m *Manager) Close() { <-m.stopped } -// Get returns the Asset for key from any thread and never blocks: a repeat ask takes no lock and posts nothing. +// Get returns the Asset for key from any thread and never blocks: a repeat ask takes no lock and posts nothing. A key the +// Skip hook says the caller holds already returns a shared finished Asset with no key. // alts are the other names it may be found under, best first, each asked only once every earlier one is known absent. func (m *Manager) Get(key Key, urgency Urgency, flags Flags, alts ...string) *Asset { + if m.cfg.Skip != nil && m.cfg.Skip(key) { + return m.skipped + } if v, ok := m.assets.Load(key); ok { a := v.(*Asset) if !m.expired(a) && !a.lacks(alts) { @@ -233,6 +251,9 @@ func (m *Manager) Get(key Key, urgency Urgency, flags Flags, alts ...string) *As if urgency == Now && !a.urgent.Load() && a.urgent.CompareAndSwap(false, true) { m.post(&request{event: eventRaise, key: key}) } + if m.cfg.MissingAgain != nil && a.State() == Missing { + m.cfg.MissingAgain(a) + } return a } fresh := newAsset(key, urgency, flags, alts) @@ -246,6 +267,7 @@ func (m *Manager) Get(key Key, urgency Urgency, flags Flags, alts ...string) *As if urgency == Later && m.count.Load() >= int64(m.cfg.MaxAssets) { a := newAsset(key, urgency, flags, alts) a.finish(Refused, nil, ErrRefused, m.cfg.Clock()) + m.refused.Add(1) return a } a := newAsset(key, urgency, flags, alts) @@ -345,6 +367,9 @@ func (m *Manager) Run(pool *Pool, urgency Urgency, work func() any, done func(an m.post(&request{event: eventWork, pool: pool, urgency: urgency, work: work, done: done, step: stepWork}) } +// Refused counts the Gets turned away because the request table was full; any thread. +func (m *Manager) Refused() int64 { return m.refused.Load() } + // TakeResults hands the main thread every result that needs it, in order, once per frame, with one atomic swap. final is // false for an early page; only the final result is Finished. func (m *Manager) TakeResults(use func(a *Asset, result any, final bool)) { @@ -427,6 +452,9 @@ func (m *Manager) event(r *request) { switch r.event { case eventNew: m.active[r.asset.key] = r + if m.cfg.Asked != nil { + m.cfg.Asked(r.asset.key) + } m.search(r) case eventRaise: if a := m.active[r.key]; a != nil && a.urgency == Later { diff --git a/internal/ui/deskmissing_relay_test.go b/internal/ui/deskmissing_relay_test.go index 9c3880e2..a81b5e91 100644 --- a/internal/ui/deskmissing_relay_test.go +++ b/internal/ui/deskmissing_relay_test.go @@ -66,7 +66,7 @@ func TestDrainWarningsRelaysDeskMissing(t *testing.T) { sess := courtroom.NewSession(func(protocol.Packet) error { return nil }, "test-hdid") sess.Background = "gs4" urls := courtroom.NewURLBuilder(local.BaseURL()) - room := courtroom.NewCourtroom(urls, a.d.Manager, sess, nil) + room := courtroom.NewCourtroom(urls, a.d.Manager.Media(), a.d.Manager, sess, nil) a.room = room // The def background loaded as its legacy file, so the desk follows to defensedesk. room.Assets = loadedAs{spriteProbe(func(string) bool { return false }), urls.Background("gs4", "defenseempty") + config.ExtPNG} @@ -127,7 +127,7 @@ func TestDrainWarningsRelaysBackgroundMissToGate(t *testing.T) { sess := courtroom.NewSession(func(protocol.Packet) error { return nil }, "test-hdid") sess.Background = "gs4" - room := courtroom.NewCourtroom(urls, a.d.Manager, sess, nil) + room := courtroom.NewCourtroom(urls, a.d.Manager.Media(), a.d.Manager, sess, nil) a.room = room room.SequentialWait = true // Everything but the position background resolves as "settled", so the gate diff --git a/internal/ui/disconnectdialog_test.go b/internal/ui/disconnectdialog_test.go index 538a5794..0bee241d 100644 --- a/internal/ui/disconnectdialog_test.go +++ b/internal/ui/disconnectdialog_test.go @@ -25,7 +25,7 @@ func froomApp(t *testing.T) *App { a.tabs = []*courtTab{{}} a.activeTab = 0 a.sess = courtroom.NewRehearsalSession("", []string{"Phoenix"}) - a.room = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, a.sess, courtroom.NopAudio{}) + a.room = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, nil, a.sess, courtroom.NopAudio{}) a.screen = ScreenCourtroom return a } @@ -180,7 +180,7 @@ func TestHandleInvoluntaryDropWithNoRoomGoesToLobby(t *testing.T) { func TestVoluntaryDisconnectGoesToLobby(t *testing.T) { a := froomApp(t) a.sess = courtroom.NewSession(func(protocol.Packet) error { return nil }, "") - a.room = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, a.sess, courtroom.NopAudio{}) + a.room = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, nil, a.sess, courtroom.NopAudio{}) a.deliberateClose = true // the user chose to leave a.handleInvoluntaryDrop("connection closed") if a.disconnectDlg.open { diff --git a/internal/ui/newroom.go b/internal/ui/newroom.go index a61817ba..3c53e6a9 100644 --- a/internal/ui/newroom.go +++ b/internal/ui/newroom.go @@ -10,7 +10,7 @@ import ( // newRoom builds a courtroom and wires it: char.ini callbacks, the screen-effect overlay engine and the visual prefs. // sess and audio may be nil; NewCourtroom substitutes a no-op sink. func (a *App) newRoom(urls courtroom.URLBuilder, sess *courtroom.Session, audio courtroom.AudioSink) *courtroom.Courtroom { - room := courtroom.NewCourtroom(urls, a.d.Manager, sess, audio) + room := courtroom.NewCourtroom(urls, a.d.Manager.Media(), a.d.Manager, sess, audio) // One call so a speaker blips, skins and flashes identically in every mode. a.wireRoomCharMeta(room) a.applyVisualPrefsToRoom(room) diff --git a/internal/ui/reconnect_decision_test.go b/internal/ui/reconnect_decision_test.go index f0c47aa4..c0905db7 100644 --- a/internal/ui/reconnect_decision_test.go +++ b/internal/ui/reconnect_decision_test.go @@ -165,7 +165,7 @@ func TestPumpConnectionFreezesAnInCourtDrop(t *testing.T) { return conn.Send(p) }, "test-hdid") // The difference from the test above: a courtroom the user is looking at. - a.room = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, a.sess, courtroom.NopAudio{}) + a.room = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, nil, a.sess, courtroom.NopAudio{}) a.screen = ScreenCourtroom if err := conn.Send(protocol.NewPacket("HI", "x")); err != nil { diff --git a/internal/ui/sendonchange_test.go b/internal/ui/sendonchange_test.go index 5d138efa..e86256ff 100644 --- a/internal/ui/sendonchange_test.go +++ b/internal/ui/sendonchange_test.go @@ -38,7 +38,7 @@ func newRoomForTest(t testing.TB) *courtroom.Courtroom { }) t.Cleanup(mgr.CloseMedia) mgr.SetFolders(local.Mounts(), nil) - return courtroom.NewCourtroom(courtroom.NewURLBuilder(local.BaseURL()), mgr, nil, courtroom.NopAudio{}) + return courtroom.NewCourtroom(courtroom.NewURLBuilder(local.BaseURL()), mgr.Media(), mgr, nil, courtroom.NopAudio{}) } func msgFor(charID int, name, text string) *protocol.ChatMessage { diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go index b7d57396..22b934dc 100644 --- a/internal/ui/tabs_test.go +++ b/internal/ui/tabs_test.go @@ -841,7 +841,7 @@ func TestRenderFullClientTextureRestores(t *testing.T) { // A pinned client whose swapped-in session is nil → the inner drawCourtroom // early-returns (and sets a.screen=lobby, which the snapshot must undo). a.splitVP = render.NewViewport(nil, false) - a.splitRoom = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, nil, courtroom.NopAudio{}) + a.splitRoom = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, nil, nil, courtroom.NopAudio{}) a.splitTab = &courtTab{state: sessionState{serverName: "PinnedServer"}} // sess stays nil a.renderFullClientTexture(640, 480) @@ -1579,7 +1579,7 @@ func TestRederiveMessageDuckClearsStale(t *testing.T) { }) // ducking enabled, so the phase is what decides - a.room = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, nil, courtroom.NopAudio{}) + a.room = courtroom.NewCourtroom(courtroom.URLBuilder{}, nil, nil, nil, courtroom.NopAudio{}) // A message finished (phase is Idle) but the duck flag is stale-true. a.musicDucked = true a.rederiveMessageDuck() diff --git a/internal/ui/webaohold_test.go b/internal/ui/webaohold_test.go index 17256847..59d10148 100644 --- a/internal/ui/webaohold_test.go +++ b/internal/ui/webaohold_test.go @@ -15,7 +15,7 @@ func TestWebAOModeBriefHold(t *testing.T) { local, cleanup := wireLocalManager(t, a, dir) defer cleanup() sess := courtroom.NewSession(func(protocol.Packet) error { return nil }, "test-hdid") - a.room = courtroom.NewCourtroom(courtroom.NewURLBuilder(local.BaseURL()), a.d.Manager, sess, nil) + a.room = courtroom.NewCourtroom(courtroom.NewURLBuilder(local.BaseURL()), a.d.Manager.Media(), a.d.Manager, sess, nil) a.room.Assets = spriteProbe(func(string) bool { return false }) a.d.Prefs.SetSpriteLoadMode(config.SpriteLoadHoldPrev) a.applyTimingToRoom() From 6359ae8b3260d65fbb2cbadcdadd62cf44dbe975 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:35:57 +0100 Subject: [PATCH 31/43] assets: background decodes wait for uploads under a memory limit Images declared no memory claim, so the media system's claim limit never applied: decodes ran far ahead of the upload pump (about one animated sprite per frame) and every decoded frame waited in the pump's carry. bridgeImage now measures a decode from the file header (canvas bytes times frames, capped at the animated budget; PNG/APNG, GIF, JPEG, WebP, AVIF) and the bridge sets a 64 MiB claim limit. Requests for the current message still pass it. Headless burst of 112 animated sprites from the official vanilla base: peak live heap ~950 MiB -> ~220 MiB, heap left after the burst ~700 MiB -> 31-56 MiB. The burst finishes in 2.2 s instead of 1.6 s, since a 331-frame preanim waits for the queue to empty before it decodes. Co-Authored-By: Claude Opus 5.5 --- docs/RESTRUCTURING_PLAN.md | 9 ++- internal/assets/claim.go | 141 +++++++++++++++++++++++++++++++++ internal/assets/claim_test.go | 130 ++++++++++++++++++++++++++++++ internal/assets/mediabridge.go | 9 ++- 4 files changed, 285 insertions(+), 4 deletions(-) create mode 100644 internal/assets/claim.go create mode 100644 internal/assets/claim_test.go diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index 2d84ddbc..62a3da67 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -132,9 +132,12 @@ in **Status**. Update Status in the same commit that completes a step. Settings → Check folders now end every folder check's trust. The old pipeline (network pool, mount index and layer, conclusive-miss set, Local-only mode in the Manager) and `-old-media` are deleted, and with them the wait gate's refusal re-ask: high-priority requests are never refused - - [ ] known problem from the benchmark: peak heap with files asked for every frame is 384-617 MiB, unexplained (the - request count on hosts with no `extensions.json` is answered by character mapping above). Lead: images declare - no memory claim and the bridge sets no `ClaimLimit`, so decoded pages are bounded by nothing + - [ ] known problem from the benchmark: peak heap with files asked for every frame is 384-617 MiB (the request count + on hosts with no `extensions.json` is answered by character mapping above) + - [x] background decodes claim their decoded size from the file header and wait under a 64 MiB limit until the + pump uploads (2026-11-15). Burst of 112 vanilla APNGs: peak live heap ~950 → ~220 MiB, heap after it + ~700 → 31-56 MiB; the burst takes 2.2 s instead of 1.6 s. Requests for the current message are not limited + - [ ] still open: what is left of the 220 MiB peak, and a profile from the real client - [ ] move callers (decided 2026-11-15): callers call `media.Manager` directly with keys from small assets helpers, and the bridge goes at the end. Order: `Pump` on `TakeResults`, then courtroom, screens, theme and audio; music streaming after them diff --git a/internal/assets/claim.go b/internal/assets/claim.go new file mode 100644 index 00000000..0c7fa640 --- /dev/null +++ b/internal/assets/claim.go @@ -0,0 +1,141 @@ +package assets + +import ( + "bytes" + "encoding/binary" + "image/jpeg" +) + +const ( + // imageClaimLimit bounds the decoded pixels background decodes hold before the render thread uploads them. + imageClaimLimit = 64 << 20 + // unknownImageClaim stands in for a payload whose header can't be read: one 1920x1080 frame. + unknownImageClaim = 1920 * 1080 * rgbaBytesPerPixel + + pngIHDRDataOffset = pngSigLen + pngChunkHdrLen + pngIHDRDimsLen = 8 + pngACTLFramesLen = 4 + + gifScreenOffset = 6 + gifScreenLen = 7 + gifFlagsOffset = 4 + gifTableFlag = 0x80 + gifTableSizeMask = 0x07 + gifTableEntryLen = 3 + gifExtension = 0x21 + gifImage = 0x2C + gifExtHeaderLen = 2 + gifImageHeaderLen = 10 + gifLZWCodeLen = 1 +) + +// decodeClaim estimates the memory a decode of data holds, from its header: canvas bytes times the frames kept. +func decodeClaim(data []byte, playAnimations bool) int64 { + w, h, frames, ok := peekImage(data) + if !ok { + return unknownImageClaim + } + if !playAnimations || frames < 1 { + frames = 1 + } + canvas := int64(w) * int64(h) * rgbaBytesPerPixel + claim := canvas * int64(frames) + if budget := maxAnimatedDecodedAssetBytes.Load(); frames > 1 && budget > 0 && claim > budget { + claim = max(budget, canvas) // the decoder downscales or drops frames to fit the budget + } + return claim +} + +// peekImage reads an image's canvas size and frame count without decoding pixels. +func peekImage(data []byte) (width, height, frames int, ok bool) { + switch Sniff(data) { + case FormatPNG, FormatAPNG: + return peekPNG(data) + case FormatGIF: + return peekGIF(data) + case FormatJPEG: + cfg, err := jpeg.DecodeConfig(bytes.NewReader(data)) + return cfg.Width, cfg.Height, 1, err == nil + case FormatWebP, FormatWebPAnim: + return peekWebPAnimDims(data) + case FormatAVIF, FormatAVIFAnim: + return peekAVIFAnimDims(data) + default: + return 0, 0, 0, false + } +} + +// peekPNG reads IHDR's size and, for APNG, acTL's frame count. +func peekPNG(data []byte) (width, height, frames int, ok bool) { + if len(data) < pngIHDRDataOffset+pngIHDRDimsLen { + return 0, 0, 0, false + } + width = int(binary.BigEndian.Uint32(data[pngIHDRDataOffset:])) + height = int(binary.BigEndian.Uint32(data[pngIHDRDataOffset+4:])) + frames = 1 + for offset := pngSigLen; offset+pngChunkHdrLen <= len(data); { + length := int(binary.BigEndian.Uint32(data[offset:])) + body := offset + pngChunkHdrLen + next := body + length + pngChunkCRCLen + if length < 0 || next <= offset || next > len(data) { + break + } + chunk := string(data[offset+4 : body]) + if chunk == "acTL" && length >= pngACTLFramesLen { + frames = int(binary.BigEndian.Uint32(data[body:])) + break + } + if chunk == "IDAT" { + break + } + offset = next + } + return width, height, frames, width > 0 && height > 0 +} + +// peekGIF reads the logical screen size and counts image descriptors by skipping each block's data. +func peekGIF(data []byte) (width, height, frames int, ok bool) { + if len(data) < gifScreenOffset+gifScreenLen { + return 0, 0, 0, false + } + width = int(binary.LittleEndian.Uint16(data[gifScreenOffset:])) + height = int(binary.LittleEndian.Uint16(data[gifScreenOffset+2:])) + offset := gifScreenOffset + gifScreenLen + gifTableLen(data[gifScreenOffset+gifFlagsOffset]) + for offset < len(data) { + switch data[offset] { + case gifExtension: + offset = skipGIFSubBlocks(data, offset+gifExtHeaderLen) + case gifImage: + if offset+gifImageHeaderLen > len(data) { + return width, height, max(frames, 1), width > 0 && height > 0 + } + frames++ + offset += gifImageHeaderLen + gifTableLen(data[offset+gifImageHeaderLen-1]) + offset = skipGIFSubBlocks(data, offset+gifLZWCodeLen) + default: // the trailer, or damage: what was counted stands + return width, height, max(frames, 1), width > 0 && height > 0 + } + } + return width, height, max(frames, 1), width > 0 && height > 0 +} + +// gifTableLen is the size of the colour table a screen or image descriptor's flags byte declares. +func gifTableLen(flags byte) int { + if flags&gifTableFlag == 0 { + return 0 + } + return gifTableEntryLen << (int(flags&gifTableSizeMask) + 1) +} + +// skipGIFSubBlocks returns the offset after the sub-block run starting at offset, or len(data) if it runs off the end. +func skipGIFSubBlocks(data []byte, offset int) int { + for offset < len(data) { + n := int(data[offset]) + offset++ + if n == 0 { + return offset + } + offset += n + } + return len(data) +} diff --git a/internal/assets/claim_test.go b/internal/assets/claim_test.go new file mode 100644 index 00000000..c4585825 --- /dev/null +++ b/internal/assets/claim_test.go @@ -0,0 +1,130 @@ +package assets + +import ( + "bytes" + "fmt" + "image" + "image/color" + "image/gif" + "image/png" + "testing" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +const ( + claimTestSide = 8 + claimTestFrames = 3 + claimFrameBytes = claimTestSide * claimTestSide * rgbaBytesPerPixel + + // claimBigSide makes each background claim a quarter of imageClaimLimit. + claimBigSide = 2048 + claimBigShare = imageClaimLimit / (claimBigSide * claimBigSide * rgbaBytesPerPixel) + claimBigAsks = 2 * claimBigShare + claimTestQuiet = 200 * time.Millisecond +) + +// encodeGIFGlobal is a GIF whose frames share one global colour table. +func encodeGIFGlobal(t *testing.T, frames int) []byte { + t.Helper() + palette := color.Palette{color.Transparent, color.Black, color.White} + g := &gif.GIF{Config: image.Config{Width: claimTestSide, Height: claimTestSide, ColorModel: palette}} + for range frames { + g.Image = append(g.Image, image.NewPaletted(image.Rect(0, 0, claimTestSide, claimTestSide), palette)) + g.Delay = append(g.Delay, 1) + } + var buf bytes.Buffer + if err := gif.EncodeAll(&buf, g); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func TestDecodeClaimReadsEveryFormatsHeader(t *testing.T) { + cases := []struct { + name string + data []byte + want int64 + }{ + {"png", encodePNG(t, claimTestSide, claimTestSide, color.White), claimFrameBytes}, + {"apng", encodeAPNG(t, claimTestFrames), claimTestFrames * claimFrameBytes}, + {"gif with a table per frame", encodeGIF(t, claimTestFrames), claimTestFrames * claimFrameBytes}, + {"gif with one global table", encodeGIFGlobal(t, claimTestFrames), claimTestFrames * claimFrameBytes}, + {"jpeg", encodeJPEG(t), claimFrameBytes}, + {"not an image", []byte("OggS\x00more"), unknownImageClaim}, + } + for _, c := range cases { + if got := decodeClaim(c.data, true); got != c.want { + t.Errorf("%s: claim %d, want %d", c.name, got, c.want) + } + } + if got := decodeClaim(encodeAPNG(t, claimTestFrames), false); got != claimFrameBytes { + t.Errorf("an animation with animations off claims %d, want one frame %d", got, claimFrameBytes) + } +} + +func TestDecodeClaimStopsAtTheAnimatedBudget(t *testing.T) { + const budget = claimFrameBytes * (claimTestFrames - 1) + old := maxAnimatedDecodedAssetBytes.Swap(budget) + t.Cleanup(func() { maxAnimatedDecodedAssetBytes.Store(old) }) + if got := decodeClaim(encodeAPNG(t, claimTestFrames), true); got != budget { + t.Fatalf("claim %d, want the animated budget %d", got, budget) + } +} + +func TestDecodeClaimSurvivesTruncatedHeaders(t *testing.T) { + for _, data := range [][]byte{encodeAPNG(t, claimTestFrames), encodeGIF(t, claimTestFrames), encodeJPEG(t)} { + for n := range len(data) { + if got := decodeClaim(data[:n], true); got <= 0 { + t.Fatalf("%d bytes of a %s claim %d", n, Sniff(data), got) + } + } + } +} + +func TestBackgroundDecodesWaitForUploads(t *testing.T) { + img := image.NewRGBA(image.Rect(0, 0, claimBigSide, claimBigSide)) + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatal(err) + } + host := &bridgeFakeHost{files: map[string][]byte{}} + var bases []string + for i := range claimBigAsks + 1 { + base := fmt.Sprintf("%sbackground/b/%d", bridgeTestOrigin, i) + host.files[base+".png"] = buf.Bytes() + bases = append(bases, base) + } + rig := newBridgeRig(t, host) + for _, base := range bases[:claimBigAsks] { + rig.manager.Prefetch(base, AssetTypeBackground, network.PriorityLow) // AssetType: Background + } + + var held []Delivery + take := func() { rig.manager.TakeDeliveries(func(d Delivery) { held = append(held, d) }) } + waitUntil(t, "the first background decodes", func() bool { take(); return len(held) >= claimBigShare }) + time.Sleep(claimTestQuiet) + take() + if len(held) != claimBigShare { + t.Fatalf("%d background decodes delivered while none were uploaded, want %d", len(held), claimBigShare) + } + + rig.manager.Prefetch(bases[claimBigAsks], AssetTypeBackground, network.PriorityHigh) // AssetType: Background + waitUntil(t, "the current message's decode", func() bool { take(); return len(held) > claimBigShare }) + + for _, d := range held { + d.Asset.Release() + rig.manager.Done(d) + } + done := len(held) + held = nil + waitUntil(t, "the rest after uploads", func() bool { + rig.manager.TakeDeliveries(func(d Delivery) { + d.Asset.Release() + rig.manager.Done(d) + done++ + }) + return done == claimBigAsks+1 + }) +} diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index d61da357..33d86d4e 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -74,7 +74,7 @@ func newMediaBridge(m *Manager) *mediaBridge { b.learned = saver.New(m.learnedPath, learnedSaveDelay, b.encodeLearned) cfg := media.Config{Candidates: b.builder.Build, AllFormats: media.EveryFormat, Found: b.found, Finished: b.finished, Delivered: m.NotifyDelivery, Skip: b.skip, Asked: b.asked, MissingAgain: b.missingAgain, - Compute: b.compute} + Compute: b.compute, ClaimLimit: imageClaimLimit} b.remote = media.NewRemoteSource(ctx, bridgeFetcher{m}, media.DefaultMissingTTL, time.Now) cfg.Chains = map[media.Place]*media.Chain{media.PlaceServer: media.NewChain( media.Entry{Source: bridgeMemory{m.t2, b.pin, m}}, @@ -578,8 +578,15 @@ func (b *mediaBridge) hitOf(hit media.Hit) (string, bool) { // thread as early pages, and the last page is the result. type bridgeImage struct{ b *mediaBridge } +var _ media.Measurer = bridgeImage{} + func (f bridgeImage) OnMainThread() bool { return true } +// Measure claims the decoded size, so background decodes wait while the render thread is behind on uploads. +func (f bridgeImage) Measure(data []byte) int64 { + return decodeClaim(data, f.b.m.prefs.Load().PreferAnimated) +} + func (f bridgeImage) Decode(k media.Key, hit media.Hit, data []byte, page func(any)) (any, error) { url, fromPack := f.b.hitOf(hit) t := AssetType(k.Tag) From b1db06d0b6909e5b0d1d770a5ea012aa362ba1d0 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:47:02 +0100 Subject: [PATCH 32/43] assets: exact-size frames, and APNG decodes one frame at a time The pixel pool rounded every frame up to a size class (a 256x192 frame took 256 KiB for 192 KiB of pixels) and sync.Pool kept freed buffers alive through a collection. With background decodes bounded by the claim limit there is little churn left for it to save, so frames are now plain exact-size allocations and Release only drops the references. kettek/apng's DecodeAll inflates every frame before returning, so a full-frame APNG briefly held twice its decoded size. The client now reads the chunks once and inflates each frame through image/png right before compositing it. Output is identical to the library's on all 14 official vanilla APNGs (pixels, delays, downscaled and first-frame-only); the library stays as a test dependency for encoding fixtures. Headless burst of 112 animated sprites: peak live heap ~220 -> ~155 MiB, heap left after it ~85 -> 18 MiB, 2.2 s -> 2.0 s. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 4 +- docs/PERFORMANCE.md | 12 +-- docs/RESTRUCTURING_PLAN.md | 5 +- internal/assets/apng.go | 165 ++++++++++++++++++++++++++++++++ internal/assets/apng_test.go | 62 ++++++++++++ internal/assets/avif_cgo.go | 34 ++----- internal/assets/decoder.go | 152 ++++++++--------------------- internal/assets/decoder_test.go | 30 ------ internal/assets/pixpool.go | 54 ----------- internal/assets/types.go | 9 +- internal/assets/webp_cgo.go | 38 ++------ internal/ui/about.go | 1 - 12 files changed, 297 insertions(+), 269 deletions(-) create mode 100644 internal/assets/apng.go create mode 100644 internal/assets/apng_test.go delete mode 100644 internal/assets/pixpool.go diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 662aec0d..ac3ac7b5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -179,7 +179,7 @@ Prefetch(base, type, prio) PrefetchWithFallback(base, altBase, ...) → Warning{base, formats tried} → UI banner (12 s, courtroom + char select) chain already exhausted → warn, submit nothing ← the gate, above the pool - decode pool: sniff magic bytes (never extensions) → RGBA frames (pooled px); + decode pool: sniff magic bytes (never extensions) → RGBA frames; STILL assets capped at maxDecodedAssetBytes (T1 budget / 4, the cache.MaxDecodedAssetBytes single source of truth — one landing page can never evict even half the main tier); ANIMATED assets @@ -631,7 +631,7 @@ a solo sprite. | `hashicorp/golang-lru/v2` (+expirable) | thread-safe LRU; wrapped only for byte accounting | | `golang.org/x/sync` singleflight | fetch dedup (v0.20.0, matching the Go 1.25 directive) | | `cespare/xxhash/v2` | fast non-crypto cache keys | -| `kettek/apng` | APNG decode (the draft's pick was a diff library!) | +| `kettek/apng` | test-only: encodes APNG fixtures. The client decodes APNG itself (`internal/assets/apng.go`), one frame at a time through `image/png`, so a frame's pixels exist only until they are composited; the library decodes every frame before returning | | `golang.org/x/image` | pure-Go WebP fallback + embedded Go font | | `coder/websocket` | **addition:** AO2 ≥ 2.11 is WebSocket-only; stdlib has no WS client. Zero-dependency, maintained, context-aware. | | MSYS2 `libavif` (CGO, no Go module) | **addition (user request):** `.avif` as a probe format — native dav1d/aom decode for stills *and* AV1 image sequences, bound exactly like the libwebp CGO shim (~100 lines). The pure-Go alternatives embed a WASM runtime (gen2brain/avif → wazero), the opposite of this project's soul. CGO-less builds degrade to a descriptive decode error; sniffing (`ftyp` + `avif`/`avis` brands) stays pure Go. | diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index b341f96f..596b7dfc 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -64,10 +64,10 @@ Power user tab's "Decode downscale & texture memory" group: compressed GPU textures, which is most of the ~4-8x RAM gap on integrated GPUs. Restart-applied. -Under the hood the pixel pool gained an 8 MiB class: native 1600x1200 frames -(~7.3 MiB) used to land in the 16 MiB class (~2x waste per frame), and with -`NumCPU/2` decode workers that waste multiplied into the multi-GiB spike. The -8 MiB class keeps per-frame overhead near 1.1x and halves the burst. +Frames are allocated at their exact size. The size-classed pixel pool that used +to supply them rounded each frame up to its class (a 256x192 frame took 256 KiB +for 192 KiB of pixels) and kept freed buffers alive across a collection; removing +it lowered a burst's peak heap by about a third at the same speed. Rough expectations (DXT5 compression on): 128 MiB budget ~= ~33 MiB per animation on the GPU; 256 MiB ~= ~67 MiB; 500 MiB ~= ~110 MiB. At 128 MiB + @@ -116,10 +116,10 @@ Watch for: | Format resolution | atomic snapshot, pooled candidates, 1 alloc — and the unlearned path reads a generation-cached format table (no prefs lock, no rebuild) | | Cache hits | lock-free-ish LRU (internal lock, no wrapper), atomics for stats | | Fetch dedup | singleflight; 404 LRU; per-host backoff off the hot path | -| Decode | worker pool, size-classed pixel pools, SIMD libwebp via CGO | +| Decode | worker pool, SIMD libwebp via CGO; background decodes claim their decoded size and wait under a 64 MiB limit until uploaded | | Texture upload | budgeted per frame; live message bypasses the budget | | Typewriter | rasterize once per message; reveal = src-rect width per frame | | Animations | precomputed delay tables; frame advance is an index bump | | Render | zero allocations steady-state (cgo-escape pitfalls: never take the address of a stack rect for `Renderer.Copy` — use a reused field); texture pages are generation-cached per layer, so steady frames do zero LRU lookups | -| Animated decode | composition canvas + DisposalPrevious snapshot from the pixel pool — allocations limited to the output frames | +| Animated decode | one composition canvas + DisposalPrevious snapshot per decode; APNG frames inflate one at a time | | HTTP transport | 3 s response-header timeout fails stalled hosts before the 5 s deadline, freeing the per-host connection slot | diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index 62a3da67..248715cf 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -137,7 +137,10 @@ in **Status**. Update Status in the same commit that completes a step. - [x] background decodes claim their decoded size from the file header and wait under a 64 MiB limit until the pump uploads (2026-11-15). Burst of 112 vanilla APNGs: peak live heap ~950 → ~220 MiB, heap after it ~700 → 31-56 MiB; the burst takes 2.2 s instead of 1.6 s. Requests for the current message are not limited - - [ ] still open: what is left of the 220 MiB peak, and a profile from the real client + - [x] the size-classed pixel pool is gone (it rounded 192 KiB frames to 256 KiB and kept freed buffers through a + collection) and APNG decodes one frame at a time (`assets/apng.go`, output identical to `kettek/apng`): + same burst, peak ~220 → ~155 MiB, heap after it ~85 → 18 MiB, 2.2 → 2.0 s + - [ ] still open: a profile from the real client - [ ] move callers (decided 2026-11-15): callers call `media.Manager` directly with keys from small assets helpers, and the bridge goes at the end. Order: `Pump` on `TakeResults`, then courtroom, screens, theme and audio; music streaming after them diff --git a/internal/assets/apng.go b/internal/assets/apng.go new file mode 100644 index 00000000..487f2bb4 --- /dev/null +++ b/internal/assets/apng.go @@ -0,0 +1,165 @@ +package assets + +import ( + "bytes" + "encoding/binary" + "errors" + "hash/crc32" + "image" + "image/png" + "time" +) + +// APNG chunk layouts (https://wiki.mozilla.org/APNG_Specification). +const ( + pngIHDRLen = 13 + apngFCTLLen = 26 + apngSeqLen = 4 + apngDelayUnits = 100 // a zero denominator means hundredths of a second + + apngDisposeBackground = 1 + apngDisposePrevious = 2 + apngBlendSource = 0 +) + +var ( + errAPNGDamaged = errors.New("assets: apng chunk runs past the end of the file") + errAPNGFrame = errors.New("assets: apng frame lies outside the canvas") + pngIEND = []byte{0, 0, 0, 0, 'I', 'E', 'N', 'D', 0xAE, 0x42, 0x60, 0x82} +) + +// apngFrame is one frame's control fields and its compressed data, still inside the file's bytes. +type apngFrame struct { + rect image.Rectangle + delayNum, delayDen uint16 + dispose, blend byte + data [][]byte +} + +// apngFile is an APNG read as far as its chunks: frames decode one at a time from it. +type apngFile struct { + width, height int + ihdr []byte + // palette holds the PLTE and tRNS chunks, whole, which every frame's stream repeats. + palette [][]byte + frames []apngFrame + // still is the default image when no fcTL comes before IDAT: shown by viewers without APNG, not part of the animation. + still *apngFrame +} + +// parseAPNG walks the chunks once, keeping offsets into data, without inflating anything. +func parseAPNG(data []byte) (*apngFile, error) { + f := &apngFile{} + var current *apngFrame + for offset := pngSigLen; offset+pngChunkHdrLen <= len(data); { + length := int(binary.BigEndian.Uint32(data[offset:])) + body := offset + pngChunkHdrLen + next := body + length + pngChunkCRCLen + if length < 0 || next <= offset || next > len(data) { + return nil, errAPNGDamaged + } + chunk, content := string(data[offset+4:body]), data[body:body+length] + switch chunk { + case "IHDR": + if length != pngIHDRLen { + return nil, errAPNGDamaged + } + f.ihdr = content + f.width, f.height = int(binary.BigEndian.Uint32(content)), int(binary.BigEndian.Uint32(content[4:])) + case "PLTE", "tRNS": + f.palette = append(f.palette, data[offset:next]) + case "fcTL": + fr, err := f.control(content) + if err != nil { + return nil, err + } + f.frames = append(f.frames, fr) + current = &f.frames[len(f.frames)-1] + case "IDAT": + if current == nil { + f.still = &apngFrame{rect: image.Rect(0, 0, f.width, f.height)} + current = f.still + } + current.data = append(current.data, content) + case "fdAT": + if current == nil || current == f.still || length < apngSeqLen { + return nil, errAPNGDamaged + } + current.data = append(current.data, content[apngSeqLen:]) + case "IEND": + return f, nil + } + offset = next + } + return f, nil +} + +// control reads an fcTL chunk, refusing a frame that doesn't fit the canvas. +func (f *apngFile) control(c []byte) (apngFrame, error) { + if len(c) != apngFCTLLen || f.ihdr == nil { + return apngFrame{}, errAPNGDamaged + } + be := binary.BigEndian + w, h := int64(be.Uint32(c[4:])), int64(be.Uint32(c[8:])) + x, y := int64(be.Uint32(c[12:])), int64(be.Uint32(c[16:])) + if w <= 0 || h <= 0 || x+w > int64(f.width) || y+h > int64(f.height) { + return apngFrame{}, errAPNGFrame + } + return apngFrame{ + rect: image.Rect(int(x), int(y), int(x+w), int(y+h)), + delayNum: be.Uint16(c[20:]), delayDen: be.Uint16(c[22:]), + dispose: c[24], blend: c[25], + }, nil +} + +// decode inflates one frame by handing image/png a stream of its own: IHDR at the frame's size, the palette, its data. +func (f *apngFile) decode(fr *apngFrame) (image.Image, error) { + size := len(pngSignature) + 3*pngChunkHdrLen + pngIHDRLen + len(pngIEND) + for _, c := range f.palette { + size += len(c) + } + for _, d := range fr.data { + size += pngChunkHdrLen + len(d) + pngChunkCRCLen + } + var buf bytes.Buffer + buf.Grow(size) + buf.Write(pngSignature) + ihdr := make([]byte, pngIHDRLen) + copy(ihdr, f.ihdr) + binary.BigEndian.PutUint32(ihdr, uint32(fr.rect.Dx())) + binary.BigEndian.PutUint32(ihdr[4:], uint32(fr.rect.Dy())) + writeChunk(&buf, "IHDR", ihdr) + for _, c := range f.palette { + buf.Write(c) + } + for _, d := range fr.data { + writeChunk(&buf, "IDAT", d) + } + buf.Write(pngIEND) + return png.Decode(&buf) +} + +func writeChunk(buf *bytes.Buffer, kind string, data []byte) { + var head [pngChunkHdrLen]byte + binary.BigEndian.PutUint32(head[:], uint32(len(data))) + copy(head[4:], kind) + buf.Write(head[:]) + buf.Write(data) + crc := crc32.NewIEEE() + crc.Write(head[4:]) + crc.Write(data) + var sum [pngChunkCRCLen]byte + binary.BigEndian.PutUint32(sum[:], crc.Sum32()) + buf.Write(sum[:]) +} + +func (fr *apngFrame) delay() time.Duration { + den := fr.delayDen + if den == 0 { + den = apngDelayUnits + } + if d := time.Duration(fr.delayNum) * time.Second / time.Duration(den); d > 0 { + return d + } + return defaultZeroFrameDelay +} diff --git a/internal/assets/apng_test.go b/internal/assets/apng_test.go new file mode 100644 index 00000000..2d07d97b --- /dev/null +++ b/internal/assets/apng_test.go @@ -0,0 +1,62 @@ +package assets + +import ( + "bytes" + "encoding/binary" + "image" + "image/color" + "testing" + + "github.com/kettek/apng" +) + +const ( + apngTestSide = 8 + apngTestFrames = 2 + apngFCTLXAt = 12 // fcTL's x_offset, counted from the chunk's data +) + +var apngStillRed = color.RGBA{R: 0xFF, A: 0xFF} + +func TestAPNGLeavesTheDefaultStillOutOfTheAnimation(t *testing.T) { + still := image.NewRGBA(image.Rect(0, 0, apngTestSide, apngTestSide)) + for p := 0; p < len(still.Pix); p += rgbaBytesPerPixel { + copy(still.Pix[p:], []byte{apngStillRed.R, apngStillRed.G, apngStillRed.B, apngStillRed.A}) + } + a := apng.APNG{Frames: []apng.Frame{{Image: still, IsDefault: true}}} + for range apngTestFrames { + a.Frames = append(a.Frames, apng.Frame{Image: image.NewRGBA(still.Rect), DelayNumerator: 1}) + } + var buf bytes.Buffer + if err := apng.Encode(&buf, a); err != nil { + t.Fatal(err) + } + d, err := DecodeImage(buf.Bytes(), true) + if err != nil { + t.Fatal(err) + } + if len(d.Frames) != apngTestFrames { + t.Fatalf("%d frames, want the %d animation frames", len(d.Frames), apngTestFrames) + } + if got := d.Frames[0].RGBAAt(0, 0); got == apngStillRed { + t.Fatal("the default still image played as the first frame") + } +} + +func TestAPNGRefusesAFrameOutsideTheCanvas(t *testing.T) { + data := encodeAPNG(t, apngTestFrames) + at := bytes.Index(data, []byte("fcTL")) + len("fcTL") + binary.BigEndian.PutUint32(data[at+apngFCTLXAt:], apngTestSide) + if _, err := DecodeImage(data, true); err == nil { + t.Fatal("a frame past the canvas edge decoded") + } +} + +func TestAPNGSurvivesTruncation(t *testing.T) { + data := encodeAPNG(t, apngTestFrames) + for n := range len(data) { + if d, err := DecodeImage(data[:n], true); err == nil && len(d.Frames) == 0 { + t.Fatalf("%d bytes decoded to no frames without an error", n) + } + } +} diff --git a/internal/assets/avif_cgo.go b/internal/assets/avif_cgo.go index b032b5bf..6ba1f1b9 100644 --- a/internal/assets/avif_cgo.go +++ b/internal/assets/avif_cgo.go @@ -2,7 +2,7 @@ package assets -// CGO binding over libavif: dav1d/aom decode into pooled RGBA, for still images and AV1 image sequences. +// CGO binding over libavif: dav1d/aom decode into RGBA, for still images and AV1 image sequences. /* #cgo pkg-config: libavif @@ -94,29 +94,21 @@ func decodeAVIF(data []byte, playAnimations bool, maxH int) (*Decoded, error) { rgb.format = C.AVIF_RGB_FORMAT_RGBA rgb.depth = 8 - rgba, token := newPooledRGBA(width, height) + rgba := image.NewRGBA(image.Rect(0, 0, width, height)) // The rgb struct carries a Go pointer into C, legal only while the buffer is pinned (cgo pointer rules). pinner.Pin(&rgba.Pix[0]) rgb.pixels = (*C.uint8_t)(unsafe.Pointer(&rgba.Pix[0])) rgb.rowBytes = C.uint32_t(rgba.Stride) if res := C.avifImageYUVToRGB(dec.image, &rgb); res != C.AVIF_RESULT_OK { - putPixBuf(token) d.Release() return nil, avifError(fmt.Sprintf("frame %d yuv→rgb", i), res) } if down { - small, smallTok := downscaleFrame(rgba, tw, th) - putPixBuf(token) + small := downscaleFrame(rgba, tw, th) d.Frames = append(d.Frames, small) - if smallTok != nil { - d.pooledPix = append(d.pooledPix, smallTok) - } } else { d.Frames = append(d.Frames, rgba) - if token != nil { - d.pooledPix = append(d.pooledPix, token) - } } d.Delays = append(d.Delays, folded) } @@ -159,17 +151,11 @@ func decodeAVIFAnimStream(data []byte, maxH int, emit func(*Decoded)) (streamed return false, walk, nil // decimation needed — fall back to the full decode } - // When downscaling, reuse one native buffer instead of churning the pool; else it is the delivered frame. + // When downscaling, one native buffer is reused for every frame; else it is the delivered frame. var reuse *image.RGBA - var reuseToken *[]byte if down { - reuse, reuseToken = newPooledRGBA(width, height) + reuse = image.NewRGBA(image.Rect(0, 0, width, height)) pinner.Pin(&reuse.Pix[0]) - defer func() { - if reuseToken != nil { - putPixBuf(reuseToken) - } - }() } for i := 0; i < walk; i++ { @@ -185,11 +171,10 @@ func decodeAVIFAnimStream(data []byte, maxH int, emit func(*Decoded)) (streamed } var rgba *image.RGBA - var token *[]byte if down { rgba = reuse } else { - rgba, token = newPooledRGBA(width, height) + rgba = image.NewRGBA(image.Rect(0, 0, width, height)) } var rgb C.avifRGBImage @@ -203,14 +188,12 @@ func decodeAVIFAnimStream(data []byte, maxH int, emit func(*Decoded)) (streamed rgb.rowBytes = C.uint32_t(rgba.Stride) if res := C.avifImageYUVToRGB(dec.image, &rgb); res != C.AVIF_RESULT_OK { - putPixBuf(token) return true, walk, avifError(fmt.Sprintf("frame %d yuv→rgb", i), res) } out := rgba if down { - small, smallTok := downscaleFrame(rgba, tw, th) + small := downscaleFrame(rgba, tw, th) out = small - token = smallTok } chunk := &Decoded{ Frames: []*image.RGBA{out}, @@ -223,9 +206,6 @@ func decodeAVIFAnimStream(data []byte, maxH int, emit func(*Decoded)) (streamed FrameOffset: i, Partial: true, } - if token != nil { - chunk.pooledPix = append(chunk.pooledPix, token) - } emit(chunk) } return true, walk, nil diff --git a/internal/assets/decoder.go b/internal/assets/decoder.go index 39335330..67d6e812 100644 --- a/internal/assets/decoder.go +++ b/internal/assets/decoder.go @@ -15,7 +15,6 @@ import ( "sync/atomic" "time" - "github.com/kettek/apng" xdraw "golang.org/x/image/draw" "github.com/SyntaxNyah/AsyncAO/internal/cache" @@ -87,12 +86,9 @@ func downscaleDecoded(d *Decoded, target int) *Decoded { SourceFrames: d.SourceFrames, } for _, frame := range d.Frames { - small, token := newPooledRGBA(target, target) + small := image.NewRGBA(image.Rect(0, 0, target, target)) xdraw.ApproxBiLinear.Scale(small, small.Rect, frame, frame.Rect, xdraw.Src, nil) out.Frames = append(out.Frames, small) - if token != nil { - out.pooledPix = append(out.pooledPix, token) - } } d.Release() return out @@ -117,12 +113,9 @@ func downscaleDecodedAspect(d *Decoded, maxH int) *Decoded { SourceFrames: d.SourceFrames, // see downscaleDecoded: pixels shrink, the frame space does not } for _, frame := range d.Frames { - small, token := newPooledRGBA(newW, maxH) + small := image.NewRGBA(image.Rect(0, 0, newW, maxH)) xdraw.CatmullRom.Scale(small, small.Rect, frame, frame.Rect, xdraw.Src, nil) out.Frames = append(out.Frames, small) - if token != nil { - out.pooledPix = append(out.pooledPix, token) - } } d.Release() return out @@ -172,9 +165,9 @@ func decodeTargetDimsBudgeted(width, height, maxH, frames int) (tw, th int, down // downscaleFrame uses an area-average filter, as ApproxBiLinear skips source pixels and aliases. // Alpha is averaged premultiplied so transparent pixels cannot darken an edge. -func downscaleFrame(src *image.RGBA, tw, th int) (*image.RGBA, *[]byte) { +func downscaleFrame(src *image.RGBA, tw, th int) *image.RGBA { sw, sh := src.Rect.Dx(), src.Rect.Dy() - out, token := newPooledRGBA(tw, th) + out := image.NewRGBA(image.Rect(0, 0, tw, th)) spix, dpix := src.Pix, out.Pix sstride, dstride := src.Stride, out.Stride @@ -213,7 +206,7 @@ func downscaleFrame(src *image.RGBA, tw, th int) (*image.RGBA, *[]byte) { dpix[q+3] = uint8(sumA / uint32((x1-x0)*(y1-y0))) } } - return out, token + return out } // boundedFrameCount reports how many evenly spaced frames fit the budget, at least one. @@ -704,11 +697,8 @@ func fitEstablishingPrefix(first *Decoded, data []byte, maxH int) *Decoded { SourceFrames: first.SourceFrames, // pixels shrink, the frame space does not } for _, frame := range first.Frames { - small, token := downscaleFrame(frame, tw, th) + small := downscaleFrame(frame, tw, th) out.Frames = append(out.Frames, small) - if token != nil { - out.pooledPix = append(out.pooledPix, token) - } } first.Release() return out @@ -853,7 +843,7 @@ func decodeJPEG(data []byte) (*Decoded, error) { // staticDecoded wraps a still image, converting to RGBA when needed. func staticDecoded(img image.Image) *Decoded { - rgba, token := toRGBA(img) + rgba := toRGBA(img) d := &Decoded{ Frames: []*image.RGBA{rgba}, Delays: []time.Duration{0}, @@ -861,33 +851,18 @@ func staticDecoded(img image.Image) *Decoded { Width: rgba.Rect.Dx(), Height: rgba.Rect.Dy(), } - if token != nil { - d.pooledPix = append(d.pooledPix, token) - } return d } -// toRGBA returns img as *image.RGBA; the pool token is nil when img was already RGBA. -func toRGBA(img image.Image) (*image.RGBA, *[]byte) { +// toRGBA returns img as *image.RGBA, converting only when it isn't one. +func toRGBA(img image.Image) *image.RGBA { if rgba, ok := img.(*image.RGBA); ok { - return rgba, nil + return rgba } bounds := img.Bounds() - rgba, token := newPooledRGBA(bounds.Dx(), bounds.Dy()) + rgba := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy())) draw.Draw(rgba, rgba.Rect, img, bounds.Min, draw.Src) - return rgba, token -} - -// newPooledRGBA builds a w×h RGBA image whose Pix comes from the pixel pool. -func newPooledRGBA(w, h int) (*image.RGBA, *[]byte) { - const bytesPerPixel = 4 - n := w * h * bytesPerPixel - buf, token := getPixBuf(n) - return &image.RGBA{ - Pix: buf, - Stride: w * bytesPerPixel, - Rect: image.Rect(0, 0, w, h), - }, token + return rgba } // decodeGIF composes a GIF onto a persistent canvas, honoring disposal, producing full-canvas RGBA frames. @@ -930,11 +905,8 @@ func decodeGIF(data []byte, playAnimations bool, maxH int) (*Decoded, error) { } // The backdrop snapshot supports DisposalPrevious. - canvas, canvasTok := newPooledRGBA(width, height) - defer putPixBuf(canvasTok) + canvas := image.NewRGBA(image.Rect(0, 0, width, height)) var prevSnapshot *image.RGBA - var snapTok *[]byte - defer func() { putPixBuf(snapTok) }() // Compose every source frame, because a kept frame depends on the disposal before it; copy out only the kept ones. for i := 0; i < walk; i++ { @@ -946,7 +918,7 @@ func decodeGIF(data []byte, playAnimations bool, maxH int) (*Decoded, error) { if disposal == gif.DisposalPrevious { if prevSnapshot == nil { - prevSnapshot, snapTok = newPooledRGBA(width, height) + prevSnapshot = image.NewRGBA(image.Rect(0, 0, width, height)) } copy(prevSnapshot.Pix, canvas.Pix) } @@ -954,20 +926,13 @@ func decodeGIF(data []byte, playAnimations bool, maxH int) (*Decoded, error) { draw.Draw(canvas, frame.Bounds(), frame, frame.Bounds().Min, draw.Over) if folded, keepIt := dec.step(i, gifFrameDelay(g, i)); keepIt { - out, token := newPooledRGBA(width, height) + out := image.NewRGBA(image.Rect(0, 0, width, height)) copy(out.Pix, canvas.Pix) if down { - small, smallTok := downscaleFrame(out, tw, th) - putPixBuf(token) + small := downscaleFrame(out, tw, th) d.Frames = append(d.Frames, small) - if smallTok != nil { - d.pooledPix = append(d.pooledPix, smallTok) - } } else { d.Frames = append(d.Frames, out) - if token != nil { - d.pooledPix = append(d.pooledPix, token) - } } d.Delays = append(d.Delays, folded) } @@ -1010,27 +975,18 @@ func clearRect(canvas *image.RGBA, r image.Rectangle) { // decodeAPNG composes APNG frames onto a persistent canvas, as decodeGIF does. func decodeAPNG(data []byte, playAnimations bool, maxH int) (*Decoded, error) { - a, err := apng.DecodeAll(bytes.NewReader(data)) + file, err := parseAPNG(data) if err != nil { - return nil, fmt.Errorf("assets: apng decode: %w", err) - } - if len(a.Frames) == 0 { - return nil, fmt.Errorf("assets: apng has no frames") + return nil, err } - - first := a.Frames[0].Image.Bounds() - width, height := first.Dx(), first.Dy() - - // Frames flagged IsDefault are the static fallback image, not part of the animation. - animFrames := make([]apng.Frame, 0, len(a.Frames)) - for _, f := range a.Frames { - if !f.IsDefault { - animFrames = append(animFrames, f) - } + animFrames := file.frames + if len(animFrames) == 0 && file.still != nil { + animFrames = []apngFrame{*file.still} } if len(animFrames) == 0 { - animFrames = a.Frames + return nil, fmt.Errorf("assets: apng has no frames") } + width, height := file.width, file.height total := len(animFrames) animated := total > 1 @@ -1043,7 +999,7 @@ func decodeAPNG(data []byte, playAnimations bool, maxH int) (*Decoded, error) { dec := newFrameDecimator(walk, keep) sourceDelays := make([]time.Duration, walk) for i := 0; i < walk; i++ { - sourceDelays[i] = apngFrameDelay(animFrames[i]) + sourceDelays[i] = animFrames[i].delay() } d := &Decoded{ @@ -1055,58 +1011,47 @@ func decodeAPNG(data []byte, playAnimations bool, maxH int) (*Decoded, error) { Delays: make([]time.Duration, 0, keep), } - canvas, canvasTok := newPooledRGBA(width, height) - defer putPixBuf(canvasTok) + canvas := image.NewRGBA(image.Rect(0, 0, width, height)) var prevSnapshot *image.RGBA - var snapTok *[]byte - defer func() { putPixBuf(snapTok) }() // Compose every source frame, because a kept frame depends on the dispose and blend before it. for i := 0; i < walk; i++ { - frame := animFrames[i] - target := image.Rect( - frame.XOffset, - frame.YOffset, - frame.XOffset+frame.Image.Bounds().Dx(), - frame.YOffset+frame.Image.Bounds().Dy(), - ) - - if frame.DisposeOp == apng.DISPOSE_OP_PREVIOUS { + frame := &animFrames[i] + target := frame.rect + img, err := file.decode(frame) + if err != nil { + return nil, fmt.Errorf("assets: apng frame %d: %w", i, err) + } + + if frame.dispose == apngDisposePrevious { if prevSnapshot == nil { - prevSnapshot, snapTok = newPooledRGBA(width, height) + prevSnapshot = image.NewRGBA(image.Rect(0, 0, width, height)) } copy(prevSnapshot.Pix, canvas.Pix) } op := draw.Over - if frame.BlendOp == apng.BLEND_OP_SOURCE { + if frame.blend == apngBlendSource { op = draw.Src } - draw.Draw(canvas, target, frame.Image, frame.Image.Bounds().Min, op) + draw.Draw(canvas, target, img, img.Bounds().Min, op) - if folded, keepIt := dec.step(i, apngFrameDelay(frame)); keepIt { - out, token := newPooledRGBA(width, height) + if folded, keepIt := dec.step(i, frame.delay()); keepIt { + out := image.NewRGBA(image.Rect(0, 0, width, height)) copy(out.Pix, canvas.Pix) if down { - small, smallTok := downscaleFrame(out, tw, th) - putPixBuf(token) + small := downscaleFrame(out, tw, th) d.Frames = append(d.Frames, small) - if smallTok != nil { - d.pooledPix = append(d.pooledPix, smallTok) - } } else { d.Frames = append(d.Frames, out) - if token != nil { - d.pooledPix = append(d.pooledPix, token) - } } d.Delays = append(d.Delays, folded) } - switch frame.DisposeOp { - case apng.DISPOSE_OP_BACKGROUND: + switch frame.dispose { + case apngDisposeBackground: clearRect(canvas, target) - case apng.DISPOSE_OP_PREVIOUS: + case apngDisposePrevious: if prevSnapshot != nil { copy(canvas.Pix, prevSnapshot.Pix) } @@ -1115,16 +1060,3 @@ func decodeAPNG(data []byte, playAnimations bool, maxH int) (*Decoded, error) { spreadLoopDelays(d, sourceDelays) return d, nil } - -func apngFrameDelay(f apng.Frame) time.Duration { - num := f.DelayNumerator - den := f.DelayDenominator - if den == 0 { - den = 100 // APNG spec: zero denominator means 1/100 s units - } - delay := time.Duration(num) * time.Second / time.Duration(den) - if delay <= 0 { - return defaultZeroFrameDelay - } - return delay -} diff --git a/internal/assets/decoder_test.go b/internal/assets/decoder_test.go index bfbbf99e..0b87dd4c 100644 --- a/internal/assets/decoder_test.go +++ b/internal/assets/decoder_test.go @@ -247,36 +247,6 @@ func TestDecoderDeliversResults(t *testing.T) { } } -func TestPixPoolRoundTrip(t *testing.T) { - buf, token := getPixBuf(1024) - if len(buf) != 1024 { - t.Fatalf("len = %d", len(buf)) - } - for i := range buf { - buf[i] = 0xAA - } - putPixBuf(token) - buf2, token2 := getPixBuf(2048) - defer putPixBuf(token2) - for i, b := range buf2 { - if b != 0 { - t.Fatalf("recycled buffer not zeroed at %d", i) - } - } -} - -func TestPixPoolOversizeUnpooled(t *testing.T) { - huge := pixClassSizes[len(pixClassSizes)-1] + 1 - buf, token := getPixBuf(huge) - if token != nil { - t.Error("oversize buffer claims pool token") - } - if len(buf) != huge { - t.Errorf("len = %d, want %d", len(buf), huge) - } - putPixBuf(token) // must be a no-op -} - // pinSmallAnimatedBudget shrinks the live animated frame budget so the // budget-fit downscale can be exercised deterministically regardless of the // shipped (128 MiB) default, restoring the prior value on cleanup. diff --git a/internal/assets/pixpool.go b/internal/assets/pixpool.go deleted file mode 100644 index afbf8d91..00000000 --- a/internal/assets/pixpool.go +++ /dev/null @@ -1,54 +0,0 @@ -package assets - -import "sync" - -// Pooled pixel buffers by size class, released by the render thread after upload. - -// pixClassSizes are the pooled capacities; 8 MiB fits 1600x1200 animated frames, which waste 2x in the 16 MiB class. -var pixClassSizes = [...]int{256 << 10, 1 << 20, 4 << 20, 8 << 20, 16 << 20} - -var pixPools = func() [len(pixClassSizes)]*sync.Pool { - var pools [len(pixClassSizes)]*sync.Pool - for i, size := range pixClassSizes { - size := size - pools[i] = &sync.Pool{New: func() any { - buf := make([]byte, size) - return &buf - }} - } - return pools -}() - -// getPixBuf returns a zeroed buffer from the smallest fitting class, or an unpooled one with a nil token. -func getPixBuf(n int) ([]byte, *[]byte) { - for i, size := range pixClassSizes { - if n <= size { - token := pixPools[i].Get().(*[]byte) - buf := (*token)[:n] - clearPix(buf) - return buf, token - } - } - return make([]byte, n), nil -} - -// putPixBuf returns a pooled buffer to its class; nil tokens are ignored. -func putPixBuf(token *[]byte) { - if token == nil { - return - } - n := cap(*token) - for i, size := range pixClassSizes { - if n == size { - pixPools[i].Put(token) - return - } - } -} - -// clearPix zeroes a recycled buffer so transparent regions stay transparent. -func clearPix(buf []byte) { - for i := range buf { - buf[i] = 0 - } -} diff --git a/internal/assets/types.go b/internal/assets/types.go index ce9b6461..1c987ea1 100644 --- a/internal/assets/types.go +++ b/internal/assets/types.go @@ -97,9 +97,6 @@ type Decoded struct { DXTFormat uint32 // Opaque reports that every pixel of every frame has full alpha, so the frames can be copied without blending. Opaque bool - - // pooledPix tracks pool-drawn frame buffers to return on Release. - pooledPix []*[]byte } // PixelBytes returns the payload size the T1 budget accounts for: w*h*4 per frame, or the DXT size when compressed. @@ -119,12 +116,8 @@ func (d *Decoded) PixelBytes() int64 { return total } -// Release returns pooled frame buffers; call exactly once, after upload, and do not use the Decoded afterwards. +// Release drops the frames after upload, so they can be collected while something still holds the Decoded. func (d *Decoded) Release() { - for _, buf := range d.pooledPix { - putPixBuf(buf) - } - d.pooledPix = nil d.Frames = nil d.Compressed = nil } diff --git a/internal/assets/webp_cgo.go b/internal/assets/webp_cgo.go index 70a71f0c..b1204339 100644 --- a/internal/assets/webp_cgo.go +++ b/internal/assets/webp_cgo.go @@ -59,14 +59,14 @@ func peekWebPAnimDims(data []byte) (width, height, frames int, ok bool) { return w, h, n, true } -// decodeWebPStatic decodes a still WebP directly into a pooled RGBA buffer. +// decodeWebPStatic decodes a still WebP directly into an RGBA buffer. func decodeWebPStatic(data []byte) (*Decoded, error) { var w, h C.int if C.WebPGetInfo((*C.uint8_t)(unsafe.Pointer(&data[0])), C.size_t(len(data)), &w, &h) == 0 { return nil, fmt.Errorf("assets: invalid webp header") } width, height := int(w), int(h) - rgba, token := newPooledRGBA(width, height) + rgba := image.NewRGBA(image.Rect(0, 0, width, height)) out := C.WebPDecodeRGBAInto( (*C.uint8_t)(unsafe.Pointer(&data[0])), C.size_t(len(data)), @@ -74,7 +74,6 @@ func decodeWebPStatic(data []byte) (*Decoded, error) { C.int(rgba.Stride), ) if out == nil { - putPixBuf(token) return nil, fmt.Errorf("assets: webp decode failed (%dx%d payload)", width, height) } @@ -85,9 +84,6 @@ func decodeWebPStatic(data []byte) (*Decoded, error) { Width: width, Height: height, } - if token != nil { - d.pooledPix = append(d.pooledPix, token) - } return d, nil } @@ -183,21 +179,14 @@ func decodeWebPAnim(data []byte, playAnimations bool, maxH int) (*Decoded, error if !keepIt { continue } - rgba, token := newPooledRGBA(width, height) + rgba := image.NewRGBA(image.Rect(0, 0, width, height)) src := unsafe.Slice((*byte)(unsafe.Pointer(frameRGBA)), canvasBytes) copy(rgba.Pix, src) if down { - small, smallTok := downscaleFrame(rgba, tw, th) - putPixBuf(token) + small := downscaleFrame(rgba, tw, th) d.Frames = append(d.Frames, small) - if smallTok != nil { - d.pooledPix = append(d.pooledPix, smallTok) - } } else { d.Frames = append(d.Frames, rgba) - if token != nil { - d.pooledPix = append(d.pooledPix, token) - } } d.Delays = append(d.Delays, folded) } @@ -269,16 +258,10 @@ func decodeWebPAnimStream(data []byte, maxH int, emit func(*Decoded)) (streamed canvasBytes := width * height * webpBytesPerPixel - // When downscaling, reuse one native buffer instead of churning the pool; else it is the delivered frame. + // When downscaling, one native buffer is reused for every frame; else it is the delivered frame. var reuse *image.RGBA - var reuseToken *[]byte if down { - reuse, reuseToken = newPooledRGBA(width, height) - defer func() { - if reuseToken != nil { - putPixBuf(reuseToken) - } - }() + reuse = image.NewRGBA(image.Rect(0, 0, width, height)) } for i := 0; i < walk; i++ { @@ -294,19 +277,17 @@ func decodeWebPAnimStream(data []byte, maxH int, emit func(*Decoded)) (streamed continue // frame 0 already delivered by the progressive first frame } var rgba *image.RGBA - var token *[]byte if down { rgba = reuse } else { - rgba, token = newPooledRGBA(width, height) + rgba = image.NewRGBA(image.Rect(0, 0, width, height)) } src := unsafe.Slice((*byte)(unsafe.Pointer(frameRGBA)), canvasBytes) copy(rgba.Pix, src) out := rgba if down { - small, smallTok := downscaleFrame(rgba, tw, th) + small := downscaleFrame(rgba, tw, th) out = small - token = smallTok } chunk := &Decoded{ Frames: []*image.RGBA{out}, @@ -319,9 +300,6 @@ func decodeWebPAnimStream(data []byte, maxH int, emit func(*Decoded)) (streamed FrameOffset: i, Partial: true, } - if token != nil { - chunk.pooledPix = append(chunk.pooledPix, token) - } emit(chunk) } return true, walk, nil diff --git a/internal/ui/about.go b/internal/ui/about.go index 07a19aa9..58285c2b 100644 --- a/internal/ui/about.go +++ b/internal/ui/about.go @@ -105,7 +105,6 @@ var aboutLinks = []aboutLink{ {"golang.org/x/text — text encoding (BSD-3)", "https://pkg.go.dev/golang.org/x/text"}, {"cespare/xxhash — fast hashing for cache keys (MIT)", "https://github.com/cespare/xxhash"}, {"hashicorp/golang-lru — LRU caches (MPL-2.0)", "https://github.com/hashicorp/golang-lru"}, - {"kettek/apng — animated-PNG decoding (BSD)", "https://github.com/kettek/apng"}, {"AO-Underground/aolib (go/v2) — AO2 wire protocol codec, FantaCode + JSON (MIT)", "https://github.com/AO-Underground/aolib"}, {"santhosh-tekuri/jsonschema (v6) — JSON Schema validation (Apache-2.0)", "https://github.com/santhosh-tekuri/jsonschema"}, From ee15c1b02e946f5f3556fe452f4310fbe67891b4 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:03:04 +0100 Subject: [PATCH 33/43] ui, render, assets: screens and audio ask the media system directly Every remaining request in ui and render is media.Get with a key from assets.ChainKey, ExactKey or RawKey; network.PriorityHigh/Low became media.Now/Later. assets.Manager loses Prefetch, PrefetchChain, PrefetchSticky (unused), PrefetchExact and PrefetchRaw, the bridge loses its ask helpers, and network.Priority has no users left and is deleted. The empty-name guard those methods carried moves into media.Get: a key with no path names no file, so it comes back Missing and asks nothing. The synchronous ResolveRaw* lookups used by scene export and the content job stay until the bridge is deleted. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 +++--- docs/GROUP_PAIRING.md | 4 +-- docs/RESTRUCTURING_PLAN.md | 5 +++- internal/assets/charmap_test.go | 2 +- internal/assets/claim_test.go | 6 ++--- internal/assets/folders_test.go | 6 ++--- internal/assets/learned_test.go | 5 ++-- internal/assets/manager.go | 37 --------------------------- internal/assets/manager_test.go | 27 +++++++++---------- internal/assets/mediabridge.go | 31 +++------------------- internal/assets/mediabridge_test.go | 30 +++++++++++----------- internal/assets/musicexact_test.go | 3 ++- internal/assets/notify_test.go | 4 +-- internal/assets/scenerypin_test.go | 3 +-- internal/courtroom/courtroom.go | 5 ++-- internal/media/manager.go | 9 ++++++- internal/media/sources_test.go | 11 ++++++++ internal/network/priority.go | 11 -------- internal/render/audio.go | 8 +++--- internal/render/pump_test.go | 7 ++--- internal/ui/app.go | 9 ++++--- internal/ui/app_connect.go | 2 +- internal/ui/app_ic.go | 7 ++--- internal/ui/app_room.go | 10 ++++---- internal/ui/bgpicker.go | 5 ++-- internal/ui/court_extras.go | 22 ++++++++-------- internal/ui/deskmissing_relay_test.go | 4 +-- internal/ui/effectspicker.go | 4 +-- internal/ui/evidserverpicker.go | 3 +-- internal/ui/gifexport.go | 5 ++-- internal/ui/messaging_fancy.go | 4 +-- internal/ui/replaywarm.go | 6 ++--- internal/ui/screensemote.go | 14 +++++----- internal/ui/slideshow.go | 4 +-- internal/ui/stylebox.go | 6 ++--- 35 files changed, 139 insertions(+), 188 deletions(-) delete mode 100644 internal/network/priority.go diff --git a/CLAUDE.md b/CLAUDE.md index 37011dd3..927ad558 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -145,7 +145,7 @@ heap corruption. | `internal/saver` | the one background file writer: a change schedules one whole-file replace (temp file + rename) | no | | `internal/config` | preferences + debounced atomic saver; favorites; local mounts; the Wardrobe's `wardrobe.json` | no | | `internal/cache` | ByteBudgetLRU (T1/T2) + async disk tier (T3, xxhash full-URL keys) | no | -| `internal/network` | dedup HTTP client (singleflight, 404 TTL, backoff, DNS warm), request priority, master list + tiers + direct connect | no | +| `internal/network` | dedup HTTP client (singleflight, 404 TTL, backoff, DNS warm), master list + tiers + direct connect | no | | `internal/assets` | AssetType enum, `Manager` over `internal/media` (the bridge; learned formats and winners kept in `learned.json`), the player's folders as a media source, decode pool (magic-byte sniffing), WebP/AVIF CGO binding + fallback, Markov prefetcher | no (decoder is SDL-free by rule) | | `internal/media` | the media system every asset request goes through: `Manager` owns every table on one goroutine, `Get` is safe from any thread, pools run single steps; sources memory → disk cache → `Folders` (the player's folders and .zip packs) → web | no | | `internal/protocol` | AO wire (delegated to aolib-go: FantaCode + JSON), MS 2.6/2.8 parse/build, pairing semantics, FeatureSet, WebSocket conn | no | @@ -184,7 +184,7 @@ Protocol gotchas already encoded in code/tests — don't "fix" them: `askchaa` (sent on PN). Only the askchar2 *paging* is legacy — drop the askchaa reply and every server hangs at "handshaking". - Sprites have two spellings: `(a)X`/`(b)X` **or** bare `X` (AO2-Client - CharLayer::load_image probes both). `PrefetchWithFallback` owns that + CharLayer::load_image probes both). The alts passed to `media.Get` own that chain; the prefixed base stays the asset's identity everywhere. - MS evidence ids are shifted by 1 on the wire (0 = none, legacy); LE shares SC's lossy double-decode — a literal `&` in evidence text cannot @@ -197,7 +197,7 @@ Protocol gotchas already encoded in code/tests — don't "fix" them: keys are the discovery source. Receive strips a trailing extension from `4&` (other clients send their dir-scan filename). - Evidence images are EXACT URLs (`evidence/` — the extension - ships in the LE name): `PrefetchExact`, never the format-probing path. + ships in the LE name): `assets.ExactKey`, never the format-probing path. - Theme chatbox skin candidates are `chat` → `chatbox` → `chatblank` (courtroom.cpp:3328) — the stock default theme has NO chatbox.png. Theme text colors apply only while the theme's own skin drew: they're @@ -240,7 +240,7 @@ Protocol gotchas already encoded in code/tests — don't "fix" them: reports, what the code used to do and how it got here belong in commit messages. Trim by content, never by length: length-based rounds lost the reasons and were reverted (47e3f7d7). -- Every `Prefetch` call site carries an `// AssetType: X` comment. +- Every `media.Get` call site for an asset carries an `// AssetType: X` comment. - Tests pin behavior, including performance gates (`testing.AllocsPerRun`). - Cache keys are full URLs (host included) — per-server separation is structural. Never key by bare path. diff --git a/docs/GROUP_PAIRING.md b/docs/GROUP_PAIRING.md index d1faec93..1102ae89 100644 --- a/docs/GROUP_PAIRING.md +++ b/docs/GROUP_PAIRING.md @@ -48,8 +48,8 @@ list). There is no size limit. - **`ChatMessage` now contains a slice (`Additional`).** Any `==` / `!=` comparison of a `ChatMessage` value no longer compiles — use `reflect.DeepEqual` in tests (see `demoms_test.go`). -- **Prefetch is eager.** `begin()` prefetches each member's idle sprite with - `network.PriorityHigh`, so the first frame isn't missing layers. +- **Prefetch is eager.** `begin()` asks for each member's idle sprite at + `media.Now`, so the first frame isn't missing layers. - **Offset is not forced.** `drawSprite` applies `layer.OffsetX/Y` (percent of viewport) per layer; the value flows per member from the roster/MS, never zeroed except for AO2-faithful desk-mod handling on the speaker. diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index 248715cf..b226ea74 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -150,7 +150,10 @@ in **Status**. Update Status in the same commit that completes a step. - [x] courtroom: asks `media.Get(assets.ChainKey(base, t), …)`. What the bridge did per request (skip a texture already uploaded, start character mapping, warn on a repeat ask while missing, count refusals) is media's `Skip`/`Asked`/`MissingAgain` hooks and `Refused()` - - [ ] screens, theme and audio + - [x] screens and audio (2026-11-15): every request in `ui` and `render` is `media.Get` with `assets.ChainKey`, + `ExactKey` or `RawKey`; the theme had no requests of its own. `Manager.Prefetch*` and `network.Priority` are + gone, and `media.Get` answers a key with no path as Missing. The synchronous `ResolveRaw*` export lookups + (archive, content job) stay until the bridge is deleted, as their own step - [ ] music streaming - [ ] off-thread texture preparation: waits for the renderer overhaul (decided 2026-11-02). See below - [x] a sprite sometimes shows its old animation for a frame before the right one (reported 2026-11-01): the wait gate diff --git a/internal/assets/charmap_test.go b/internal/assets/charmap_test.go index ae8ad8a2..bbbe7aac 100644 --- a/internal/assets/charmap_test.go +++ b/internal/assets/charmap_test.go @@ -23,7 +23,7 @@ func TestMappedCharacterSkipsMissingSpellings(t *testing.T) { ask := func(name string) { t.Helper() base := cs.srv.URL + "/characters/c/" - rig.manager.PrefetchChain(base+"(a)"+name, []string{base + name}, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + rig.manager.Media().Get(ChainKey(base+"(a)"+name, AssetTypeCharSprite), media.Now, 0, []string{base + name}...) // AssetType: CharSprite waitDecoded(t, rig).Asset.Release() } ask("first") diff --git a/internal/assets/claim_test.go b/internal/assets/claim_test.go index c4585825..9d22e270 100644 --- a/internal/assets/claim_test.go +++ b/internal/assets/claim_test.go @@ -10,7 +10,7 @@ import ( "testing" "time" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" ) const ( @@ -98,7 +98,7 @@ func TestBackgroundDecodesWaitForUploads(t *testing.T) { } rig := newBridgeRig(t, host) for _, base := range bases[:claimBigAsks] { - rig.manager.Prefetch(base, AssetTypeBackground, network.PriorityLow) // AssetType: Background + rig.manager.Media().Get(ChainKey(base, AssetTypeBackground), media.Later, 0) // AssetType: Background } var held []Delivery @@ -110,7 +110,7 @@ func TestBackgroundDecodesWaitForUploads(t *testing.T) { t.Fatalf("%d background decodes delivered while none were uploaded, want %d", len(held), claimBigShare) } - rig.manager.Prefetch(bases[claimBigAsks], AssetTypeBackground, network.PriorityHigh) // AssetType: Background + rig.manager.Media().Get(ChainKey(bases[claimBigAsks], AssetTypeBackground), media.Now, 0) // AssetType: Background waitUntil(t, "the current message's decode", func() bool { take(); return len(held) > claimBigShare }) for _, d := range held { diff --git a/internal/assets/folders_test.go b/internal/assets/folders_test.go index 8c43d429..fcdb1988 100644 --- a/internal/assets/folders_test.go +++ b/internal/assets/folders_test.go @@ -213,7 +213,7 @@ func TestPrefetchRawSkipsWhatTheFolderHolds(t *testing.T) { map[string]string{"characters/witch/char.ini": "PACK INI"}, ) - pr.rig.manager.PrefetchRaw(pr.base("characters/witch/char.ini"), network.PriorityLow) + pr.rig.manager.Media().Get(RawKey(pr.base("characters/witch/char.ini")), media.Later, media.Quiet) if awaitNetFetches(t, pr.rig.manager, 1) { t.Error("the warm asked the server for a file the folder holds") @@ -226,7 +226,7 @@ func TestPrefetchRawStillWarmsWhatTheFolderLacks(t *testing.T) { map[string]string{"characters/witch/char.ini": "PACK INI"}, ) - pr.rig.manager.PrefetchRaw(pr.base("characters/other/char.ini"), network.PriorityLow) + pr.rig.manager.Media().Get(RawKey(pr.base("characters/other/char.ini")), media.Later, media.Quiet) if !awaitNetFetches(t, pr.rig.manager, 1) { t.Error("the server was never asked — mounting a folder disarmed the warm for everything else") @@ -274,7 +274,7 @@ func TestFolderSpriteIsFoundInAFormatTheServerDoesNotList(t *testing.T) { t.Fatal(err) } base := pr.base("characters/witch/normal") - pr.rig.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + pr.rig.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite if d := nextDecoded(t, pr.rig, base); d.Err != nil { t.Fatalf("the folder's .png was not used: %v", d.Err) } diff --git a/internal/assets/learned_test.go b/internal/assets/learned_test.go index 8fe12b06..2745d4b5 100644 --- a/internal/assets/learned_test.go +++ b/internal/assets/learned_test.go @@ -7,6 +7,7 @@ import ( "testing" "time" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/netproxy" "github.com/SyntaxNyah/AsyncAO/internal/network" ) @@ -40,7 +41,7 @@ func TestLearnedFormatOutlivesTheSession(t *testing.T) { first := newRigAt(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false, learned) waitRecalled(t, first.manager) - first.manager.Prefetch(cs.srv.URL+"/characters/a/(a)x", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + first.manager.Media().Get(ChainKey(cs.srv.URL+"/characters/a/(a)x", AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite waitDecoded(t, first).Asset.Release() first.manager.CloseMedia() if _, err := os.Stat(learned); err != nil { @@ -50,7 +51,7 @@ func TestLearnedFormatOutlivesTheSession(t *testing.T) { next := newRigAt(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false, learned) waitRecalled(t, next.manager) before := cs.total() - next.manager.Prefetch(cs.srv.URL+"/characters/a/(a)y", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + next.manager.Media().Get(ChainKey(cs.srv.URL+"/characters/a/(a)y", AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite waitDecoded(t, next).Asset.Release() if n := cs.total() - before; n != 1 { t.Errorf("the next session needed %d requests, want 1", n) diff --git a/internal/assets/manager.go b/internal/assets/manager.go index 2902e222..1f0a5587 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -307,43 +307,6 @@ func (m *Manager) reportMusicFailure(url string, err error) { } } -// Prefetch asks for base (URL without extension), with no other spelling. -func (m *Manager) Prefetch(base string, t AssetType, prio network.Priority) { - m.PrefetchChain(base, nil, t, prio) -} - -// PrefetchChain asks for base, then each alt while earlier names miss, like CharLayer::load_image ("(a)X" then "X"); -// call sites bound the length (hard rule 4). -func (m *Manager) PrefetchChain(base string, alts []string, t AssetType, prio network.Priority) { - if base == "" || !t.Valid() { - return - } - m.bridge.askChain(base, alts, t, prio, false) -} - -// PrefetchSticky is Prefetch for assets that survive room changes, such as UI chrome. -func (m *Manager) PrefetchSticky(base string, t AssetType, prio network.Priority) { - if base == "" || !t.Valid() { - return - } - m.bridge.askChain(base, nil, t, prio, true) -} - -// PrefetchExact asks for a complete URL with no candidate probing, such as a music track. -func (m *Manager) PrefetchExact(url string, t AssetType, prio network.Priority) { - if url == "" || !t.Valid() { - return - } - m.bridge.askExact(url, t, prio) -} - -// PrefetchRaw warms the caches for a complete URL without decoding (char.ini on hover); silent on 404. -func (m *Manager) PrefetchRaw(url string, prio network.Priority) { - if url != "" { - m.bridge.askRaw(url, prio) - } -} - // IsMissing reports whether base is remembered as found nowhere, so asking again now costs no request; nil-safe. func (m *Manager) IsMissing(base string, t AssetType) bool { if m == nil { diff --git a/internal/assets/manager_test.go b/internal/assets/manager_test.go index edb01c0a..9c3e518e 100644 --- a/internal/assets/manager_test.go +++ b/internal/assets/manager_test.go @@ -14,6 +14,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/cache" "github.com/SyntaxNyah/AsyncAO/internal/config" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/netproxy" "github.com/SyntaxNyah/AsyncAO/internal/network" ) @@ -225,7 +226,7 @@ func TestManagerWebPOnlyServerOneProbePerAsset(t *testing.T) { {cs.srv.URL + "/background/court/defenseempty", AssetTypeBackground}, } for _, b := range bases { - rig.manager.Prefetch(b.base, b.typ, network.PriorityHigh) // AssetType: mixed (test) + rig.manager.Media().Get(ChainKey(b.base, b.typ), media.Now, 0) // AssetType: mixed (test) } for range bases { d := waitDecoded(t, rig) @@ -259,7 +260,7 @@ func TestManagerT1ShortCircuitUsesBaseKey(t *testing.T) { resident := map[string]bool{} rig.manager.t1Contains = func(key string) bool { return resident[key] } - rig.manager.Prefetch(base, AssetTypeCharIcon, network.PriorityHigh) // AssetType: CharIcon + rig.manager.Media().Get(ChainKey(base, AssetTypeCharIcon), media.Now, 0) // AssetType: CharIcon d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("decode error: %v", d.Err) @@ -280,7 +281,7 @@ func TestManagerT1ShortCircuitUsesBaseKey(t *testing.T) { if time.Now().After(deadline) { t.Fatal("T1 short-circuit never hit for a resident base") } - rig.manager.Prefetch(base, AssetTypeCharIcon, network.PriorityHigh) // AssetType: CharIcon + rig.manager.Media().Get(ChainKey(base, AssetTypeCharIcon), media.Now, 0) // AssetType: CharIcon time.Sleep(5 * time.Millisecond) } if got := cs.total(); got != firstLoad { @@ -309,7 +310,7 @@ func TestManagerUnprefixedSpriteFallback(t *testing.T) { resident := map[string]bool{} rig.manager.t1Contains = func(key string) bool { return resident[key] } - rig.manager.PrefetchChain(primary, []string{bare}, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + rig.manager.Media().Get(ChainKey(primary, AssetTypeCharSprite), media.Now, 0, []string{bare}...) // AssetType: CharSprite d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("decode error: %v", d.Err) @@ -330,7 +331,7 @@ func TestManagerUnprefixedSpriteFallback(t *testing.T) { if time.Now().After(deadline) { t.Fatal("T1 short-circuit never hit for the resident primary base") } - rig.manager.PrefetchChain(primary, []string{bare}, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + rig.manager.Media().Get(ChainKey(primary, AssetTypeCharSprite), media.Now, 0, []string{bare}...) // AssetType: CharSprite time.Sleep(5 * time.Millisecond) } if got := cs.total(); got != firstLoad { @@ -356,7 +357,7 @@ func TestManagerPrefetchChain(t *testing.T) { cs.srv.URL + "/misc/yttd/chatbox", // duplicate: skipped, no re-probe } - rig.manager.PrefetchChain(identity, alts, AssetTypeMisc, network.PriorityHigh) // AssetType: Misc (test chain) + rig.manager.Media().Get(ChainKey(identity, AssetTypeMisc), media.Now, 0, alts...) // AssetType: Misc (test chain) d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("decode error: %v", d.Err) @@ -376,7 +377,7 @@ func TestManagerAudioBypassesDecode(t *testing.T) { }) rig := newRig(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false) - rig.manager.Prefetch(cs.srv.URL+"/sounds/blips/male", AssetTypeBlip, network.PriorityHigh) // AssetType: Blip + rig.manager.Media().Get(ChainKey(cs.srv.URL+"/sounds/blips/male", AssetTypeBlip), media.Now, 0) // AssetType: Blip select { case a := <-rig.manager.Audio(): if string(a.Data) != string(opus) { @@ -426,7 +427,7 @@ func TestManagerLocalMounts(t *testing.T) { rig := newRig(t, local, true) origin := local.BaseURL() - rig.manager.Prefetch(origin+"characters/phoenix/(a)normal", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + rig.manager.Media().Get(ChainKey(origin+"characters/phoenix/(a)normal", AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite d := waitDecoded(t, rig) if d.Err != nil { t.Fatalf("local decode error: %v", d.Err) @@ -436,7 +437,7 @@ func TestManagerLocalMounts(t *testing.T) { } d.Asset.Release() - rig.manager.Prefetch(origin+"characters/phoenix/(b)normal", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + rig.manager.Media().Get(ChainKey(origin+"characters/phoenix/(b)normal", AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite d = waitDecoded(t, rig) if d.Err != nil { t.Fatalf("local decode error: %v", d.Err) @@ -447,7 +448,7 @@ func TestManagerLocalMounts(t *testing.T) { d.Asset.Release() // Missing asset → the same §4 warning machinery. - rig.manager.Prefetch(origin+"characters/phoenix/(a)void", AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + rig.manager.Media().Get(ChainKey(origin+"characters/phoenix/(a)void", AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite w := waitWarning(t, rig.manager) if !strings.HasSuffix(w.Base, "(a)void") { t.Errorf("warning base = %q", w.Base) @@ -473,7 +474,7 @@ func TestManagerInflightDedup(t *testing.T) { base := cs.srv.URL + "/characters/godot/(a)normal" for i := 0; i < 4; i++ { - rig.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + rig.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite } d := waitDecoded(t, rig) if d.Err != nil { @@ -503,7 +504,7 @@ func TestManagerPrefetchRawWarmsTiers(t *testing.T) { rig := newRig(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false) url := cs.srv.URL + "/characters/tung/char.ini" - rig.manager.PrefetchRaw(url, network.PriorityLow) // raw text: char.ini + rig.manager.Media().Get(RawKey(url), media.Later, media.Quiet) // raw text: char.ini deadline := time.Now().Add(managerWait) for { if _, ok := rig.t2.Get(url); ok { @@ -541,7 +542,7 @@ func TestPurgeCorruptEvictsTiers(t *testing.T) { base := cs.srv.URL + "/characters/torn/(a)normal" wantURL := base + ".webp" // the format probed first — the T2/T3 key - rig.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite + rig.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite d := waitDecoded(t, rig) if d.Err == nil { t.Fatal("corrupt payload decoded without error") diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index 33d86d4e..35f31af3 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -210,13 +210,6 @@ func (m *Manager) RescanDisk() { } } -func urgencyOf(p network.Priority) media.Urgency { - if p == network.PriorityHigh { - return media.Now - } - return media.Later -} - func classOf(t AssetType) media.Class { switch t { case AssetTypeCharIcon: @@ -257,27 +250,9 @@ func ExactKey(url string, t AssetType) media.Key { return k } -func flagsOf(quiet, sticky bool) media.Flags { - var f media.Flags - if quiet { - f |= media.Quiet - } - if sticky { - f |= media.Sticky - } - return f -} - -func (b *mediaBridge) askChain(base string, alts []string, t AssetType, p network.Priority, sticky bool) { - b.media.Get(ChainKey(base, t), urgencyOf(p), flagsOf(false, sticky), alts...) -} - -func (b *mediaBridge) askExact(url string, t AssetType, p network.Priority) { - b.media.Get(ExactKey(url, t), urgencyOf(p), 0) -} - -func (b *mediaBridge) askRaw(url string, p network.Priority) { - b.media.Get(media.Key{Place: media.PlaceServer, Path: url, Kind: media.KindRaw, Class: media.ClassExact}, urgencyOf(p), media.Quiet) +// RawKey is the key for a complete URL kept as bytes, such as a char.ini, never decoded. +func RawKey(url string) media.Key { + return media.Key{Place: media.PlaceServer, Path: url, Kind: media.KindRaw, Class: media.ClassExact} } // skip is Config.Skip: an uploaded texture is held already, and one that failed to decode lately is left alone. diff --git a/internal/assets/mediabridge_test.go b/internal/assets/mediabridge_test.go index 8390e10f..ad820f36 100644 --- a/internal/assets/mediabridge_test.go +++ b/internal/assets/mediabridge_test.go @@ -104,7 +104,7 @@ func TestBridgeDeliversAndLearns(t *testing.T) { host := &bridgeFakeHost{files: map[string][]byte{bridgeTestOrigin + "c/(a)e.webp": webp}} r := newBridgeRig(t, host) base := bridgeTestOrigin + "c/(a)e" - r.manager.PrefetchChain(base, []string{bridgeTestOrigin + "c/e"}, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0, []string{bridgeTestOrigin + "c/e"}...) d := nextDecoded(t, r, base) if d.Err != nil || d.Asset == nil || d.URL != base+".webp" { t.Fatalf("url %q err %v", d.URL, d.Err) @@ -116,7 +116,7 @@ func TestBridgeAsksAgainAfterDelivery(t *testing.T) { host := &bridgeFakeHost{files: map[string][]byte{bridgeTestOrigin + "e.webp": webp}} r := newBridgeRig(t, host) base := bridgeTestOrigin + "e" - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) nextDecoded(t, r, base) deadline := time.Now().Add(bridgeTestTimeout) // An evicted texture asks again and comes back from memory, with no second request. @@ -124,7 +124,7 @@ func TestBridgeAsksAgainAfterDelivery(t *testing.T) { got := make(chan DecodedAsset, 1) go func() { got <- nextDecoded(t, r, base) }() for time.Now().Before(deadline) { - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) select { case d = <-got: if d.Err != nil { @@ -144,7 +144,7 @@ func TestBridgeMissingWarnsAndDoesNotAskAgain(t *testing.T) { host := &bridgeFakeHost{files: map[string][]byte{}} r := newBridgeRig(t, host) base := bridgeTestOrigin + "none" - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) select { case w := <-r.manager.Warnings(): if w.Base != base { @@ -157,7 +157,7 @@ func TestBridgeMissingWarnsAndDoesNotAskAgain(t *testing.T) { t.Fatal("not remembered as missing") } asked := len(host.askedFor()) - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) select { case <-r.manager.Warnings(): case <-time.After(bridgeTestTimeout): @@ -177,7 +177,7 @@ func TestBridgeTransportFailureIsTransient(t *testing.T) { host := &bridgeFakeHost{files: map[string][]byte{}, broken: errors.New("refused")} r := newBridgeRig(t, host) base := bridgeTestOrigin + "e" - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) deadline := time.Now().Add(bridgeTestTimeout) for r.manager.Stats().Failed == 0 { if time.Now().After(deadline) { @@ -200,10 +200,10 @@ func TestBridgeHungHostDoesNotBlockOtherWork(t *testing.T) { t.Cleanup(func() { close(host.hold) }) r := newBridgeRig(t, host) for i := range bridgeHungAsks { - r.manager.Prefetch(fmt.Sprintf("%sc%d", bridgeHungOrigin, i), AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(fmt.Sprintf("%sc%d", bridgeHungOrigin, i), AssetTypeCharSprite), media.Now, 0) } base := bridgeTestOrigin + "e" - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) if d := nextDecoded(t, r, base); d.Err != nil { t.Fatal(d.Err) } @@ -213,7 +213,7 @@ func TestBridgeRawWarmsMemorySilently(t *testing.T) { host := &bridgeFakeHost{files: map[string][]byte{bridgeTestOrigin + "char.ini": []byte("[Options]")}} r := newBridgeRig(t, host) url := bridgeTestOrigin + "char.ini" - r.manager.PrefetchRaw(url, network.PriorityLow) + r.manager.Media().Get(RawKey(url), media.Later, media.Quiet) deadline := time.Now().Add(bridgeTestTimeout) for !r.t2.Contains(url) { if time.Now().After(deadline) { @@ -221,7 +221,7 @@ func TestBridgeRawWarmsMemorySilently(t *testing.T) { } time.Sleep(time.Millisecond) } - r.manager.PrefetchRaw(bridgeTestOrigin+"none.ini", network.PriorityLow) + r.manager.Media().Get(RawKey(bridgeTestOrigin+"none.ini"), media.Later, media.Quiet) select { case w := <-r.manager.Warnings(): t.Fatalf("raw miss warned: %v", w) @@ -244,7 +244,7 @@ func TestBridgeManifestSetsOrderAndIsFetchedFresh(t *testing.T) { } } base := bridgeTestOrigin + "e" - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) nextDecoded(t, r, base) want := []string{bridgeTestOrigin + media.ManifestFile, bridgeTestOrigin + media.ManifestFile, base + ".png", base + ".webp"} if asked := host.askedFor(); !slices.Equal(asked, want) { @@ -258,7 +258,7 @@ func TestBridgeOfflineRecordsNothing(t *testing.T) { r := newBridgeRig(t, host) base := bridgeTestOrigin + "e" r.manager.SetOffline(true) - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) select { case <-r.manager.Warnings(): case <-time.After(bridgeTestTimeout): @@ -269,7 +269,7 @@ func TestBridgeOfflineRecordsNothing(t *testing.T) { } time.Sleep(bridgeSettle) r.manager.SetOffline(false) - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) if d := nextDecoded(t, r, base); d.Err != nil { t.Fatalf("a file offline said nothing about was not fetched: %v", d.Err) } @@ -281,7 +281,7 @@ func TestBridgeExtraHostServesWhatTheServerLacks(t *testing.T) { host := &bridgeFakeHost{files: map[string][]byte{mirror + "c/e.webp": webp}} r := newBridgeRig(t, host) base := bridgeTestOrigin + "c/e" - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) select { case <-r.manager.Warnings(): case <-time.After(bridgeTestTimeout): @@ -289,7 +289,7 @@ func TestBridgeExtraHostServesWhatTheServerLacks(t *testing.T) { } r.manager.SetAssetHosts(bridgeTestOrigin, []string{mirror}) waitUntil(t, "the miss to be forgotten", func() bool { return !r.manager.IsMissing(base, AssetTypeCharSprite) }) - r.manager.Prefetch(base, AssetTypeCharSprite, network.PriorityHigh) + r.manager.Media().Get(ChainKey(base, AssetTypeCharSprite), media.Now, 0) d := nextDecoded(t, r, base) if d.Err != nil || d.Asset == nil || d.URL != mirror+"c/e.webp" { t.Fatalf("url %q err %v", d.URL, d.Err) diff --git a/internal/assets/musicexact_test.go b/internal/assets/musicexact_test.go index 3f4581d5..9c925231 100644 --- a/internal/assets/musicexact_test.go +++ b/internal/assets/musicexact_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/netproxy" "github.com/SyntaxNyah/AsyncAO/internal/network" ) @@ -39,7 +40,7 @@ func TestMP3MusicFetchesExactlyTheURLItWasGiven(t *testing.T) { rig := newRig(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false) url := srv.URL + "/sounds/music/cornered.mp3" - rig.manager.PrefetchExact(url, AssetTypeMusic, network.PriorityHigh) // AssetType: Music (Exact) + rig.manager.Media().Get(ExactKey(url, AssetTypeMusic), media.Now, 0) // AssetType: Music (Exact) select { case a := <-rig.manager.Audio(): diff --git a/internal/assets/notify_test.go b/internal/assets/notify_test.go index be1959bf..986b9756 100644 --- a/internal/assets/notify_test.go +++ b/internal/assets/notify_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/SyntaxNyah/AsyncAO/internal/config" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" ) // TestManagerDeliveryNotify pins the decode-delivery wake hook (the @@ -37,7 +37,7 @@ func TestManagerDeliveryNotify(t *testing.T) { base := local.BaseURL() + "characters/witch/emotions/button1_off" rig.manager.AllowFormats(local.BaseURL(), map[AssetType]string{AssetTypeEmoteButton: config.ExtPNG}) - rig.manager.Prefetch(base, AssetTypeEmoteButton, network.PriorityHigh) // AssetType: EmoteButton (test) + rig.manager.Media().Get(ChainKey(base, AssetTypeEmoteButton), media.Now, 0) // AssetType: EmoteButton (test) deadline := time.After(managerWait) select { diff --git a/internal/assets/scenerypin_test.go b/internal/assets/scenerypin_test.go index cef24534..5bda4194 100644 --- a/internal/assets/scenerypin_test.go +++ b/internal/assets/scenerypin_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/SyntaxNyah/AsyncAO/internal/media" - "github.com/SyntaxNyah/AsyncAO/internal/network" ) const ( @@ -53,7 +52,7 @@ func TestAFetchedBackgroundIsServedFromThePinAfterTheSharedCacheDropsIt(t *testi host := &bridgeFakeHost{files: map[string][]byte{base + ".webp": webp}} r := newBridgeRig(t, host) r.manager.PinScenery(bridgeTestOrigin + "background/court/") - r.manager.PrefetchChain(base, nil, AssetTypeBackground, network.PriorityHigh) // AssetType: Background + r.manager.Media().Get(ChainKey(base, AssetTypeBackground), media.Now, 0, nil...) // AssetType: Background nextDecoded(t, r, base) r.t2.Purge() if (bridgeMemory{r.t2, r.manager.bridge.pin, r.manager}).Has(media.File(base+".webp")) != media.Yes { diff --git a/internal/courtroom/courtroom.go b/internal/courtroom/courtroom.go index 8058ebba..9cb562c1 100644 --- a/internal/courtroom/courtroom.go +++ b/internal/courtroom/courtroom.go @@ -406,10 +406,9 @@ type Courtroom struct { RealizationSFX string } -// ask asks the media system for base, then each alt while earlier names miss, as CharLayer::load_image does; an empty -// base or no media system asks nothing. +// ask asks the media system for base, then each alt while earlier names miss, as CharLayer::load_image does. func (c *Courtroom) ask(base string, alts []string, t assets.AssetType) { - if base == "" || c.media == nil || !t.Valid() { + if c.media == nil { return } c.media.Get(assets.ChainKey(base, t), media.Now, 0, alts...) diff --git a/internal/media/manager.go b/internal/media/manager.go index 3ec48a28..89e70b89 100644 --- a/internal/media/manager.go +++ b/internal/media/manager.go @@ -210,6 +210,8 @@ type Manager struct { refused atomic.Int64 // skipped is what Get returns when Config.Skip says the caller holds the key already. skipped *Asset + // unnamed is what Get returns for a key with no path: Missing, as it names no file. + unnamed *Asset } // NewManager starts a Manager's goroutine. @@ -227,6 +229,8 @@ func NewManager(cfg Config) *Manager { active: map[Key]*request{}, queues: map[*Pool]*poolQueue{}, hostBusy: map[string]int{}, winners: map[Key]File{}} m.skipped = newAsset(Key{}, Later, 0, nil) m.skipped.finish(Ready, nil, nil, cfg.Clock()) + m.unnamed = newAsset(Key{}, Later, 0, nil) + m.unnamed.finish(Missing, nil, nil, cfg.Clock()) go m.run() return m } @@ -238,9 +242,12 @@ func (m *Manager) Close() { } // Get returns the Asset for key from any thread and never blocks: a repeat ask takes no lock and posts nothing. A key the -// Skip hook says the caller holds already returns a shared finished Asset with no key. +// Skip hook says the caller holds already returns a shared finished Asset with no key, and so does a key with no path. // alts are the other names it may be found under, best first, each asked only once every earlier one is known absent. func (m *Manager) Get(key Key, urgency Urgency, flags Flags, alts ...string) *Asset { + if key.Path == "" { + return m.unnamed + } if m.cfg.Skip != nil && m.cfg.Skip(key) { return m.skipped } diff --git a/internal/media/sources_test.go b/internal/media/sources_test.go index 665083d4..9cced4f1 100644 --- a/internal/media/sources_test.go +++ b/internal/media/sources_test.go @@ -503,3 +503,14 @@ func waitUntil(t *testing.T, cond func() bool) { time.Sleep(testPollEvery) } } + +func TestAKeyWithNoPathIsMissingAndAsksNothing(t *testing.T) { + r := newRemoteRig(t, nil) + if a := r.m.Get(sprite(""), Now, 0); a.State() != Missing { + t.Fatalf("state %v, want Missing", a.State()) + } + r.m.Call(func() {}) + if asked := r.fetch.askedFor(); len(asked) != 0 { + t.Fatalf("asked %v", asked) + } +} diff --git a/internal/network/priority.go b/internal/network/priority.go deleted file mode 100644 index 2567443e..00000000 --- a/internal/network/priority.go +++ /dev/null @@ -1,11 +0,0 @@ -package network - -// Priority says how soon a request is needed. -type Priority int - -const ( - // PriorityHigh is for assets the live message needs right now; the media system never refuses it. - PriorityHigh Priority = iota - // PriorityLow is for speculative prefetches, refused while the media system is at its cap. - PriorityLow -) diff --git a/internal/render/audio.go b/internal/render/audio.go index e1621182..d8820a6f 100644 --- a/internal/render/audio.go +++ b/internal/render/audio.go @@ -10,8 +10,8 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/mix" - "github.com/SyntaxNyah/AsyncAO/internal/network" ) const ( @@ -555,7 +555,7 @@ func (a *Audio) request(base string, kind pendingKind) { a.pending[base] = pendingPlay{kind: kind, deadline: time.Now().Add(pendingPlayTTL)} // Nothing else prefetches SFX and shouts; without this the pending entry just expires and the sound never plays. if (kind == pendingSFX || kind == pendingShout) && a.mgr != nil { - a.mgr.Prefetch(base, assets.AssetTypeSFX, network.PriorityHigh) // AssetType: SFX + a.mgr.Media().Get(assets.ChainKey(base, assets.AssetTypeSFX), media.Now, 0) // AssetType: SFX } } @@ -612,7 +612,7 @@ func (a *Audio) PlayMusic(url string, loop bool, effects int) { // At most one music entry may be pending, or a late fetch of a previous track would revert playback to it. a.purgePendingMusic(url) a.pending[url] = pendingPlay{kind: pendingMusic, deadline: time.Now().Add(pendingPlayTTL), loop: loop, effects: effects, seekSec: syncPosSec} - a.mgr.PrefetchExact(url, assets.AssetTypeMusic, network.PriorityHigh) // AssetType: Music + a.mgr.Media().Get(assets.ExactKey(url, assets.AssetTypeMusic), media.Now, 0) // AssetType: Music } // purgePendingMusic drops pending music except keep ("" = all), so a late delivery is ignored; render thread only. @@ -687,7 +687,7 @@ func (a *Audio) PlayMusicAt(url string, loop bool, effects int, seekSec float64) } a.purgePendingMusic(url) a.pending[url] = pendingPlay{kind: pendingMusic, deadline: time.Now().Add(pendingPlayTTL), loop: loop, effects: effects, seekSec: seekSec} - a.mgr.PrefetchExact(url, assets.AssetTypeMusic, network.PriorityHigh) // AssetType: Music + a.mgr.Media().Get(assets.ExactKey(url, assets.AssetTypeMusic), media.Now, 0) // AssetType: Music } // startMusic decodes and plays a fetched track, following AO2's effects (aomusicplayer.cpp:24-160). diff --git a/internal/render/pump_test.go b/internal/render/pump_test.go index 26dd854c..ed92d81f 100644 --- a/internal/render/pump_test.go +++ b/internal/render/pump_test.go @@ -17,6 +17,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/cache" "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/netproxy" "github.com/SyntaxNyah/AsyncAO/internal/network" ) @@ -103,7 +104,7 @@ func TestPumpUploadsPrefetchByBase(t *testing.T) { defer store.Purge() pump := NewPump(store, mgr, nil) - mgr.Prefetch(base, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (warm-gate prefetch) + mgr.Media().Get(assets.ChainKey(base, assets.AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite (warm-gate prefetch) // Pump every "frame" until the async decode lands in T1 — the same loop the // export's warm phase runs (Pump.Frame() takes the waiting deliveries each frame). @@ -148,7 +149,7 @@ func TestPumpTransientErrorsDontPin(t *testing.T) { // Sick origin: the fetch (with its bounded retry) fails at the network // stage → counted as a failed fetch, NOT pinned. sick := srvSick.URL + "/characters/witch/(a)sick" - mgr.Prefetch(sick, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (test) + mgr.Media().Get(assets.ChainKey(sick, assets.AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite (test) deadline := time.Now().Add(5 * time.Second) for mgr.Stats().Failed == 0 && time.Now().Before(deadline) { pump.Frame() @@ -163,7 +164,7 @@ func TestPumpTransientErrorsDontPin(t *testing.T) { // Corrupt bytes: a genuine decode failure still pins (the cache's job). corrupt := srvCorrupt.URL + "/characters/witch/(a)corrupt" - mgr.Prefetch(corrupt, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (test) + mgr.Media().Get(assets.ChainKey(corrupt, assets.AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite (test) deadline = time.Now().Add(5 * time.Second) for !store.FailedRecently(corrupt) && time.Now().Before(deadline) { pump.Frame() diff --git a/internal/ui/app.go b/internal/ui/app.go index 78a9c784..726a9e45 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -12,6 +12,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" "github.com/SyntaxNyah/AsyncAO/internal/logbrowser" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/metrics" "github.com/SyntaxNyah/AsyncAO/internal/netproxy" "github.com/SyntaxNyah/AsyncAO/internal/network" @@ -1586,7 +1587,7 @@ func (a *App) warmBase(base string, t assets.AssetType) { } a.activeWarmDemands[base]++ a.activeWarmLastDemand = time.Now() - a.d.Manager.Prefetch(base, t, network.PriorityHigh) + a.d.Manager.Media().Get(assets.ChainKey(base, t), media.Now, 0) } // sceneWarmRedemandEvery throttles re-requests across the scene so the per-frame warm can't spam the pool during @@ -1646,11 +1647,11 @@ func (a *App) keepSceneAssetsWarm() { if throttleOpen && !demanded && a.sceneHealAllowed(base) { switch t { case assets.AssetTypeCharSprite: - a.d.Manager.PrefetchChain(base, courtroom.SpriteHealAlts(base), t, network.PriorityHigh) // AssetType: CharSprite (folder + bare, so no spelling ever false-flags missing) + a.d.Manager.Media().Get(assets.ChainKey(base, t), media.Now, 0, courtroom.SpriteHealAlts(base)...) // AssetType: CharSprite (folder + bare, so no spelling ever false-flags missing) case assets.AssetTypeBackground: - a.d.Manager.PrefetchChain(base, sc.BackgroundAlts, t, network.PriorityHigh) // AssetType: Background (every name AO2 tries) + a.d.Manager.Media().Get(assets.ChainKey(base, t), media.Now, 0, sc.BackgroundAlts...) // AssetType: Background (every name AO2 tries) default: - a.d.Manager.Prefetch(base, t, network.PriorityHigh) + a.d.Manager.Media().Get(assets.ChainKey(base, t), media.Now, 0) } demanded = true a.sceneWarmLastDemand = now diff --git a/internal/ui/app_connect.go b/internal/ui/app_connect.go index 5ecec742..3f387384 100644 --- a/internal/ui/app_connect.go +++ b/internal/ui/app_connect.go @@ -1469,7 +1469,7 @@ func (a *App) prefetchCharIcons() { if i >= charIconWarmup { break } - a.d.Manager.Prefetch(a.urls.CharIcon(c.Name), assets.AssetTypeCharIcon, network.PriorityLow) // AssetType: CharIcon + a.d.Manager.Media().Get(assets.ChainKey(a.urls.CharIcon(c.Name), assets.AssetTypeCharIcon), media.Later, 0) // AssetType: CharIcon } } diff --git a/internal/ui/app_ic.go b/internal/ui/app_ic.go index 28d0fe28..465f404a 100644 --- a/internal/ui/app_ic.go +++ b/internal/ui/app_ic.go @@ -12,6 +12,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/network" "github.com/SyntaxNyah/AsyncAO/internal/protocol" "github.com/SyntaxNyah/AsyncAO/internal/render" @@ -794,13 +795,13 @@ func (a *App) healScenery() { // each heal would evict another live base forever. if sc.BackgroundBase != "" && !(sc.BackgroundBase == a.bgAskBase && now.Sub(a.bgAskAt) < charIconRetryInterval) && !a.d.Store.Contains(sc.BackgroundBase) && a.sceneHealAllowed(sc.BackgroundBase) { a.bgAskBase, a.bgAskAt = sc.BackgroundBase, now - a.d.Manager.PrefetchChain(sc.BackgroundBase, sc.BackgroundAlts, assets.AssetTypeBackground, network.PriorityHigh) // AssetType: Background + a.d.Manager.Media().Get(assets.ChainKey(sc.BackgroundBase, assets.AssetTypeBackground), media.Now, 0, sc.BackgroundAlts...) // AssetType: Background } // A conclusively 404'd base never becomes Contains, so without IsMissing this re-demands a known-absent desk. // The background arm skips the check: Background is never marked, to keep the viewport's hold-previous behaviour. if sc.DeskBase != "" && !(sc.DeskBase == a.deskAskBase && now.Sub(a.deskAskAt) < charIconRetryInterval) && !a.d.Store.Contains(sc.DeskBase) && !a.d.Store.IsMissing(sc.DeskBase) && a.sceneHealAllowed(sc.DeskBase) { a.deskAskBase, a.deskAskAt = sc.DeskBase, now - a.d.Manager.Prefetch(sc.DeskBase, assets.AssetTypeDeskOverlay, network.PriorityHigh) // AssetType: DeskOverlay + a.d.Manager.Media().Get(assets.ChainKey(sc.DeskBase, assets.AssetTypeDeskOverlay), media.Now, 0) // AssetType: DeskOverlay } a.healSpriteLayer(&sc.Speaker, &a.spkAskBase, &a.spkAskAt, now) a.healSpriteLayer(&sc.Pair, &a.pairAskBase, &a.pairAskAt, now) @@ -822,7 +823,7 @@ func (a *App) healSpriteLayer(layer *courtroom.SpriteLayer, askBase *string, ask return // per-scene futility budget spent (over-tier churn / permanent 404) — quiet until the scene changes } *askBase, *askAt = layer.Active, now - a.d.Manager.PrefetchChain(layer.Active, courtroom.SpriteHealAlts(layer.Active), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (heal evicted live sprite: bare + folder) + a.d.Manager.Media().Get(assets.ChainKey(layer.Active, assets.AssetTypeCharSprite), media.Now, 0, courtroom.SpriteHealAlts(layer.Active)...) // AssetType: CharSprite (heal evicted live sprite: bare + folder) } // icEntry is one IC log line with its AO text color preserved. diff --git a/internal/ui/app_room.go b/internal/ui/app_room.go index 0cd9a716..4366ac28 100644 --- a/internal/ui/app_room.go +++ b/internal/ui/app_room.go @@ -11,7 +11,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/protocol" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" @@ -1393,7 +1393,7 @@ func (a *App) demandAsset(stamps *[]time.Time, n, idx int, base string, t assets } (*stamps)[idx] = now a.iconAskBudget-- - a.d.Manager.PrefetchChain(base, alts, t, network.PriorityLow) + a.d.Manager.Media().Get(assets.ChainKey(base, t), media.Later, 0, alts...) return true } @@ -1413,7 +1413,7 @@ func (a *App) warmCharINI(name string) { return } a.iniWarmed = name - a.d.Manager.PrefetchRaw(a.charINIURL(name), network.PriorityLow) // raw text: char.ini + a.d.Manager.Media().Get(assets.RawKey(a.charINIURL(name)), media.Later, media.Quiet) // raw text: char.ini } // previewEmoteCap bounds one previewed character's parsed emote list (hard rule 4). @@ -1495,7 +1495,7 @@ func (a *App) setCharPortraitPreview(name string) { anim := a.previewPortraitAnim(name) a.previewBase = a.urls.Emote(name, anim, courtroom.EmoteIdle) a.notePreviewChar(name) - a.d.Manager.PrefetchChain(a.previewBase, a.urls.EmoteAlts(name, anim, courtroom.EmoteIdle), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (preview) + a.d.Manager.Media().Get(assets.ChainKey(a.previewBase, assets.AssetTypeCharSprite), media.Now, 0, a.urls.EmoteAlts(name, anim, courtroom.EmoteIdle)...) // AssetType: CharSprite (preview) } // correctPortraitPreview moves an open portrait only if "normal" is still shown and the pack has no such emote. @@ -1596,7 +1596,7 @@ func (a *App) pollCharINI() { break } // A mixed-naming pack may ship this emote unprefixed; one spelling would 404 and flag it missing. - a.d.Manager.PrefetchChain(a.urls.Emote(me, e.Anim, courtroom.EmoteIdle), a.urls.EmoteAlts(me, e.Anim, courtroom.EmoteIdle), assets.AssetTypeCharSprite, network.PriorityLow) // AssetType: CharSprite + a.d.Manager.Media().Get(assets.ChainKey(a.urls.Emote(me, e.Anim, courtroom.EmoteIdle), assets.AssetTypeCharSprite), media.Later, 0, a.urls.EmoteAlts(me, e.Anim, courtroom.EmoteIdle)...) // AssetType: CharSprite } default: } diff --git a/internal/ui/bgpicker.go b/internal/ui/bgpicker.go index 02ca8894..940ba2b3 100644 --- a/internal/ui/bgpicker.go +++ b/internal/ui/bgpicker.go @@ -14,7 +14,6 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/media" - "github.com/SyntaxNyah/AsyncAO/internal/network" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" ) @@ -374,13 +373,13 @@ func (a *App) drawBgCell(idx int, cell sdl.Rect, budget *int64) { // Hover shows the large preview at high priority; click selects the /bg target. if c.HoverPreview("bg:"+name, cell) { a.previewBase = base - a.d.Manager.Prefetch(base, assets.AssetTypeBackground, network.PriorityHigh) // AssetType: Background (preview) + a.d.Manager.Media().Get(assets.ChainKey(base, assets.AssetTypeBackground), media.Now, 0) // AssetType: Background (preview) } if c.hovering(cell) && c.clicked { a.bgPick.sel = name a.bgPick.status = "" a.previewBase = base - a.d.Manager.Prefetch(base, assets.AssetTypeBackground, network.PriorityHigh) // AssetType: Background (selected preview) + a.d.Manager.Media().Get(assets.ChainKey(base, assets.AssetTypeBackground), media.Now, 0) // AssetType: Background (selected preview) } } diff --git a/internal/ui/court_extras.go b/internal/ui/court_extras.go index 85c97ae8..084f8467 100644 --- a/internal/ui/court_extras.go +++ b/internal/ui/court_extras.go @@ -15,7 +15,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/protocol" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" @@ -600,17 +600,17 @@ func (a *App) drawJudgeRow(x, y int32) int32 { func (a *App) prewarmServer() { info := a.d.Prefs.Load().ServerWarmInfoFor(a.serverKey) if info.Char != "" { - a.d.Manager.Prefetch(a.urls.CharIcon(info.Char), assets.AssetTypeCharIcon, network.PriorityLow) // AssetType: CharIcon (pre-warm) + a.d.Manager.Media().Get(assets.ChainKey(a.urls.CharIcon(info.Char), assets.AssetTypeCharIcon), media.Later, 0) // AssetType: CharIcon (pre-warm) idle := a.urls.Emote(info.Char, "normal", courtroom.EmoteIdle) talk := a.urls.Emote(info.Char, "normal", courtroom.EmoteTalk) - a.d.Manager.PrefetchChain(idle, a.urls.EmoteAlts(info.Char, "normal", courtroom.EmoteIdle), assets.AssetTypeCharSprite, network.PriorityLow) // AssetType: CharSprite (pre-warm) - a.d.Manager.PrefetchChain(talk, a.urls.EmoteAlts(info.Char, "normal", courtroom.EmoteTalk), assets.AssetTypeCharSprite, network.PriorityLow) // AssetType: CharSprite (pre-warm) + a.d.Manager.Media().Get(assets.ChainKey(idle, assets.AssetTypeCharSprite), media.Later, 0, a.urls.EmoteAlts(info.Char, "normal", courtroom.EmoteIdle)...) // AssetType: CharSprite (pre-warm) + a.d.Manager.Media().Get(assets.ChainKey(talk, assets.AssetTypeCharSprite), media.Later, 0, a.urls.EmoteAlts(info.Char, "normal", courtroom.EmoteTalk)...) // AssetType: CharSprite (pre-warm) } if info.Background != "" { // wit/def/pro/jud cover the courtroom core (standardPositions leads with those four). for _, pos := range standardPositions[:4] { s := a.urls.PositionScenery(info.Background, pos, nil) - a.d.Manager.PrefetchChain(s.Background, s.Alts, assets.AssetTypeBackground, network.PriorityLow) // AssetType: Background (pre-warm) + a.d.Manager.Media().Get(assets.ChainKey(s.Background, assets.AssetTypeBackground), media.Later, 0, s.Alts...) // AssetType: Background (pre-warm) } } } @@ -620,13 +620,13 @@ func (a *App) prewarmServer() { func (a *App) speculateEmote(me string, e *courtroom.Emote) { idle := a.urls.Emote(me, e.Anim, courtroom.EmoteIdle) talk := a.urls.Emote(me, e.Anim, courtroom.EmoteTalk) - a.d.Manager.PrefetchChain(idle, a.urls.EmoteAlts(me, e.Anim, courtroom.EmoteIdle), assets.AssetTypeCharSprite, network.PriorityLow) // AssetType: CharSprite (picked emote idle) - a.d.Manager.PrefetchChain(talk, a.urls.EmoteAlts(me, e.Anim, courtroom.EmoteTalk), assets.AssetTypeCharSprite, network.PriorityLow) // AssetType: CharSprite (picked emote talk) + a.d.Manager.Media().Get(assets.ChainKey(idle, assets.AssetTypeCharSprite), media.Later, 0, a.urls.EmoteAlts(me, e.Anim, courtroom.EmoteIdle)...) // AssetType: CharSprite (picked emote idle) + a.d.Manager.Media().Get(assets.ChainKey(talk, assets.AssetTypeCharSprite), media.Later, 0, a.urls.EmoteAlts(me, e.Anim, courtroom.EmoteTalk)...) // AssetType: CharSprite (picked emote talk) if e.Preanim != "" && e.Preanim != "-" { - a.d.Manager.Prefetch(a.urls.Emote(me, e.Preanim, courtroom.EmotePreanim), assets.AssetTypeCharSprite, network.PriorityLow) // AssetType: CharSprite (picked preanim) + a.d.Manager.Media().Get(assets.ChainKey(a.urls.Emote(me, e.Preanim, courtroom.EmotePreanim), assets.AssetTypeCharSprite), media.Later, 0) // AssetType: CharSprite (picked preanim) } if e.SFXName != "" && e.SFXName != "0" && e.SFXName != "1" { - a.d.Manager.Prefetch(a.urls.SFX(e.SFXName), assets.AssetTypeSFX, network.PriorityLow) // AssetType: SFX (picked emote) + a.d.Manager.Media().Get(assets.ChainKey(a.urls.SFX(e.SFXName), assets.AssetTypeSFX), media.Later, 0) // AssetType: SFX (picked emote) } } @@ -840,7 +840,7 @@ func (a *App) noteEvidencePresented(msg *protocol.ChatMessage) { a.pushIC(name+" presented evidence: "+item.Name, 0, fr, fc, "") // system line — no speaker tint a.evShowImg = img a.evShowAt = time.Now() - a.d.Manager.PrefetchExact(a.evidURL(img), assets.AssetTypeMisc, network.PriorityHigh) // AssetType: Misc (evidence image, exact URL) + a.d.Manager.Media().Get(assets.ExactKey(a.evidURL(img), assets.AssetTypeMisc), media.Now, 0) // AssetType: Misc (evidence image, exact URL) } // evidURL resolves an evidence image name to its pixel source, honouring the panel's "stream from server" toggle: @@ -861,7 +861,7 @@ func (a *App) demandEvidence(idx int, url string) { return } a.evidAsk[idx] = time.Now() - a.d.Manager.PrefetchExact(url, assets.AssetTypeMisc, network.PriorityLow) // AssetType: Misc (evidence thumbnail, exact URL) + a.d.Manager.Media().Get(assets.ExactKey(url, assets.AssetTypeMisc), media.Later, 0) // AssetType: Misc (evidence thumbnail, exact URL) } // toggleEvidence flips the Evidence floating window; its button and hotkey toggle rather than only open. diff --git a/internal/ui/deskmissing_relay_test.go b/internal/ui/deskmissing_relay_test.go index a81b5e91..19aea669 100644 --- a/internal/ui/deskmissing_relay_test.go +++ b/internal/ui/deskmissing_relay_test.go @@ -7,7 +7,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/protocol" "github.com/SyntaxNyah/AsyncAO/internal/theme" ) @@ -97,7 +97,7 @@ func TestDrainWarningsRelaysDeskMissing(t *testing.T) { if bgBase == deskBase { t.Fatal("test setup: the bg and desk bases must differ for the type-gate control") } - a.d.Manager.Prefetch(bgBase, assets.AssetTypeBackground, network.PriorityHigh) // AssetType: Background + a.d.Manager.Media().Get(assets.ChainKey(bgBase, assets.AssetTypeBackground), media.Now, 0) // AssetType: Background ctrl := time.Now().Add(500 * time.Millisecond) for time.Now().Before(ctrl) { a.drainWarnings() diff --git a/internal/ui/effectspicker.go b/internal/ui/effectspicker.go index d8fa6492..010b48bf 100644 --- a/internal/ui/effectspicker.go +++ b/internal/ui/effectspicker.go @@ -12,7 +12,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" "github.com/SyntaxNyah/AsyncAO/internal/theme" @@ -354,7 +354,7 @@ func (a *App) overlayResolve(name, folder string) (courtroom.OverlayResolved, bo } out.Base = cands[0] // AssetType: Effect (the one network rung of the effect ladder) - a.d.Manager.PrefetchChain(cands[0], cands[1:], assets.AssetTypeEffect, network.PriorityHigh) + a.d.Manager.Media().Get(assets.ChainKey(cands[0], assets.AssetTypeEffect), media.Now, 0, cands[1:]...) return out, true } diff --git a/internal/ui/evidserverpicker.go b/internal/ui/evidserverpicker.go index 34711e88..fbfc1f0f 100644 --- a/internal/ui/evidserverpicker.go +++ b/internal/ui/evidserverpicker.go @@ -12,7 +12,6 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/media" - "github.com/SyntaxNyah/AsyncAO/internal/network" "github.com/SyntaxNyah/AsyncAO/internal/sdl" ) @@ -189,7 +188,7 @@ func (a *App) drawServerEvidencePicker(w, h int32) { c.copy(page.Frames[0], nil, &rc) } else { c.Fill(rc, ColPanelHi) - a.d.Manager.PrefetchExact(url, assets.AssetTypeMisc, network.PriorityLow) // AssetType: Misc (server evidence picker thumbnail) + a.d.Manager.Media().Get(assets.ExactKey(url, assets.AssetTypeMisc), media.Later, 0) // AssetType: Misc (server evidence picker thumbnail) } c.Border(rc, ColPanelHi) c.LabelClipped(cx, cy+evidServerCell+2, evidServerCell, name, ColTextDim) diff --git a/internal/ui/gifexport.go b/internal/ui/gifexport.go index c6c873a6..92c9f104 100644 --- a/internal/ui/gifexport.go +++ b/internal/ui/gifexport.go @@ -9,11 +9,12 @@ import ( "strings" "time" + "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/gifenc" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" "github.com/SyntaxNyah/AsyncAO/internal/theme" @@ -710,7 +711,7 @@ func (a *App) tickGifWarm(j *gifExportJob) { if r.Base == "" { continue // prefetchChain drops an empty base — don't count a no-op submit } - a.d.Manager.PrefetchChain(r.Base, r.Alts, r.Type, network.PriorityHigh) // AssetType: from SceneAssets + a.d.Manager.Media().Get(assets.ChainKey(r.Base, r.Type), media.Now, 0, r.Alts...) // AssetType: from SceneAssets if j.warmInFlight == nil { j.warmInFlight = make(map[string]struct{}) } diff --git a/internal/ui/messaging_fancy.go b/internal/ui/messaging_fancy.go index 7086f18f..68fa883b 100644 --- a/internal/ui/messaging_fancy.go +++ b/internal/ui/messaging_fancy.go @@ -7,7 +7,7 @@ import ( "time" "github.com/SyntaxNyah/AsyncAO/internal/assets" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/sdl" ) @@ -74,7 +74,7 @@ func (a *App) demandMsgIcon(base string) { a.msgIconAsk = make(map[string]time.Time, msgIconAskCap) } a.msgIconAsk[base] = time.Now() - a.d.Manager.Prefetch(base, assets.AssetTypeCharIcon, network.PriorityLow) // AssetType: CharIcon + a.d.Manager.Media().Get(assets.ChainKey(base, assets.AssetTypeCharIcon), media.Later, 0) // AssetType: CharIcon } // drawMsgCharIcon paints a small char icon for char (resolved folder) into cell, falling back to an initial disc in the diff --git a/internal/ui/replaywarm.go b/internal/ui/replaywarm.go index 5801747f..fc5b9021 100644 --- a/internal/ui/replaywarm.go +++ b/internal/ui/replaywarm.go @@ -6,7 +6,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" ) // Replay pre-warm for flat (non-bundled) recordings. A bundled .aorec reads local files, but a flat one streams from @@ -147,7 +147,7 @@ func (a *App) tickReplayWarm() { if r.Base == "" { continue } - a.d.Manager.PrefetchChain(r.Base, r.Alts, r.Type, network.PriorityHigh) // AssetType: from SceneAssets + a.d.Manager.Media().Get(assets.ChainKey(r.Base, r.Type), media.Now, 0, r.Alts...) // AssetType: from SceneAssets if w.warmInFlight == nil { w.warmInFlight = make(map[string]struct{}) } @@ -161,7 +161,7 @@ func (a *App) tickReplayWarm() { // Exact URLs (music carries its extension) use PrefetchExact, not the format-probing path. if !w.musicDone { for _, m := range w.musicRefs { - a.d.Manager.PrefetchExact(m.Base, assets.AssetTypeMusic, network.PriorityHigh) // AssetType: Music (Exact) + a.d.Manager.Media().Get(assets.ExactKey(m.Base, assets.AssetTypeMusic), media.Now, 0) // AssetType: Music (Exact) } w.musicDone = true } diff --git a/internal/ui/screensemote.go b/internal/ui/screensemote.go index e5cf7346..521fb642 100644 --- a/internal/ui/screensemote.go +++ b/internal/ui/screensemote.go @@ -12,7 +12,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/config" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/protocol" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" @@ -30,13 +30,13 @@ func (a *App) previewEmote(char string, e *courtroom.Emote) { a.previewBase = a.urls.Emote(char, e.Preanim, courtroom.EmotePreanim) a.previewName, a.previewNameFor = name, a.previewBase a.notePreviewChar(char) - a.d.Manager.Prefetch(a.previewBase, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (preanim preview) + a.d.Manager.Media().Get(assets.ChainKey(a.previewBase, assets.AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite (preanim preview) return } a.previewBase = a.urls.Emote(char, e.Anim, courtroom.EmoteTalk) a.previewName, a.previewNameFor = name, a.previewBase a.notePreviewChar(char) - a.d.Manager.PrefetchChain(a.previewBase, a.urls.EmoteAlts(char, e.Anim, courtroom.EmoteTalk), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (preview) + a.d.Manager.Media().Get(assets.ChainKey(a.previewBase, assets.AssetTypeCharSprite), media.Now, 0, a.urls.EmoteAlts(char, e.Anim, courtroom.EmoteTalk)...) // AssetType: CharSprite (preview) } // followPinnedPreview retargets an open, pinned preview box to the picked emote; others are left alone. @@ -207,8 +207,8 @@ func (a *App) selectEmote(i int) { a.icPreanim = emoteHasPreanim(&a.emotes[i]) // "Pre" auto-follows the pick (AO2-Client ui_pre, emotes.cpp:211-221) me := a.activeCharName() // Warm both states: _on for the selected cell and _off, which it falls back to while _on streams in. - a.d.Manager.Prefetch(a.urls.EmoteButton(me, i+1, true), assets.AssetTypeEmoteButton, network.PriorityHigh) // AssetType: EmoteButton (on) - a.d.Manager.Prefetch(a.urls.EmoteButton(me, i+1, false), assets.AssetTypeEmoteButton, network.PriorityHigh) // AssetType: EmoteButton (off fallback) + a.d.Manager.Media().Get(assets.ChainKey(a.urls.EmoteButton(me, i+1, true), assets.AssetTypeEmoteButton), media.Now, 0) // AssetType: EmoteButton (on) + a.d.Manager.Media().Get(assets.ChainKey(a.urls.EmoteButton(me, i+1, false), assets.AssetTypeEmoteButton), media.Now, 0) // AssetType: EmoteButton (off fallback) a.speculateEmote(me, &a.emotes[i]) a.followPinnedPreview(me, &a.emotes[i]) // a pinned box follows the pick; a closed one stays closed a.ctx.FocusField("ic") @@ -734,7 +734,7 @@ func (a *App) drawPairGhost(pv, grip sdl.Rect) { } else { c.Fill(pv, sdl.Color{R: 12, G: 12, B: 16, A: 255}) if a.sess.Background != "" { - a.d.Manager.PrefetchChain(base, scenery.Alts, assets.AssetTypeBackground, network.PriorityHigh) // AssetType: Background (pair preview) + a.d.Manager.Media().Get(assets.ChainKey(base, assets.AssetTypeBackground), media.Now, 0, scenery.Alts...) // AssetType: Background (pair preview) } } c.Border(pv, ColPanelHi) @@ -820,7 +820,7 @@ func (a *App) drawGhostSprite(pv sdl.Rect, name, base string, alts []string, off _, known := a.ghostWarm[name] if known || len(a.ghostWarm) < ghostWarmCap { a.ghostWarm[name] = base - a.d.Manager.PrefetchChain(base, alts, assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (ghost editor) + a.d.Manager.Media().Get(assets.ChainKey(base, assets.AssetTypeCharSprite), media.Now, 0, alts...) // AssetType: CharSprite (ghost editor) } } c.Label(pv.X+pv.W/2-c.TextWidth(name)/2, pv.Y+pv.H/2, name, ColTextDim) diff --git a/internal/ui/slideshow.go b/internal/ui/slideshow.go index f0956405..8a109ae7 100644 --- a/internal/ui/slideshow.go +++ b/internal/ui/slideshow.go @@ -8,7 +8,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" ) // updateSlideshow advances the rotation, clearing the override when the slideshow is off or the room isn't idle. @@ -34,7 +34,7 @@ func (a *App) updateSlideshow(phase courtroom.MessagePhase) { a.slideAt = a.now() a.slideIdx = (a.slideIdx + 1) % len(names) // Low priority so it never competes with live assets. - a.d.Manager.Prefetch(a.slideBG, assets.AssetTypeBackground, network.PriorityLow) // AssetType: Background (slideshow) + a.d.Manager.Media().Get(assets.ChainKey(a.slideBG, assets.AssetTypeBackground), media.Later, 0) // AssetType: Background (slideshow) } // renderScene returns the scene to draw: the replay, the live scene, or a copy with the rotating background and no diff --git a/internal/ui/stylebox.go b/internal/ui/stylebox.go index 1d33f1fd..10672a4b 100644 --- a/internal/ui/stylebox.go +++ b/internal/ui/stylebox.go @@ -8,7 +8,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/helper/parse" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" - "github.com/SyntaxNyah/AsyncAO/internal/network" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/sdl" ) @@ -420,7 +420,7 @@ func (a *App) drawSpriteStyleBox(w, h int32, pressed *bool) { } else { c.Fill(pv, sdl.Color{R: 12, G: 12, B: 16, A: 255}) if a.sess.Background != "" { - a.d.Manager.PrefetchChain(bgBase, scenery.Alts, assets.AssetTypeBackground, network.PriorityHigh) // AssetType: Background (style preview) + a.d.Manager.Media().Get(assets.ChainKey(bgBase, assets.AssetTypeBackground), media.Now, 0, scenery.Alts...) // AssetType: Background (style preview) } } if me := a.activeCharName(); me != "" && a.d.Viewport != nil { @@ -431,7 +431,7 @@ func (a *App) drawSpriteStyleBox(w, h int32, pressed *bool) { sbase := a.urls.Emote(me, anim, courtroom.EmoteIdle) if a.stylePrevWarm != sbase { // warm once per emote base, not per frame a.stylePrevWarm = sbase - a.d.Manager.PrefetchChain(sbase, a.urls.EmoteAlts(me, anim, courtroom.EmoteIdle), assets.AssetTypeCharSprite, network.PriorityHigh) // AssetType: CharSprite (style preview) + a.d.Manager.Media().Get(assets.ChainKey(sbase, assets.AssetTypeCharSprite), media.Now, 0, a.urls.EmoteAlts(me, anim, courtroom.EmoteIdle)...) // AssetType: CharSprite (style preview) } a.d.Viewport.RenderStylePreview(c.Ren, sbase, styleFromPref(p), pv) } else { From 88bc32665fbe4dc6091b42a07b5b7dc98421e966 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:14:55 +0100 Subject: [PATCH 34/43] network: open a body as it arrives, and read one byte range Groundwork for streaming music. Open returns once the host answers 200 and hands the body over as it arrives; it is cut when it stops sending for 30 s, never for taking long, so a long track on a slow host keeps going. ReadRange fetches one span, or reports ErrNoRanges when the host sends the whole file. Both keep Fetch's 404 cache, backoff and header deadline: the request start, status check and refusal are now shared helpers that fetchAttempt uses too. Co-Authored-By: Claude Opus 5.5 --- internal/network/client.go | 106 ++++++++++++++------------ internal/network/stream.go | 131 ++++++++++++++++++++++++++++++++ internal/network/stream_test.go | 117 ++++++++++++++++++++++++++++ 3 files changed, 306 insertions(+), 48 deletions(-) create mode 100644 internal/network/stream.go create mode 100644 internal/network/stream_test.go diff --git a/internal/network/client.go b/internal/network/client.go index db827332..48ec0c19 100644 --- a/internal/network/client.go +++ b/internal/network/client.go @@ -84,8 +84,9 @@ type Client struct { backoff sync.Map // host string → *hostBackoff hostLat sync.Map // host string → *hostLatency (TTFB EWMA) timeout time.Duration - // bodyBudget is a field rather than the const so tests can shrink it. + // bodyBudget and stallLimit are fields rather than the consts so tests can shrink them. bodyBudget time.Duration + stallLimit time.Duration bufPool sync.Pool // *bytes.Buffer for unknown-length reads requests atomic.Int64 @@ -162,6 +163,7 @@ func newClient(timeout, notFoundTTL time.Duration, sockets *netproxy.Factory) *C dns: dns, timeout: timeout, bodyBudget: bodyTransferBudget, + stallLimit: streamStallLimit, bufPool: sync.Pool{ New: func() any { buf := &bytes.Buffer{} @@ -206,16 +208,9 @@ func (c *Client) PreResolve(ctx context.Context, host string) { // Fetch shares one upstream request between callers; ctx cancels only this caller's wait, and the returned // slice must be treated as immutable. func (c *Client) Fetch(ctx context.Context, url string) ([]byte, error) { - if _, found := c.notFound.Get(url); found { - c.cached404s.Add(1) - return nil, fmt.Errorf("%w: %s (cached)", ErrAssetNotFound, url) - } - if host := hostOf(url); host != "" { - if until, backing := c.backingOff(host); backing { - return nil, fmt.Errorf("%w: %s until %s", ErrHostBackingOff, host, until.Format(time.RFC3339)) - } + if err := c.refuse(url); err != nil { + return nil, err } - ch := c.group.DoChan(url, func() (any, error) { return c.fetchOnce(url) }) @@ -231,6 +226,20 @@ func (c *Client) Fetch(ctx context.Context, url string) ([]byte, error) { } } +// refuse answers without a request: a 404 cached inside its TTL, or a host inside its backoff window. +func (c *Client) refuse(url string) error { + if _, found := c.notFound.Get(url); found { + c.cached404s.Add(1) + return fmt.Errorf("%w: %s (cached)", ErrAssetNotFound, url) + } + if host := hostOf(url); host != "" { + if until, backing := c.backingOff(host); backing { + return fmt.Errorf("%w: %s until %s", ErrHostBackingOff, host, until.Format(time.RFC3339)) + } + } + return nil +} + // hostLatency uses plain load and store, as a lost update only delays the average by one sample. type hostLatency struct{ ewmaNs atomic.Int64 } @@ -308,65 +317,66 @@ func (c *Client) fetchOnce(url string) ([]byte, error) { // fetchAttempt is one request: 200 gives bytes, 404 the negative-cached miss, anything else a transient error. func (c *Client) fetchAttempt(url string) ([]byte, error) { - c.requests.Add(1) - host := hostOf(url) // One timer drives two deadlines: adaptive TTFB for headers, then the body budget, so a small-asset EWMA // can't cut a large body mid-stream. - ctx, cancel := context.WithCancel(context.Background()) - deadline := time.AfterFunc(c.adaptiveTimeout(host), cancel) - defer cancel() - defer deadline.Stop() - - req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) - if err != nil { - return nil, fmt.Errorf("network: building request for %s: %w", url, err) - } - req.Header.Set("User-Agent", clientUserAgent) - if o := c.assetOrigin.Load(); o != nil { // power-user Origin/CORS override - req.Header.Set("Origin", *o) - req.Header.Set("Referer", *o+"/") // some bases gate by Referer (hotlink protection) rather than Origin - } - - start := time.Now() - resp, err := c.assetHTTP().Do(req) + resp, host, deadline, cancel, err := c.start(context.Background(), url, "") if err != nil { - c.recordFailure(host) - c.failures.Add(1) - return nil, fmt.Errorf("network: fetching %s: %w", url, err) + return nil, err } + defer cancel() + defer deadline.Stop() // Headers arrived: swap to the body budget. If the timer already fired, ctx is canceled and the read fails fast. deadline.Reset(c.bodyBudget) - c.observeLatency(host, time.Since(start)) defer func() { // Drain so the keep-alive connection is reusable. _, _ = io.Copy(io.Discard, resp.Body) resp.Body.Close() }() - switch { - case resp.StatusCode == http.StatusOK: - data, err := c.readBody(resp) - if err != nil { - c.failures.Add(1) - return nil, fmt.Errorf("network: reading %s: %w", url, err) - } - c.recordSuccess(host) - c.hits.Add(1) - c.bytesRead.Add(int64(len(data))) - return data, nil + if err := c.checkStatus(url, host, resp, http.StatusOK); err != nil { + return nil, err + } + data, err := c.readBody(resp) + if err != nil { + c.failures.Add(1) + return nil, fmt.Errorf("network: reading %s: %w", url, err) + } + c.recordSuccess(host) + c.hits.Add(1) + c.bytesRead.Add(int64(len(data))) + return data, nil +} - case resp.StatusCode == http.StatusNotFound: +// checkStatus passes the status a request wanted; a 404 is cached as missing, and anything else counts against the host. +func (c *Client) checkStatus(url, host string, resp *http.Response, want int) error { + switch resp.StatusCode { + case want: + return nil + case http.StatusNotFound: c.notFound.Add(url, struct{}{}) c.notFounds.Add(1) c.recordSuccess(host) // the host is healthy; the asset just isn't there - return nil, fmt.Errorf("%w: %s", ErrAssetNotFound, url) - + return fmt.Errorf("%w: %s", ErrAssetNotFound, url) default: // 5xx means the host is misbehaving, so it counts toward backoff; fetchOnce's retry absorbs one-off hiccups. c.recordFailure(host) c.failures.Add(1) - return nil, fmt.Errorf("%w: fetching %s: %s", ErrUnexpectedStatus, url, resp.Status) + return fmt.Errorf("%w: fetching %s: %s", ErrUnexpectedStatus, url, resp.Status) + } +} + +// newRequest is a GET for url with the headers every asset request carries. +func (c *Client) newRequest(ctx context.Context, url string) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, fmt.Errorf("network: building request for %s: %w", url, err) + } + req.Header.Set("User-Agent", clientUserAgent) + if o := c.assetOrigin.Load(); o != nil { // power-user Origin/CORS override + req.Header.Set("Origin", *o) + req.Header.Set("Referer", *o+"/") // some bases gate by Referer (hotlink protection) rather than Origin } + return req, nil } // readBody allocates once for a known length; that path can't pool because T2 and T3 retain the payload diff --git a/internal/network/stream.go b/internal/network/stream.go new file mode 100644 index 00000000..de9556b4 --- /dev/null +++ b/internal/network/stream.go @@ -0,0 +1,131 @@ +package network + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "time" +) + +// streamStallLimit cuts a download that has sent nothing for this long; one that keeps sending is never cut. +const streamStallLimit = 30 * time.Second + +// ErrNoRanges reports a host that answered a range request with the whole file. +var ErrNoRanges = errors.New("network: host does not serve byte ranges") + +// Body is a response body read as it arrives; Close ends the request. +type Body struct { + body io.ReadCloser + stall *time.Timer + cancel context.CancelFunc + c *Client + host string + // Size is the body's length, or -1 when the host didn't say. + Size int64 +} + +// Open starts a GET for url and returns once the host answers 200, for a caller that reads the body as it arrives. +// The 404 cache and backoff apply as in Fetch; the read is cut when it stalls, never for taking long. +func (c *Client) Open(ctx context.Context, url string) (*Body, error) { + if err := c.refuse(url); err != nil { + return nil, err + } + resp, host, stall, cancel, err := c.start(ctx, url, "") + if err != nil { + return nil, err + } + if err := c.checkStatus(url, host, resp, http.StatusOK); err != nil { + stall.Stop() + cancel() + resp.Body.Close() + return nil, err + } + stall.Reset(c.stallLimit) + size := resp.ContentLength + if size < 0 { + size = -1 + } + return &Body{body: resp.Body, stall: stall, cancel: cancel, c: c, host: host, Size: size}, nil +} + +func (b *Body) Read(p []byte) (int, error) { + n, err := b.body.Read(p) + if n > 0 { + b.stall.Reset(b.c.stallLimit) + b.c.bytesRead.Add(int64(n)) + } + if errors.Is(err, io.EOF) { + b.c.recordSuccess(b.host) + b.c.hits.Add(1) + } + return n, err +} + +// Close ends the request, whether or not the body was read to the end. +func (b *Body) Close() error { + b.stall.Stop() + b.cancel() + return b.body.Close() +} + +// ReadRange returns n bytes of url from offset from, or ErrNoRanges when the host sends the whole file instead. +func (c *Client) ReadRange(ctx context.Context, url string, from, n int64) ([]byte, error) { + if err := c.refuse(url); err != nil { + return nil, err + } + span := "bytes=" + strconv.FormatInt(from, 10) + "-" + strconv.FormatInt(from+n-1, 10) + resp, host, deadline, cancel, err := c.start(ctx, url, span) + if err != nil { + return nil, err + } + defer deadline.Stop() + defer cancel() + defer resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return nil, fmt.Errorf("%w: %s", ErrNoRanges, url) + } + if err := c.checkStatus(url, host, resp, http.StatusPartialContent); err != nil { + return nil, err + } + deadline.Reset(c.bodyBudget) + data := make([]byte, n) + got, err := io.ReadFull(resp.Body, data) + if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) { + c.failures.Add(1) + return nil, fmt.Errorf("network: reading %s: %w", url, err) + } + c.bytesRead.Add(int64(got)) + return data[:got], nil +} + +// start sends one request, with span as its Range header when set, and waits for the headers under the host's adaptive +// deadline; the timer it returns cancels the request when it fires, and the caller resets it for the body. +func (c *Client) start(ctx context.Context, url, span string) (*http.Response, string, *time.Timer, context.CancelFunc, error) { + c.requests.Add(1) + host := hostOf(url) + ctx, cancel := context.WithCancel(ctx) + timer := time.AfterFunc(c.adaptiveTimeout(host), cancel) + req, err := c.newRequest(ctx, url) + if err != nil { + timer.Stop() + cancel() + return nil, host, nil, nil, err + } + if span != "" { + req.Header.Set("Range", span) + } + began := time.Now() + resp, err := c.assetHTTP().Do(req) + if err != nil { + timer.Stop() + cancel() + c.recordFailure(host) + c.failures.Add(1) + return nil, host, nil, nil, fmt.Errorf("network: fetching %s: %w", url, err) + } + c.observeLatency(host, time.Since(began)) + return resp, host, timer, cancel, nil +} diff --git a/internal/network/stream_test.go b/internal/network/stream_test.go new file mode 100644 index 00000000..528dcd93 --- /dev/null +++ b/internal/network/stream_test.go @@ -0,0 +1,117 @@ +package network + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strconv" + "sync/atomic" + "testing" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/netproxy" +) + +const ( + streamTestHalf = 4096 + streamTestStall = 50 * time.Millisecond + streamTestFrom = 100 + streamTestSpan = 64 +) + +var streamTestFile = bytes.Repeat([]byte("0123456789abcdef"), 2*streamTestHalf/len("0123456789abcdef")) + +func TestOpenHandsOverBytesBeforeTheHostFinishes(t *testing.T) { + rest := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", strconv.Itoa(len(streamTestFile))) + _, _ = w.Write(streamTestFile[:streamTestHalf]) + w.(http.Flusher).Flush() + <-rest + _, _ = w.Write(streamTestFile[streamTestHalf:]) + })) + defer srv.Close() + body, err := NewClientNotFoundTTL(0, netproxy.Direct()).Open(context.Background(), srv.URL+"/music/a.opus") + if err != nil { + t.Fatal(err) + } + defer body.Close() + if body.Size != int64(len(streamTestFile)) { + t.Fatalf("size %d, want %d", body.Size, len(streamTestFile)) + } + first := make([]byte, streamTestHalf) + if _, err := io.ReadFull(body, first); err != nil { + t.Fatal(err) + } + close(rest) + all, err := io.ReadAll(body) + if err != nil || !bytes.Equal(append(first, all...), streamTestFile) { + t.Fatalf("body differs, err %v", err) + } +} + +func TestOpenCachesAMissingTrack(t *testing.T) { + var asked atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + http.NotFound(w, r) + })) + defer srv.Close() + c := NewClientNotFoundTTL(0, netproxy.Direct()) + for range 2 { + if _, err := c.Open(context.Background(), srv.URL+"/music/gone.opus"); !errors.Is(err, ErrAssetNotFound) { + t.Fatalf("err %v, want not found", err) + } + } + if asked.Load() != 1 { + t.Fatalf("asked %d times, want once", asked.Load()) + } +} + +func TestOpenCutsAStalledBody(t *testing.T) { + hold := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", strconv.Itoa(len(streamTestFile))) + w.(http.Flusher).Flush() + <-hold + })) + defer srv.Close() + defer close(hold) // before srv.Close, which waits for the handler + c := NewClientNotFoundTTL(0, netproxy.Direct()) + c.stallLimit = streamTestStall + body, err := c.Open(context.Background(), srv.URL+"/music/slow.opus") + if err != nil { + t.Fatal(err) + } + defer body.Close() + if _, err := io.ReadAll(body); err == nil { + t.Fatal("a body that stopped sending read to the end") + } +} + +func TestReadRangeReadsOnlyTheSpan(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.ServeContent(w, r, "a.opus", time.Time{}, bytes.NewReader(streamTestFile)) + })) + defer srv.Close() + got, err := NewClientNotFoundTTL(0, netproxy.Direct()).ReadRange(context.Background(), srv.URL+"/music/a.opus", streamTestFrom, streamTestSpan) + if err != nil { + t.Fatal(err) + } + if want := streamTestFile[streamTestFrom : streamTestFrom+streamTestSpan]; !bytes.Equal(got, want) { + t.Fatalf("got %q, want %q", got, want) + } +} + +func TestReadRangeReportsAHostWithoutRanges(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write(streamTestFile) + })) + defer srv.Close() + if _, err := NewClientNotFoundTTL(0, netproxy.Direct()).ReadRange(context.Background(), srv.URL+"/music/a.opus", streamTestFrom, streamTestSpan); !errors.Is(err, ErrNoRanges) { + t.Fatalf("err %v, want ErrNoRanges", err) + } +} From bfb07ff0fc006343e5b5b9b5bcb8ad948f213883 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:16:05 +0100 Subject: [PATCH 35/43] cache: downloads arrive in a partial file and are adopted when complete Groundwork for streaming music. PartialFile creates a .tmp file under /partial for a download to write into as it arrives (prune and Relocate already skip .tmp files); Adopt queues the finished file to the writer goroutine, which renames it into place, or copies it when the cache moved drives meanwhile. The writer empties the partial folder at open, so a download a crash cut short never lingers. Path exposes where a URL's copy lives, for a reader that opens the file itself. The download goroutine writes its own partial file; that is not on the render, image decode or resolver paths hard rule 2 protects, and the single writer still owns every change to finished blobs. Co-Authored-By: Claude Opus 5.5 --- internal/cache/disk.go | 51 +++++++++++++++++++++++++++-- internal/cache/partial_test.go | 60 ++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 2 deletions(-) create mode 100644 internal/cache/partial_test.go diff --git a/internal/cache/disk.go b/internal/cache/disk.go index b9a2b670..9010905d 100644 --- a/internal/cache/disk.go +++ b/internal/cache/disk.go @@ -32,6 +32,9 @@ const ( diskDirPerm = 0o755 diskTmpPattern = "w-*.tmp" + // partialDir holds downloads still arriving, as .tmp files that prune and Relocate skip; the writer empties it at open. + partialDir = "partial" + partialPattern = "*.tmp" hashHexLen = 16 // xxhash64 → 8 bytes → 16 hex chars // diskPruneEvery is how many stored blobs pass between sweeps; the walk runs only on the writer goroutine. @@ -48,10 +51,12 @@ func Key(url string) string { return hex.EncodeToString(buf[:]) } -// diskWrite is one queued blob operation; del=true removes the blob, and the single FIFO writer preserves order. +// diskWrite is one queued blob operation: store data, move a finished download from from, or with del remove the blob; +// the single FIFO writer preserves order. type diskWrite struct { path string data []byte + from string del bool } @@ -262,6 +267,31 @@ func (d *DiskCache) Get(url string) ([]byte, bool) { return data, true } +// Path is where url's copy is kept, whether or not it exists yet, for a reader that opens the file itself. +func (d *DiskCache) Path(url string) string { return d.pathFor(url) } + +// PartialFile creates the file a download is written into while it arrives; Adopt hands it to the cache when complete. +func (d *DiskCache) PartialFile() (*os.File, error) { + dir := filepath.Join(d.Root(), partialDir) + if err := os.MkdirAll(dir, diskDirPerm); err != nil { + return nil, fmt.Errorf("cache: creating %s: %w", dir, err) + } + return os.CreateTemp(dir, partialPattern) +} + +// Adopt queues a finished download at path to become url's copy; a full queue or closed cache deletes it instead. +func (d *DiskCache) Adopt(url, path string) { + if !d.stopped.Load() { + select { + case d.queue <- diskWrite{path: d.pathFor(url), from: path}: + return + default: + } + } + d.dropped.Add(1) + _ = os.Remove(path) +} + // Put queues data and takes ownership, as T2 shares the payload; a full queue or closed cache drops this copy. func (d *DiskCache) Put(url string, data []byte) { if len(data) == 0 || d.stopped.Load() { @@ -316,7 +346,8 @@ func (d *DiskCache) Close() { // writerLoop is the only blob writer and owns the prune: at open, every diskPruneEvery stores, on each SetBudget. func (d *DiskCache) writerLoop() { defer close(d.done) - d.prune() // enforce the initial budget on whatever a previous session left + _ = os.RemoveAll(filepath.Join(d.Root(), partialDir)) // downloads a previous session never finished + d.prune() // enforce the initial budget on whatever a previous session left sincePrune := 0 for { select { @@ -358,6 +389,9 @@ func (d *DiskCache) write(w diskWrite) bool { d.reportError(fmt.Errorf("cache: creating shard dir %s: %w", dir, err)) return false } + if w.from != "" { + return d.adopt(w) + } tmp, err := os.CreateTemp(dir, diskTmpPattern) if err != nil { d.reportError(fmt.Errorf("cache: creating temp blob in %s: %w", dir, err)) @@ -384,6 +418,19 @@ func (d *DiskCache) write(w diskWrite) bool { return true } +// adopt moves a finished download into place, copying when the cache moved to another drive while it arrived. +func (d *DiskCache) adopt(w diskWrite) bool { + defer os.Remove(w.from) + if err := os.Rename(w.from, w.path); err != nil { + if err := copyFile(w.from, w.path); err != nil { + d.reportError(fmt.Errorf("cache: adopting download %s: %w", w.path, err)) + return false + } + } + d.writes.Add(1) + return true +} + // diskFileAge is one blob's path, size and mtime, for the prune sweep. type diskFileAge struct { path string diff --git a/internal/cache/partial_test.go b/internal/cache/partial_test.go new file mode 100644 index 00000000..daca7ef5 --- /dev/null +++ b/internal/cache/partial_test.go @@ -0,0 +1,60 @@ +package cache + +import ( + "bytes" + "os" + "path/filepath" + "testing" +) + +const partialTestURL = "https://host.test/base/sounds/music/a.opus" + +var partialTestBody = []byte("a whole track, arrived") + +func TestAdoptMakesAFinishedDownloadTheCachedCopy(t *testing.T) { + d, err := NewDiskCache(t.TempDir(), 0) + if err != nil { + t.Fatal(err) + } + defer d.Close() + f, err := d.PartialFile() + if err != nil { + t.Fatal(err) + } + if _, err := f.Write(partialTestBody); err != nil { + t.Fatal(err) + } + f.Close() + d.Adopt(partialTestURL, f.Name()) + if got := waitForBlob(t, d, partialTestURL); !bytes.Equal(got, partialTestBody) { + t.Fatalf("cached %q, want %q", got, partialTestBody) + } + if _, err := os.Stat(f.Name()); !os.IsNotExist(err) { + t.Fatalf("the partial file is still there: %v", err) + } + if got, err := os.ReadFile(d.Path(partialTestURL)); err != nil || !bytes.Equal(got, partialTestBody) { + t.Fatalf("Path reads %q, %v", got, err) + } +} + +func TestOpeningClearsDownloadsALastSessionLeft(t *testing.T) { + root := t.TempDir() + d, err := NewDiskCache(root, 0) + if err != nil { + t.Fatal(err) + } + f, err := d.PartialFile() + if err != nil { + t.Fatal(err) + } + f.Close() + d.Close() + again, err := NewDiskCache(root, 0) + if err != nil { + t.Fatal(err) + } + again.Close() // Close waits for the writer, which clears before anything else + if _, err := os.Stat(filepath.Join(root, partialDir)); !os.IsNotExist(err) { + t.Fatalf("leftover downloads survived opening: %v", err) + } +} From 083057a0dae5e33ca83e4f5c04b8d89a3a21d020 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:56:58 +0100 Subject: [PATCH 36/43] cache: clear a crashed session's downloads before the cache opens The writer goroutine emptied the partial folder when it started, which races a download begun right after NewDiskCache returns: on Linux and macOS the removal deletes the file the download is writing (Windows refuses to delete an open file, which hid it). The leftovers are now removed in NewDiskCache, before anyone can ask for a partial file. Caught by the partial-file tests on the Linux and macOS CI runners. Co-Authored-By: Claude Opus 5.5 --- internal/cache/disk.go | 7 ++++--- internal/cache/partial_test.go | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/internal/cache/disk.go b/internal/cache/disk.go index 9010905d..1e185027 100644 --- a/internal/cache/disk.go +++ b/internal/cache/disk.go @@ -32,7 +32,7 @@ const ( diskDirPerm = 0o755 diskTmpPattern = "w-*.tmp" - // partialDir holds downloads still arriving, as .tmp files that prune and Relocate skip; the writer empties it at open. + // partialDir holds downloads still arriving, as .tmp files that prune and Relocate skip; opening the cache empties it. partialDir = "partial" partialPattern = "*.tmp" hashHexLen = 16 // xxhash64 → 8 bytes → 16 hex chars @@ -217,6 +217,8 @@ func NewDiskCache(root string, initialBudget int64) (*DiskCache, error) { if err := os.MkdirAll(root, diskDirPerm); err != nil { return nil, fmt.Errorf("cache: creating disk cache root %s: %w", root, err) } + // Here, not on the writer: once this returns a download may already be arriving in the folder. + _ = os.RemoveAll(filepath.Join(root, partialDir)) // downloads a previous session never finished d := &DiskCache{ queue: make(chan diskWrite, writeQueueCap), pruneReq: make(chan struct{}, pruneReqCap), @@ -346,8 +348,7 @@ func (d *DiskCache) Close() { // writerLoop is the only blob writer and owns the prune: at open, every diskPruneEvery stores, on each SetBudget. func (d *DiskCache) writerLoop() { defer close(d.done) - _ = os.RemoveAll(filepath.Join(d.Root(), partialDir)) // downloads a previous session never finished - d.prune() // enforce the initial budget on whatever a previous session left + d.prune() // enforce the initial budget on whatever a previous session left sincePrune := 0 for { select { diff --git a/internal/cache/partial_test.go b/internal/cache/partial_test.go index daca7ef5..a03d9868 100644 --- a/internal/cache/partial_test.go +++ b/internal/cache/partial_test.go @@ -53,7 +53,7 @@ func TestOpeningClearsDownloadsALastSessionLeft(t *testing.T) { if err != nil { t.Fatal(err) } - again.Close() // Close waits for the writer, which clears before anything else + again.Close() if _, err := os.Stat(filepath.Join(root, partialDir)); !os.IsNotExist(err) { t.Fatalf("leftover downloads survived opening: %v", err) } From f251e8590ec2020b22f56e970ef798bd7d5769c8 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:56:58 +0100 Subject: [PATCH 37/43] assets: give the claim-limit test time for small CI runners Four 2048x2048 background decodes run on the one Compute worker left for background work on a two-core runner, which under the race detector took about 8 s on the Linux and macOS runners, past the shared 5 s wait. The test now waits up to a minute; waitWithin takes the limit, and waitUntil keeps the usual one. Co-Authored-By: Claude Opus 5.5 --- internal/assets/claim_test.go | 8 +++++--- internal/assets/manager_test.go | 8 +++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/internal/assets/claim_test.go b/internal/assets/claim_test.go index 9d22e270..8322a69f 100644 --- a/internal/assets/claim_test.go +++ b/internal/assets/claim_test.go @@ -23,6 +23,8 @@ const ( claimBigShare = imageClaimLimit / (claimBigSide * claimBigSide * rgbaBytesPerPixel) claimBigAsks = 2 * claimBigShare claimTestQuiet = 200 * time.Millisecond + // claimTestWait covers several 16 MiB decodes on one background worker under the race detector on a small runner. + claimTestWait = time.Minute ) // encodeGIFGlobal is a GIF whose frames share one global colour table. @@ -103,7 +105,7 @@ func TestBackgroundDecodesWaitForUploads(t *testing.T) { var held []Delivery take := func() { rig.manager.TakeDeliveries(func(d Delivery) { held = append(held, d) }) } - waitUntil(t, "the first background decodes", func() bool { take(); return len(held) >= claimBigShare }) + waitWithin(t, "the first background decodes", claimTestWait, func() bool { take(); return len(held) >= claimBigShare }) time.Sleep(claimTestQuiet) take() if len(held) != claimBigShare { @@ -111,7 +113,7 @@ func TestBackgroundDecodesWaitForUploads(t *testing.T) { } rig.manager.Media().Get(ChainKey(bases[claimBigAsks], AssetTypeBackground), media.Now, 0) // AssetType: Background - waitUntil(t, "the current message's decode", func() bool { take(); return len(held) > claimBigShare }) + waitWithin(t, "the current message's decode", claimTestWait, func() bool { take(); return len(held) > claimBigShare }) for _, d := range held { d.Asset.Release() @@ -119,7 +121,7 @@ func TestBackgroundDecodesWaitForUploads(t *testing.T) { } done := len(held) held = nil - waitUntil(t, "the rest after uploads", func() bool { + waitWithin(t, "the rest after uploads", claimTestWait, func() bool { rig.manager.TakeDeliveries(func(d Delivery) { d.Asset.Release() rig.manager.Done(d) diff --git a/internal/assets/manager_test.go b/internal/assets/manager_test.go index 9c3e518e..550d7473 100644 --- a/internal/assets/manager_test.go +++ b/internal/assets/manager_test.go @@ -593,7 +593,13 @@ func TestPurgeCorruptEvictsTiers(t *testing.T) { // waitUntil polls done until it holds, failing the test after managerWait. func waitUntil(t *testing.T, what string, done func() bool) { t.Helper() - deadline := time.Now().Add(managerWait) + waitWithin(t, what, managerWait, done) +} + +// waitWithin polls done until it holds, failing the test after wait. +func waitWithin(t *testing.T, what string, wait time.Duration, done func() bool) { + t.Helper() + deadline := time.Now().Add(wait) for !done() { if time.Now().After(deadline) { t.Fatalf("timed out waiting for %s", what) From 0aa6db752c8320cdc95150f7cd7edf050b110558 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:04:18 +0100 Subject: [PATCH 38/43] media, mix, render: music plays while it downloads Music started only once its whole file had downloaded, then played from a copy held in memory (a 28 MB track sat in the heap). Now no track is held whole in memory, and a new one starts within moments. - media: KindStream keys (music) open a Stream instead of reading bytes. The disk cache and the player's folders open the file in place (a .zip entry is read into memory); the web downloads into a partial file with the file's last 64 KiB fetched by range, as decoders read a file's end when they open it (an Opus file's length, an MP3's tags). Reads wait for bytes not yet arrived; without range support they wait for the download, as before. A finished download is adopted by the disk cache, copied with a streamed copy when Windows won't rename the open file. At most four downloads run at once. - mix: a Decoder over a Go reader (SDL_IOStream callbacks), an SDL audio stream, and a track fed from one. SDL documents these calls as safe from any thread; SDL3_mixer ends a stream track that runs dry, so the player restarts it. - render: a complete file plays through SDL3_mixer by path, as before. A track still downloading, or held in memory, is decoded on its own goroutine into the music track's audio stream, about 2 s ahead of playback; each loop reopens the decoder, so loops stay gapless, and sidecar loop points apply at the next chunk. A download that falls behind pauses only the music, never blips or sound effects. A crossfade starts once the new song does, so a slow first download leaves no gap. The clock knows a streamed song's length after its first full pass. The decoder goroutine reads the partial or cached file from disk; it is not on the render, image decode or resolver paths hard rule 2 protects. Tried in the client on miku.pizza: ten tracks switched about once a second with crossfades, each starting at once; 12 finished downloads landed in the disk cache; heap 56 MiB against about 140 MiB before. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 +- docs/RESTRUCTURING_PLAN.md | 8 +- internal/assets/folders.go | 12 ++ internal/assets/manager.go | 2 + internal/assets/mediabridge.go | 70 ++++++- internal/assets/musicexact_test.go | 11 +- internal/cache/disk.go | 6 +- internal/media/folders.go | 52 +++++ internal/media/manager.go | 14 ++ internal/media/sources.go | 28 ++- internal/media/stream.go | 264 ++++++++++++++++++++++++++ internal/media/stream_test.go | 204 ++++++++++++++++++++ internal/media/types.go | 2 + internal/mix/decoder.go | 174 +++++++++++++++++ internal/mix/decoder_test.go | 148 +++++++++++++++ internal/mix/iostream.c | 28 +++ internal/mix/mix.go | 22 ++- internal/render/audio.go | 229 +++++++++++++++++----- internal/render/audio_music_test.go | 51 +++-- internal/render/audio_test.go | 4 +- internal/render/musicclock.go | 5 +- internal/render/musicloop.go | 21 +- internal/render/musicloop_arm_test.go | 2 +- internal/render/musicstream.go | 260 +++++++++++++++++++++++++ internal/render/musicstream_test.go | 136 +++++++++++++ 25 files changed, 1679 insertions(+), 80 deletions(-) create mode 100644 internal/media/stream.go create mode 100644 internal/media/stream_test.go create mode 100644 internal/mix/decoder.go create mode 100644 internal/mix/decoder_test.go create mode 100644 internal/mix/iostream.c create mode 100644 internal/render/musicstream.go create mode 100644 internal/render/musicstream_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 927ad558..688ef3ab 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -144,16 +144,16 @@ heap corruption. | `internal/netproxy` | the socket factory: opens every outbound connection (direct or through an HTTP proxy) by the one configuration | no | | `internal/saver` | the one background file writer: a change schedules one whole-file replace (temp file + rename) | no | | `internal/config` | preferences + debounced atomic saver; favorites; local mounts; the Wardrobe's `wardrobe.json` | no | -| `internal/cache` | ByteBudgetLRU (T1/T2) + async disk tier (T3, xxhash full-URL keys) | no | +| `internal/cache` | ByteBudgetLRU (T1/T2) + async disk tier (T3, xxhash full-URL keys; downloads arrive in `partial/` and are adopted when complete) | no | | `internal/network` | dedup HTTP client (singleflight, 404 TTL, backoff, DNS warm), master list + tiers + direct connect | no | | `internal/assets` | AssetType enum, `Manager` over `internal/media` (the bridge; learned formats and winners kept in `learned.json`), the player's folders as a media source, decode pool (magic-byte sniffing), WebP/AVIF CGO binding + fallback, Markov prefetcher | no (decoder is SDL-free by rule) | -| `internal/media` | the media system every asset request goes through: `Manager` owns every table on one goroutine, `Get` is safe from any thread, pools run single steps; sources memory → disk cache → `Folders` (the player's folders and .zip packs) → web | no | +| `internal/media` | the media system every asset request goes through: `Manager` owns every table on one goroutine, `Get` is safe from any thread, pools run single steps; sources memory → disk cache → `Folders` (the player's folders and .zip packs) → web; music opens as a `Stream` (downloaded as it plays) instead of bytes | no | | `internal/protocol` | AO wire (delegated to aolib-go: FantaCode + JSON), MS 2.6/2.8 parse/build, pairing semantics, FeatureSet, WebSocket conn | no | | `internal/packetutil` | thin bridge over aolib-go: FantaCode primitives, enum maps, typed-parser dispatch, MS both-wire codec | no | | `internal/courtroom` | session handshake reducer, message lifecycle state machine, typewriter pacing, URL conventions, char.ini | no | | `internal/theme` | AO2 theme INIs (design/fonts/sounds), asset lookup ladder | no | | `internal/metrics` | 1 Hz sampler (heap, GC p99, hit rates), cold-load report | no | -| `internal/sdl`, `ttf`, `mix` | our cgo binding to SDL3, SDL3_ttf and SDL3_mixer (Go-style names, Rect/event/display conversion at the boundary) | **yes** | +| `internal/sdl`, `ttf`, `mix` | our cgo binding to SDL3, SDL3_ttf and SDL3_mixer (Go-style names, Rect/event/display conversion at the boundary); `mix.Decoder` reads a Go reader, for music decoded off the main thread | **yes** | | `internal/render` | TextureStore (T1), viewport compositor, message raster, upload pump, SDL3_mixer audio | **yes** | | `internal/ui` | immediate-mode kit + screens (lobby/phone book, char select, courtroom, settings, about) | **yes** | | `internal/ui/wardrobe` | what the Wardrobe window lists: filtering, sorting and grouping saved characters, and parsing the server's `iniswaps.ini` | no | diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index b226ea74..3f697a69 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -154,7 +154,13 @@ in **Status**. Update Status in the same commit that completes a step. `ExactKey` or `RawKey`; the theme had no requests of its own. `Manager.Prefetch*` and `network.Priority` are gone, and `media.Get` answers a key with no path as Missing. The synchronous `ResolveRaw*` export lookups (archive, content job) stay until the bridge is deleted, as their own step - - [ ] music streaming + - [x] music streaming (2026-11-15): music is a `media.KindStream` key whose sources open a `media.Stream` + instead of reading bytes. The web downloads into a partial file on disk with the file's last 64 KiB + fetched by range (decoders read a file's end when they open it), and the disk cache adopts it when + complete; a complete file (disk cache, folders) plays through SDL3_mixer by path. A track still + downloading or held in memory (.zip packs) is decoded on its own goroutine into an SDL audio stream on the + music track, ahead of playback, reopening at each loop so loops stay gapless; a download that falls behind + pauses only the music. No track is held whole in memory - [ ] off-thread texture preparation: waits for the renderer overhaul (decided 2026-11-02). See below - [x] a sprite sometimes shows its old animation for a frame before the right one (reported 2026-11-01): the wait gate released on a first frame or a reduced page. The speaker's sprites now wait for every frame; a pair partner's still diff --git a/internal/assets/folders.go b/internal/assets/folders.go index 4a3da8fe..2cd93107 100644 --- a/internal/assets/folders.go +++ b/internal/assets/folders.go @@ -37,6 +37,18 @@ func (f *bridgeFolders) Data(file media.File) ([]byte, error) { return b, err } +// Open is Data for a music track, opened where it lies. +func (f *bridgeFolders) Open(file media.File) (media.Stream, error) { + if f.bad.has(string(file)) { + return nil, media.ErrAbsent + } + st, err := f.Folders.Open(file) + if err == nil { + f.m.mountFetches.Add(1) + } + return st, err +} + // read is Data for the synchronous fetch paths; workers only. func (f *bridgeFolders) read(url string) ([]byte, bool) { b, err := f.Data(media.File(url)) diff --git a/internal/assets/manager.go b/internal/assets/manager.go index 1f0a5587..cd14fb9a 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -40,6 +40,8 @@ type AudioAsset struct { Base string Type AssetType Data []byte + // Stream is a music track, opened where it lies or still downloading, in place of Data; the receiver closes it. + Stream media.Stream // FromPack is as on DecodedAsset; audio skips the upload pump, so the audio loader quarantines itself. FromPack bool } diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index 35f31af3..b9fa4527 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -1,8 +1,10 @@ package assets import ( + "bytes" "context" "errors" + "io" "os" "slices" "strings" @@ -232,6 +234,9 @@ func classOf(t AssetType) media.Class { } func kindOf(t AssetType) media.Kind { + if t == AssetTypeMusic { + return media.KindStream + } if t.IsAudio() { return media.KindSound } @@ -343,6 +348,19 @@ func (b *mediaBridge) finished(a *media.Asset) { default: // Delivered: from here T1 answers, and an evicted texture has to be able to ask again. b.media.ForgetAsset(a) + if st, ok := a.Result().(media.Stream); ok { + b.sendStream(k, t, st) + } + } +} + +// sendStream hands a music track to the audio side; with the hand-off full, the track is closed and dropped. +func (b *mediaBridge) sendStream(k media.Key, t AssetType, st media.Stream) { + select { + case b.m.audioCh <- AudioAsset{URL: k.Path, Base: k.Path, Type: t, Stream: st}: + b.m.NotifyDelivery() + default: + st.Close() } } @@ -454,6 +472,54 @@ func (m *Manager) CloseMedia() { type bridgeFetcher struct{ m *Manager } +var _ media.Downloader = bridgeFetcher{} + +// streamer is an HTTP client that hands a body over as it arrives, as *network.Client does. +type streamer interface { + Open(ctx context.Context, url string) (*network.Body, error) + ReadRange(ctx context.Context, url string, from, n int64) ([]byte, error) +} + +// Open is netFetch for a body read as it arrives; a replay archive or a client that can't stream answers whole. +func (f bridgeFetcher) Open(ctx context.Context, url string) (io.ReadCloser, int64, error) { + s, ok := f.m.client.(streamer) + if !ok || f.m.archiveServes(url) || f.m.offline.Load() || strings.HasPrefix(url, LocalScheme) { + data, err := f.Fetch(ctx, url) + if err != nil { + return nil, 0, err + } + return io.NopCloser(bytes.NewReader(data)), int64(len(data)), nil + } + body, err := s.Open(ctx, url) + if err != nil { + return nil, 0, err + } + f.m.netFetches.Add(1) + return body, body.Size, nil +} + +// ReadRange fetches one span when the client can; without it, reads of a track's end wait for its download. +func (f bridgeFetcher) ReadRange(ctx context.Context, url string, from, n int64) ([]byte, error) { + if s, ok := f.m.client.(streamer); ok && !f.m.offline.Load() { + return s.ReadRange(ctx, url, from, n) + } + return nil, network.ErrNoRanges +} + +// PartialFile is where a download arrives. +func (f bridgeFetcher) PartialFile() (*os.File, error) { return f.m.disk.PartialFile() } + +// Adopt gives a finished download to the disk cache. +func (f bridgeFetcher) Adopt(url, path string) { + if skipDisk(url) { + _ = os.Remove(path) + return + } + f.m.disk.Adopt(url, path) + b := f.m.bridge + b.media.Call(func() { b.disk.Index(media.File(url)) }) +} + func (f bridgeFetcher) Fetch(ctx context.Context, url string) ([]byte, error) { data, err := f.m.netFetch(ctx, url) if err == nil { @@ -511,6 +577,8 @@ func (s bridgeDisk) Observe(f media.File, data []byte, err error) { s.DiskSource.Observe(f, data, err) if err == nil { s.m.diskHits.Add(1) + } + if err == nil && len(data) > 0 { // a track opened as a stream brings no bytes s.t2.Add(string(f), data, int64(len(data))) s.pin.keep(string(f), data) } @@ -535,7 +603,7 @@ func (s bridgeRemote) Observe(f media.File, data []byte, err error) { return } s.RemoteSource.Observe(f, data, err) - if err == nil { + if err == nil && len(data) > 0 { // a download keeps itself, through Adopt s.b.m.t2.Add(string(f), data, int64(len(data))) s.b.pin.keep(string(f), data) if !skipDisk(string(f)) { diff --git a/internal/assets/musicexact_test.go b/internal/assets/musicexact_test.go index 9c925231..bca1b790 100644 --- a/internal/assets/musicexact_test.go +++ b/internal/assets/musicexact_test.go @@ -19,7 +19,7 @@ import ( // into another format. // // This is not a property of the URL builder alone: it is a property of the -// pipeline pass PrefetchExact runs (resolveExact, which has no candidate ladder +// pipeline pass an exact key runs (ClassExact, which has no candidate ladder // at all). The test proves it at the wire, by counting what the origin actually // sees: one request, for the .mp3, and no .opus/.ogg speculation beside it — // which is also the zero-fallback pillar (spec §4, one probe per asset). @@ -50,8 +50,13 @@ func TestMP3MusicFetchesExactlyTheURLItWasGiven(t *testing.T) { if a.Type != AssetTypeMusic { t.Errorf("delivered type = %v, want Music", a.Type) } - if !strings.HasPrefix(string(a.Data), "ID3") { - t.Errorf("delivered %d bytes that are not the mp3 payload", len(a.Data)) + if a.Stream == nil { + t.Fatal("music delivered without a stream") + } + defer a.Stream.Close() + head := make([]byte, len("ID3")) + if _, err := a.Stream.ReadAt(head, 0); err != nil || string(head) != "ID3" { + t.Errorf("stream starts %q (%v), not the mp3 payload", head, err) } case <-time.After(managerWait): t.Fatal("exact mp3 music fetch never delivered") diff --git a/internal/cache/disk.go b/internal/cache/disk.go index 1e185027..31873c50 100644 --- a/internal/cache/disk.go +++ b/internal/cache/disk.go @@ -4,6 +4,7 @@ import ( "encoding/hex" "errors" "fmt" + "io" "io/fs" "log" "os" @@ -191,16 +192,17 @@ func moveBlobs(from, to string) error { // copyFile copies src to dst through a temp file, so a half-copied blob never looks finished. func copyFile(src, dst string) error { - data, err := os.ReadFile(src) + in, err := os.Open(src) if err != nil { return err } + defer in.Close() tmp, err := os.CreateTemp(filepath.Dir(dst), diskTmpPattern) if err != nil { return err } tmpName := tmp.Name() - if _, err := tmp.Write(data); err != nil { + if _, err := io.Copy(tmp, in); err != nil { tmp.Close() os.Remove(tmpName) return err diff --git a/internal/media/folders.go b/internal/media/folders.go index 08a83b7a..c8db06b4 100644 --- a/internal/media/folders.go +++ b/internal/media/folders.go @@ -272,6 +272,23 @@ func (fs *Folders) Data(f File) ([]byte, error) { return data, err } +// Open opens a folder's file in place and reads a pack's entry whole, checking the folder like Data; pool workers only. +func (fs *Folders) Open(f File) (Stream, error) { + s := fs.state.Load() + if s == nil { + return nil, ErrAbsent + } + dir, name, ok := s.locate(string(f)) + if !ok { + return nil, ErrAbsent + } + st, onDisk, err := s.open(dir, name, fs.now()) + if err == nil { + fs.note(f, onDisk) + } + return st, err +} + // Size reports the pages held. func (fs *Folders) Size() Contents { n := 0 @@ -391,6 +408,41 @@ func (s *folderSet) read(dir, name string, now time.Time) ([]byte, string, error return nil, "", ErrAbsent } +// open is read for a Stream: a folder's file is opened where it lies, and only a pack's entry is read into memory. +func (s *folderSet) open(dir, name string, now time.Time) (Stream, string, error) { + if !s.mounts.acquire() { + return nil, "", ErrAbsent + } + defer s.mounts.release() + p := s.refresh(dir, now) + pf, ok := p.files[name] + if !ok { + return nil, "", ErrAbsent + } + switch m := s.mounts.mounts[pf.mount].(type) { + case *dirMount: + at, err := safepath.Join(m.root, path.Join(p.real[pf.mount], pf.name)) + if err != nil { + return nil, "", err + } + st, err := FileStream(at) + if err != nil || st.Size() == 0 { + if st != nil { + st.Close() + } + return nil, "", ErrAbsent + } + return st, at, nil + case *zipMount: + data, err := m.read(pf.name) + if err != nil { + return nil, "", err + } + return BytesStream(data), m.path, nil + } + return nil, "", ErrAbsent +} + // refresh returns dir's page, listing it again only if a folder mount's copy changed since its last check. func (s *folderSet) refresh(dir string, now time.Time) *page { prev := s.pages.load(dir) diff --git a/internal/media/manager.go b/internal/media/manager.go index 89e70b89..6afab9ce 100644 --- a/internal/media/manager.go +++ b/internal/media/manager.go @@ -613,6 +613,9 @@ func (m *Manager) handle(r *request) { m.observe(r) } if r.dead { + if s, ok := r.result.(Stream); ok { + s.Close() + } m.end(r, Withdrawn, nil, ErrWithdrawn) return } @@ -654,6 +657,10 @@ func (m *Manager) afterData(r *request) { } m.winners[r.asset.key] = r.file } + if r.asset.key.Kind == KindStream { + m.end(r, Ready, r.result, nil) + return + } format := m.cfg.Formats[r.asset.key.Kind] if format == nil { m.end(r, Ready, r.bytes, nil) @@ -743,6 +750,13 @@ func (m *Manager) start(p *Pool, r *request) { } source := m.cfg.Chains[r.asset.key.Place].entries[r.entry].Source file := r.file + if r.asset.key.Kind == KindStream { + p.jobs <- func() { + r.result, r.err = openStream(source, file) + m.report(r) + } + break + } p.jobs <- func() { r.bytes, r.err = source.Data(file) m.report(r) diff --git a/internal/media/sources.go b/internal/media/sources.go index c9c75c7b..5f88eb16 100644 --- a/internal/media/sources.go +++ b/internal/media/sources.go @@ -61,6 +61,9 @@ func (s *DiskSource) Keep(f File, data []byte) { s.add(cache.Key(string(f))) } +// Index adds a file the cache got without Keep, such as an adopted download, on the Manager's goroutine. +func (s *DiskSource) Index(f File) { s.add(cache.Key(string(f))) } + // add indexes one entry; past diskIndexCap the index starts over, which only costs repeat requests. func (s *DiskSource) add(key string) { if len(s.index) >= diskIndexCap { @@ -89,6 +92,18 @@ func (s *DiskSource) Data(f File) ([]byte, error) { return nil, ErrAbsent } +// Open opens the cached file in place on a Disk worker. +func (s *DiskSource) Open(f File) (Stream, error) { + st, err := FileStream(s.disk.Path(string(f))) + if err != nil || st.Size() == 0 { + if st != nil { + st.Close() + } + return nil, ErrAbsent + } + return st, nil +} + // Observe drops an entry whose read failed, so a stale index heals itself. func (s *DiskSource) Observe(f File, _ []byte, err error) { if err != nil { @@ -129,13 +144,16 @@ type RemoteSource struct { listed map[string]*listedFolder walks map[string]*walk refused map[string]bool + // slots bounds the downloads running at once, MaxDownloads. + slots chan struct{} } // NewRemoteSource asks through fetch. func NewRemoteSource(ctx context.Context, fetch Fetcher, missingTTL time.Duration, clock func() time.Time) *RemoteSource { return &RemoteSource{fetch: fetch, ctx: ctx, clock: clock, missingTTL: missingTTL, exists: map[File]struct{}{}, missing: map[File]time.Time{}, answered: map[string]bool{}, - listed: map[string]*listedFolder{}, walks: map[string]*walk{}, refused: map[string]bool{}} + listed: map[string]*listedFolder{}, walks: map[string]*walk{}, refused: map[string]bool{}, + slots: make(chan struct{}, MaxDownloads)} } // Has answers from the tables and the character maps; a file neither proves is Unknown, and only that costs a request. @@ -164,6 +182,14 @@ func (s *RemoteSource) Data(f File) ([]byte, error) { return data, err } +// Open downloads the file as it arrives when the fetcher can, and reads it whole otherwise. +func (s *RemoteSource) Open(f File) (Stream, error) { + if d, ok := s.fetch.(Downloader); ok { + return s.openDownload(d, f) + } + return wholeStream(s.Data(f)) +} + // Observe records the answer in the tables and what it says about the host. func (s *RemoteSource) Observe(f File, _ []byte, err error) { host := hostOf(f) diff --git a/internal/media/stream.go b/internal/media/stream.go new file mode 100644 index 00000000..cb9e9249 --- /dev/null +++ b/internal/media/stream.go @@ -0,0 +1,264 @@ +package media + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "sync" + + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +const ( + // streamTailBytes is fetched apart from the download, as decoders read a file's end when they open it: an Opus + // file's last page holds its length, an MP3's last bytes its tags. + streamTailBytes = 64 << 10 + // streamChunkBytes is how much of a download is written per read. + streamChunkBytes = 32 << 10 + // MaxDownloads bounds the downloads running at once; Open waits on a Network worker for a free one. + MaxDownloads = 4 +) + +// ErrStreamClosed is what a read of a closed Stream returns. +var ErrStreamClosed = errors.New("media: stream closed") + +// Stream is a file opened for reading, possibly still arriving: ReadAt waits for bytes that haven't come yet. +type Stream interface { + io.ReaderAt + io.Closer + // Size is the file's length, or -1 while it isn't known. + Size() int64 + // Path is the file on disk when it is complete there, or "" for one still arriving or held in memory. + Path() string +} + +// Opener is a source that opens a file as a Stream for KindStream keys, instead of reading all its bytes. +type Opener interface { + Open(File) (Stream, error) +} + +// Downloader is what a RemoteSource needs to hand out a file as it downloads: the body as it arrives, one span of it, +// and a disk file to keep it in, which Adopt gives the disk cache once complete. +type Downloader interface { + Open(ctx context.Context, url string) (body io.ReadCloser, size int64, err error) + ReadRange(ctx context.Context, url string, from, n int64) ([]byte, error) + PartialFile() (*os.File, error) + Adopt(url, path string) +} + +// BytesStream is a Stream over bytes already in memory. +func BytesStream(data []byte) Stream { return bytesStream{bytes.NewReader(data)} } + +type bytesStream struct{ *bytes.Reader } + +func (s bytesStream) Close() error { return nil } +func (s bytesStream) Path() string { return "" } + +// FileStream opens a complete file on disk as a Stream. +func FileStream(path string) (Stream, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + info, err := f.Stat() + if err != nil { + f.Close() + return nil, err + } + return fileStream{f, info.Size()}, nil +} + +type fileStream struct { + *os.File + size int64 +} + +func (s fileStream) Size() int64 { return s.size } +func (s fileStream) Path() string { return s.Name() } + +// download is a file arriving into a partial file on disk; one goroutine writes it, readers wait on cond. +type download struct { + file *os.File + size int64 + body io.ReadCloser + mu sync.Mutex + cond *sync.Cond + // have is how much of the file, from its start, is written; tail is the file's end once fetched apart. + have int64 + tail []byte + tailAt int64 + done bool + err error + closed bool +} + +// newDownload starts copying body into file, and fetches the file's end apart when readRange can. +func newDownload(url string, body io.ReadCloser, size int64, file *os.File, d Downloader, slots chan struct{}) *download { + s := &download{file: file, size: size, body: body} + s.cond = sync.NewCond(&s.mu) + go s.copy(url, d, slots) + if size > streamTailBytes { + go s.fetchTail(url, d) + } + return s +} + +func (s *download) copy(url string, d Downloader, slots chan struct{}) { + defer func() { <-slots }() + buf := make([]byte, streamChunkBytes) + var err error + for { + n, readErr := s.body.Read(buf) + if n > 0 { + s.mu.Lock() + at := s.have + s.mu.Unlock() + if _, err = s.file.WriteAt(buf[:n], at); err != nil { + break + } + s.mu.Lock() + s.have += int64(n) + s.cond.Broadcast() + s.mu.Unlock() + } + if readErr != nil { + if !errors.Is(readErr, io.EOF) { + err = readErr + } + break + } + } + s.body.Close() + s.mu.Lock() + s.done, s.err = true, err + if err == nil && s.size < 0 { + s.size = s.have + } + if err == nil && s.size >= 0 && s.have != s.size { + s.err = fmt.Errorf("media: %s ended at %d of %d bytes", url, s.have, s.size) + } + ok := s.err == nil + s.cond.Broadcast() + s.mu.Unlock() + if ok { + d.Adopt(url, s.file.Name()) + } +} + +func (s *download) fetchTail(url string, d Downloader) { + at := s.size - streamTailBytes + data, err := d.ReadRange(context.Background(), url, at, streamTailBytes) + if err != nil || int64(len(data)) != streamTailBytes { + return // reads of the end wait for the download, as with a host that has no ranges + } + s.mu.Lock() + s.tail, s.tailAt = data, at + s.cond.Broadcast() + s.mu.Unlock() +} + +// ReadAt answers from the written start or the fetched end, and waits for the download otherwise. +func (s *download) ReadAt(p []byte, off int64) (int, error) { + end := off + int64(len(p)) + s.mu.Lock() + for { + switch { + case s.closed: + s.mu.Unlock() + return 0, ErrStreamClosed + case s.tail != nil && off >= s.tailAt: + n := copy(p, s.tail[off-s.tailAt:]) + s.mu.Unlock() + if n < len(p) { + return n, io.EOF + } + return n, nil + case end <= s.have || s.done: + failed := s.done && s.err != nil && end > s.have + err := s.err + s.mu.Unlock() + if failed { + return 0, err + } + return s.file.ReadAt(p, off) + } + s.cond.Wait() + } +} + +func (s *download) Size() int64 { + s.mu.Lock() + defer s.mu.Unlock() + return s.size +} + +// Path is the partial file once the download is complete, readable until Close. +func (s *download) Path() string { + s.mu.Lock() + defer s.mu.Unlock() + if s.done && s.err == nil { + return s.file.Name() + } + return "" +} + +// Close stops the download if it is still running and deletes the partial file; a complete one is already adopted. +func (s *download) Close() error { + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return nil + } + s.closed = true + s.cond.Broadcast() + s.mu.Unlock() + s.body.Close() + name := s.file.Name() + err := s.file.Close() + _ = os.Remove(name) + return err +} + +// openDownload starts a download of f, waiting for a free slot first. +func (s *RemoteSource) openDownload(d Downloader, f File) (Stream, error) { + select { + case s.slots <- struct{}{}: + case <-s.ctx.Done(): + return nil, s.ctx.Err() + } + release := func() { <-s.slots } + body, size, err := d.Open(s.ctx, string(f)) + if err != nil { + release() + if errors.Is(err, network.ErrAssetNotFound) { + return nil, fmt.Errorf("%w: %w", ErrAbsent, err) + } + return nil, err + } + file, err := d.PartialFile() + if err != nil { + body.Close() + release() + return nil, err + } + return newDownload(string(f), body, size, file, d, s.slots), nil +} + +// openStream opens f through a source that can, and wraps its bytes otherwise. +func openStream(source Source, f File) (Stream, error) { + if o, ok := source.(Opener); ok { + return o.Open(f) + } + return wholeStream(source.Data(f)) +} + +// wholeStream wraps a source's answer of whole bytes. +func wholeStream(data []byte, err error) (Stream, error) { + if err != nil { + return nil, err + } + return BytesStream(data), nil +} diff --git a/internal/media/stream_test.go b/internal/media/stream_test.go new file mode 100644 index 00000000..abbbea97 --- /dev/null +++ b/internal/media/stream_test.go @@ -0,0 +1,204 @@ +package media + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "testing" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +const ( + streamTestURL = testOrigin + "sounds/music/a.opus" + streamTestStart = 1000 + streamTestQuiet = 50 * time.Millisecond + streamTestWait = 5 * time.Second +) + +// streamTestTrack is long enough that its end is fetched apart. +var streamTestTrack = bytes.Repeat([]byte("opus-page-bytes!"), 3*streamTailBytes/len("opus-page-bytes!")) + +// fakeDownloader serves one track whose body the test writes by hand. +type fakeDownloader struct { + dir string + body *io.PipeReader + write *io.PipeWriter + ranges bool + missing bool + adopted chan string +} + +func newFakeDownloader(t *testing.T, ranges bool) *fakeDownloader { + r, w := io.Pipe() + t.Cleanup(func() { w.Close() }) + return &fakeDownloader{dir: t.TempDir(), body: r, write: w, ranges: ranges, adopted: make(chan string, 1)} +} + +func (d *fakeDownloader) Fetch(context.Context, string) ([]byte, error) { return streamTestTrack, nil } + +func (d *fakeDownloader) Open(_ context.Context, url string) (io.ReadCloser, int64, error) { + if d.missing { + return nil, 0, fmt.Errorf("%w: %s", network.ErrAssetNotFound, url) + } + return d.body, int64(len(streamTestTrack)), nil +} + +func (d *fakeDownloader) ReadRange(_ context.Context, _ string, from, n int64) ([]byte, error) { + if !d.ranges { + return nil, network.ErrNoRanges + } + return streamTestTrack[from : from+n], nil +} + +func (d *fakeDownloader) PartialFile() (*os.File, error) { return os.CreateTemp(d.dir, "*.tmp") } +func (d *fakeDownloader) Adopt(_, path string) { d.adopted <- path } + +// send writes part of the body from a goroutine, as the pipe blocks until the download reads it. +func (d *fakeDownloader) send(part []byte, last bool) { + go func() { + _, _ = d.write.Write(part) + if last { + d.write.Close() + } + }() +} + +func openTestStream(t *testing.T, d *fakeDownloader) Stream { + t.Helper() + st, err := NewRemoteSource(context.Background(), d, testShortTTL, time.Now).Open(File(streamTestURL)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + return st +} + +// readWithin reads at off, failing the test if the read doesn't return within wait. +func readWithin(t *testing.T, st Stream, off int64, n int, wait time.Duration) ([]byte, bool) { + t.Helper() + got := make(chan []byte, 1) + go func() { + p := make([]byte, n) + k, _ := st.ReadAt(p, off) + got <- p[:k] + }() + select { + case p := <-got: + return p, true + case <-time.After(wait): + return nil, false + } +} + +func TestADownloadReadsItsStartBeforeItEnds(t *testing.T) { + d := newFakeDownloader(t, false) + st := openTestStream(t, d) + d.send(streamTestTrack[:streamTestStart], false) + p, ok := readWithin(t, st, 0, streamTestStart, streamTestWait) + if !ok || !bytes.Equal(p, streamTestTrack[:streamTestStart]) { + t.Fatalf("read %d bytes of the start, ok %v", len(p), ok) + } + if st.Path() != "" { + t.Fatal("an unfinished download names a complete file") + } +} + +func TestADownloadAnswersItsEndFromARange(t *testing.T) { + d := newFakeDownloader(t, true) + st := openTestStream(t, d) + off := int64(len(streamTestTrack) - streamTestStart) + p, ok := readWithin(t, st, off, streamTestStart, streamTestWait) + if !ok || !bytes.Equal(p, streamTestTrack[off:]) { + t.Fatalf("read %d bytes of the end before the download reached it, ok %v", len(p), ok) + } +} + +func TestWithoutRangesTheEndWaitsForTheDownload(t *testing.T) { + d := newFakeDownloader(t, false) + st := openTestStream(t, d) + off := int64(len(streamTestTrack) - streamTestStart) + got := make(chan []byte, 1) + go func() { + p := make([]byte, streamTestStart) + k, _ := st.ReadAt(p, off) + got <- p[:k] + }() + select { + case <-got: + t.Fatal("the end read returned before the download reached it") + case <-time.After(streamTestQuiet): + } + d.send(streamTestTrack, true) + select { + case p := <-got: + if !bytes.Equal(p, streamTestTrack[off:]) { + t.Fatalf("read %d wrong bytes", len(p)) + } + case <-time.After(streamTestWait): + t.Fatal("the end read never returned") + } +} + +func TestAFinishedDownloadIsAdopted(t *testing.T) { + d := newFakeDownloader(t, false) + st := openTestStream(t, d) + d.send(streamTestTrack, true) + select { + case path := <-d.adopted: + if st.Path() != path { + t.Fatalf("Path %q, adopted %q", st.Path(), path) + } + data, err := os.ReadFile(path) + if err != nil || !bytes.Equal(data, streamTestTrack) { + t.Fatalf("adopted file differs: %v", err) + } + case <-time.After(streamTestWait): + t.Fatal("a finished download was never adopted") + } +} + +func TestClosingStopsADownloadAndDeletesIt(t *testing.T) { + d := newFakeDownloader(t, false) + st := openTestStream(t, d) + d.send(streamTestTrack[:streamTestStart], false) + if _, ok := readWithin(t, st, 0, streamTestStart, streamTestWait); !ok { + t.Fatal("the start never arrived") + } + if err := st.Close(); err != nil { + t.Fatal(err) + } + if _, err := st.ReadAt(make([]byte, 1), 0); !errors.Is(err, ErrStreamClosed) { + t.Fatalf("read after close: %v", err) + } + if left, _ := os.ReadDir(d.dir); len(left) != 0 { + t.Fatalf("partial files left: %v", left) + } +} + +func TestAMissingTrackIsAbsent(t *testing.T) { + d := newFakeDownloader(t, false) + d.missing = true + if _, err := NewRemoteSource(context.Background(), d, testShortTTL, time.Now).Open(File(streamTestURL)); !IsAbsent(err) { + t.Fatalf("err %v, want absent", err) + } +} + +func TestAStreamKeyIsReadyWithAStream(t *testing.T) { + r := newRemoteRig(t, map[string][]byte{streamTestURL: streamTestTrack}) + a := r.m.Get(Key{Place: PlaceServer, Path: streamTestURL, Kind: KindStream, Class: ClassExact}, Now, 0) + waitFinal(t, a) + st, ok := a.Result().(Stream) + if !a.Ready() || !ok { + t.Fatalf("state %v, result %T", a.State(), a.Result()) + } + defer st.Close() + p := make([]byte, streamTestStart) + if _, err := st.ReadAt(p, 0); err != nil || !bytes.Equal(p, streamTestTrack[:streamTestStart]) { + t.Fatalf("stream reads %v", err) + } +} diff --git a/internal/media/types.go b/internal/media/types.go index 850227df..1b78309e 100644 --- a/internal/media/types.go +++ b/internal/media/types.go @@ -26,6 +26,8 @@ const ( KindListing KindRaw KindFont + // KindStream is a file read as it arrives, such as a music track: the result is a Stream, never the bytes. + KindStream ) // Class says which formats a file may have; ClassExact means its path already names one file. diff --git a/internal/mix/decoder.go b/internal/mix/decoder.go new file mode 100644 index 00000000..1b606dc3 --- /dev/null +++ b/internal/mix/decoder.go @@ -0,0 +1,174 @@ +package mix + +/* +#include +#include + +SDL_IOStream *asyncaoOpenIO(uintptr_t handle); +*/ +import "C" + +import ( + "errors" + "io" + "runtime/cgo" + "unsafe" +) + +const bytesPerSample = 4 // float32 + +// Reader is what a Decoder reads: a file read at offsets, which may still be arriving, so ReadAt may wait. +type Reader interface { + ReadAt(p []byte, off int64) (int, error) + // Size is the file's length, or -1 while it isn't known. + Size() int64 +} + +// reading is a Reader with the position SDL's stream keeps. +type reading struct { + r Reader + pos int64 +} + +//export asyncaoIOSize +func asyncaoIOSize(h C.uintptr_t) C.Sint64 { + return C.Sint64(cgo.Handle(h).Value().(*reading).r.Size()) +} + +//export asyncaoIOSeek +func asyncaoIOSeek(h C.uintptr_t, offset C.Sint64, whence C.int) C.Sint64 { + s := cgo.Handle(h).Value().(*reading) + to := int64(offset) + switch whence { + case C.SDL_IO_SEEK_CUR: + to += s.pos + case C.SDL_IO_SEEK_END: + size := s.r.Size() + if size < 0 { + return -1 + } + to += size + } + if to < 0 { + return -1 + } + s.pos = to + return C.Sint64(to) +} + +//export asyncaoIORead +func asyncaoIORead(h C.uintptr_t, ptr unsafe.Pointer, size C.size_t, status *C.SDL_IOStatus) C.size_t { + s := cgo.Handle(h).Value().(*reading) + p := unsafe.Slice((*byte)(ptr), int(size)) + n, err := s.r.ReadAt(p, s.pos) + s.pos += int64(n) + switch { + case errors.Is(err, io.EOF): + *status = C.SDL_IO_STATUS_EOF + case err != nil: + *status = C.SDL_IO_STATUS_ERROR + } + return C.size_t(n) +} + +//export asyncaoIOClose +func asyncaoIOClose(h C.uintptr_t) { cgo.Handle(h).Delete() } + +// Decoder turns a file into float samples on whatever thread calls it; SDL documents its calls as thread-safe. +type Decoder struct { + c *C.MIX_AudioDecoder + rate int + channels int +} + +// NewDecoder opens r, reading what the format's header needs; the Decoder reads r until Destroy. +func NewDecoder(r Reader) (*Decoder, error) { + h := cgo.NewHandle(&reading{r: r}) + stream := C.asyncaoOpenIO(C.uintptr_t(h)) + if stream == nil { + h.Delete() + return nil, failed() + } + dec := C.MIX_CreateAudioDecoder_IO(stream, true, 0) // closes stream, and so the handle, on failure too + if dec == nil { + return nil, failed() + } + var spec C.SDL_AudioSpec + if !C.MIX_GetAudioDecoderFormat(dec, &spec) { + C.MIX_DestroyAudioDecoder(dec) + return nil, failed() + } + return &Decoder{c: dec, rate: int(spec.freq), channels: int(spec.channels)}, nil +} + +// Rate is the file's sample rate. +func (d *Decoder) Rate() int { return d.rate } + +// Channels is the file's channel count; samples interleave them. +func (d *Decoder) Channels() int { return d.channels } + +// Decode fills out with interleaved samples at the file's rate and returns how many it wrote; io.EOF ends the file. +func (d *Decoder) Decode(out []float32) (int, error) { + if len(out) == 0 { + return 0, nil + } + spec := C.SDL_AudioSpec{format: C.SDL_AUDIO_F32, channels: C.int(d.channels), freq: C.int(d.rate)} + n := C.MIX_DecodeAudio(d.c, unsafe.Pointer(&out[0]), C.int(len(out)*bytesPerSample), &spec) + switch { + case n < 0: + return 0, failed() + case n == 0: + return 0, io.EOF + } + return int(n) / bytesPerSample, nil +} + +// Destroy frees the decoder and stops it reading. +func (d *Decoder) Destroy() { C.MIX_DestroyAudioDecoder(d.c) } + +// Stream is an SDL audio stream a track plays from: samples put into it are mixed as the track asks for them. +type Stream C.SDL_AudioStream + +func (s *Stream) c() *C.SDL_AudioStream { return (*C.SDL_AudioStream)(s) } + +// NewStream takes interleaved float samples at rate and converts them to the mixer's format. +func (m *Mixer) NewStream(rate, channels int) (*Stream, error) { + var out C.SDL_AudioSpec + if !C.MIX_GetMixerFormat(m.c(), &out) { + return nil, failed() + } + in := C.SDL_AudioSpec{format: C.SDL_AUDIO_F32, channels: C.int(channels), freq: C.int(rate)} + s := C.SDL_CreateAudioStream(&in, &out) + if s == nil { + return nil, failed() + } + return (*Stream)(s), nil +} + +// Put queues samples; SDL copies them, from any thread. +func (s *Stream) Put(samples []float32) error { + if len(samples) == 0 { + return nil + } + if !C.SDL_PutAudioStreamData(s.c(), unsafe.Pointer(&samples[0]), C.int(len(samples)*bytesPerSample)) { + return failed() + } + return nil +} + +// Queued is how many samples are put but not yet played. +func (s *Stream) Queued() int { return int(C.SDL_GetAudioStreamQueued(s.c())) / bytesPerSample } + +// Flush marks the end of what will be put, so the last samples play out. +func (s *Stream) Flush() { C.SDL_FlushAudioStream(s.c()) } + +// Destroy frees the stream; take it off its track first. +func (s *Stream) Destroy() { C.SDL_DestroyAudioStream(s.c()) } + +// SetStream puts a stream on the track in place of a sound; nil takes it off. +func (t *Track) SetStream(s *Stream) error { + if !C.MIX_SetTrackAudioStream(t.c(), s.c()) { + return failed() + } + return nil +} diff --git a/internal/mix/decoder_test.go b/internal/mix/decoder_test.go new file mode 100644 index 00000000..343f71e3 --- /dev/null +++ b/internal/mix/decoder_test.go @@ -0,0 +1,148 @@ +package mix + +import ( + "bytes" + "io" + "testing" +) + +const ( + decoderTestSec = 0.5 + // decoderTestChunk is how many samples one Decode call asks for. + decoderTestChunk = 256 + // streamTestDrainChunks bounds the mixing a drained stream track gets to stop in. + streamTestDrainChunks = 40 +) + +// byteReader is a Reader over a whole file. +type byteReader struct{ *bytes.Reader } + +func (r byteReader) Size() int64 { return r.Reader.Size() } + +func decodeAll(t *testing.T, d *Decoder) []float32 { + t.Helper() + var all []float32 + buf := make([]float32, decoderTestChunk) + for { + n, err := d.Decode(buf) + all = append(all, buf[:n]...) + if err == io.EOF { + return all + } + if err != nil { + t.Fatal(err) + } + } +} + +func TestDecoderReadsAWholeFileThroughAReader(t *testing.T) { + headless(t) + d, err := NewDecoder(byteReader{bytes.NewReader(silentWAV(t, decoderTestSec))}) + if err != nil { + t.Fatal(err) + } + defer d.Destroy() + if d.Rate() != testRate || d.Channels() != testChannels { + t.Fatalf("format %d Hz x%d, want %d Hz x%d", d.Rate(), d.Channels(), testRate, testChannels) + } + if got, want := len(decodeAll(t, d)), int(decoderTestSec*testRate)*testChannels; got != want { + t.Fatalf("decoded %d samples, want %d", got, want) + } +} + +func TestDecoderRefusesWhatIsNotAudio(t *testing.T) { + headless(t) + if _, err := NewDecoder(byteReader{bytes.NewReader([]byte("not a sound file at all"))}); err == nil { + t.Fatal("a text file opened as audio") + } +} + +func TestAStreamTrackPlaysWhatIsPutAndStopsWhenDrained(t *testing.T) { + m := headless(t) + s, err := m.NewStream(testRate, testChannels) + if err != nil { + t.Fatal(err) + } + tr, err := m.NewTrack() + if err != nil { + t.Fatal(err) + } + defer tr.Destroy() + defer s.Destroy() + if err := tr.SetStream(s); err != nil { + t.Fatal(err) + } + samples := make([]float32, testChunkFrames*testChannels) + if err := s.Put(samples); err != nil { + t.Fatal(err) + } + if s.Queued() != len(samples) { + t.Fatalf("queued %d, want %d", s.Queued(), len(samples)) + } + if err := tr.PlayStream(0); err != nil { + t.Fatal(err) + } + out := make([]float32, testChunkFrames*testChannels) + if err := m.Generate(out); err != nil { + t.Fatal(err) + } + if s.Queued() >= len(samples) { + t.Fatalf("still %d queued after mixing", s.Queued()) + } + s.Flush() + for range streamTestDrainChunks { + if !tr.Playing() { + return + } + if err := m.Generate(out); err != nil { + t.Fatal(err) + } + } + t.Fatal("a flushed, drained stream track kept playing") +} + +// SDL3_mixer ends a stream track whose stream runs dry, flushed or not; the music player restarts it once more arrives. +func TestAStreamTrackStopsOnAnUnderrunAndResumes(t *testing.T) { + m := headless(t) + s, err := m.NewStream(testRate, testChannels) + if err != nil { + t.Fatal(err) + } + tr, err := m.NewTrack() + if err != nil { + t.Fatal(err) + } + defer tr.Destroy() + defer s.Destroy() + if err := tr.SetStream(s); err != nil { + t.Fatal(err) + } + samples := make([]float32, testChunkFrames*testChannels) + if err := s.Put(samples); err != nil { + t.Fatal(err) + } + if err := tr.PlayStream(0); err != nil { + t.Fatal(err) + } + out := make([]float32, testChunkFrames*testChannels) + for range streamTestDrainChunks { + if err := m.Generate(out); err != nil { + t.Fatal(err) + } + } + if tr.Playing() { + t.Fatal("a dry stream kept its track playing; the restart is no longer needed") + } + if err := s.Put(samples); err != nil { + t.Fatal(err) + } + if err := tr.PlayStream(0); err != nil { + t.Fatal(err) + } + if err := m.Generate(out); err != nil { + t.Fatal(err) + } + if !tr.Playing() || s.Queued() >= len(samples) { + t.Fatalf("restart did not resume: playing %v, queued %d", tr.Playing(), s.Queued()) + } +} diff --git a/internal/mix/iostream.c b/internal/mix/iostream.c new file mode 100644 index 00000000..3aecba3d --- /dev/null +++ b/internal/mix/iostream.c @@ -0,0 +1,28 @@ +// SDL_IOStream callbacks that read through a Go Reader; userdata is its cgo.Handle. +#include +#include "_cgo_export.h" + +static Sint64 SDLCALL ioSize(void *userdata) { return asyncaoIOSize((uintptr_t)userdata); } + +static Sint64 SDLCALL ioSeek(void *userdata, Sint64 offset, SDL_IOWhence whence) { + return asyncaoIOSeek((uintptr_t)userdata, offset, (int)whence); +} + +static size_t SDLCALL ioRead(void *userdata, void *ptr, size_t size, SDL_IOStatus *status) { + return asyncaoIORead((uintptr_t)userdata, ptr, size, status); +} + +static bool SDLCALL ioClose(void *userdata) { + asyncaoIOClose((uintptr_t)userdata); + return true; +} + +SDL_IOStream *asyncaoOpenIO(uintptr_t handle) { + SDL_IOStreamInterface iface; + SDL_INIT_INTERFACE(&iface); + iface.size = ioSize; + iface.seek = ioSeek; + iface.read = ioRead; + iface.close = ioClose; + return SDL_OpenIO(&iface, (void *)handle); +} diff --git a/internal/mix/mix.go b/internal/mix/mix.go index 3f641158..66610d32 100644 --- a/internal/mix/mix.go +++ b/internal/mix/mix.go @@ -1,5 +1,6 @@ // Package mix binds SDL3_mixer; positions convert at the Audio's sample rate, so loop points land on exact frames. -// Everything here runs on the main thread (hard rule 1). +// Mixers, sounds and tracks are driven from the main thread; a Decoder and a Stream may be fed from another, as SDL +// documents those calls thread-safe (hard rule 1). package mix /* @@ -137,6 +138,17 @@ func (m *Mixer) Load(data []byte, predecode bool) (*Audio, error) { return (*Audio)(a), nil } +// OpenFile opens a sound file that SDL_mixer reads from disk as it plays, for music too long to hold decoded. +func (m *Mixer) OpenFile(path string) (*Audio, error) { + cpath := C.CString(path) + defer C.free(unsafe.Pointer(cpath)) + a := C.MIX_LoadAudio(m.c(), cpath, false) + if a == nil { + return nil, failed() + } + return (*Audio)(a), nil +} + // LoadFile decodes a sound file completely. func (m *Mixer) LoadFile(path string) (*Audio, error) { cpath := C.CString(path) @@ -224,6 +236,14 @@ func (t *Track) Play(o PlayOptions) error { return nil } +// PlayStream starts a track whose input is a Stream, fading in over fadeInMs when > 0. +func (t *Track) PlayStream(fadeInMs int) error { + if !C.asyncaoPlay(t.c(), 0, 0, 0, 0, C.Sint64(fadeInMs)) { + return failed() + } + return nil +} + // Stop stops the track, fading out over fadeOutMs first when > 0. func (t *Track) Stop(fadeOutMs int) { C.MIX_StopTrack(t.c(), C.MIX_TrackMSToFrames(t.c(), C.Sint64(fadeOutMs))) diff --git a/internal/render/audio.go b/internal/render/audio.go index d8820a6f..4449d555 100644 --- a/internal/render/audio.go +++ b/internal/render/audio.go @@ -3,8 +3,10 @@ package render import ( "context" "encoding/binary" + "errors" "log" "math" + "slices" "time" "github.com/SyntaxNyah/AsyncAO/internal/assets" @@ -81,9 +83,13 @@ type Audio struct { // modBan/modKick/modMute are the built-in mod-action sounds, used when the user set no custom file. modBan, modKick, modMute *mix.Audio - // music is the live song, musicOld the one fading out; audio streams from its bytes, so they stay pinned. + // music is the live song, musicOld the one fading out. music musicSlot musicOld musicSlot + // fadeOldOnStart holds a crossfade's fade-out until a streamed song starts, so a slow download leaves no gap. + fadeOldOnStart bool + // retired are streams taken off their tracks whose decoders may still be finishing; Close waits for them. + retired []*musicStream musicURL string // the URL of the track currently playing ("" = none); makes PlayMusic // idempotent so a room rebuild re-seeding the same track doesn't restart it. musicLoop bool // whether the current stream loops forever; a non-looping (2.9 @@ -115,12 +121,29 @@ type Audio struct { blipScale int } +// musicSlot is one music track and the song on it: audio for a complete file SDL_mixer reads itself, or stream for one +// decoded as it downloads. src is the file either reads, open until the slot clears. type musicSlot struct { - track *mix.Track - audio *mix.Audio // nil = no song loaded - bytes []byte // the encoded song the audio streams from + track *mix.Track + audio *mix.Audio + stream *musicStream + src media.Stream + // attached, started and fadeInMs are a streamed song's: on its track, playing once, and its fade-in. + attached bool + started bool + fadeInMs int } +// loaded reports a song on the slot, playing or still buffering. +func (s *musicSlot) loaded() bool { return s.audio != nil || s.stream != nil } + +const ( + // retiredCap bounds the streams waiting to finish; each ends within moments of its file closing. + retiredCap = 8 + // retiredWait bounds Close's wait for each of them. + retiredWait = time.Second +) + const fullVolumePercent = 100 const msPerSecond = 1000 @@ -402,6 +425,15 @@ func (a *Audio) Close() { return } a.stopMusic() + // A decoder still inside SDL_mixer must finish before the mixer shuts down; each ends once its file is closed. + for _, ms := range a.retired { + select { + case <-ms.done: + case <-time.After(retiredWait): + log.Printf("render: a music decoder didn't stop within %v", retiredWait) + } + } + a.retired = nil for _, c := range a.chunks { c.Destroy() } @@ -425,6 +457,7 @@ func (a *Audio) Frame() { a.onAudioBytes(asset) default: a.stepLoopMeta() + a.stepMusicStream() a.expirePending() a.stepFadeOutOld() // reap the crossfade's old track once its native fade halts it a.reapFinishedMusic() // clear a naturally-ended one-shot so it's not seen as "still playing" @@ -437,26 +470,36 @@ func (a *Audio) Frame() { // A stopped callback would fire on the audio thread (hard rule 1). // Music never pauses and Play starts synchronously, so a stopped track with a song loaded has finished. func (a *Audio) reapFinishedMusic() { - if !a.enabled() || a.music.audio == nil || a.musicLoop || a.music.track.Playing() { + if !a.enabled() || !a.music.loaded() || a.musicLoop || a.music.track.Playing() { return // disabled, nothing loaded, a looper, or still rolling } + if ms := a.music.stream; ms != nil && (!ms.finished() || ms.queuedSec() > 0) { + return // still buffering, or waiting out a download that fell behind + } a.stopMusic() // natural end: free the finished song and clear musicURL so it can be re-triggered/re-fetched } func (a *Audio) onAudioBytes(asset assets.AudioAsset) { + p, wanted := a.pending[asset.Base] if !a.enabled() { delete(a.pending, asset.Base) - return + wanted = false } - p, wanted := a.pending[asset.Base] - if wanted && p.kind == pendingMusic { + if wanted && p.kind == pendingMusic && asset.Stream != nil { delete(a.pending, asset.Base) - a.startMusic(asset.Base, asset.Data, p.loop, p.effects, p.seekSec) // 2.9 loop/effects (#15) + cross-tab resume seek + a.startMusic(asset.Base, asset.Stream, p.loop, p.effects, p.seekSec) // 2.9 loop/effects (#15) + cross-tab resume seek return } - // Music with no pending entry outlived pendingPlayTTL or was purged; these bytes are discarded, so log it. - if asset.Type == assets.AssetTypeMusic { - log.Printf("render: late music dropped for %q (no pending entry)", asset.Base) + // Music with no pending entry outlived pendingPlayTTL or was purged, so its file is closed unplayed. + if asset.Stream != nil { + asset.Stream.Close() + if a.enabled() { + log.Printf("render: late music dropped for %q (no pending entry)", asset.Base) + } + return + } + if !a.enabled() { + return } chunk := a.loadChunk(asset.Base, asset.Data) if chunk == nil || !wanted { @@ -589,7 +632,7 @@ func (a *Audio) PlayMusic(url string, loop bool, effects int) { if !a.enabled() { return } - if url == a.musicURL && a.music.audio != nil { + if url == a.musicURL && a.music.loaded() { return // already playing this exact track — don't restart } // FADE_OUT: the old track plays on during the download, then startMusic fades it. @@ -601,7 +644,7 @@ func (a *Audio) PlayMusic(url string, loop bool, effects int) { effects&musicEffectSyncPos != 0) } var syncPosSec float64 - if a.music.audio != nil && a.musicURL != "" { + if a.music.loaded() && a.musicURL != "" { // SYNC_POS: read the old position before the new track overwrites it (aomusicplayer.cpp:132-136). if effects&musicEffectSyncPos != 0 { if pos, _, ok := a.MusicClock(); ok { @@ -637,7 +680,7 @@ func (a *Audio) StopMusic() { func (a *Audio) CurrentMusicURL() string { return a.musicURL } // MusicPlaying reports whether a track is loaded and rolling; render thread only. -func (a *Audio) MusicPlaying() bool { return a.enabled() && a.music.audio != nil } +func (a *Audio) MusicPlaying() bool { return a.enabled() && a.music.loaded() } // musicSwapSnap is an outgoing track's position, duration and read time; the resume adds elapsed and wraps. type musicSwapSnap struct { @@ -682,7 +725,7 @@ func (a *Audio) PlayMusicAt(url string, loop bool, effects int, seekSec float64) if !a.enabled() { return } - if url == a.musicURL && a.music.audio != nil { + if url == a.musicURL && a.music.loaded() { return // already this exact stream — never restart or re-seek a live track } a.purgePendingMusic(url) @@ -690,16 +733,17 @@ func (a *Audio) PlayMusicAt(url string, loop bool, effects int, seekSec float64) a.mgr.Media().Get(assets.ExactKey(url, assets.AssetTypeMusic), media.Now, 0) // AssetType: Music } -// startMusic decodes and plays a fetched track, following AO2's effects (aomusicplayer.cpp:24-160). -func (a *Audio) startMusic(url string, data []byte, loop bool, effects int, seekSec float64) { +// startMusic plays a fetched track, following AO2's effects (aomusicplayer.cpp:24-160): a complete file through +// SDL_mixer by path, one still downloading or held in memory through a musicStream. +func (a *Audio) startMusic(url string, src media.Stream, loop bool, effects int, seekSec float64) { // Read the outgoing track's position before stopMusic frees it; an unreadable clock records nothing. - if a.music.audio != nil && a.musicURL != "" && a.musicURL != url { + if a.music.loaded() && a.musicURL != "" && a.musicURL != url { if pos, dur, ok := a.MusicClock(); ok { a.recordSwapSnap(a.musicURL, pos, dur, time.Now()) } } // FADE_OUT with an audible old track: keep it on the other music track and fade it in parallel with the new song. - crossfade := effects&musicEffectFadeOut != 0 && a.music.audio != nil && a.musicVol > 0 + crossfade := effects&musicEffectFadeOut != 0 && a.music.loaded() && a.musicVol > 0 if effects != 0 { log.Printf("render: startMusic %q effects=0x%x crossfade=%v musicVol=%d seek=%.2fs", url, effects, crossfade, a.musicVol, seekSec) @@ -710,21 +754,52 @@ func (a *Audio) startMusic(url string, data []byte, loop bool, effects int, seek } else { a.stopMusic() // clears musicURL; set below only on a successful start } + fadeInMs := 0 + if effects&musicEffectFadeIn != 0 { + fadeInMs = musicFadeInMs // linear 1000ms ramp (AO2 FADE_IN) + } + if path := src.Path(); path != "" { + if !a.playMusicFile(url, path, loop, fadeInMs, seekSec) { + src.Close() + a.restoreOldMusic() + return + } + if crossfade { + // stepFadeOutOld unloads the old song once the fade has stopped its track. + a.musicOld.track.Stop(musicFadeOutMs) + } + } else { + var loopStart, loopEnd float64 + if loop { + if p, ok := a.loopPointsFor(url, 0, false, seekSec); ok { + loopStart, loopEnd = p.StartSec, p.EndSec + } + } + a.music.stream = newMusicStream(a.mixer, src, seekSec, loop, loopStart, loopEnd) + a.music.fadeInMs = fadeInMs + a.fadeOldOnStart = crossfade // stepMusicStream fades the old song once this one starts + } + a.music.src = src + if loop { + a.requestLoopMeta(url, src) + } + a.musicLoop = loop // remember loop-ness so reapFinishedMusic only reaps a finished one-shot + a.musicURL = url // now this exact track is playing — PlayMusic(url) becomes a no-op +} + +// playMusicFile plays a complete file through SDL_mixer, which reads it from disk as it plays. +func (a *Audio) playMusicFile(url, path string, loop bool, fadeInMs int, seekSec float64) bool { start := time.Now() - song, err := a.mixer.Load(data, false) // streamed: data stays pinned in the slot + song, err := a.mixer.OpenFile(path) a.noteLoad(time.Since(start)) if err != nil { log.Printf("render: music decode failed: %v", err) - a.restoreOldMusic() - return + return false } - opts := mix.PlayOptions{} + opts := mix.PlayOptions{FadeInMs: fadeInMs} if loop { opts.Loops = mix.LoopForever } - if effects&musicEffectFadeIn != 0 { - opts.FadeInMs = musicFadeInMs // linear 1000ms ramp (AO2 FADE_IN) - } durSec, haveDur := song.Duration() // Wrap by the real length: the ui's wall-clock fallback isn't wrapped and short loops land past the end. if seekSec > 0 && haveDur && durSec > 0 { @@ -740,50 +815,112 @@ func (a *Audio) startMusic(url string, data []byte, loop bool, effects int, seek if err := a.music.track.SetAudio(song); err != nil { log.Printf("render: music play failed: %v", err) song.Destroy() - a.restoreOldMusic() - return + return false } // Set the gain first so a fade-in climbs to the right ceiling. a.music.track.SetGain(gain(a.musicVol)) if err := a.music.track.Play(opts); err != nil { log.Printf("render: music play failed: %v", err) song.Destroy() - a.restoreOldMusic() + return false + } + a.music.audio = song + a.musicFadeInEnd = time.Now().Add(time.Duration(fadeInMs) * time.Millisecond) + return true +} + +// stepMusicStream attaches a streamed song once its header is read and starts it once enough is decoded; it restarts it +// the same way after the download fell behind, as SDL3_mixer ends a stream track that runs dry. Called every Frame. +func (a *Audio) stepMusicStream() { + s := &a.music + ms := s.stream + if ms == nil { return } - a.music.audio, a.music.bytes = song, data - a.musicFadeInEnd = time.Now().Add(time.Duration(opts.FadeInMs) * time.Millisecond) - if loop { - a.requestLoopMeta(url, data) + if err := ms.failure(); err != nil && !errors.Is(err, errMusicStopped) { + log.Printf("render: music stream for %q failed: %v", a.musicURL, err) + a.stopMusic() + return } - a.musicLoop = loop // remember loop-ness so reapFinishedMusic only reaps a finished one-shot - if crossfade { - // stepFadeOutOld unloads the old song once the fade has stopped its track. - a.musicOld.track.Stop(musicFadeOutMs) + out := ms.output() + if out == nil || s.track.Playing() { + return + } + if !s.attached { + if err := s.track.SetStream(out); err != nil { + log.Printf("render: music play failed: %v", err) + a.stopMusic() + return + } + s.track.SetGain(gain(a.musicVol)) + s.attached = true + } + queued := ms.queuedSec() + if queued < musicResumeSec && (!ms.finished() || queued == 0) { + return + } + fade := 0 + if !s.started { + fade, s.started = s.fadeInMs, true + a.musicFadeInEnd = time.Now().Add(time.Duration(fade) * time.Millisecond) + if a.fadeOldOnStart { + a.musicOld.track.Stop(musicFadeOutMs) + a.fadeOldOnStart = false + } + } + if err := s.track.PlayStream(fade); err != nil { + log.Printf("render: music play failed: %v", err) } - a.musicURL = url // now this exact track is playing — PlayMusic(url) becomes a no-op } +// clearSlot stops and frees a slot's song and closes its file; a stream's decoder finishes on its own goroutine. func (a *Audio) clearSlot(s *musicSlot) { - if s.audio == nil { + if !s.loaded() { return } s.track.Stop(0) - s.audio.Destroy() - s.audio, s.bytes = nil, nil + if s.stream != nil { + _ = s.track.SetStream(nil) + s.stream.close() + a.retire(s.stream) + } + if s.audio != nil { + s.audio.Destroy() + } + if s.src != nil { + s.src.Close() // after close: it ends a read still waiting on the download + } + *s = musicSlot{track: s.track} +} + +// retire keeps a closed stream until its decoder has finished, for Close to wait on. +func (a *Audio) retire(ms *musicStream) { + a.retired = slices.DeleteFunc(a.retired, func(r *musicStream) bool { + select { + case <-r.done: + return true + default: + return false + } + }) + if len(a.retired) == retiredCap { + a.retired = a.retired[1:] + } + a.retired = append(a.retired, ms) } func (a *Audio) stopMusic() { a.clearSlot(&a.music) a.clearSlot(&a.musicOld) // tear down an in-flight crossfade too (StopMusic mid-fade) - a.musicURL = "" // nothing playing now; a later PlayMusic of the same URL plays again + a.fadeOldOnStart = false + a.musicURL = "" // nothing playing now; a later PlayMusic of the same URL plays again // No song loaded; reset so a stale true can't skip a future reap. a.musicLoop = false } // restoreOldMusic makes a crossfade's old song live again after a failed load, so it doesn't drop out. func (a *Audio) restoreOldMusic() { - if a.musicOld.audio == nil { + if !a.musicOld.loaded() { return } a.music, a.musicOld = a.musicOld, a.music @@ -791,8 +928,8 @@ func (a *Audio) restoreOldMusic() { // stepFadeOutOld unloads a crossfade's old song once its track stops; called every Frame. func (a *Audio) stepFadeOutOld() { - if a.musicOld.audio == nil || a.musicOld.track.Playing() { - return // nothing fading, or the fade is still running + if !a.musicOld.loaded() || a.musicOld.track.Playing() || a.fadeOldOnStart { + return // nothing fading, the fade is still running, or it hasn't started yet } log.Printf("render: fade-out of old track complete") a.clearSlot(&a.musicOld) diff --git a/internal/render/audio_music_test.go b/internal/render/audio_music_test.go index 7334a32e..79746feb 100644 --- a/internal/render/audio_music_test.go +++ b/internal/render/audio_music_test.go @@ -2,9 +2,12 @@ package render import ( "fmt" + "os" + "path/filepath" "testing" "time" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/mix" ) @@ -31,16 +34,34 @@ func newTestAudio(t *testing.T) *Audio { if !a.enabled() { t.Fatal("a headless mixer must give an enabled Audio") } + // TempDir first: cleanups run last-in first-out, so Close lets go of a song's file before its folder is removed, + // which Windows refuses while the file is open. + t.TempDir() t.Cleanup(a.Close) return a } // testSong is sec seconds of silent mono WAV. -func testSong(sec float64) []byte { +// testSongWAV is a silent mono WAV of sec seconds. +func testSongWAV(sec float64) []byte { const bytesPerSample = 2 return wavMono16(make([]byte, int(sec*testSongRate)*bytesPerSample), testSongRate) } +// testSong is a complete song on disk, which plays through SDL_mixer by path. +func testSong(t *testing.T, sec float64) media.Stream { + t.Helper() + path := filepath.Join(t.TempDir(), "song.wav") + if err := os.WriteFile(path, testSongWAV(sec), 0o600); err != nil { + t.Fatal(err) + } + st, err := media.FileStream(path) + if err != nil { + t.Fatal(err) + } + return st +} + // mixFor advances the headless mixer by sec seconds. func mixFor(t *testing.T, a *Audio, sec float64) { t.Helper() @@ -63,8 +84,8 @@ func noLoopSidecar(a *Audio, url string) { func TestStopMusicClearsCrossfade(t *testing.T) { const songSec = 2.0 a := newTestAudio(t) - a.startMusic("http://cdn/a.opus", testSong(songSec), false, 0, 0) - a.startMusic("http://cdn/b.opus", testSong(songSec), false, testFadeOutFlag, 0) + a.startMusic("http://cdn/a.opus", testSong(t, songSec), false, 0, 0) + a.startMusic("http://cdn/b.opus", testSong(t, songSec), false, testFadeOutFlag, 0) if a.musicOld.audio == nil { t.Fatal("FADE_OUT with an audible song must keep the old song fading") } @@ -80,8 +101,8 @@ func TestFadeOutGatedOnVolume(t *testing.T) { const songSec = 2.0 a := newTestAudio(t) a.SetVolumes(0, fullVolumePercent, fullVolumePercent) - a.startMusic("http://cdn/a.opus", testSong(songSec), false, 0, 0) - a.startMusic("http://cdn/b.opus", testSong(songSec), false, testFadeOutFlag, 0) + a.startMusic("http://cdn/a.opus", testSong(t, songSec), false, 0, 0) + a.startMusic("http://cdn/b.opus", testSong(t, songSec), false, testFadeOutFlag, 0) if a.musicOld.audio != nil { t.Error("a silent music volume must not crossfade") } @@ -97,8 +118,8 @@ func TestCrossfadeOldSongReapedAfterFade(t *testing.T) { pastFadeSec = float64(musicFadeOutMs)/msPerSecond + testMixStepSec*2 ) a := newTestAudio(t) - a.startMusic("http://cdn/a.opus", testSong(songSec), false, 0, 0) - a.startMusic("http://cdn/b.opus", testSong(songSec), false, testFadeOutFlag, 0) + a.startMusic("http://cdn/a.opus", testSong(t, songSec), false, 0, 0) + a.startMusic("http://cdn/b.opus", testSong(t, songSec), false, testFadeOutFlag, 0) a.stepFadeOutOld() if a.musicOld.audio == nil { t.Fatal("the old song was unloaded before its fade ran") @@ -122,9 +143,9 @@ func TestTakeoverRecordsSwapSnapshot(t *testing.T) { tolerance = 0.1 ) a := newTestAudio(t) - a.startMusic("http://cdn/a.opus", testSong(songSec), false, 0, 0) + a.startMusic("http://cdn/a.opus", testSong(t, songSec), false, 0, 0) mixFor(t, a, playedSec) - a.startMusic("http://cdn/b.opus", testSong(songSec), false, 0, 0) + a.startMusic("http://cdn/b.opus", testSong(t, songSec), false, 0, 0) pos, dur, _, ok := a.SwappedOutSnap("http://cdn/a.opus") if !ok { t.Fatal("no snapshot recorded for the swapped-out song") @@ -142,7 +163,7 @@ func TestReapFinishedMusic(t *testing.T) { mixedSec = 1.0 ) a := newTestAudio(t) - a.startMusic("http://cdn/once.opus", testSong(songSec), false, 0, 0) + a.startMusic("http://cdn/once.opus", testSong(t, songSec), false, 0, 0) a.reapFinishedMusic() if !a.MusicPlaying() { t.Fatal("a song still playing was reaped") @@ -155,7 +176,7 @@ func TestReapFinishedMusic(t *testing.T) { const loopURL = "http://cdn/area.opus" noLoopSidecar(a, loopURL) - a.startMusic(loopURL, testSong(songSec), true, 0, 0) + a.startMusic(loopURL, testSong(t, songSec), true, 0, 0) mixFor(t, a, mixedSec) a.reapFinishedMusic() if !a.MusicPlaying() { @@ -183,7 +204,7 @@ func TestMusicClock(t *testing.T) { t.Error("a nil Audio must report MusicClock ok=false") } a := newTestAudio(t) - a.startMusic("http://cdn/a.opus", testSong(songSec), false, 0, 0) + a.startMusic("http://cdn/a.opus", testSong(t, songSec), false, 0, 0) mixFor(t, a, playedSec) pos, dur, ok := a.MusicClock() if !ok || pos < playedSec-tolerance || pos > playedSec+tolerance || dur < songSec-tolerance || dur > songSec+tolerance { @@ -200,7 +221,7 @@ func TestStartMusicWrapsSeek(t *testing.T) { tolerance = 0.1 ) a := newTestAudio(t) - a.startMusic("http://cdn/a.opus", testSong(songSec), false, 0, seekSec) + a.startMusic("http://cdn/a.opus", testSong(t, songSec), false, 0, seekSec) pos, _, ok := a.MusicClock() if !ok || pos < wantSec-tolerance || pos > wantSec+tolerance { t.Errorf("start position = %.2f (ok=%v), want ≈%.1f", pos, ok, wantSec) @@ -215,10 +236,10 @@ func TestChunkEvictionWhilePlaying(t *testing.T) { mixedSec = 0.2 ) a := newTestAudio(t) - first := a.loadChunk("sounds/general/first", testSong(soundSec)) + first := a.loadChunk("sounds/general/first", testSongWAV(soundSec)) a.playChunk(first, pendingSFX) for i := range chunkCacheMax { - a.loadChunk(fmt.Sprintf("sounds/general/%d", i), testSong(soundSec)) + a.loadChunk(fmt.Sprintf("sounds/general/%d", i), testSongWAV(soundSec)) } if a.HasChunk("sounds/general/first") { t.Fatal("the oldest sound must have been evicted") diff --git a/internal/render/audio_test.go b/internal/render/audio_test.go index 755685af..bdad5ab7 100644 --- a/internal/render/audio_test.go +++ b/internal/render/audio_test.go @@ -26,7 +26,7 @@ func TestPlayMusicAtIdempotent(t *testing.T) { } live := newTestAudio(t) - live.startMusic(url, testSong(songSec), false, 0, 0) + live.startMusic(url, testSong(t, songSec), false, 0, 0) if !live.MusicPlaying() { t.Fatal("MusicPlaying must be true with a song loaded") } @@ -50,7 +50,7 @@ func TestCurrentMusicURLReflectsLiveStream(t *testing.T) { if a.CurrentMusicURL() != "" || a.MusicPlaying() { t.Errorf("a fresh device must report no current music, got %q", a.CurrentMusicURL()) } - a.startMusic(foreign, testSong(songSec), false, 0, 0) + a.startMusic(foreign, testSong(t, songSec), false, 0, 0) if a.CurrentMusicURL() != foreign || !a.MusicPlaying() { t.Errorf("CurrentMusicURL = %q playing=%v, want the live song", a.CurrentMusicURL(), a.MusicPlaying()) } diff --git a/internal/render/musicclock.go b/internal/render/musicclock.go index 8a786cee..22dd1336 100644 --- a/internal/render/musicclock.go +++ b/internal/render/musicclock.go @@ -2,9 +2,12 @@ package render // MusicClock reports the live song's position and duration in seconds; ok is false when unknown. Render thread only. func (a *Audio) MusicClock() (posSec, durSec float64, ok bool) { - if a == nil || !a.enabled() || a.music.audio == nil { + if a == nil || !a.enabled() || !a.music.loaded() { return 0, 0, false // no device / no song: nothing to read } + if ms := a.music.stream; ms != nil { + return ms.clock() + } durSec, haveDur := a.music.audio.Duration() posSec, havePos := a.music.track.Position() return posSec, durSec, haveDur && havePos diff --git a/internal/render/musicloop.go b/internal/render/musicloop.go index 69c14b0a..dccc3665 100644 --- a/internal/render/musicloop.go +++ b/internal/render/musicloop.go @@ -7,6 +7,7 @@ import ( "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" + "github.com/SyntaxNyah/AsyncAO/internal/media" "github.com/SyntaxNyah/AsyncAO/internal/mix" ) @@ -22,6 +23,8 @@ const ( // loopFetchCap bounds concurrent sidecar fetches; past it a song plays without loop points. loopFetchCap = 4 + // loopHeaderBytes is read from a song's start to find its sample rate; it covers an MP3's ID3 tag in front. + loopHeaderBytes = 256 << 10 unknownDurationSec = -1.0 ) @@ -43,7 +46,7 @@ type loopMetaResult struct { } // requestLoopMeta fetches a looping song's sidecars in the background; stepLoopMeta applies them on arrival. -func (a *Audio) requestLoopMeta(url string, data []byte) { +func (a *Audio) requestLoopMeta(url string, src media.Stream) { if !courtroom.HasLoopSidecars(url) { return } @@ -55,7 +58,10 @@ func (a *Audio) requestLoopMeta(url string, data []byte) { } a.loopFetches[url] = struct{}{} go func() { - a.loopResults <- loopMetaResult{url: url, meta: fetchLoopMeta(a.loopFetchCtx, a.fetchSidecar, url, data)} + // The sample rate is in the header; a read of a stream closed meanwhile gives nothing, and 48 kHz is assumed. + head := make([]byte, loopHeaderBytes) + n, _ := src.ReadAt(head, 0) + a.loopResults <- loopMetaResult{url: url, meta: fetchLoopMeta(a.loopFetchCtx, a.fetchSidecar, url, head[:n])} a.wake() }() } @@ -84,10 +90,19 @@ func (a *Audio) rearmLoopPoints() { if url == "" { return } - if url != a.musicURL || !a.musicLoop || a.music.audio == nil { + if url != a.musicURL || !a.musicLoop || !a.music.loaded() { a.loopRearmURL = "" return } + // A streamed song's decoder reads the loop points at each chunk, so they apply without a restart. + if ms := a.music.stream; ms != nil { + a.loopRearmURL = "" + _, durSec, haveDur := ms.clock() + if points, ok := a.loopPointsFor(url, durSec, haveDur, 0); ok { + ms.setLoop(points.StartSec, points.EndSec) + } + return + } // Replaying during a fade-in would restart the ramp from silence. if time.Now().Before(a.musicFadeInEnd) { return diff --git a/internal/render/musicloop_arm_test.go b/internal/render/musicloop_arm_test.go index 50fca5ba..27df0bee 100644 --- a/internal/render/musicloop_arm_test.go +++ b/internal/render/musicloop_arm_test.go @@ -53,7 +53,7 @@ func newSidecarAudio(t *testing.T, sidecars *blockingSidecars) *Audio { // deliverSong requests a looping song and delivers its bytes, the way Frame does. func deliverSong(a *Audio, url string) { a.pending[url] = pendingPlay{kind: pendingMusic, deadline: time.Now().Add(pendingPlayTTL), loop: true} - a.onAudioBytes(assets.AudioAsset{Base: url, Data: testSong(loopSongSec), Type: assets.AssetTypeMusic}) + a.onAudioBytes(assets.AudioAsset{Base: url, Stream: testSong(t, loopSongSec), Type: assets.AssetTypeMusic}) } // collectFetches steps until every sidecar fetch has reported back. diff --git a/internal/render/musicstream.go b/internal/render/musicstream.go new file mode 100644 index 00000000..b1086df9 --- /dev/null +++ b/internal/render/musicstream.go @@ -0,0 +1,260 @@ +package render + +import ( + "errors" + "io" + "sync" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/media" + "github.com/SyntaxNyah/AsyncAO/internal/mix" +) + +const ( + // musicAheadSec is how far decoding runs ahead of playback; it also covers a download's short stalls. + musicAheadSec = 2 + // musicResumeSec is what must be queued before a track starts, or restarts after the download fell behind. + musicResumeSec = 0.5 + // musicChunkSamples is how much one decode call produces. + musicChunkSamples = 8192 + // musicWaitStep is how long the decoder sleeps while far enough ahead. + musicWaitStep = 20 * time.Millisecond + // musicPassesCap bounds the loop passes the clock remembers: only those still queued matter. + musicPassesCap = 8 +) + +var errMusicFormatChanged = errors.New("render: a looped track came back in another format") + +// musicPass is where one pass through the file starts: at sample at of the stream, from second from of the file. +type musicPass struct { + at int64 + from float64 +} + +// musicStream plays a track from a media.Stream that may still be downloading: one goroutine decodes it ahead of +// playback into an SDL audio stream, and reopens the decoder at each loop, so loops stay gapless. The goroutine owns +// the SDL stream and frees it once close is called; the render thread attaches it to a track and reads the clock. +type musicStream struct { + src media.Stream + stop chan struct{} + done chan struct{} + + mu sync.Mutex + out *mix.Stream + rate int + channels int + loop bool + // loopStart and loopEnd are seconds into the file; loopEnd 0 loops at the file's end. + loopStart, loopEnd float64 + pushed int64 + passes []musicPass + durSec float64 + ended bool + err error +} + +// newMusicStream starts decoding src from startSec; loop repeats it from loopStart, cut at loopEnd when set. +func newMusicStream(m *mix.Mixer, src media.Stream, startSec float64, loop bool, loopStart, loopEnd float64) *musicStream { + s := &musicStream{src: src, stop: make(chan struct{}), done: make(chan struct{}), loop: loop, + loopStart: loopStart, loopEnd: loopEnd} + go s.run(m, startSec) + return s +} + +// close stops the decoder; the caller has taken the stream off its track first and closes src after. +func (s *musicStream) close() { close(s.stop) } + +// output is the SDL stream to attach, nil until the file's header is read. +func (s *musicStream) output() *mix.Stream { + s.mu.Lock() + defer s.mu.Unlock() + return s.out +} + +// failure is why decoding stopped early, or nil. +func (s *musicStream) failure() error { + s.mu.Lock() + defer s.mu.Unlock() + return s.err +} + +// finished reports a one-shot track decoded to its end, so an empty stream means it has played out. +func (s *musicStream) finished() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.ended +} + +// queuedSec is how much is decoded but not yet played. +func (s *musicStream) queuedSec() float64 { + s.mu.Lock() + out, rate, ch := s.out, s.rate, s.channels + s.mu.Unlock() + if out == nil || rate == 0 || ch == 0 { + return 0 + } + return float64(out.Queued()) / float64(rate*ch) +} + +// setLoop changes the loop points; the decoder reads them at each chunk, so they apply from the current pass. +func (s *musicStream) setLoop(start, end float64) { + s.mu.Lock() + s.loopStart, s.loopEnd = start, end + s.mu.Unlock() +} + +// clock is the position played in the file, and its length once a pass from the start has reached the end. +func (s *musicStream) clock() (posSec, durSec float64, ok bool) { + s.mu.Lock() + defer s.mu.Unlock() + if s.out == nil || s.rate == 0 || len(s.passes) == 0 { + return 0, 0, false + } + played := s.pushed - int64(s.out.Queued()) + p := s.passes[0] + for _, q := range s.passes { + if q.at <= played { + p = q + } + } + posSec = p.from + float64(played-p.at)/float64(s.rate*s.channels) + return posSec, s.durSec, s.durSec > 0 +} + +func (s *musicStream) run(m *mix.Mixer, startSec float64) { + defer close(s.done) + from := startSec + for first := true; ; first = false { + dec, err := mix.NewDecoder(s.src) + if err == nil && first { + err = s.open(m, dec) + } else if err == nil && (dec.Rate() != s.rate || dec.Channels() != s.channels) { + err = errMusicFormatChanged + } + if err != nil { + if dec != nil { + dec.Destroy() + } + s.finish(err) + return + } + natural, err := s.pass(dec, from) + dec.Destroy() + if err != nil { + s.finish(err) + return + } + s.mu.Lock() + loop, start, end := s.loop, s.loopStart, s.loopEnd + if natural && from == 0 && end == 0 && s.durSec == 0 { + s.durSec = float64(s.pushed-s.passes[len(s.passes)-1].at) / float64(s.rate*s.channels) + } + s.mu.Unlock() + if !loop { + s.out.Flush() + s.finish(nil) + return + } + from = start + } +} + +// open creates the SDL stream once the first decoder knows the file's format. +func (s *musicStream) open(m *mix.Mixer, dec *mix.Decoder) error { + out, err := m.NewStream(dec.Rate(), dec.Channels()) + if err != nil { + return err + } + s.mu.Lock() + s.out, s.rate, s.channels = out, dec.Rate(), dec.Channels() + s.mu.Unlock() + return nil +} + +// finish records why decoding ended and waits for close, so the SDL stream outlives every queued sample. +func (s *musicStream) finish(err error) { + s.mu.Lock() + s.ended, s.err = true, err + out := s.out + s.mu.Unlock() + <-s.stop + if out != nil { + out.Destroy() + } +} + +// pass decodes one run through the file from second from, skipping what comes before it, until the end or the loop +// end; natural reports that it reached the file's end. +func (s *musicStream) pass(dec *mix.Decoder, from float64) (natural bool, err error) { + ch := int64(s.channels) + skip := int64(from*float64(s.rate)) * ch + ahead := int(musicAheadSec * float64(s.rate) * float64(ch)) + buf := make([]float32, musicChunkSamples*ch) + var at int64 // samples decoded from the file's start + marked := false + for { + select { + case <-s.stop: + return false, errMusicStopped + default: + } + n, derr := dec.Decode(buf) + if derr != nil && !errors.Is(derr, io.EOF) { + return false, derr + } + chunk := buf[:n] + if at < skip { + drop := min(int64(n), skip-at) + chunk = chunk[drop:] + } + s.mu.Lock() + end := int64(0) + if s.loop && s.loopEnd > 0 { + end = int64(s.loopEnd*float64(s.rate)) * ch + } + s.mu.Unlock() + cut := end > 0 && at+int64(n) >= end + if cut { + chunk = chunk[:max(0, len(chunk)-int(at+int64(n)-end))] + } + if len(chunk) > 0 { + if !s.waitRoom(ahead) { + return false, errMusicStopped + } + s.mu.Lock() + if !marked { + if len(s.passes) == musicPassesCap { + s.passes = append(s.passes[:0], s.passes[1:]...) + } + s.passes = append(s.passes, musicPass{at: s.pushed, from: from}) + marked = true + } + s.pushed += int64(len(chunk)) + s.mu.Unlock() + if err := s.out.Put(chunk); err != nil { + return false, err + } + } + at += int64(n) + if cut { + return false, nil + } + if errors.Is(derr, io.EOF) { + return true, nil + } + } +} + +var errMusicStopped = errors.New("render: music stopped") + +// waitRoom sleeps while ahead samples are already queued; false means the track was stopped. +func (s *musicStream) waitRoom(ahead int) bool { + for s.out.Queued() > ahead { + select { + case <-s.stop: + return false + case <-time.After(musicWaitStep): + } + } + return true +} diff --git a/internal/render/musicstream_test.go b/internal/render/musicstream_test.go new file mode 100644 index 00000000..b2fe0a3a --- /dev/null +++ b/internal/render/musicstream_test.go @@ -0,0 +1,136 @@ +package render + +import ( + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/media" +) + +const ( + streamTestSongSec = 1.0 + streamTestStepSec = 0.05 + streamTestWait = 10 * time.Second + // streamTestHeldBytes is the part of the file a held stream lets through: the header and a little audio. + streamTestHeldBytes = 2048 + // streamTestAll lets every byte through. + streamTestAll = 1 << 62 +) + +// heldStream is a file still arriving: reads past open wait until release, and a closed one stops waiting. +type heldStream struct { + media.Stream + open atomic.Int64 + gate chan struct{} + stopped chan struct{} + once sync.Once + closed atomic.Bool +} + +func newHeldStream(data []byte, open int64) *heldStream { + s := &heldStream{Stream: media.BytesStream(data), gate: make(chan struct{}), stopped: make(chan struct{})} + s.open.Store(open) + return s +} + +func (s *heldStream) ReadAt(p []byte, off int64) (int, error) { + if off+int64(len(p)) > s.open.Load() { + select { + case <-s.gate: + case <-s.stopped: + return 0, media.ErrStreamClosed + } + } + return s.Stream.ReadAt(p, off) +} + +func (s *heldStream) release() { s.open.Store(streamTestAll); close(s.gate) } + +func (s *heldStream) Close() error { + s.closed.Store(true) + s.once.Do(func() { close(s.stopped) }) + return nil +} + +// playUntil mixes and steps the music until done holds, failing the test after streamTestWait. +func playUntil(t *testing.T, a *Audio, what string, done func() bool) { + t.Helper() + deadline := time.Now().Add(streamTestWait) + for !done() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting until %s", what) + } + a.stepMusicStream() + a.reapFinishedMusic() + mixFor(t, a, streamTestStepSec) + time.Sleep(time.Millisecond) + } +} + +func TestAStreamedSongPlaysToItsEnd(t *testing.T) { + a := newTestAudio(t) + src := newHeldStream(testSongWAV(streamTestSongSec), streamTestAll) + a.startMusic("http://cdn/once.wav", src, false, 0, 0) + playUntil(t, a, "it starts", func() bool { return a.music.track.Playing() }) + playUntil(t, a, "it ends and its slot clears", func() bool { return !a.MusicPlaying() }) + if !src.closed.Load() { + t.Fatal("the finished song's file was left open") + } +} + +func TestAStreamedLoopKeepsPlayingAndLearnsItsLength(t *testing.T) { + const passes = 2.5 + a := newTestAudio(t) + url := "http://cdn/loop.wav" + noLoopSidecar(a, url) + a.startMusic(url, newHeldStream(testSongWAV(streamTestSongSec), streamTestAll), true, 0, 0) + playUntil(t, a, "it starts", func() bool { return a.music.track.Playing() }) + playUntil(t, a, "it has played past its own length", func() bool { return a.clockPasses() >= passes }) + pos, dur, _ := a.MusicClock() + if !a.MusicPlaying() || dur < streamTestSongSec-streamTestStepSec || pos > dur { + t.Fatalf("playing %v at %.2fs of %.2fs; want it still playing, wrapped inside a %.1fs song", a.MusicPlaying(), pos, dur, streamTestSongSec) + } +} + +// clockPasses is how many song lengths the music track has played, from what the stream pushed and still holds. +func (a *Audio) clockPasses() float64 { + ms := a.music.stream + ms.mu.Lock() + defer ms.mu.Unlock() + if ms.out == nil || ms.rate == 0 { + return 0 + } + played := ms.pushed - int64(ms.out.Queued()) + return float64(played) / float64(ms.rate*ms.channels) / streamTestSongSec +} + +func TestAStreamedSongRestartsAfterTheDownloadCatchesUp(t *testing.T) { + a := newTestAudio(t) + src := newHeldStream(testSongWAV(streamTestSongSec), streamTestHeldBytes) + a.startMusic("http://cdn/slow.wav", src, false, 0, 0) + time.Sleep(time.Duration(streamTestStepSec * float64(time.Second))) + for range int(musicResumeSec/streamTestStepSec) + 1 { + a.stepMusicStream() + mixFor(t, a, streamTestStepSec) + } + if a.music.track.Playing() { + t.Fatal("a song started before enough of it had arrived") + } + if !a.MusicPlaying() { + t.Fatal("a song still downloading was dropped") + } + src.release() + playUntil(t, a, "it plays once the rest arrives", func() bool { return a.music.track.Playing() }) +} + +func TestStoppingAStreamedSongClosesItsFile(t *testing.T) { + a := newTestAudio(t) + src := newHeldStream(testSongWAV(streamTestSongSec), streamTestHeldBytes) + a.startMusic("http://cdn/stop.wav", src, false, 0, 0) + a.StopMusic() + if !src.closed.Load() || a.MusicPlaying() { + t.Fatalf("closed %v, playing %v after StopMusic", src.closed.Load(), a.MusicPlaying()) + } +} From 0ddc7ce0339511d21b9be73b07bdc349a130c7cd Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:35:30 +0000 Subject: [PATCH 39/43] ui: remove the deprecated Theater mode Theater mode was a legacy borderless, stage-only view that bypassed the normal and theme layouts. Remove its App state, hotkey, toolbox chip, menu and palette rows, Esc handling, layout gates, tests and docs. Closes #97 --- docs/ARCHITECTURE.md | 2 +- docs/FEATURES.md | 10 ++++----- internal/ui/app.go | 16 -------------- internal/ui/app_frame.go | 2 +- internal/ui/app_room.go | 4 ++-- internal/ui/chrometop_test.go | 8 +------ internal/ui/court_extras.go | 5 ++--- internal/ui/courttoolbox.go | 28 +++++++------------------ internal/ui/courttoolbox_test.go | 2 +- internal/ui/fieldwordops_test.go | 18 ---------------- internal/ui/floatbox.go | 10 +-------- internal/ui/hotkeysheet.go | 2 +- internal/ui/layoutedit.go | 4 ---- internal/ui/layoutnudge.go | 4 ++-- internal/ui/layoutnudge_test.go | 1 - internal/ui/menubar.go | 8 +++---- internal/ui/menubar_test.go | 6 ++---- internal/ui/menucontent_test.go | 6 +++--- internal/ui/palette.go | 5 ++--- internal/ui/palette_test.go | 10 ++++----- internal/ui/qol.go | 36 -------------------------------- internal/ui/screens.go | 14 ++----------- internal/ui/tabs.go | 2 +- internal/ui/tabstripedit_test.go | 3 +-- internal/ui/themeeditor.go | 2 +- 25 files changed, 44 insertions(+), 164 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ac3ac7b5..82011bcb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -519,7 +519,7 @@ so a release hit-tests where it actually happened. server-tab strip (`tabs.go`), and **every screen offsets its content by it** — no screen may hardcode `menuBarH` or `tabBarH`. Both halves self-zero (the menu bar in the full-window modes that preempt the - screen dispatch — gif export, replay, scene maker, theater; the strip + screen dispatch — gif export, replay, scene maker; the strip when there are no sessions or the user has dragged it out of the band), so a screen never has to ask *which* chrome is showing. The strip has exactly two draw sites — inside the courtroom pass, beneath a layout diff --git a/docs/FEATURES.md b/docs/FEATURES.md index e46fed13..78ecbd07 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -704,7 +704,7 @@ canonical reference it mirrors. AO2-Client wins every semantic conflict - Settings shows a live chatbox preview with the applied colors. - **Floating Extras box** (the "★ Extras" button / **Ctrl+X**): a legacy AO2 `courtroom_design.ini` has no element keys for AsyncAO's own features - (Jukebox, Background, Theater, Pair, Evidence, Login, Settings, …), + (Jukebox, Background, Pair, Evidence, Login, Settings, …), so when a theme drives the courtroom layout they'd be unreachable. Pressing **★ Extras** (pinned bottom-left) — or **Ctrl+X** — opens a **non-blocking floating box** of all of them: the courtroom, chat and logs stay live @@ -718,7 +718,7 @@ canonical reference it mirrors. AO2-Client wins every semantic conflict box-closed courtroom frame is byte-identical. - **Hover toolbox**: a slim, semi-transparent grip (a drawn hamburger, no glyph dependency) in the bottom-right corner of normal play (classic and themed). - Hovering expands it left into small labelled chips — **Theater**, **Edit + Hovering expands it left into small labelled chips — **Edit layout**, **Hide UI** — so those actions no longer live only inside the Hide-UI dialog (whose footer is now just **Done**). The toolbox is itself hideable (its own entry in the hide list) and is a pure hover reveal, so it stays on the @@ -789,7 +789,7 @@ canonical reference it mirrors. AO2-Client wins every semantic conflict Phone Book, direct connect, disconnect, quit), **View** (keep aspect ratio, a **Theme fit ▸** submenu, plain backdrops, the F3 performance overlay), **Window** (restore default size, **Theme's design size**, fit to screen, - fullscreen), **Extras** (theater, edit layout, hide UI pieces, the floating + fullscreen), **Extras** (edit layout, hide UI pieces, the floating toolbox switch, Settings) and **Help** (hotkeys, What's New with its unread badge, privacy, glossary, chat logs, the server-owner guide, About). It **reserves its own band**, so nothing is painted over and no screen has to dodge @@ -1766,9 +1766,7 @@ canonical reference it mirrors. AO2-Client wins every semantic conflict — **Chat log text** and **Chatbox text** — that resize just the IC/OOC log + message text *without* zooming the courtroom art (the same persisted scales the in-courtroom Ctrl+wheel zoom tunes, so a change here shows at once and survives - restart). **Theater mode** (Ctrl+T, the UI... panel, Esc exits): the - borderless stage alone — viewport, chat overlay, splashes — session- - only by design. + restart). - **AsyncAO chrome themes** (#M3, **Settings → AsyncAO appearance**): pick the **client UI** palette — **Dark** (default), **Soft Dark** and **Warm** (the eye-friendly pair: gentler contrast, one calm accent, dim-but-readable diff --git a/internal/ui/app.go b/internal/ui/app.go index 726a9e45..fbc08ceb 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -1069,9 +1069,6 @@ type App struct { // lastDPIDisplayIndex is the display last queried, so a move within one monitor costs no syscall or font rebuild. // -1 = never queried. lastDPIDisplayIndex int - // theaterOn is the borderless viewport-only mode. Session-only, so it can't persist someone into a chrome-less - // client. - theaterOn bool // fontPick lists the fonts a family can name, for the font fields' suggestions. fontPick fontPicker @@ -1345,19 +1342,6 @@ func (a *App) SetAutoScaleFromWindow(winW, winH int32) { } } -// setTheater flips the borderless viewport-only mode; every caller is on the render thread, so the SDL call is legal. -func (a *App) setTheater(on bool) { - a.theaterOn = on - if on { - // No toolbox draws in theater, so clear the pieces panel and pin: an invisible armed panel would swallow - // clicks. - a.toolboxPieces, a.toolboxPinned = false, false - } - if a.ctx.win != nil { - a.ctx.win.SetBordered(!on) - } -} - // setDND flips Do Not Disturb, saving it only when the user opted into persistence; the default clears every launch. func (a *App) setDND(on bool) { a.dndOn = on diff --git a/internal/ui/app_frame.go b/internal/ui/app_frame.go index 56d55e6d..1aaa17aa 100644 --- a/internal/ui/app_frame.go +++ b/internal/ui/app_frame.go @@ -458,7 +458,7 @@ func (a *App) Frame(dt time.Duration, winW, winH int32) { a.drawCourtroom(winW, winH) // primary always full-screen; the pinned server floats on top a.drawFloatingPanels(winW, winH) // non-blocking Extras + Pair + the floating client window, on top of the live courtroom (input already restored) // Here because boxFencesPointer runs the courtroom pass pointer-blind while the cursor is over the panel. - // It checks toolboxPinned and toolboxPieces itself, so theater and modals suppress it. + // It checks toolboxPinned and toolboxPieces itself, so modals suppress it. // The editor block sets c.modalOn for the whole pass, and unblocking leaves it: release it for this draw. editingLayout := a.classicEdit || a.layoutEdit if editingLayout { diff --git a/internal/ui/app_room.go b/internal/ui/app_room.go index 4366ac28..f0931dd8 100644 --- a/internal/ui/app_room.go +++ b/internal/ui/app_room.go @@ -256,9 +256,9 @@ func (a *App) drawFloatClient(w, h int32, pressed *bool) { a.drawResizeGrip(grip) } -// canRenderFullClient is false in theater and the layout editors: they reskin drawCourtroom globally. +// canRenderFullClient is false in the layout editors: they reskin drawCourtroom globally. func (a *App) canRenderFullClient() bool { - return !a.theaterOn && !a.classicEdit && !a.layoutEdit + return !a.classicEdit && !a.layoutEdit } // drawClientBody lays out the pinned server's stage, chat log and IC input; clicking the stage takes control. diff --git a/internal/ui/chrometop_test.go b/internal/ui/chrometop_test.go index 9d0bf674..5d88e7a6 100644 --- a/internal/ui/chrometop_test.go +++ b/internal/ui/chrometop_test.go @@ -27,7 +27,7 @@ func TestTopChromeHIsTheSumOfTheTwoStrips(t *testing.T) { } // TestTopChromeHDropsTheMenuBarOnFullWindowOverlays pins the L3 decision: gif -// export, replay, the scene maker and theater mode all PREEMPT the screen dispatch +// export, replay and the scene maker all PREEMPT the screen dispatch // and take the whole window, so the menu bar neither paints nor reserves space // there. The tab strip does still paint over them (app.go draws it after the // dispatch), so its band survives — which is why the scene maker's content top and the @@ -40,7 +40,6 @@ func TestTopChromeHDropsTheMenuBarOnFullWindowOverlays(t *testing.T) { {"gif export", func(a *App) { a.gifExporting = true }}, {"replay", func(a *App) { a.replaying, a.replayRoom = true, newRoomForTest(t) }}, {"scene maker", func(a *App) { a.makerOpen = true }}, - {"theater", func(a *App) { a.theaterOn = true }}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -829,9 +828,4 @@ func TestTabStripFollowsTheThemeRect(t *testing.T) { if got := a.tabStripOrigin(def, w, h); got != def { t.Errorf("on the lobby the strip = %+v, want the docked default %+v", got, def) } - // Theater mode is stage-only: the themed courtroom is not what is drawn there. - a.screen, a.theaterOn = ScreenCourtroom, true - if got := a.tabStripOrigin(def, w, h); got != def { - t.Errorf("in theater the strip = %+v, want the docked default %+v", got, def) - } } diff --git a/internal/ui/court_extras.go b/internal/ui/court_extras.go index 084f8467..2ef1b6eb 100644 --- a/internal/ui/court_extras.go +++ b/internal/ui/court_extras.go @@ -58,8 +58,7 @@ const ( // so hiding it gives the canvas the whole window. menuBarHeight() reports 0 when hidden and screens offset by // topChromeH(). It is a mouse lifeline (mouseLifelines, courttoolbox.go); hiding the last one is refused. panelMenuBar = "menubar" - // panelToolbox hides the compact hover toolbox, the bottom-right grip that reveals Theater / Edit-layout / - // Hide-UI + // panelToolbox hides the compact hover toolbox, the bottom-right grip that reveals Edit-layout / Hide-UI // chips. Hideable from the dialog one of its chips opens. panelToolbox = "toolbox" // Individual right-column tabs. A hidden tab leaves the docked strip and isn't drawn even if torn out. @@ -106,7 +105,7 @@ var hideablePanels = []struct{ id, label, short string }{ {panelTestimony, "Testimony recording badge", "Testimony"}, {panelJudge, "Judge controls (even when granted)", "Judge"}, {panelMenuBar, "Top menu bar (Servers / View / Window / Extras / Help)", "Menu bar"}, - {panelToolbox, "Compact toolbox (bottom-right hover chips: Theater / Edit layout / Hide UI)", "Toolbox"}, + {panelToolbox, "Compact toolbox (bottom-right hover chips: Edit layout / Hide UI)", "Toolbox"}, } // ctrlSettingsSlot is the toolbar Settings button's ctrl.* key; it and panelToolbox are two of the mouse lifelines diff --git a/internal/ui/courttoolbox.go b/internal/ui/courttoolbox.go index 25f2b48a..f3184de0 100644 --- a/internal/ui/courttoolbox.go +++ b/internal/ui/courttoolbox.go @@ -44,11 +44,10 @@ const ( type iconKind int const ( - iconTheater iconKind = iota // a wide stage bar over two short legs - iconEdit // a diagonal-stepped 3-rect pencil - iconEyeOff // a horizontal lens bar with a slash - iconPin // a head rect over a vertical stem - iconGrid // a 2×2 block of small rects + iconEdit iconKind = iota // a diagonal-stepped 3-rect pencil + iconEyeOff // a horizontal lens bar with a slash + iconPin // a head rect over a vertical stem + iconGrid // a 2×2 block of small rects // The Music panel's header row: AO2 uses Qt pixmaps here, and a font glyph can show as a missing-character box. iconStop // an inset filled square (matches KFO's stop button) iconDice // a bordered square with five pips — "play a random song" @@ -69,15 +68,6 @@ func drawToolIcon(c *Ctx, k iconKind, r sdl.Rect, col sdl.Color) { return } switch k { - case iconTheater: - // A wide top bar resting on two short legs. - bar := sdl.Rect{X: ix, Y: iy, W: iw, H: ih / 3} - c.Fill(bar, col) - legW := iw / 4 - legY := iy + ih/3 - legH := ih - ih/3 - c.Fill(sdl.Rect{X: ix, Y: legY, W: legW, H: legH}, col) - c.Fill(sdl.Rect{X: ix + iw - legW, Y: legY, W: legW, H: legH}, col) case iconEdit: // A pencil: three stepped squares along the diagonal plus a nib square. step := iw / 4 @@ -206,7 +196,7 @@ const ( toolboxTipIDGrip = "toolbox:grip" ) -var toolboxChipTipIDs = [...]string{"toolbox:chip:0", "toolbox:chip:1", "toolbox:chip:2", "toolbox:chip:3"} +var toolboxChipTipIDs = [...]string{"toolbox:chip:0", "toolbox:chip:1", "toolbox:chip:2"} // toolboxChipTipID falls back to the grip's id past the table's end; a shared id only shares a dwell timer. func toolboxChipTipID(i int) string { @@ -216,15 +206,13 @@ func toolboxChipTipID(i int) string { return toolboxChipTipIDs[i] } -// compactToolboxChips is the fixed chip set, right to left from the grip: Pin, Theater, Edit layout, Hide-UI. +// compactToolboxChips is the fixed chip set, right to left from the grip: Pin, Edit layout, Hide-UI. var compactToolboxChips = []compactChip{ {iconPin, "Pin the toolbox open (press again or the grip to unpin)", (*App).compactTogglePin}, - {iconTheater, "Theater mode — stage only, Esc exits", (*App).compactTheater}, {iconEdit, "Edit layout — drag & resize every box", (*App).compactEditLayout}, {iconEyeOff, "Hide UI pieces — per-piece show/hide list", (*App).compactHideUI}, } -func (a *App) compactTheater() { a.setTheater(!a.theaterOn) } func (a *App) compactEditLayout() { a.openLayoutEditor() } // compactTogglePin pins the flyout; unpinning also closes the per-piece panel so a later hover doesn't reveal it. @@ -262,7 +250,7 @@ func (a *App) drawCompactToolboxOverEditor(w, h int32) { } // drawCompactToolbox paints the grip and, while hovered or pinned, the chips, from an already-decided answer. Not drawn -// in theater mode or when hidden via panelToolbox. While a layout editor is armed it draws post-courtroom. +// when hidden via panelToolbox. While a layout editor is armed it draws post-courtroom. func (a *App) drawCompactToolbox(lat compactToolboxLatch) { if !lat.draws { return @@ -297,7 +285,7 @@ func (a *App) drawCompactToolbox(lat compactToolboxLatch) { ring := sdl.Rect{X: grip.X - 1, Y: grip.Y - 1, W: grip.W + 2, H: grip.H + 2} c.Border(ring, sdl.Color{R: ColAccent.R, G: ColAccent.G, B: ColAccent.B, A: toolboxRingAlpha}) } - c.TooltipAfter(toolboxTipIDCollapsed, hoverArea, "Toolbox — hover or click for Theater, Edit layout & Hide UI") + c.TooltipAfter(toolboxTipIDCollapsed, hoverArea, "Toolbox — hover or click for Edit layout & Hide UI") return } diff --git a/internal/ui/courttoolbox_test.go b/internal/ui/courttoolbox_test.go index 223e5a93..49c0c69f 100644 --- a/internal/ui/courttoolbox_test.go +++ b/internal/ui/courttoolbox_test.go @@ -61,7 +61,7 @@ func TestToolIconAllocFree(t *testing.T) { r := sdl.Rect{X: 10, Y: 10, W: compactChipH, H: compactChipH} col := ColText // Every iconKind the chip set uses, drawn in a tight loop, must be 0-alloc. - kinds := []iconKind{iconTheater, iconEdit, iconEyeOff, iconPin, iconGrid} + kinds := []iconKind{iconEdit, iconEyeOff, iconPin, iconGrid} draw := func() { for _, k := range kinds { drawToolIcon(c, k, r, col) diff --git a/internal/ui/fieldwordops_test.go b/internal/ui/fieldwordops_test.go index dbe53f9c..bcfb2abf 100644 --- a/internal/ui/fieldwordops_test.go +++ b/internal/ui/fieldwordops_test.go @@ -140,21 +140,3 @@ func TestReserveFieldTailIsOneSlotAndSelfClearing(t *testing.T) { t.Errorf("a degenerate reservation stuck (%d px)", got) } } - -// TestToggleExtrasBoxLeavesTheaterFirst pins setTheater's invariant: theater is -// stage-only, so summoning the box from there means "give me the UI back" rather -// than floating chrome over a bare stage. -func TestToggleExtrasBoxLeavesTheaterFirst(t *testing.T) { - a := &App{ctx: &Ctx{}, theaterOn: true} - a.toggleExtrasBox() - if a.theaterOn { - t.Error("summoning the Extras box from theater must exit theater") - } - if !a.showWidgets { - t.Error("…and must SHOW the box, never toggle it off") - } - a.toggleExtrasBox() - if a.showWidgets { - t.Error("a second press outside theater must hide it again") - } -} diff --git a/internal/ui/floatbox.go b/internal/ui/floatbox.go index 71f615cb..70838b14 100644 --- a/internal/ui/floatbox.go +++ b/internal/ui/floatbox.go @@ -131,14 +131,8 @@ func (a *App) extrasWidgets() []extrasWidget { return a.extrasWidgetCache } -// toggleExtrasBox shows or hides the box (hotkeyExtras, or Esc in the bare courtroom); -// from theater it exits theater instead of drawing over the stage-only view. +// toggleExtrasBox shows or hides the box (hotkeyExtras, or Esc in the bare courtroom). func (a *App) toggleExtrasBox() { - if a.theaterOn { - a.setTheater(false) - a.showWidgets = true - return - } a.showWidgets = !a.showWidgets } @@ -297,8 +291,6 @@ func (a *App) closeTopOverlay() bool { // A pinned sprite preview paints inside the courtroom pass, under the panels above; unpinned boxes close on leave. case a.previewBase != "" && a.previewIsPinned(): a.closeSpritePreview() - case a.theaterOn: // theater mode's "Esc exits" — handled here so it beats the leave-server shortcut - a.setTheater(false) default: return false } diff --git a/internal/ui/hotkeysheet.go b/internal/ui/hotkeysheet.go index dfb2e762..421c4d6e 100644 --- a/internal/ui/hotkeysheet.go +++ b/internal/ui/hotkeysheet.go @@ -57,7 +57,7 @@ func (a *App) hotkeyCheatEntries() []hkEntry { {"F1", "show / hide this list"}, {"F3", "performance HUD"}, {"F8", "Debug panel (diagnostics)"}, - {"Esc", "close menus / exit theater"}, + {"Esc", "close menus"}, {"Ctrl+wheel", "resize text · zoom the stage"}, } { out = append(out, hkEntry{key: fx.key, label: fx.label}) diff --git a/internal/ui/layoutedit.go b/internal/ui/layoutedit.go index 3bd8818a..95f43dd1 100644 --- a/internal/ui/layoutedit.go +++ b/internal/ui/layoutedit.go @@ -233,10 +233,6 @@ func (a *App) stopLayoutEdit() { // openLayoutEditor opens from a menu: the theme's design rects on a themed courtroom, otherwise the classic box editor. func (a *App) openLayoutEditor() { - // Leave theater first, or the editor arms behind a view that never draws it. - if a.theaterOn { - a.setTheater(false) - } if a.themeLay.valid && a.d.Prefs.Load().ThemeLayoutOn { a.startLayoutEdit() return diff --git a/internal/ui/layoutnudge.go b/internal/ui/layoutnudge.go index ef86ebe4..2ffd40c9 100644 --- a/internal/ui/layoutnudge.go +++ b/internal/ui/layoutnudge.go @@ -20,10 +20,10 @@ const ( ) // editorDrawSiteRuns reports whether an armed editor's draw reaches the screen this frame; the editor flag can outlive -// its overlay (no room, theater, gif, replay, scene maker), and then it must not eat arrow keys. +// its overlay (no room, gif, replay, scene maker), and then it must not eat arrow keys. func (a *App) editorDrawSiteRuns() bool { return a.layoutEditorArmed() && a.screen == ScreenCourtroom && - a.room != nil && a.sess != nil && !a.theaterOn && !a.screenDispatchPreempted() + a.room != nil && a.sess != nil && !a.screenDispatchPreempted() } // keyboardSurfaceOverEditor reports whether another keyboard surface owns the arrows despite an armed editor: the diff --git a/internal/ui/layoutnudge_test.go b/internal/ui/layoutnudge_test.go index 6bb43847..5c00a16e 100644 --- a/internal/ui/layoutnudge_test.go +++ b/internal/ui/layoutnudge_test.go @@ -528,7 +528,6 @@ func TestArrowsAreUntouchedWithNoEditorArmed(t *testing.T) { {"not on the courtroom screen", func(a *App) { a.screen = ScreenSettings }}, {"no room", func(a *App) { a.room = nil }}, {"no session", func(a *App) { a.sess = nil }}, - {"theater mode owns the stage", func(a *App) { a.theaterOn = true }}, {"a gif export preempts the screen dispatch", func(a *App) { a.gifExporting = true }}, {"the scene maker preempts the screen dispatch", func(a *App) { a.makerOpen = true }}, } { diff --git a/internal/ui/menubar.go b/internal/ui/menubar.go index c7c4c788..cea4ab9d 100644 --- a/internal/ui/menubar.go +++ b/internal/ui/menubar.go @@ -182,7 +182,6 @@ var menuExtrasItems = []menuItem{ {kind: menuItemCheck, label: "Mod dashboard", checked: menuModDashOpen, enabled: menuAmIMod, act: menuActModDash}, {kind: menuItemCheck, label: "CM area controls", checked: menuCMPanelOpen, enabled: menuAmICM, act: menuActCMPanel}, {kind: menuItemSeparator}, - {kind: menuItemAction, label: "Theater mode", enabled: menuInCourtroom, act: menuActTheater}, {kind: menuItemAction, label: "Edit layout…", enabled: menuInCourtroom, act: menuActEditLayout}, {kind: menuItemCheck, label: "Hide UI pieces…", checked: menuToolboxPiecesOpen, enabled: menuInCourtroom, act: menuActHideUIPieces}, {kind: menuItemCheck, label: "Floating toolbox", checked: menuToolboxShown, act: menuToggleToolbox}, @@ -302,7 +301,6 @@ func menuToggleFullscreen(a *App, _ int) { a.toggleFullscreen() } func menuInCourtroom(a *App, _ int) bool { return a.screen == ScreenCourtroom } // These call the toolbox's own methods, so the menu, chips, command palette and hotkeys are one implementation each. -func menuActTheater(a *App, _ int) { a.compactTheater() } func menuActEditLayout(a *App, _ int) { a.compactEditLayout() } func menuActHideUIPieces(a *App, _ int) { a.compactHideUI() } @@ -421,10 +419,10 @@ func newMenuBarLatch(mark int) menuBarLatch { return menuBarLatch{open: -1, subRow: -1, mark: mark} } -// menuBarShows reports whether the strip reserves its band at all: false for full-window modes, theater mode, and when -// the user hid it, in which case they want the pixels back. +// menuBarShows reports whether the strip reserves its band at all: false for full-window modes, and when the user hid +// it, in which case they want the pixels back. func (a *App) menuBarShows() bool { - return !a.screenDispatchPreempted() && !a.theaterOn && !a.panelHidden(panelMenuBar) + return !a.screenDispatchPreempted() && !a.panelHidden(panelMenuBar) } // menuBarPaints is phase 1's answer to whether the strip paints: menuBarShows minus any layout editor or the theme diff --git a/internal/ui/menubar_test.go b/internal/ui/menubar_test.go index 9a9c7e78..7372cdfe 100644 --- a/internal/ui/menubar_test.go +++ b/internal/ui/menubar_test.go @@ -210,7 +210,6 @@ func TestMenuBarPaintDecisionSurvivesAMidFrameEditor(t *testing.T) { // recover — editorHeld must stay clear or the bar would paint over an export. for name, set := range map[string]func(*App){ "gif export": func(a *App) { a.gifExporting = true }, - "theater": func(a *App) { a.theaterOn = true }, "scene maker": func(a *App) { a.makerOpen = true }, } { a := stageMenuBarApp(t) @@ -474,10 +473,10 @@ func TestMenuBarModalFenceHeldAndReleased(t *testing.T) { // A frame on which the bar is not shown at all still has to release it. a.menuOpen = menuBarMenus[1].title menuBarFrameFor(a, w, h) - a.theaterOn = true + a.gifExporting = true menuBarFrameFor(a, w, h) if c.modalOn || a.menuFenceOn || a.menuBarOpen() { - t.Fatal("hiding the bar (theater mode) must close the pane and release the fence") + t.Fatal("hiding the bar (gif export) must close the pane and release the fence") } } @@ -702,7 +701,6 @@ func TestMenuBarHeightIsZeroWhenHidden(t *testing.T) { set func() undo func() }{ - {"theater", func() { a.theaterOn = true }, func() { a.theaterOn = false }}, {"gif export", func() { a.gifExporting = true }, func() { a.gifExporting = false }}, {"scene maker", func() { a.makerOpen = true }, func() { a.makerOpen = false }}, } { diff --git a/internal/ui/menucontent_test.go b/internal/ui/menucontent_test.go index ff8912b2..a84fede7 100644 --- a/internal/ui/menucontent_test.go +++ b/internal/ui/menucontent_test.go @@ -236,13 +236,13 @@ func TestMenuWindowRowsExist(t *testing.T) { // TestMenuExtrasCarriesEveryToolboxCommand is the migration itself: every command the // floating chip strip offers is reachable from the menu, so the strip is no longer -// the only way to reach Theater / Edit layout / the per-piece panel — which is what +// the only way to reach Edit layout / the per-piece panel — which is what // made the reporter keep pressing the theme's "Call Mod" button underneath it. // // The Pin chip is deliberately NOT mirrored: it latches the FLOATING strip open, a // property of a surface the menu replaces rather than a command. func TestMenuExtrasCarriesEveryToolboxCommand(t *testing.T) { - for _, label := range []string{"Theater mode", "Edit layout…", "Hide UI pieces…", "Floating toolbox"} { + for _, label := range []string{"Edit layout…", "Hide UI pieces…", "Floating toolbox"} { menuRow(t, menuExtrasTitle, label) } // The layout editor must stay reachable whatever happens to the strip. @@ -282,7 +282,7 @@ func TestMenuExtrasTogglesTheFloatingToolbox(t *testing.T) { // because both editors live inside drawCourtroom — would leave no way out. func TestMenuExtrasCourtroomRowsDimElsewhere(t *testing.T) { a := stageMenuBarApp(t) - rows := []string{"Theater mode", "Edit layout…", "Hide UI pieces…"} + rows := []string{"Edit layout…", "Hide UI pieces…"} a.screen = ScreenLobby for _, label := range rows { diff --git a/internal/ui/palette.go b/internal/ui/palette.go index 1988519f..26dc0429 100644 --- a/internal/ui/palette.go +++ b/internal/ui/palette.go @@ -31,7 +31,7 @@ type paletteMatch struct { run func(a *App) } -// paletteExtra is one palette-only action row: the actions of the retired Extras "Hide chrome"/"Theater"/"Edit Layout" +// paletteExtra is one palette-only action row: the actions of the retired Extras "Hide chrome"/"Edit Layout" // widgets plus the toolbox's own entries, which have no extrasWidgets() slot. run is a method value bound at // table-build time, never a closure capturing an *App, so the table is package-level and iteration stays // allocation-free (as with compactToolboxChips). @@ -44,7 +44,6 @@ type paletteExtra struct { // compact* method values so the palette, hotkey and toolbox chip behave identically. var paletteExtraActions = []paletteExtra{ {"Edit Layout", "Rearrange the courtroom — drag & resize every box", (*App).compactEditLayout}, - {"Theater", "Theater mode — stage only, Esc exits", (*App).compactTheater}, {"Hide UI pieces", "Per-piece show/hide list for the courtroom chrome", (*App).compactHideUI}, } @@ -138,7 +137,7 @@ func (a *App) runPaletteMatch(m paletteMatch) { } return } - if m.run != nil { // a palette-only extra action (Edit Layout / Theater / Hide UI pieces) + if m.run != nil { // a palette-only extra action (Edit Layout / Hide UI pieces) m.run(a) return } diff --git a/internal/ui/palette_test.go b/internal/ui/palette_test.go index 3aab19d4..f2800b1b 100644 --- a/internal/ui/palette_test.go +++ b/internal/ui/palette_test.go @@ -55,13 +55,13 @@ func TestPaletteMatches(t *testing.T) { } // TestPaletteExtraActions pins FIX 2a: the palette-only actions (Edit Layout, -// Theater, Hide UI pieces) — which have no extrasWidgets() slot because the +// Hide UI pieces) — which have no extrasWidgets() slot because the // bottom-right toolbox owns them — are again reachable from the palette. Each // must appear as a runnable row (widget < 0, a non-nil run method value) when // searched for by name. func TestPaletteExtraActions(t *testing.T) { a := &App{ctx: &Ctx{}} - for _, want := range []string{"Edit Layout", "Theater", "Hide UI pieces"} { + for _, want := range []string{"Edit Layout", "Hide UI pieces"} { matches := a.paletteMatches(want) var found *paletteMatch for i := range matches { @@ -80,10 +80,10 @@ func TestPaletteExtraActions(t *testing.T) { t.Errorf("%q must carry a run method value so runPaletteMatch can fire it", want) } } - // The three actions must also be package-level (no per-App closure): the table + // The two actions must also be package-level (no per-App closure): the table // is a fixed slice, so a nil-ctx App can enumerate it. Guard the count so a // future edit can't silently drop one. - if len(paletteExtraActions) != 3 { - t.Fatalf("paletteExtraActions = %d rows, want 3 (Edit Layout / Theater / Hide UI pieces)", len(paletteExtraActions)) + if len(paletteExtraActions) != 2 { + t.Fatalf("paletteExtraActions = %d rows, want 2 (Edit Layout / Hide UI pieces)", len(paletteExtraActions)) } } diff --git a/internal/ui/qol.go b/internal/ui/qol.go index 9e991e44..f0d2e106 100644 --- a/internal/ui/qol.go +++ b/internal/ui/qol.go @@ -36,7 +36,6 @@ const ( hotkeyScreenshot = "screenshot" hotkeyRecordScene = "record_scene" hotkeyReplayLast = "replay_last" - hotkeyTheater = "theater" hotkeyLogin = "login" hotkeyMuteSFX = "mute_sfx" hotkeyEmoteCycle = "emote_cycle" @@ -94,7 +93,6 @@ var hotkeyDefs = []struct { {hotkeyScreenshot, "Screenshot", "s"}, {hotkeyRecordScene, "Record scene to a replay file (start/stop)", "w"}, {hotkeyReplayLast, "Replay the last recording (start/stop)", "i"}, - {hotkeyTheater, "Theater mode", "t"}, {hotkeyLogin, "Server login (saved creds)", "g"}, {hotkeyMuteSFX, "Mute sound effects", "{"}, {hotkeyEmoteCycle, "Cycle emote (next)", "e"}, @@ -306,8 +304,6 @@ func (a *App) handleHotkeys() { a.clipInstantReplay() case a.hotkeyFor(hotkeyPalette): a.togglePalette() - case a.hotkeyFor(hotkeyTheater): - a.setTheater(!a.theaterOn) case a.hotkeyFor(hotkeyLogin): a.loginNow() case a.hotkeyFor(hotkeyMuteSFX): @@ -350,10 +346,6 @@ func (a *App) handleHotkeys() { a.showModcall = true case a.hotkeyFor(hotkeyUIChrome): // Opens the per-piece panel even when the grip is hidden, so a user who hid the toolbox can recover it. - // Theater mode exits first: re-arming these flags under theater would float the panel over the bare stage. - if a.theaterOn { - a.setTheater(false) - } a.toolboxPinned, a.toolboxPieces = true, true case a.hotkeyFor(hotkeyToggleMenuBar): a.toggleChromePanel(panelMenuBar, "Menu bar") @@ -788,34 +780,6 @@ func (a *App) drawHotkeyCheatSheet(w, h int32) { } } -const theaterHint = "Esc exits theater" - -// drawTheater is the borderless viewport-only courtroom: the stage letterboxed to 4:3, chat overlay and hotkeys. -func (a *App) drawTheater(w, h int32) { - c := a.ctx - c.Fill(sdl.Rect{X: 0, Y: 0, W: w, H: h}, sdl.Color{A: 255}) - vpW, vpH := w, w*3/4 - if vpH > h { - vpH = h - vpW = vpH * 4 / 3 - } - vp := sdl.Rect{X: (w - vpW) / 2, Y: (h - vpH) / 2, W: vpW, H: vpH} - a.renderViewportZoomed(vp) - chatBandH := vp.H / 4 * int32(a.boxPct) / DefaultScalePct - a.handleViewportZoom(vp, c.mouseY >= vp.Y+vp.H-chatBandH) - if a.vpZoom <= 1 { - a.handleSpriteDrag(vp) - a.handleSpriteHide(vp) // right-click → hide-sprite confirm (default ON) - } - a.handleHotkeys() - a.drawChatOverlay(vp, false, 0, 0) // theater mode keeps the clean stage-bottom chatbox - a.drawCourtOverlays(vp, nil) // splashes/HP still play — part of the show - c.Label(w-c.TextWidth(theaterHint)-8, 6, theaterHint, ColTextDim) - if c.escPressed { - a.setTheater(false) - } -} - // cyclePos advances our side through posChoices (the SD list when sent). func (a *App) cyclePos() { choices := a.posChoices() diff --git a/internal/ui/screens.go b/internal/ui/screens.go index 8a19dfb9..a904cf87 100644 --- a/internal/ui/screens.go +++ b/internal/ui/screens.go @@ -256,11 +256,10 @@ func (a *App) drawCourtroom(w, h int32) { fenceMark := c.overlayFenceMark() defer c.overlayFenceRelease(fenceMark) c.Fill(sdl.Rect{X: 0, Y: 0, W: w, H: h}, ColBackground) - // Only drawCourtroomThemed re-arms this; a stale true would misplace the classic or theater toolbox, which draws + // Only drawCourtroomThemed re-arms this; a stale true would misplace the classic toolbox, which draws // post-court in app.go. a.toolboxThemeRectOn = false - // Only fenceCompactToolbox sets this, so a theater, dropped-session or lobby frame can't replay last frame's - // answer. + // Only fenceCompactToolbox sets this, so a dropped-session or lobby frame can't replay last frame's answer. a.toolboxFence = compactToolboxLatch{} // Decided once here and replayed by both paint sites (chrometop.go). It must precede anything that arms or disarms // an editor mid-pass, or the strip paints twice or not at all. @@ -275,15 +274,6 @@ func (a *App) drawCourtroom(w, h int32) { return } - // Theater mode preempts both layouts. - if a.theaterOn { - if a.classicEdit { - a.stopClassicEdit() // can't edit the layout from theater mode — release the fence - } - a.drawTheater(w, h) - return - } - // When the theme ships courtroom_design.ini and the toggle is on, the courtroom is the theme's layout. // themeWindowLayout fits the canvas under the app-chrome band. if lay := a.themeWindowLayout(w, h); lay.valid && a.d.Prefs.Load().ThemeLayoutOn { diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go index 132fed92..a59a5066 100644 --- a/internal/ui/tabs.go +++ b/internal/ui/tabs.go @@ -704,7 +704,7 @@ func (a *App) tabStripOrigin(def sdl.Rect, w, h int32) sdl.Rect { // Excludes gif export, replay and scene maker: they keep a.screen == Courtroom but rebuild the shared layout cache at // the export's own dimensions. func (a *App) tabStripThemeRect() (sdl.Rect, bool) { - if a.screen != ScreenCourtroom || a.room == nil || a.theaterOn || a.screenDispatchPreempted() { + if a.screen != ScreenCourtroom || a.room == nil || a.screenDispatchPreempted() { return sdl.Rect{}, false } if !a.themeLay.valid || !a.d.Prefs.Load().ThemeLayoutOn { diff --git a/internal/ui/tabstripedit_test.go b/internal/ui/tabstripedit_test.go index 61fc5f01..ec5c2ff9 100644 --- a/internal/ui/tabstripedit_test.go +++ b/internal/ui/tabstripedit_test.go @@ -425,7 +425,7 @@ func TestTabStripUndoOfTheFirstDragSendsItHome(t *testing.T) { // editor armed the strip painted AFTER drawLayoutEditor and buried its banner. The // predicate must not simply be "an editor is armed" either: an editor flag outlives // the frames where its draw site actually runs (drawCourtroom bails to the lobby with -// no room, returns early in theater, and gif export / replay / the scene maker preempt +// no room, and gif export / replay / the scene maker preempt // the whole screen dispatch), and the strip would then vanish on those frames. func TestTabStripPaintSiteIsExclusiveWhileEditing(t *testing.T) { arm := map[string]func(*App){ @@ -451,7 +451,6 @@ func TestTabStripPaintSiteIsExclusiveWhileEditing(t *testing.T) { "lobby": func(a *App) { a.screen = ScreenLobby }, "no room": func(a *App) { a.room = nil }, "no session": func(a *App) { a.sess = nil }, - "theater": func(a *App) { a.theaterOn = true }, "gif export": func(a *App) { a.gifExporting = true }, "replay": func(a *App) { a.replaying, a.replayRoom = true, a.room }, "scene maker": func(a *App) { a.makerOpen = true }, diff --git a/internal/ui/themeeditor.go b/internal/ui/themeeditor.go index bda533f4..a9874695 100644 --- a/internal/ui/themeeditor.go +++ b/internal/ui/themeeditor.go @@ -486,7 +486,7 @@ func (a *App) closeEditorPanels() { // drawEditorCanvas paints the theme full bleed: the real courtroom with a live room, else the fitted geometry canvas. func (a *App) drawEditorCanvas(w, h int32) { - if a.room != nil && a.sess != nil && !a.theaterOn { + if a.room != nil && a.sess != nil { // Courtroom widgets go inert while used as a canvas: the kit is single-pass, so a select press would also press // them. // Save and restore, not assign: a rail's open dropdown may hold modalOn legitimately. From a5fa79977a42258868a6ea7f083c7493602c8e43 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:34:08 +0100 Subject: [PATCH 40/43] media, assets: raw lookups are media requests First step of deleting the bridge. assets.Raw reads a complete URL as a raw media key, and assets.Resolve finds a base name as a chain on a raw key, saying which URL answered and whether the player's folders held it; they replace FetchRaw (14 call sites) and ResolveRawLayered/Full (scene archive, content report). The second lookup path inside assets.Manager (resolveIn, cachedRaw, remoteRaw) is gone, so everything follows the one order: memory, disk cache, folders in every format, web, whose hits teach the host's format through the Found hook as before. media gains what that needs: Load is Get plus Wait for callers off the main thread (the old Load had no callers), Asset.Hit names the file and source that answered, and the Unlisted flag also asks the web for the formats the host's list leaves out, which the content report's full lookup relied on. Asset.Wait also returns ErrStopped when the media system stops: a char.ini load still in flight when a tab closed would otherwise have waited forever, where the old path ended on the network's own timeouts. The race test run caught it as leaked goroutines. A test that compared allocation counts as a stand-in for "a memory hit never reads the folders" now counts folder reads instead. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 2 +- docs/RESTRUCTURING_PLAN.md | 8 ++ internal/archive/archive.go | 11 +-- internal/archive/archive_test.go | 7 +- internal/assets/folders.go | 6 -- internal/assets/folders_changed_test.go | 4 +- internal/assets/folders_test.go | 53 ++++++------ internal/assets/manager.go | 105 ------------------------ internal/assets/manager_test.go | 19 +++-- internal/assets/mediabridge.go | 15 ---- internal/assets/raw.go | 68 +++++++++++++++ internal/courtroom/urlbuilder.go | 2 +- internal/media/asset.go | 38 ++++++++- internal/media/manager.go | 38 +++++---- internal/media/manager_test.go | 8 +- internal/media/types.go | 3 + internal/media/wait_test.go | 76 +++++++++++++++++ internal/render/audio.go | 3 +- internal/ui/app_connect.go | 2 +- internal/ui/app_room.go | 4 +- internal/ui/bgdesign.go | 3 +- internal/ui/bgpicker.go | 4 +- internal/ui/charmeta.go | 7 +- internal/ui/contentjob.go | 26 +++--- internal/ui/contentjob_test.go | 8 +- internal/ui/contentseed_test.go | 12 +-- internal/ui/effectspicker.go | 2 +- internal/ui/evidserverpicker.go | 2 +- internal/ui/gifexport.go | 2 +- internal/ui/missingno_noblip_test.go | 2 +- internal/ui/newroom_test.go | 2 +- internal/ui/packcharini_test.go | 2 +- internal/ui/wardrobewin.go | 2 +- 33 files changed, 317 insertions(+), 229 deletions(-) create mode 100644 internal/assets/raw.go create mode 100644 internal/media/wait_test.go diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 82011bcb..e1ab5244 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -598,7 +598,7 @@ The Wardrobe saves characters for the player, across servers: server's list. The window rebuilds its list only when the store's revision, the query or the server changes, so painting allocates nothing per frame. - **The server's list:** `/iniswaps.ini`, AO2's name for it (courtroom.cpp:5349), fetched once per - server through `FetchRaw` (T2 + disk cached, singleflight), at most 4096 names. + server through `assets.Raw` (a media request: memory, disk cache, folders, web), at most 4096 names. - **Drawing:** rounded shapes and line icons come from `ui/shapes.go`, white masks rasterised once with `golang.org/x/image/vector` and tinted per draw, so they cost a few copies and no allocation. - **Character Select's ★** reads a lowercase membership set rebuilt only when the store's revision moves. diff --git a/docs/RESTRUCTURING_PLAN.md b/docs/RESTRUCTURING_PLAN.md index 3f697a69..dfab86af 100644 --- a/docs/RESTRUCTURING_PLAN.md +++ b/docs/RESTRUCTURING_PLAN.md @@ -161,6 +161,14 @@ in **Status**. Update Status in the same commit that completes a step. downloading or held in memory (.zip packs) is decoded on its own goroutine into an SDL audio stream on the music track, ahead of playback, reopening at each loop so loops stay gapless; a download that falls behind pauses only the music. No track is held whole in memory + - [ ] delete the bridge (decided 2026-11-15): `assets.Manager` goes; `assets` exports the parts (formats, the T2 and + disk sources, the web fetcher with offline and archive handling, the folders source, the hooks, learned.json) + and `cmd/asyncao/main.go` wires `media.Manager` from them. One commit per group: + - [x] raw lookups: `assets.Raw` (a raw key) and `assets.Resolve` (a chain on a raw key; `media.Unlisted` also asks + the formats the host's list leaves out) replace `FetchRaw` and `ResolveRaw*`; `media.Manager.Load` is `Get` + plus `Asset.Wait`, which also returns when the media system stops, and `Asset.Hit` says which file answered + - [ ] settings pass-throughs, folders, learned formats and hosts, stats + - [ ] the wiring moves to `main.go` and the bridge goes - [ ] off-thread texture preparation: waits for the renderer overhaul (decided 2026-11-02). See below - [x] a sprite sometimes shows its old animation for a frame before the right one (reported 2026-11-01): the wait gate released on a first frame or a reduced page. The speaker's sprites now wait for every frame; a pair partner's still diff --git a/internal/archive/archive.go b/internal/archive/archive.go index 0ab7eaa7..fe09c8f4 100644 --- a/internal/archive/archive.go +++ b/internal/archive/archive.go @@ -61,11 +61,11 @@ func ExportAssets(ctx context.Context, mgr *assets.Manager, origin, startBg stri return res, nil } -// resolveRef probes candidates and alternate sprite spellings (EmoteAlts order). ResolveRawLayered checks -// local packs but never teaches learned formats or writes pack bytes into server-keyed caches. +// resolveRef probes candidates and alternate sprite spellings (EmoteAlts order). assets.Resolve checks local packs but +// never teaches learned formats or writes pack bytes into server-keyed caches. func resolveRef(ctx context.Context, mgr *assets.Manager, ref courtroom.AssetRef) (string, []byte, bool, bool) { if ref.Exact { - if data, err := mgr.FetchRaw(ctx, ref.Base); err == nil && len(data) > 0 { + if data, err := assets.Raw(ctx, mgr.Media(), ref.Base); err == nil && len(data) > 0 { return ref.Base, data, false, true } return "", nil, false, false @@ -74,11 +74,12 @@ func resolveRef(ctx context.Context, mgr *assets.Manager, ref courtroom.AssetRef if base == "" { continue } - url, data, fromPack, ok := mgr.ResolveRawLayered(base, ref.Type) + found, ok := assets.Resolve(ctx, mgr.Media(), base, ref.Type, false) if !ok { continue } - if fromPack { + url, data := found.URL, found.Data + if found.FromPack { // A pack answers under a local:// URL, so return the server-side path; the transport URL would fail the // caller's prefix test and silently drop every pack asset. return base + path.Ext(url), data, true, true diff --git a/internal/archive/archive_test.go b/internal/archive/archive_test.go index ab3c236b..9e7c83b4 100644 --- a/internal/archive/archive_test.go +++ b/internal/archive/archive_test.go @@ -105,7 +105,8 @@ func TestExportReplayRoundTrip(t *testing.T) { repUrls := courtroom.NewURLBuilder(repLocal.BaseURL()) idle := repUrls.Emote("Phoenix", "normal", courtroom.EmoteIdle) - _, data, ok := repMgr.ResolveRaw(idle, assets.AssetTypeCharSprite) + found, ok := assets.Resolve(context.Background(), repMgr.Media(), idle, assets.AssetTypeCharSprite, false) + data := found.Data if !ok { t.Fatal("speaker idle sprite did NOT resolve from the archive — round-trip broken") } @@ -213,7 +214,9 @@ func TestExportDecodesBundleNames(t *testing.T) { repLocal := assets.NewLocalFetcher([]string{archDir}) repMgr := buildManager(t, repLocal, true) repUrls := courtroom.NewURLBuilder(repLocal.BaseURL()) - _, data, ok := repMgr.ResolveRaw(repUrls.Emote(char, "normal", courtroom.EmoteIdle), assets.AssetTypeCharSprite) + found, ok := assets.Resolve(context.Background(), repMgr.Media(), repUrls.Emote(char, "normal", courtroom.EmoteIdle), + assets.AssetTypeCharSprite, false) + data := found.Data if !ok { t.Fatal("decoded-name character did NOT resolve from the clean archive — round-trip broken") } diff --git a/internal/assets/folders.go b/internal/assets/folders.go index 2cd93107..a8ca5fa3 100644 --- a/internal/assets/folders.go +++ b/internal/assets/folders.go @@ -49,12 +49,6 @@ func (f *bridgeFolders) Open(file media.File) (media.Stream, error) { return st, err } -// read is Data for the synchronous fetch paths; workers only. -func (f *bridgeFolders) read(url string) ([]byte, bool) { - b, err := f.Data(media.File(url)) - return b, err == nil -} - // SetFolders mounts the player's folders and .zip packs, in order, for their local:// origin and for each server // asset origin given, when they layer over streaming. It reads nothing, so it is safe on the render thread. func (m *Manager) SetFolders(mounts, serverOrigins []string) { diff --git a/internal/assets/folders_changed_test.go b/internal/assets/folders_changed_test.go index f6585d16..dc975c38 100644 --- a/internal/assets/folders_changed_test.go +++ b/internal/assets/folders_changed_test.go @@ -16,7 +16,7 @@ func TestChangedFolderFilesReloadsAnEdit(t *testing.T) { pr := newPackRig(t, nil, map[string]string{"characters/witch/char.ini": before}) m := pr.rig.manager url := pr.base("characters/witch/char.ini") - if data, err := m.FetchRaw(context.Background(), url); err != nil || string(data) != before { + if data, err := Raw(context.Background(), m.Media(), url); err != nil || string(data) != before { t.Fatalf("first read = %q, %v", data, err) } if got := m.ChangedFolderFiles(); len(got) != 0 { @@ -37,7 +37,7 @@ func TestChangedFolderFilesReloadsAnEdit(t *testing.T) { if got := m.ChangedFolderFiles(); !slices.Equal(got, []string{url}) { t.Fatalf("ChangedFolderFiles() = %v, want [%s]", got, url) } - if data, err := m.FetchRaw(context.Background(), url); err != nil || string(data) != after { + if data, err := Raw(context.Background(), m.Media(), url); err != nil || string(data) != after { t.Errorf("read after the edit = %q, %v; want the new copy", data, err) } } diff --git a/internal/assets/folders_test.go b/internal/assets/folders_test.go index fcdb1988..0d7aaaf1 100644 --- a/internal/assets/folders_test.go +++ b/internal/assets/folders_test.go @@ -102,9 +102,9 @@ func TestFolderServesCharINI(t *testing.T) { map[string]string{"characters/witch/char.ini": ini}, ) - data, err := pr.rig.manager.FetchRaw(context.Background(), pr.base("characters/witch/char.ini")) + data, err := Raw(context.Background(), pr.rig.manager.Media(), pr.base("characters/witch/char.ini")) if err != nil { - t.Fatalf("FetchRaw: %v", err) + t.Fatalf("Raw: %v", err) } if string(data) != ini { t.Errorf("got %q, want the folder's ini", data) @@ -124,14 +124,14 @@ func TestCachedServerCopyBeatsTheFolders(t *testing.T) { map[string]string{}, ) url := pr.base("characters/witch/char.ini") - if _, err := pr.rig.manager.FetchRaw(context.Background(), url); err != nil { + if _, err := Raw(context.Background(), pr.rig.manager.Media(), url); err != nil { t.Fatalf("seeding the server copy: %v", err) } writePack(t, pr.dir, map[string]string{"characters/witch/char.ini": "FOLDER INI"}) - data, err := pr.rig.manager.FetchRaw(context.Background(), url) + data, err := Raw(context.Background(), pr.rig.manager.Media(), url) if err != nil { - t.Fatalf("FetchRaw: %v", err) + t.Fatalf("Raw: %v", err) } if string(data) != "SERVER INI" { t.Errorf("got %q, want the cached server copy", data) @@ -144,9 +144,9 @@ func TestFolderMissFallsThroughToServer(t *testing.T) { map[string]string{"characters/witch/char.ini": "PACK INI"}, ) - data, err := pr.rig.manager.FetchRaw(context.Background(), pr.base("characters/other/char.ini")) + data, err := Raw(context.Background(), pr.rig.manager.Media(), pr.base("characters/other/char.ini")) if err != nil { - t.Fatalf("FetchRaw: %v", err) + t.Fatalf("Raw: %v", err) } if string(data) != "SERVER INI" { t.Errorf("got %q, want the server's copy", data) @@ -165,8 +165,8 @@ func TestFolderTextWritesNoServerKeyedCache(t *testing.T) { ) url := pr.base("characters/witch/char.ini") - if _, err := pr.rig.manager.FetchRaw(context.Background(), url); err != nil { - t.Fatalf("FetchRaw: %v", err) + if _, err := Raw(context.Background(), pr.rig.manager.Media(), url); err != nil { + t.Fatalf("Raw: %v", err) } if _, ok := pr.rig.manager.t2.Get(url); ok { t.Error("folder bytes were cached in memory under the server's URL") @@ -181,8 +181,8 @@ func TestFolderTextNeverTeachesLearnedFormats(t *testing.T) { map[string]string{}, map[string]string{"characters/witch/char.ini": "PACK INI"}, ) - if _, err := pr.rig.manager.FetchRaw(context.Background(), pr.base("characters/witch/char.ini")); err != nil { - t.Fatalf("FetchRaw: %v", err) + if _, err := Raw(context.Background(), pr.rig.manager.Media(), pr.base("characters/witch/char.ini")); err != nil { + t.Fatalf("Raw: %v", err) } if n := pr.rig.manager.LearnedHosts(); n != 0 { t.Errorf("the folder taught %d hosts a format", n) @@ -197,9 +197,9 @@ func TestFolderNeverAnswersTheServerFormatList(t *testing.T) { map[string]string{media.ManifestFile: "PACK MANIFEST"}, ) - data, err := pr.rig.manager.FetchRaw(context.Background(), pr.base(media.ManifestFile)) + data, err := Raw(context.Background(), pr.rig.manager.Media(), pr.base(media.ManifestFile)) if err != nil { - t.Fatalf("FetchRaw(%s): %v", media.ManifestFile, err) + t.Fatalf("Raw(%s): %v", media.ManifestFile, err) } if string(data) != "SERVER MANIFEST" { t.Errorf("got %q — the folder answered for the server's own format list", data) @@ -241,7 +241,7 @@ func TestFileDroppedInAfterAMissIsFoundOnRecheck(t *testing.T) { map[string]string{"characters/witch/(a)normal.png": "x"}, ) url := pr.base("characters/witch/char.ini") - if _, err := pr.rig.manager.FetchRaw(context.Background(), url); err == nil { + if _, err := Raw(context.Background(), pr.rig.manager.Media(), url); err == nil { t.Fatal("found a char.ini that is not there yet") } asked := pr.hitsFor("/base/characters/witch/char.ini") @@ -253,7 +253,7 @@ func TestFileDroppedInAfterAMissIsFoundOnRecheck(t *testing.T) { } pr.rig.manager.RecheckFolders() - data, err := pr.rig.manager.FetchRaw(context.Background(), url) + data, err := Raw(context.Background(), pr.rig.manager.Media(), url) if err != nil || string(data) != "DROPPED IN" { t.Fatalf("after RecheckFolders: %q, %v", data, err) } @@ -285,20 +285,25 @@ func TestFolderSpriteIsFoundInAFormatTheServerDoesNotList(t *testing.T) { } } -func TestFetchRawWithoutFoldersAllocatesNoMore(t *testing.T) { +// TestRawAnswersFromMemoryBeforeTheFolders: a server copy already in memory answers before the player's folders are +// read, as memory comes first in the lookup order. +func TestRawAnswersFromMemoryBeforeTheFolders(t *testing.T) { pr := newPackRig(t, map[string]string{"/base/characters/witch/char.ini": "SERVER INI"}, - map[string]string{}, + map[string]string{"characters/witch/char.ini": "FOLDER INI"}, ) url := pr.base("characters/witch/char.ini") ctx := context.Background() - if _, err := pr.rig.manager.FetchRaw(ctx, url); err != nil { - t.Fatalf("priming: %v", err) - } - withFolders := testing.AllocsPerRun(100, func() { _, _ = pr.rig.manager.FetchRaw(ctx, url) }) pr.rig.manager.SetFolders(nil, nil) - without := testing.AllocsPerRun(100, func() { _, _ = pr.rig.manager.FetchRaw(ctx, url) }) - if withFolders > without { - t.Errorf("a memory hit allocates %v with folders vs %v without: the cache is answered first", withFolders, without) + if data, err := Raw(ctx, pr.rig.manager.Media(), url); err != nil || string(data) != "SERVER INI" { + t.Fatalf("priming from the server: %q, %v", data, err) + } + pr.rig.manager.SetFolders([]string{pr.dir}, []string{pr.origin}) + data, err := Raw(ctx, pr.rig.manager.Media(), url) + if err != nil || string(data) != "SERVER INI" { + t.Fatalf("got %q, %v; want the copy already in memory", data, err) + } + if n := pr.rig.manager.Stats().MountFetches; n != 0 { + t.Fatalf("the folders were read %d time(s) for a file memory held", n) } } diff --git a/internal/assets/manager.go b/internal/assets/manager.go index cd14fb9a..d865c877 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -2,7 +2,6 @@ package assets import ( "context" - "slices" "strings" "sync/atomic" "time" @@ -349,110 +348,6 @@ func (m *Manager) skipExhausted(base string, t AssetType, quiet bool) { } } -// FetchRaw fetches a complete URL through memory, the disk cache, the player's folders and the web without decoding; -// call it off the render thread. -func (m *Manager) FetchRaw(ctx context.Context, url string) ([]byte, error) { - data, _, err := m.fetchRaw(ctx, url) - return data, err -} - -// fetchRaw is FetchRaw that also says whether the bytes came from the player's folders. -func (m *Manager) fetchRaw(ctx context.Context, url string) (data []byte, fromPack bool, err error) { - if data, ok := m.cachedRaw(url); ok { - return data, false, nil - } - if data, ok := m.bridge.folders.read(url); ok { - return data, true, nil // counted by the folder source - } - data, err = m.remoteRaw(ctx, url) - return data, false, err -} - -// cachedRaw reads a URL from memory or the disk cache. -func (m *Manager) cachedRaw(url string) ([]byte, bool) { - if data, ok := m.t2.Get(url); ok { - m.t2Hits.Add(1) - return data, true - } - if skipDisk(url) { - return nil, false - } - data, ok := m.disk.Get(url) - if ok { - m.diskHits.Add(1) - m.t2.Add(url, data, int64(len(data))) - } - return data, ok -} - -// remoteRaw fetches a URL from the web and keeps it in memory and the disk cache. -func (m *Manager) remoteRaw(ctx context.Context, url string) ([]byte, error) { - data, err := m.netFetch(ctx, url) - if err != nil { - return nil, err - } - m.netFetches.Add(1) - m.t2.Add(url, data, int64(len(data))) - if !skipDisk(url) { - m.disk.Put(url, data) - } - return data, nil -} - -// ResolveRaw returns the first candidate whose bytes fetch and learns its format; export and replay share this order. -func (m *Manager) ResolveRaw(base string, t AssetType) (string, []byte, bool) { - url, data, _, ok := m.ResolveRawLayered(base, t) - return url, data, ok -} - -// ResolveRawLayered is ResolveRaw that also says whether the bytes came from the player's folders, for the content -// report and scene exporter. -func (m *Manager) ResolveRawLayered(base string, t AssetType) (url string, data []byte, fromPack, ok bool) { - if base == "" || !t.Valid() { - return "", nil, false, false - } - return m.resolveIn(base, t, m.bridge.candidates(base, t)) -} - -// ResolveRawFull is ResolveRawLayered for report and export passes, which also ask the formats the host's list leaves -// out. -func (m *Manager) ResolveRawFull(base string, t AssetType) (string, []byte, bool) { - if base == "" || !t.Valid() { - return "", nil, false - } - urls := m.bridge.candidates(base, t) - for _, f := range media.EveryFormat(media.Key{Class: classOf(t)}, base) { - if !slices.Contains(urls, string(f)) { - urls = append(urls, string(f)) - } - } - url, data, _, ok := m.resolveIn(base, t, urls) - return url, data, ok -} - -// resolveIn finds one name in the live chain's order: memory and the disk cache, then the player's folders in every -// format, then the web. Server hits teach the host's format; a folder hit teaches nothing, as the files are the player's. -func (m *Manager) resolveIn(base string, t AssetType, urls []string) (url string, data []byte, fromPack, ok bool) { - for _, u := range urls { - if data, ok := m.cachedRaw(u); ok { - m.bridge.learn(base, t, u) - return u, data, false, true - } - } - for _, f := range media.EveryFormat(media.Key{Class: classOf(t)}, base) { - if data, ok := m.bridge.folders.read(string(f)); ok { - return string(f), data, true, true - } - } - for _, u := range urls { - if data, err := m.remoteRaw(context.Background(), u); err == nil && len(data) > 0 { - m.bridge.learn(base, t, u) - return u, data, false, true - } - } - return "", nil, false, false -} - // PurgeCorrupt evicts url from memory and the disk cache so the next demand refetches; url is the full fetch URL. func (m *Manager) PurgeCorrupt(url string) { if url == "" { diff --git a/internal/assets/manager_test.go b/internal/assets/manager_test.go index 550d7473..5092d1b5 100644 --- a/internal/assets/manager_test.go +++ b/internal/assets/manager_test.go @@ -78,13 +78,13 @@ func newRigAt(tb testing.TB, source Fetcher, localMode bool, learnedPath string) return &testRig{prefs: prefs, manager: m, decoder: decoder, disk: disk, t2: t2} } -// TestResolveRawFromLocalArchive is the load-bearing round-trip proof for the +// TestResolveFromLocalArchive is the load-bearing round-trip proof for the // self-contained scene archive: an asset written into a local folder at the // webAO relative path is resolved back by the SAME candidate chain replay uses, // and the resolved URL minus the origin is exactly that relative path. If this // holds, export (write at relpath) and replay (resolve to relpath) are // symmetric — a bundled .aorec replays with the CDN gone. -func TestResolveRawFromLocalArchive(t *testing.T) { +func TestResolveFromLocalArchive(t *testing.T) { dir := t.TempDir() write := func(rel string, data []byte) { full := filepath.Join(dir, filepath.FromSlash(rel)) @@ -104,7 +104,8 @@ func TestResolveRawFromLocalArchive(t *testing.T) { // to (export/replay symmetry). write("characters/Phoenix/(a)normal.webp", []byte("WEBP")) base := local.BaseURL() + "characters/Phoenix/(a)normal" - url, data, ok := rig.manager.ResolveRaw(base, AssetTypeCharSprite) + found, ok := Resolve(context.Background(), rig.manager.Media(), base, AssetTypeCharSprite, false) + url, data := found.URL, found.Data if !ok || url != base+config.ExtWebP || string(data) != "WEBP" { t.Fatalf("webp archive asset not resolved: ok=%v url=%q", ok, url) } @@ -116,8 +117,8 @@ func TestResolveRawFromLocalArchive(t *testing.T) { // host nothing. write("characters/Edgeworth/(a)normal.png", []byte("PNG")) pbase := local.BaseURL() + "characters/Edgeworth/(a)normal" - if url, data, ok := rig.manager.ResolveRaw(pbase, AssetTypeCharSprite); !ok || string(data) != "PNG" { - t.Fatalf("folder .png not resolved: ok=%v url=%q", ok, url) + if f, ok := Resolve(context.Background(), rig.manager.Media(), pbase, AssetTypeCharSprite, false); !ok || string(f.Data) != "PNG" { + t.Fatalf("folder .png not resolved: ok=%v url=%q", ok, f.URL) } if n := rig.manager.LearnedHosts(); n != 0 { t.Errorf("folder hits taught %d hosts a format", n) @@ -495,7 +496,7 @@ func TestManagerInflightDedup(t *testing.T) { // TestManagerPrefetchRawWarmsTiers pins the decode-free raw lane: one // network probe lands the payload in T2 + disk, and a later synchronous -// FetchRaw is a pure memory hit (hover-warm → instant character pick). +// Raw is a pure memory hit (hover-warm → instant character pick). func TestManagerPrefetchRawWarmsTiers(t *testing.T) { ini := []byte("[Options]\nside = def\n") cs := newCountingServer(t, map[string][]byte{ @@ -519,12 +520,12 @@ func TestManagerPrefetchRawWarmsTiers(t *testing.T) { t.Fatalf("probes = %d, want 1", got) } - data, err := rig.manager.FetchRaw(context.Background(), url) + data, err := Raw(context.Background(), rig.manager.Media(), url) if err != nil || string(data) != string(ini) { - t.Fatalf("FetchRaw after warm: %v / %q", err, data) + t.Fatalf("Raw after warm: %v / %q", err, data) } if got := cs.total(); got != 1 { - t.Fatalf("probes after warmed FetchRaw = %d, want still 1 (memory hit)", got) + t.Fatalf("probes after a warmed Raw = %d, want still 1 (memory hit)", got) } } diff --git a/internal/assets/mediabridge.go b/internal/assets/mediabridge.go index b9fa4527..e22768cf 100644 --- a/internal/assets/mediabridge.go +++ b/internal/assets/mediabridge.go @@ -102,21 +102,6 @@ func (b *mediaBridge) found(k media.Key, f media.File) { } // learn is found for a raw walk on a worker: url turned up for base. -func (b *mediaBridge) learn(base string, t AssetType, url string) { - b.media.Do(func() { b.found(ChainKey(base, t), media.File(url)) }) -} - -// candidates lists the URLs base may be, in the order the live chain asks; for workers, as it waits on the Manager. -func (b *mediaBridge) candidates(base string, t AssetType) []string { - var files []media.File - b.media.Call(func() { files = b.builder.Build(ChainKey(base, t), base) }) - urls := make([]string, len(files)) - for i, f := range files { - urls[i] = string(f) - } - return urls -} - // AllowFormats gives origin a format list per asset type, as its extensions.json would, such as a replay archive's // recorded formats. func (m *Manager) AllowFormats(origin string, byType map[AssetType]string) { diff --git a/internal/assets/raw.go b/internal/assets/raw.go new file mode 100644 index 00000000..90af9882 --- /dev/null +++ b/internal/assets/raw.go @@ -0,0 +1,68 @@ +package assets + +import ( + "context" + "fmt" + + "github.com/SyntaxNyah/AsyncAO/internal/media" + "github.com/SyntaxNyah/AsyncAO/internal/network" +) + +// playerFiles marks the source of the player's own folders and packs, so a lookup can say a file came from them. +type playerFiles interface{ playerFiles() } + +func (f *bridgeFolders) playerFiles() {} + +// Raw reads a complete URL through the media system without decoding it, waiting for it, so call it off the render +// thread. A file found nowhere is network.ErrAssetNotFound; it is asked quietly, as no one shows a missing raw file. +func Raw(ctx context.Context, m *media.Manager, url string) ([]byte, error) { + a, err := m.Load(ctx, RawKey(url), media.Now, media.Quiet) + if err != nil { + return nil, err + } + return rawResult(a, url) +} + +// Found is where Resolve found a file: the URL that answered, its bytes, and whether the player's folders held it. +type Found struct { + URL string + Data []byte + FromPack bool +} + +// Resolve finds base as an asset of type t in the live order: memory and the disk cache, the player's folders in every +// format, then the web, whose hits teach the host's format. Unlisted also asks the web for the formats the host's list +// leaves out, for export. It waits, so call it off the render thread. +func Resolve(ctx context.Context, m *media.Manager, base string, t AssetType, unlisted bool) (Found, bool) { + key := ChainKey(base, t) + key.Kind = media.KindRaw + flags := media.Quiet + if unlisted { + flags |= media.Unlisted + } + a, err := m.Load(ctx, key, media.Now, flags) + if err != nil { + return Found{}, false + } + data, err := rawResult(a, base) + if err != nil || len(data) == 0 { + return Found{}, false + } + hit := a.Hit() + _, pack := hit.Source.(playerFiles) + return Found{URL: string(hit.File), Data: data, FromPack: pack}, true +} + +// rawResult is a finished raw Asset's bytes, or why it has none. +func rawResult(a *media.Asset, name string) ([]byte, error) { + if data, ok := a.Result().([]byte); ok && a.Ready() { + return data, nil + } + if a.State() == media.Missing { + return nil, fmt.Errorf("%w: %s", network.ErrAssetNotFound, name) + } + if err := a.Err(); err != nil { + return nil, err + } + return nil, fmt.Errorf("assets: %s ended %v", name, a.State()) +} diff --git a/internal/courtroom/urlbuilder.go b/internal/courtroom/urlbuilder.go index fadf35db..8f64f239 100644 --- a/internal/courtroom/urlbuilder.go +++ b/internal/courtroom/urlbuilder.go @@ -395,7 +395,7 @@ const ( chatboxChatConfigIni = "chat_config.ini" ) -// ChatboxChatConfigIni returns the spellings of chat_config.ini; fetch with FetchRaw, never format-probe. +// ChatboxChatConfigIni returns the spellings of chat_config.ini; fetch with assets.Raw, never format-probe. func (u URLBuilder) ChatboxChatConfigIni(misc string) []string { return u.chatboxIniCandidates(misc, chatboxChatConfigIni, "") } diff --git a/internal/media/asset.go b/internal/media/asset.go index 7d7d9056..295eeb45 100644 --- a/internal/media/asset.go +++ b/internal/media/asset.go @@ -1,6 +1,7 @@ package media import ( + "context" "errors" "slices" "sync/atomic" @@ -27,6 +28,9 @@ var ErrMissing = errors.New("media: file not found in any source") // ErrRefused reports that the request table was full; ask again later. var ErrRefused = errors.New("media: too many requests") +// ErrStopped reports that the media system stopped before the Asset finished. +var ErrStopped = errors.New("media: the media system stopped") + // ErrWithdrawn reports that the request was withdrawn before it finished. var ErrWithdrawn = errors.New("media: request withdrawn") @@ -41,11 +45,15 @@ type Asset struct { urgent atomic.Bool quiet atomic.Bool sticky atomic.Bool + every bool + hit atomic.Pointer[Hit] finished atomic.Int64 // unix nanoseconds, for expiring Missing done chan struct{} + // stopped is the Manager's, closed when it stops, after which an unfinished Asset never finishes. + stopped <-chan struct{} } -func newAsset(key Key, u Urgency, f Flags, alts []string) *Asset { +func newAsset(key Key, u Urgency, f Flags, alts []string, stopped <-chan struct{}) *Asset { names := make([]string, 0, min(len(alts)+1, maxNames)) names = append(names, key.Path) for _, alt := range alts { @@ -53,7 +61,7 @@ func newAsset(key Key, u Urgency, f Flags, alts []string) *Asset { names = append(names, alt) } } - a := &Asset{key: key, names: names, done: make(chan struct{})} + a := &Asset{key: key, names: names, done: make(chan struct{}), every: f&Unlisted != 0, stopped: stopped} a.urgent.Store(u == Now) a.quiet.Store(f&Quiet != 0) a.sticky.Store(f&Sticky != 0) @@ -106,6 +114,32 @@ func (a *Asset) Result() any { return nil } +// Wait blocks until the Asset is finished, ctx ends or the media system stops, for a caller off the main thread; it +// returns ctx's error or ErrStopped then. +func (a *Asset) Wait(ctx context.Context) error { + select { + case <-a.done: + return nil + case <-ctx.Done(): + return ctx.Err() + case <-a.stopped: + select { + case <-a.done: + return nil + default: + return ErrStopped + } + } +} + +// Hit is the file and source that answered a Ready Asset, or the zero Hit. +func (a *Asset) Hit() Hit { + if h := a.hit.Load(); h != nil { + return *h + } + return Hit{} +} + // Err returns why the Asset can't be ready, or nil. func (a *Asset) Err() error { if e := a.err.Load(); e != nil { diff --git a/internal/media/manager.go b/internal/media/manager.go index 6afab9ce..e8a17d58 100644 --- a/internal/media/manager.go +++ b/internal/media/manager.go @@ -227,9 +227,9 @@ func NewManager(cfg Config) *Manager { } m := &Manager{cfg: cfg, wake: make(chan struct{}, 1), stop: make(chan struct{}), stopped: make(chan struct{}), active: map[Key]*request{}, queues: map[*Pool]*poolQueue{}, hostBusy: map[string]int{}, winners: map[Key]File{}} - m.skipped = newAsset(Key{}, Later, 0, nil) + m.skipped = newAsset(Key{}, Later, 0, nil, m.stopped) m.skipped.finish(Ready, nil, nil, cfg.Clock()) - m.unnamed = newAsset(Key{}, Later, 0, nil) + m.unnamed = newAsset(Key{}, Later, 0, nil, m.stopped) m.unnamed.finish(Missing, nil, nil, cfg.Clock()) go m.run() return m @@ -263,7 +263,7 @@ func (m *Manager) Get(key Key, urgency Urgency, flags Flags, alts ...string) *As } return a } - fresh := newAsset(key, urgency, flags, alts) + fresh := newAsset(key, urgency, flags, alts, m.stopped) if m.assets.CompareAndSwap(key, a, fresh) { m.post(&request{event: eventNew, asset: fresh, urgency: urgency}) return fresh @@ -272,12 +272,12 @@ func (m *Manager) Get(key Key, urgency Urgency, flags Flags, alts ...string) *As } // Later work is refused at the cap, unstored, so the caller's next ask tries again. if urgency == Later && m.count.Load() >= int64(m.cfg.MaxAssets) { - a := newAsset(key, urgency, flags, alts) + a := newAsset(key, urgency, flags, alts, m.stopped) a.finish(Refused, nil, ErrRefused, m.cfg.Clock()) m.refused.Add(1) return a } - a := newAsset(key, urgency, flags, alts) + a := newAsset(key, urgency, flags, alts, m.stopped) if v, loaded := m.assets.LoadOrStore(key, a); loaded { v.(*Asset).add(flags) return v.(*Asset) @@ -291,18 +291,14 @@ func (m *Manager) expired(a *Asset) bool { return a.State() == Missing && m.cfg.Clock().Sub(time.Unix(0, a.finished.Load())) >= m.cfg.MissingTTL } -// Load waits for key on a worker thread; it panics on the main thread, which must never wait. -func (m *Manager) Load(ctx context.Context, key Key, urgency Urgency) (any, error) { +// Load is Get that waits until the Asset finishes, ctx ends or the media system stops, for a caller off the main thread; +// it panics on the main thread, which must never wait. +func (m *Manager) Load(ctx context.Context, key Key, urgency Urgency, flags Flags, alts ...string) (*Asset, error) { if m.cfg.IsMainThread != nil && m.cfg.IsMainThread() { panic("media: Load called on the main thread") } - a := m.Get(key, urgency, 0) - select { - case <-a.done: - return a.Result(), a.Err() - case <-ctx.Done(): - return nil, ctx.Err() - } + a := m.Get(key, urgency, flags, alts...) + return a, a.Wait(ctx) } // Forget drops a finished Asset, such as one whose texture was evicted, so the next Get asks again. @@ -506,6 +502,9 @@ func (m *Manager) end(r *request, state AssetState, result any, err error) { if state == Failed && m.assets.CompareAndDelete(r.asset.key, r.asset) { m.count.Add(-1) } + if state == Ready && r.file != "" { + r.asset.hit.Store(&Hit{File: r.file, Source: m.cfg.Chains[r.asset.key.Place].entries[r.entry].Source}) + } r.asset.finish(state, result, err, m.cfg.Clock()) if m.cfg.Finished != nil { m.cfg.Finished(r.asset) @@ -566,6 +565,17 @@ func (m *Manager) namesOf(a *Asset) []nameFiles { if m.cfg.AllFormats != nil { files.all = m.cfg.AllFormats(a.key, name) } + if a.every { + every := files.all + if m.cfg.AllFormats == nil { + every = EveryFormat(a.key, name) + } + for _, f := range every { + if !slices.Contains(files.server, f) { + files.server = append(files.server, f) + } + } + } names = append(names, files) } if !won { diff --git a/internal/media/manager_test.go b/internal/media/manager_test.go index 2f9094a5..1fda5c3c 100644 --- a/internal/media/manager_test.go +++ b/internal/media/manager_test.go @@ -465,9 +465,9 @@ func TestLoadWaitsOffMainAndRefusesOnMain(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), testTimeout) defer cancel() - got, err := m.Load(ctx, image("a"), Now) - if err != nil || got != "x" { - t.Fatalf("got %v err %v", got, err) + a, err := m.Load(ctx, image("a"), Now, 0) + if err != nil || a.Result() != "x" { + t.Fatalf("got %v err %v", a.Result(), err) } onMain.Store(true) defer func() { @@ -475,7 +475,7 @@ func TestLoadWaitsOffMainAndRefusesOnMain(t *testing.T) { t.Fatal("Load on the main thread did not panic") } }() - _, _ = m.Load(ctx, image("a"), Now) + _, _ = m.Load(ctx, image("a"), Now, 0) } // Every request ends in one final state, whatever mix of paths it takes; a hang here would freeze the wait gate. diff --git a/internal/media/types.go b/internal/media/types.go index 1b78309e..b6dff230 100644 --- a/internal/media/types.go +++ b/internal/media/types.go @@ -77,6 +77,9 @@ const ( Quiet Flags = 1 << iota // Sticky marks work the caller keeps when it withdraws the rest; one caller asking is enough. Sticky + // Unlisted also asks the web for the formats the host's list leaves out, after the ones it names, for a caller that + // must find a file however the host lists it, such as an export. It holds for the request it starts. + Unlisted ) // File is one exact location a source can answer for, such as a candidate URL. diff --git a/internal/media/wait_test.go b/internal/media/wait_test.go new file mode 100644 index 00000000..1f160d34 --- /dev/null +++ b/internal/media/wait_test.go @@ -0,0 +1,76 @@ +package media + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/SyntaxNyah/AsyncAO/internal/config" +) + +const waitTestShort = 20 * time.Millisecond + +func TestWaitReturnsOnceTheAssetFinishes(t *testing.T) { + r := newRemoteRig(t, map[string][]byte{testOrigin + "a" + config.ExtPNG: []byte("x")}) + a := r.m.Get(sprite("a"), Now, 0) + ctx, cancel := context.WithTimeout(context.Background(), testTimeout) + defer cancel() + if err := a.Wait(ctx); err != nil || !a.Ready() { + t.Fatalf("wait %v, state %v", err, a.State()) + } + if h := a.Hit(); h.File != File(testOrigin+"a"+config.ExtPNG) || h.Source != Source(r.remote) { + t.Fatalf("hit %+v, want the png from the remote source", h) + } +} + +func TestWaitGivesUpWithItsContext(t *testing.T) { + r := newRemoteRig(t, nil) + hold := make(chan struct{}) + r.fetch.setHang(hold) + a := r.m.Get(sprite("a"), Now, 0) + ctx, cancel := context.WithTimeout(context.Background(), waitTestShort) + defer cancel() + if err := a.Wait(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("wait %v, want the context's deadline", err) + } + if h := a.Hit(); h != (Hit{}) { + t.Fatalf("an unfinished asset has a hit: %+v", h) + } +} + +func TestUnlistedFindsAFormatTheHostLeavesOut(t *testing.T) { + files := map[string][]byte{testOrigin + "a" + config.ExtPNG: []byte("x")} + listedOnly := newRemoteRig(t, files) + listedOnly.m.Call(func() { listedOnly.builder.Allow(testOrigin, map[Class][]string{ClassEmote: {config.ExtWebP}}) }) + a := listedOnly.m.Get(sprite("a"), Now, 0) + waitFinal(t, a) + if a.Ready() { + t.Fatal("a png the host's list leaves out was found without asking for it") + } + + unlisted := newRemoteRig(t, files) + unlisted.m.Call(func() { unlisted.builder.Allow(testOrigin, map[Class][]string{ClassEmote: {config.ExtWebP}}) }) + b := unlisted.m.Get(sprite("a"), Now, Unlisted) + waitFinal(t, b) + if !b.Ready() || b.Hit().File != File(testOrigin+"a"+config.ExtPNG) { + t.Fatalf("state %v hit %+v, want the png", b.State(), b.Hit()) + } +} + +func TestWaitReturnsWhenTheMediaSystemStops(t *testing.T) { + r := newRemoteRig(t, nil) + r.fetch.setHang(make(chan struct{})) + a := r.m.Get(sprite("a"), Now, 0) + got := make(chan error, 1) + go func() { got <- a.Wait(context.Background()) }() + r.m.Close() + select { + case err := <-got: + if !errors.Is(err, ErrStopped) { + t.Fatalf("wait %v, want ErrStopped", err) + } + case <-time.After(testTimeout): + t.Fatal("a wait outlived the media system") + } +} diff --git a/internal/render/audio.go b/internal/render/audio.go index 4449d555..15ebc441 100644 --- a/internal/render/audio.go +++ b/internal/render/audio.go @@ -199,7 +199,8 @@ func newAudio(mgr *assets.Manager, m *mix.Mixer) *Audio { } a.loopFetchCtx, a.cancelLoopFetch = context.WithCancel(context.Background()) if mgr != nil { - a.fetchSidecar = mgr.FetchRaw + m := mgr.Media() + a.fetchSidecar = func(ctx context.Context, url string) ([]byte, error) { return assets.Raw(ctx, m, url) } a.wake = mgr.NotifyDelivery } if m == nil { diff --git a/internal/ui/app_connect.go b/internal/ui/app_connect.go index 3f387384..c4dea66c 100644 --- a/internal/ui/app_connect.go +++ b/internal/ui/app_connect.go @@ -1173,7 +1173,7 @@ func (a *App) probeCasing(host, name, origin string) { base := courtroom.NewURLBuilder(origin).WithCharCase(cc).CharIcon(name) found := false for _, ext := range []string{config.ExtPNG, config.ExtWebP} { - if _, err := a.d.Manager.FetchRaw(ctx, base+ext); err == nil { + if _, err := assets.Raw(ctx, a.d.Manager.Media(), base+ext); err == nil { found = true break } diff --git a/internal/ui/app_room.go b/internal/ui/app_room.go index f0931dd8..b4ec12ee 100644 --- a/internal/ui/app_room.go +++ b/internal/ui/app_room.go @@ -1438,7 +1438,7 @@ func (a *App) ensurePreviewEmotes(name string) { ctx, cancel := context.WithTimeout(context.Background(), smallFetchTimeout) defer cancel() // Layered: a character from the user's own pack must show their emotes, not the server's. - data, err := mgr.FetchRaw(ctx, url) + data, err := assets.Raw(ctx, mgr.Media(), url) if err != nil { return } @@ -1530,7 +1530,7 @@ func (a *App) loadCharINI() { ch := a.charINIres go func() { // Layered: a character from the user's own folders must bring its own emote list. - data, err := mgr.FetchRaw(context.Background(), url) + data, err := assets.Raw(context.Background(), mgr.Media(), url) if err != nil { ch <- charINIFetch{key: key, char: name, err: err} PushWake() // wake the event-driven loop so Background drains this at idle=0 diff --git a/internal/ui/bgdesign.go b/internal/ui/bgdesign.go index b7e374d7..4201d125 100644 --- a/internal/ui/bgdesign.go +++ b/internal/ui/bgdesign.go @@ -5,6 +5,7 @@ import ( "context" "time" + "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/theme" ) @@ -43,7 +44,7 @@ func (a *App) backgroundDesign(url string) (*theme.INI, bool) { defer cancel() var design *theme.INI // Layered: a pack in the user's own folders ships its design.ini beside its art. - if data, err := mgr.FetchRaw(ctx, url); err == nil { + if data, err := assets.Raw(ctx, mgr.Media(), url); err == nil { design, _ = theme.ParseINI(bytes.NewReader(data)) } res <- bgDesignRead{url, design} diff --git a/internal/ui/bgpicker.go b/internal/ui/bgpicker.go index 940ba2b3..9991369b 100644 --- a/internal/ui/bgpicker.go +++ b/internal/ui/bgpicker.go @@ -77,7 +77,7 @@ func (a *App) openBgPicker() { a.ensureBgList() } -// ensureBgList rebuilds the list from local seeds at once and fetches background/ once via Manager.FetchRaw (cached). +// ensureBgList rebuilds the list from local seeds at once and fetches background/ once via assets.Raw (cached). func (a *App) ensureBgList() { if a.bgPick.forKey != a.serverKey { // New server: seed from last session's cached discovery, then refresh. Cloned so prefs stay unmutated. @@ -110,7 +110,7 @@ func (a *App) ensureBgList() { }() ctx, cancel := context.WithTimeout(context.Background(), bgFetchTimeout) defer cancel() - data, err := mgr.FetchRaw(ctx, listURL) + data, err := assets.Raw(ctx, mgr.Media(), listURL) if err != nil { ch <- bgFetch{key: key, err: err} return diff --git a/internal/ui/charmeta.go b/internal/ui/charmeta.go index 912e10d9..cc020290 100644 --- a/internal/ui/charmeta.go +++ b/internal/ui/charmeta.go @@ -5,6 +5,7 @@ import ( "strings" "time" + "github.com/SyntaxNyah/AsyncAO/internal/assets" "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/theme" ) @@ -116,7 +117,7 @@ func (a *App) charMetaFetchOne(url, char string) { defer cancel() res := charMetaFetch{url: url, showname: char} // no ini ⇒ get_showname's unreadable-ini answer // Layered: a user testing their own character from a mounted folder must see the ini they are editing. - if data, err := mgr.FetchRaw(ctx, url); err == nil { + if data, err := assets.Raw(ctx, mgr.Media(), url); err == nil { if ini, err := courtroom.ParseCharINI(data); err == nil && ini != nil { res.blips = strings.TrimSpace(ini.Blips) res.chat = strings.TrimSpace(ini.Chat) @@ -129,7 +130,7 @@ func (a *App) charMetaFetchOne(url, char string) { // (courtroom_fonts.ini showname_color), each tried down its casing chain. if res.chat != "" { for _, u := range ub.ChatboxChatConfigIni(res.chat) { - if data, err := mgr.FetchRaw(ctx, u); err == nil { + if data, err := assets.Raw(ctx, mgr.Media(), u); err == nil { if rgb, ok := courtroom.ParseChatboxDefaultColor(data); ok { res.chatMsgRGB, res.chatMsgHas = rgb, true } @@ -137,7 +138,7 @@ func (a *App) charMetaFetchOne(url, char string) { } } for _, u := range ub.ChatboxFontsIni(res.chat) { - if data, err := mgr.FetchRaw(ctx, u); err == nil { + if data, err := assets.Raw(ctx, mgr.Media(), u); err == nil { showname, nameOK, message, msgOK := courtroom.ParseChatboxFontsIni(data) if nameOK { res.chatNameRGB, res.chatNameHas = showname, true diff --git a/internal/ui/contentjob.go b/internal/ui/contentjob.go index 0ba1fdd0..f871f6ce 100644 --- a/internal/ui/contentjob.go +++ b/internal/ui/contentjob.go @@ -5,9 +5,9 @@ package ui // found/missing/unreachable per category) and "Package this RP" (write every found asset into a bundle folder in // the archive format, with the report as MISSING-CONTENT.txt). // One contentJob runs at a time (enumerate, probe, report ready, optionally package). Probing runs off the render -// thread because Manager.ResolveRaw / FetchRaw block; a bounded set of workers feeds a bounded result channel that +// thread because assets.Resolve and assets.Raw block; a bounded set of workers feeds a bounded result channel that // tickContentJob polls once per frame, and contentProbeHardCap ends the phase for a dead origin. -// ResolveRaw/FetchRaw go through T2, T3, then source, so nothing here re-probes. +// Both go through memory, the disk cache, the folders, then the web, so nothing here re-probes. // Packaging runs in one generation-checked goroutine with a 1-buffered delivery and writes to disk off the render // thread. Cancel is safe at every phase: the job is replaced by generation and every goroutine finishes. @@ -671,8 +671,8 @@ func contentProbeWorker(mgr *assets.Manager, workCh <-chan contentProbeItem, res } // probeRef resolves one enumerated ref to a status and, if found, its URL. Exact refs (music) are a direct -// FetchRaw; bases probe via ResolveRawFull over the alt spellings (bare X / "(a)/X" for sprites, authored case for -// blips). ResolveRawFull tries a learned host's format first and full-chain-walks a host with no learned entry or +// assets.Raw; bases probe via assets.Resolve with unlisted formats over the alt spellings (bare X / "(a)/X" for sprites, authored case for +// blips). It tries a learned host's format first and full-chain-walks a host with no learned entry or // whose learned format missed. That walk keeps a no-manifest host with mixed per-asset formats honest: workers run // concurrently, so one sprite's RecordSuccess must not lock a sibling of another format out. The live path // deliberately won't do this. Still one probe per candidate (404-TTL and singleflight dedupe), and the winner is @@ -690,7 +690,7 @@ func probeRef(mgr *assets.Manager, ref courtroom.AssetRef) (string, AssetStatus, // other error is a transport fault, Unreachable. Empty without error is Missing. ctx, cancel := context.WithTimeout(context.Background(), exactFetchTimeout) defer cancel() - data, err := mgr.FetchRaw(ctx, ref.Base) + data, err := assets.Raw(ctx, mgr.Media(), ref.Base) if err != nil { if fromPack { return ref.Base, StatusFound, true // your folders have it even though the server does not @@ -708,15 +708,15 @@ func probeRef(mgr *assets.Manager, ref courtroom.AssetRef) (string, AssetStatus, } return ref.Base, StatusFound, fromPack } - if url, _, ok := mgr.ResolveRawFull(ref.Base, ref.Type); ok { - return url, StatusFound, fromPack + if f, ok := assets.Resolve(context.Background(), mgr.Media(), ref.Base, ref.Type, true); ok { + return f.URL, StatusFound, fromPack } for _, alt := range ref.Alts { if alt == "" { continue } - if url, _, ok := mgr.ResolveRawFull(alt, ref.Type); ok { - return url, StatusFound, fromPack + if f, ok := assets.Resolve(context.Background(), mgr.Media(), alt, ref.Type, true); ok { + return f.URL, StatusFound, fromPack } } if fromPack { @@ -725,13 +725,13 @@ func probeRef(mgr *assets.Manager, ref courtroom.AssetRef) (string, AssetStatus, // report implying a recipient would see it. return ref.Base, StatusFound, true } - // ResolveRawFull returns ok=false for both an all-format 404 and a swallowed transport failure, so an unresolved + // assets.Resolve returns ok=false for both an all-format 404 and a transport failure, so an unresolved // base is reported Missing. A wholly dead origin surfaces via the hard cap, which marks the unprobed tail // Unreachable. return ref.Base, StatusMissing, false } -// assetLikelyMissing reports whether a FetchRaw error is a clean 404 (network.ErrAssetNotFound) rather than a +// assetLikelyMissing reports whether an assets.Raw error is a clean 404 (network.ErrAssetNotFound) rather than a // transport problem, which is reported Unreachable. func assetLikelyMissing(err error) bool { return errors.Is(err, network.ErrAssetNotFound) @@ -1104,7 +1104,7 @@ func writeContentBundleCancel(mgr *assets.Manager, destDir, stem string, rec *sc return contentPackageResult{dir: destDir, msg: msg} } -// fetchBundleBytes re-drains one found asset's bytes. The URL is the resolved one the probe fetched, so FetchRaw +// fetchBundleBytes re-drains one found asset's bytes. The URL is the resolved one the probe fetched, so assets.Raw // hits T2 or T3 and touches the network only if both evicted, fetching the same URL with no format probing. // exactFetchTimeout bounds one exact-URL fetch, so a dead host cannot stall a content worker. const exactFetchTimeout = 30 * time.Second @@ -1116,7 +1116,7 @@ func fetchBundleBytes(mgr *assets.Manager, url string) ([]byte, error) { } ctx, cancel := context.WithTimeout(context.Background(), exactFetchTimeout) defer cancel() - return mgr.FetchRaw(ctx, url) + return assets.Raw(ctx, mgr.Media(), url) } // assetTypeFromBundlePath infers the AssetType from the origin-relative directory so the Formats manifest can seed diff --git a/internal/ui/contentjob_test.go b/internal/ui/contentjob_test.go index a156d100..22d87506 100644 --- a/internal/ui/contentjob_test.go +++ b/internal/ui/contentjob_test.go @@ -272,7 +272,7 @@ func TestFormatReportShape(t *testing.T) { // --------------------------------------------------------------------------- // TestContentProbeWindowBounded pins that the probe never runs more than -// contentProbeWorkers ResolveRaw/FetchRaw calls concurrently, however many +// contentProbeWorkers lookups concurrently, however many // assets a scene references — the wave-1 in-flight-window discipline. It wires a // REAL Manager over a slow origin that COUNTS concurrent in-flight fetches; the // observed peak must never exceed the worker window. @@ -1091,7 +1091,7 @@ func existingAorecs(t *testing.T) map[string]bool { // --------------------------------------------------------------------------- // headlessProbeApp wires a headless App with a REAL streaming Manager (no SDL / -// no TextureStore — the content probe path is pure Manager: ResolveRaw/FetchRaw +// no TextureStore — the content probe path is pure media lookups // never touch T1 or the pool's async delivery, so no channel drainer is needed). func headlessProbeApp(t *testing.T, source assets.Fetcher, localMode bool) *App { t.Helper() @@ -1121,7 +1121,7 @@ func headlessProbeApp(t *testing.T, source assets.Fetcher, localMode bool) *App } // localMgr builds a bare Manager over a LocalFetcher mount and returns it plus -// the mount's origin (BaseURL). FetchRaw over that origin reads files written by +// the mount's origin (BaseURL). assets.Raw over that origin reads files written by // seedMount — standing in for the cache tiers the probe would have filled. func localMgr(t *testing.T, mount string) (*assets.Manager, string) { t.Helper() @@ -1151,7 +1151,7 @@ func localMgr(t *testing.T, mount string) (*assets.Manager, string) { } // seedMount writes an asset file into a LocalFetcher mount at its forward-slash -// relative path, so FetchRaw(origin+rel) reads it back. +// relative path, so assets.Raw(origin+rel) reads it back. func seedMount(t *testing.T, mount, rel string, data []byte) { t.Helper() full := filepath.Join(mount, filepath.FromSlash(rel)) diff --git a/internal/ui/contentseed_test.go b/internal/ui/contentseed_test.go index a6cb16ce..3a99c646 100644 --- a/internal/ui/contentseed_test.go +++ b/internal/ui/contentseed_test.go @@ -17,6 +17,8 @@ package ui // through the mounts in the probe path (AO2-parity). import ( + "context" + "github.com/SyntaxNyah/AsyncAO/internal/media" "net/http" @@ -100,7 +102,7 @@ func TestContentSeedGifManifestResolves(t *testing.T) { // TestContentFullChainProbeFindsPNG pins part 2: an origin with NO manifest whose // sprite exists only as .png is FOUND via the full-chain walk (the seed comes // back absent, so the unlearned host is probed across the full configured chain, -// which includes .png). RecordSuccess must learn .png, so a second ResolveRaw is +// which includes .png). RecordSuccess must learn .png, so a second lookup is // a single probe. A genuinely absent asset stays missing after the whole walk. func TestContentFullChainProbeFindsPNG(t *testing.T) { sprite := pngBytes() @@ -168,12 +170,12 @@ func TestContentFullChainProbeFindsPNG(t *testing.T) { // diagnostic walk. What must NOT happen is a probe of a candidate AFTER .png or // a re-walk. Assert instead on the learned-first repeat below. - // A second ResolveRaw (learned-first now) is exactly one probe of .png — served + // A second lookup (learned-first now) is exactly one probe of .png — served // from T2 (already fetched) so the wire count does NOT grow. base := rec.Origin + "characters/phoenix/(a)normal" before := probeCount("/characters/phoenix/(a)normal.png") - if _, _, ok := a.d.Manager.ResolveRaw(base, assets.AssetTypeCharSprite); !ok { - t.Fatal("learned-first ResolveRaw should still find the .png sprite") + if _, ok := assets.Resolve(context.Background(), a.d.Manager.Media(), base, assets.AssetTypeCharSprite, false); !ok { + t.Fatal("learned-first lookup should still find the .png sprite") } if got := probeCount("/characters/phoenix/(a)normal.png"); got != before { t.Errorf(".png probed %d times on the learned-first repeat, want %d (a learned hit re-drains from T2, no new probe)", got, before) @@ -317,7 +319,7 @@ func TestExportSeedBeforeWarm(t *testing.T) { mu.Lock() asked = nil mu.Unlock() - a.d.Manager.ResolveRaw(origin+"characters/x/(a)y", assets.AssetTypeCharSprite) + assets.Resolve(context.Background(), a.d.Manager.Media(), origin+"characters/x/(a)y", assets.AssetTypeCharSprite, false) mu.Lock() defer mu.Unlock() if len(asked) == 0 || asked[0] != "/characters/x/(a)y"+config.ExtGIF { diff --git a/internal/ui/effectspicker.go b/internal/ui/effectspicker.go index 010b48bf..ea787c00 100644 --- a/internal/ui/effectspicker.go +++ b/internal/ui/effectspicker.go @@ -175,7 +175,7 @@ func (a *App) overlayRosterFetchOne(key, folder string) { if manifestURL != "" && mgr != nil { ctx, cancel := context.WithTimeout(context.Background(), overlayFetchTimeout) // Layered: a pack in the user's own folders ships its effects.ini beside its art. - if data, ferr := mgr.FetchRaw(ctx, manifestURL); ferr == nil { + if data, ferr := assets.Raw(ctx, mgr.Media(), manifestURL); ferr == nil { if remote, perr := theme.ParseOverlayFX(bytes.NewReader(data)); perr == nil { remoteNames = theme.OverlayFXNames(remote) // Last in the property pass: a manifest beside the art is the most specific file in the ladder. diff --git a/internal/ui/evidserverpicker.go b/internal/ui/evidserverpicker.go index fbfc1f0f..1f40bcf0 100644 --- a/internal/ui/evidserverpicker.go +++ b/internal/ui/evidserverpicker.go @@ -63,7 +63,7 @@ func (a *App) fetchServerEvidenceIndex() { }() ctx, cancel := context.WithTimeout(context.Background(), evidServerFetchTO) defer cancel() - data, err := a.d.Manager.FetchRaw(ctx, a.urls.EvidenceRoot()) + data, err := assets.Raw(ctx, a.d.Manager.Media(), a.urls.EvidenceRoot()) if err != nil { a.evidServerRes <- nil return diff --git a/internal/ui/gifexport.go b/internal/ui/gifexport.go index 92c9f104..f3503938 100644 --- a/internal/ui/gifexport.go +++ b/internal/ui/gifexport.go @@ -328,7 +328,7 @@ type gifExportJob struct { // per-origin dedupe as the session path. seedDone (1-buffered) delivers the outcome to tickGifSeed. Where the // manifest does not answer, the warm keeps its behavior (demand pipeline and missingno): walking the full chain on // the render path would break zero-fallback. A prior content report of the same demo already learned the formats - // (probeRef, ResolveRawFull). + // (probeRef, assets.Resolve). seeding bool seedDone chan seedResult seedOriginTo string // the origin being seeded (for WarmFromPrefs gating + the overlay) diff --git a/internal/ui/missingno_noblip_test.go b/internal/ui/missingno_noblip_test.go index fd76e287..a1b2bf59 100644 --- a/internal/ui/missingno_noblip_test.go +++ b/internal/ui/missingno_noblip_test.go @@ -208,7 +208,7 @@ func TestSceneWarmNoMissingnoForBareOnlySprite(t *testing.T) { prefixed := local.BaseURL() + "characters/hobo/(a)normal" // Seed the format learn to .png for this host so the folder resolves the bare // PNG (the default probe list is webp-only; a real server would have learned or - // the manifest seeded it — see TestResolveRawFromLocalArchive). + // the manifest seeded it — see TestResolveFromLocalArchive). a.room = &courtroom.Courtroom{} a.room.Scene.Speaker.Visible = true diff --git a/internal/ui/newroom_test.go b/internal/ui/newroom_test.go index 3be0299f..f08ecccc 100644 --- a/internal/ui/newroom_test.go +++ b/internal/ui/newroom_test.go @@ -50,7 +50,7 @@ func roomFactoryApp(t *testing.T) (*App, func()) { // roomFactoryAppMounted is roomFactoryApp with the Manager's local mount FOLDER // handed back, so a gate can write a real asset file into it and drive the byte // path end to end (write characters//char.ini, point urls at -// assets.LocalOriginFor of the same folder, and Manager.FetchRaw reads it). +// assets.LocalOriginFor of the same folder, and assets.Raw reads it). // // The split exists because a fixture that owns its mount privately can only ever // serve misses: every consumer of roomFactoryApp before this one drove the diff --git a/internal/ui/packcharini_test.go b/internal/ui/packcharini_test.go index 816a4823..85ce2b6f 100644 --- a/internal/ui/packcharini_test.go +++ b/internal/ui/packcharini_test.go @@ -2,7 +2,7 @@ package ui // The UI half of "a mounted base answers char.ini too" (issue #72). // -// internal/assets proves FetchRaw reads the pack. These prove the two +// internal/assets proves assets.Raw reads the pack. These prove the two // things only this package can answer: that the ini readers actually CALL it — // the whole defect was a working pack layer nothing on this side reached — and // that a source change drops the PARSED copies, which no texture invalidation diff --git a/internal/ui/wardrobewin.go b/internal/ui/wardrobewin.go index 6d783181..650f1bdc 100644 --- a/internal/ui/wardrobewin.go +++ b/internal/ui/wardrobewin.go @@ -316,7 +316,7 @@ func (a *App) fetchWardrobeServerList() { }() ctx, cancel := context.WithTimeout(context.Background(), wardrobeListTimeout) defer cancel() - data, err := mgr.FetchRaw(ctx, url) + data, err := assets.Raw(ctx, mgr.Media(), url) if err != nil { ch <- wardrobeListFetch{key: key, err: err} } else { From a3a4b68f663709e39be9c7833dba831487773929 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:18:40 +0100 Subject: [PATCH 41/43] render, assets: a pair never shows a character twice With a partner on stage, hold-previous kept whatever a layer last drew. After a paired speaker swap that was the partner, so a cold sprite drew the partner in its slot as well. A layer now holds a different character only while one character is on stage; the same character's previous sprite still bridges a load. A sprite whose bytes arrived but decoded to nothing was never counted as missing: the message waited out strict sequencing's 10 s and the stage then fell back to hold-previous. The pump now raises the missing-asset warning for it, so the message starts and the placeholder draws. Reported with Patty Thompson's one-frame animated "(a)embarrassed" paired with Chihiro Nanami and Dorothy; 3dae85e4 fixed that file's decode. Co-Authored-By: Claude Opus 5.5 --- internal/assets/manager.go | 5 ++ internal/render/holdprev_test.go | 79 ++++++++++++++++++++++++++++++++ internal/render/pump.go | 4 ++ internal/render/pump_test.go | 40 ++++++++++++++++ internal/render/viewport.go | 9 +++- 5 files changed, 136 insertions(+), 1 deletion(-) diff --git a/internal/assets/manager.go b/internal/assets/manager.go index d865c877..0bf0cf54 100644 --- a/internal/assets/manager.go +++ b/internal/assets/manager.go @@ -342,6 +342,11 @@ func (m *Manager) skipExhausted(base string, t AssetType, quiet bool) { if quiet { return // speculative: no one asked for this, so no one hears about it } + m.ReportUndecodable(base, t) +} + +// ReportUndecodable raises the missing-asset warning for an asset whose bytes decode to nothing, which can't load either. +func (m *Manager) ReportUndecodable(base string, t AssetType) { select { case m.warningCh <- Warning{Base: base, Type: t}: default: diff --git a/internal/render/holdprev_test.go b/internal/render/holdprev_test.go index 86b4bc28..ff406c99 100644 --- a/internal/render/holdprev_test.go +++ b/internal/render/holdprev_test.go @@ -378,3 +378,82 @@ func TestSpriteMaskClipsToStage(t *testing.T) { t.Errorf("sprite-mask render allocates %.1f/op, want 0", allocs) } } + +// TestHoldPreviousNeverShowsThePartner: after a paired speaker swap, a cold sprite must not stand in with the +// character who is now on the other side; the same character's previous sprite still does. +func TestHoldPreviousNeverShowsThePartner(t *testing.T) { + const ( + targetW, targetH = 512, 384 + fixtureSize = 64 + bytesPerPixel = 4 + frameDelay = 50 * time.Millisecond + step = 16 * time.Millisecond + pairX, speakerX = 64, 448 + sampleY = targetH / 2 + leftPct, rightPct = -50, 50 + ) + ren, cleanup := newHeadlessRenderer(t) + defer cleanup() + store, err := NewTextureStoreBudget(ren, 0) + if err != nil { + t.Fatal(err) + } + defer store.Purge() + if err := store.Upload("patty", decodedFixture()); err != nil { // red + t.Fatal(err) + } + green := image.NewRGBA(image.Rect(0, 0, fixtureSize, fixtureSize)) + for p := 0; p < len(green.Pix); p += bytesPerPixel { + green.Pix[p+1], green.Pix[p+3] = 0xFF, 0xFF + } + if err := store.Upload("chihiro", &assets.Decoded{ + Width: fixtureSize, Height: fixtureSize, Frames: []*image.RGBA{green}, Delays: []time.Duration{frameDelay}, + }); err != nil { + t.Fatal(err) + } + ct, err := NewCaptureTarget(ren, targetW, targetH) + if err != nil { + t.Skipf("capture target unavailable headlessly: %v", err) + } + defer ct.Close() + + vp := NewViewport(store, false) + vp.SetSpriteLoadMode(SpriteLoadHoldPrev) + scene := &courtroom.Scene{PairActive: true} + scene.Speaker = courtroom.SpriteLayer{Name: "Patty", Active: "patty", Visible: true, OffsetX: rightPct} + scene.Pair = courtroom.SpriteLayer{Name: "Chihiro", Active: "chihiro", Visible: true, OffsetX: leftPct} + pairSide := func() (r, g uint8) { + img, err := ct.Capture(ren, func(dst sdl.Rect) { + vp.Update(scene, step) + vp.Render(ren, scene, dst) + }) + if err != nil { + t.Skipf("ReadPixels unavailable headlessly: %v", err) + } + if spk := img.RGBAAt(speakerX, sampleY); spk.R == 0 && spk.G == 0 { + t.Fatal("setup: the speaker did not draw") + } + px := img.RGBAAt(pairX, sampleY) + return px.R, px.G + } + if _, g := pairSide(); g == 0 { + t.Fatal("setup: the pair partner did not draw") + } + + // Chihiro now speaks; Patty's sprite on the pair side has not arrived. + scene.Speaker = courtroom.SpriteLayer{Name: "Chihiro", Active: "chihiro", Visible: true, OffsetX: rightPct} + scene.Pair = courtroom.SpriteLayer{Name: "Patty", Active: "patty-cold", Visible: true, OffsetX: leftPct} + if r, g := pairSide(); r != 0 || g != 0 { + t.Errorf("Patty's cold slot drew another character (r=%d g=%d), want it empty", r, g) + } + + // Patty's own previous sprite still bridges her next cold one. + scene.Pair.Active = "patty" + if r, _ := pairSide(); r == 0 { + t.Fatal("setup: Patty's sprite did not draw on the pair side") + } + scene.Pair.Active = "patty-cold" + if r, _ := pairSide(); r == 0 { + t.Error("the same character's previous sprite must still hold while the new one loads") + } +} diff --git a/internal/render/pump.go b/internal/render/pump.go index b6ef20e6..2b7ffdfe 100644 --- a/internal/render/pump.go +++ b/internal/render/pump.go @@ -71,6 +71,10 @@ func (p *Pump) Frame() { if d.Err != nil && p.store.MarkFailed(d.Base) { log.Printf("render: asset %s failed: %v", d.Base, d.Err) } + // Shown as missing, so a message waiting on it starts and the sprite draws the placeholder. + if !d.FromPack { + p.mgr.ReportUndecodable(d.Base, d.Type) + } return } // The carry can reorder a partial after its own full set; uploading it would reduce the animation to one frame. diff --git a/internal/render/pump_test.go b/internal/render/pump_test.go index ed92d81f..baef7f7f 100644 --- a/internal/render/pump_test.go +++ b/internal/render/pump_test.go @@ -174,3 +174,43 @@ func TestPumpTransientErrorsDontPin(t *testing.T) { t.Error("corrupt bytes never entered the decode negative cache") } } + +// TestPumpUndecodableReportsMissing: bytes that arrive but don't decode raise the missing-asset warning, so a message +// waiting on the sprite starts and the stage draws the placeholder instead of waiting out its timeout. +func TestPumpUndecodableReportsMissing(t *testing.T) { + const ( + waitLimit = 5 * time.Second + pollEvery = 5 * time.Millisecond + ) + ren, cleanup := newHeadlessRenderer(t) + defer cleanup() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "these bytes are not an image") + })) + defer srv.Close() + + mgr := buildPumpManager(t, network.NewClientNotFoundTTL(0, netproxy.Direct()), false) + store, err := NewTextureStoreBudget(ren, 0) + if err != nil { + t.Fatal(err) + } + defer store.Purge() + pump := NewPump(store, mgr, nil) + + base := srv.URL + "/characters/patty/(a)embarrassed" + mgr.Media().Get(assets.ChainKey(base, assets.AssetTypeCharSprite), media.Now, 0) // AssetType: CharSprite (test) + deadline := time.Now().Add(waitLimit) + for time.Now().Before(deadline) { + pump.Frame() + select { + case w := <-mgr.Warnings(): + if w.Base != base || w.Type != assets.AssetTypeCharSprite { + t.Fatalf("warning for %q (%v), want %q as a character sprite", w.Base, w.Type, base) + } + return + default: + } + time.Sleep(pollEvery) + } + t.Fatal("an undecodable sprite raised no missing-asset warning") +} diff --git a/internal/render/viewport.go b/internal/render/viewport.go index 3575dc50..f841f0b1 100644 --- a/internal/render/viewport.go +++ b/internal/render/viewport.go @@ -48,6 +48,8 @@ type animState struct { // lastGood is the base last drawn; reset keeps it, and a string because a page pointer could be evicted. lastGood string + // lastGoodName is the character lastGood belongs to. + lastGoodName string // scaleName/scaleIdleH hold the idle page height; reset keeps them so a character shares one filter height. scaleName string @@ -339,6 +341,8 @@ type Viewport struct { // spriteLoadMode chooses what a layer draws while its new sprite loads; drawSprite's miss path only. spriteLoadMode int + // soloStage is true while one character is on stage; only then may hold-previous show a different character. + soloStage bool // clipSprites masks character sprites to the stage so a big offset can't spill over the chatbox or log. clipSprites bool @@ -824,6 +828,7 @@ func (v *Viewport) Render(ren *sdl.Renderer, scene *courtroom.Scene, vp sdl.Rect v.maskClip = stage _ = ren.SetClipRect(&v.maskClip) } + v.soloStage = !scene.PairActive && len(scene.Group) == 0 // Group pairing (JSON-only GP roster): draw other members first, front-most last, so the roster's z-order holds. if sl := &scene.Slide; sl.Active { lastVP := vp @@ -1259,7 +1264,9 @@ func (v *Viewport) drawSprite(ren *sdl.Renderer, layer *courtroom.SpriteLayer, a return } // Hold by string as the LRU owns lifetime; draw path only, so the preanim lifecycle never sees it. + // With a partner on stage, another character's sprite would draw them twice. if v.spriteLoadMode == SpriteLoadHoldPrev && anim.lastGood != "" && anim.lastGood != anim.base && + (v.soloStage || anim.lastGoodName == layer.Name) && (v.holdMaxAge <= 0 || anim.coldFor <= v.holdMaxAge) { // max-age knob: 0 = bridge forever if held, ok2 := v.store.Get(anim.lastGood); ok2 && len(held.Frames) > 0 { v.drawHeldSprite(ren, layer, held, vp) @@ -1269,7 +1276,7 @@ func (v *Viewport) drawSprite(ren *sdl.Renderer, layer *courtroom.SpriteLayer, a } // During a crossfade lastGood must keep naming the old sprite while it draws under the ramp. if anim.fadeLeft <= 0 && anim.lastGood != anim.base { - anim.lastGood = anim.base + anim.lastGood, anim.lastGoodName = anim.base, layer.Name } frame := clampFrame(anim.frame, len(page.Frames)) From 5c05a888e13c02d1b7b1554bd3d0192ea9d71a48 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:20:21 +0100 Subject: [PATCH 42/43] ui: IC log colours land on the letters that were coloured The log's word wrap folds whitespace (strings.Fields), but the colour offsets counted the unfolded text. The timestamp's two-space gap became one, so with timestamps on every colour started one letter late and ran one letter long; each wrapped row added the space it broke at, and a double space or newline in the message shifted everything after it. A styled entry is now folded first, with its colour runs kept in step, and each row is found in the folded text. Co-Authored-By: Claude Opus 5.5 --- internal/ui/logcolor.go | 51 ++++++++++++++++++++++++++++++++++++ internal/ui/logcolor_test.go | 43 ++++++++++++++++++++++++++++++ internal/ui/qol.go | 21 ++++++++++++--- internal/ui/screensooc.go | 4 +-- 4 files changed, 114 insertions(+), 5 deletions(-) diff --git a/internal/ui/logcolor.go b/internal/ui/logcolor.go index 3cb7ebff..91454741 100644 --- a/internal/ui/logcolor.go +++ b/internal/ui/logcolor.go @@ -1,6 +1,9 @@ package ui import ( + "strings" + "unicode" + "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/render" "github.com/SyntaxNyah/AsyncAO/internal/sdl" @@ -10,6 +13,54 @@ import ( // Inline-colour rendering for the IC log: maps the chatbox's StyleRuns (see buildColorSpans) onto the log's wrapped // rows. +// collapseStyled folds whitespace as the log's word wrap does (strings.Fields), keeping the head length and the body's +// style runs in step with the folded text; body runes past the runs take the default colour. +func collapseStyled(text string, headRunes int, styles []courtroom.StyleRun) (string, int, []courtroom.StyleRun) { + src := []rune(text) + body := make([]courtroom.StyleRun, 0, len(src)) + for _, s := range styles { + one := s + one.Len = 1 + for range s.Len { + body = append(body, one) + } + } + var b strings.Builder + head := 0 + out := make([]courtroom.StyleRun, 0, len(styles)) + keep := func(r rune, i int) { + b.WriteRune(r) + if i < headRunes { + head++ + return + } + run := courtroom.StyleRun{Len: 1, Color: courtroom.ColorDefault} + if k := i - headRunes; k < len(body) { + run = body[k] + } + if n := len(out); n > 0 && out[n-1].Color == run.Color && out[n-1].Bold == run.Bold && out[n-1].Italic == run.Italic { + out[n-1].Len++ + return + } + out = append(out, run) + } + space := -1 // the first rune of a whitespace run after kept text; it becomes the run's one space + for i, r := range src { + if unicode.IsSpace(r) { + if space < 0 && b.Len() > 0 { + space = i + } + continue + } + if space >= 0 { + keep(' ', space) + space = -1 + } + keep(r, i) + } + return b.String(), head, out +} + // inlineSpanAt returns the colour spans for one wrapped log row: a default-colour span for the head (timestamp and // speaker), then the style runs covering body runes [bodyOff, bodyOff+bodyLen). Pure, so it is testable without SDL. func inlineSpanAt(styles []courtroom.StyleRun, headRunes, bodyOff, bodyLen int, def sdl.Color) []render.ColorSpan { diff --git a/internal/ui/logcolor_test.go b/internal/ui/logcolor_test.go index 9da676a0..0a177412 100644 --- a/internal/ui/logcolor_test.go +++ b/internal/ui/logcolor_test.go @@ -89,3 +89,46 @@ func TestICLogEntryBodyOffset(t *testing.T) { t.Errorf("styles = %v, want one green run of 3", styles) } } + +// TestICLogColorsLandOnTheirLetters: the coloured letters of an IC log entry are the ones the sender coloured, with +// timestamps on, across wrapped rows, and with whitespace the wrap folds away. +func TestICLogColorsLandOnTheirLetters(t *testing.T) { + const ( + wide = 2000 + narrow = 120 // the headless 8 px/char measure: 15 characters a row + ) + def := sdl.Color{A: 255} + for _, tc := range []struct { + name, msg, want string + stamps bool + width int32 + }{ + {"plain", "ab~cd~ef", "cd", false, wide}, + {"timestamp", "ab~cd~ef", "cd", true, wide}, + {"wrapped", "aaaa bbbb cccc dddd ~eeee~ ffff", "eeee", false, narrow}, + {"double space", "ab ~cd~ ef", "cd", false, wide}, + {"newline", `ab\n~cd~ef`, "cd", false, wide}, + } { + t.Run(tc.name, func(t *testing.T) { + a := testTabApp(t) + a.logPct = DefaultScalePct + line, speaker, start, styles := icLogEntry(&protocol.ChatMessage{CharName: "Nya", Message: tc.msg}, true, "", nil) + a.icLog = append(a.icLog, icEntry{text: line, speaker: speaker, styles: styles, bodyRuneStart: start, stamp: "[12:00]"}) + a.icLogSeq++ + colored := "" + for _, row := range a.icWrapped(tc.width, tc.stamps) { + rs := []rune(row.text) + pos := 0 + for _, s := range inlineSpanAt(row.styles, row.headRunes, row.bodyOff, len(rs)-row.headRunes, def) { + if s.Color != def { + colored += string(rs[pos:min(pos+s.Len, len(rs))]) + } + pos += s.Len + } + } + if colored != tc.want { + t.Errorf("coloured letters %q, want %q", colored, tc.want) + } + }) + } +} diff --git a/internal/ui/qol.go b/internal/ui/qol.go index f0d2e106..539e38fb 100644 --- a/internal/ui/qol.go +++ b/internal/ui/qol.go @@ -17,6 +17,7 @@ import ( "unicode/utf8" "github.com/SyntaxNyah/AsyncAO/internal/config" + "github.com/SyntaxNyah/AsyncAO/internal/courtroom" "github.com/SyntaxNyah/AsyncAO/internal/helper/value" "github.com/SyntaxNyah/AsyncAO/internal/protocol" "github.com/SyntaxNyah/AsyncAO/internal/render" @@ -1313,6 +1314,8 @@ type icWrapLine struct { // Both are 0 unless the entry has inline-colour runs. headRunes int bodyOff int + // styles is the entry's runs over its whitespace-folded body, the text the rows were cut from. + styles []courtroom.StyleRun } // logWrapIndentPx is the hanging indent of wrapped rows; drawers wrap against width-logWrapIndentPx. @@ -1369,6 +1372,15 @@ func (a *App) icWrapped(width int32, showStamps bool) []icWrapLine { text = prefix + text stampRunes = utf8.RuneCountInString(prefix) } + // The wrap folds whitespace, so a styled entry is folded first and its offsets count what the rows hold. + styled := len(entry.styles) > 0 + var styles []courtroom.StyleRun + var src []rune + bodyStart := 0 + if styled { + text, bodyStart, styles = collapseStyled(text, stampRunes+entry.bodyRuneStart, entry.styles) + src = []rune(text) + } // Wrap against the drawn width; emoji entries use the rune-granular wrap, as the word-wrap sizes them as tofu. // Trigger the font load off the whole entry first: per-candidate picks see only rows within the cap. a.ctx.noteScript(text) @@ -1379,12 +1391,15 @@ func (a *App) icWrapped(width int32, showStamps bool) []icWrapLine { wrapped = wrapToWidthMeasured(measure, text, width, icWrapMaxLinesPerEntry) } // For inline-colour entries, track each row's rune offset and fold the head into a leading default-colour span. - styled := len(entry.styles) > 0 - bodyStart := stampRunes + entry.bodyRuneStart off := 0 for _, ln := range wrapped { - row := icWrapLine{text: ln, entry: i} + row := icWrapLine{text: ln, entry: i, styles: styles} if styled { + // A row break drops the space it broke at. + first, _ := utf8.DecodeRuneInString(ln) + for off < len(src) && src[off] != first && unicode.IsSpace(src[off]) { + off++ + } n := utf8.RuneCountInString(ln) if head := bodyStart - off; head > 0 { row.headRunes = head diff --git a/internal/ui/screensooc.go b/internal/ui/screensooc.go index 854aab7f..37109e0d 100644 --- a/internal/ui/screensooc.go +++ b/internal/ui/screensooc.go @@ -233,9 +233,9 @@ func (a *App) drawICLogList(list sdl.Rect, canvasInk bool) { indent := a.logRowIndent(logSelIC, ri) // continuation rows hang right of their first row // Inline-colour body: a styled entry draws in its authored colours; ghosted or link-hovered rows use the // single-colour path. - if styles := a.icLog[row.entry].styles; len(styles) > 0 && row.entry != hoverLinkEntry && !ghostedRow { + if len(row.styles) > 0 && row.entry != hoverLinkEntry && !ghostedRow { bodyLen := utf8.RuneCountInString(row.text) - row.headRunes - spans := inlineSpanAt(styles, row.headRunes, row.bodyOff, bodyLen, col) + spans := inlineSpanAt(row.styles, row.headRunes, row.bodyOff, bodyLen, col) a.drawColoredLogRow(font, c.EmojiFont(icPct), list.X+indent, y, wrapW-indent, row.text, spans) } else { a.drawLogLineNamed(font, c.EmojiFont(icPct), list.X+indent, y, wrapW-indent, row.text, lineSpeaker, col, nameInk, boldNames) From ea2e8d97c6d3c93e97e78d84e3833950fe782244 Mon Sep 17 00:00:00 2001 From: SyntaxNyah <235356625+SyntaxNyah@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:24:14 +0100 Subject: [PATCH 43/43] ui: the Wardrobe is square under the Sharp UI shape The Wardrobe drew every panel, row, field, button and checkbox with fixed rounded corners whatever the chrome shape. Its radii now go through wardRad, which is 0 under Sharp (also the default); round icons (the check disc, colour swatches, status dot, iniswap tag) stay round. Ctx.sharp replaces the three copies of the Sharp-or-unset check. Co-Authored-By: Claude Opus 5.5 --- internal/ui/shapemask.go | 7 ++- internal/ui/uiwidgets.go | 2 +- internal/ui/wardrobeadd.go | 12 ++--- internal/ui/wardrobedraw.go | 84 ++++++++++++++++++--------------- internal/ui/wardrobewin_test.go | 17 +++++++ 5 files changed, 75 insertions(+), 47 deletions(-) diff --git a/internal/ui/shapemask.go b/internal/ui/shapemask.go index 930a0ca7..7fea10bd 100644 --- a/internal/ui/shapemask.go +++ b/internal/ui/shapemask.go @@ -270,10 +270,13 @@ func (a *App) shapePage(kind, role string, tier int) (*render.TexturePage, bool) return a.d.Store.Get(shapeTexKey(kind, role, tier)) } +// sharp reports whether the chrome shape is Sharp, which is also the default. +func (c *Ctx) sharp() bool { return c.activeShape == shapeSharp || c.activeShape == "" } + // FillShaped fills r with col in the active chrome shape, or exactly c.Fill on sharp or before masks are resident. // Panel bodies under a flat title bar stay on Fill: the sharp bar would poke square nubs past rounded corners. func (c *Ctx) FillShaped(r sdl.Rect, col sdl.Color) { - if c.activeShape == shapeSharp || c.activeShape == "" || !c.shapeMaskReady || c.shapeFillTex == nil { + if c.sharp() || !c.shapeMaskReady || c.shapeFillTex == nil { c.Fill(r, col) return } @@ -282,7 +285,7 @@ func (c *Ctx) FillShaped(r sdl.Rect, col sdl.Color) { // borderShaped outlines r in col in the active chrome shape, or exactly c.Border on sharp or before masks are resident. func (c *Ctx) borderShaped(r sdl.Rect, col sdl.Color) { - if c.activeShape == shapeSharp || c.activeShape == "" || !c.shapeMaskReady || c.shapeStrokeTex == nil { + if c.sharp() || !c.shapeMaskReady || c.shapeStrokeTex == nil { c.Border(r, col) return } diff --git a/internal/ui/uiwidgets.go b/internal/ui/uiwidgets.go index b0b8246b..fb7eefad 100644 --- a/internal/ui/uiwidgets.go +++ b/internal/ui/uiwidgets.go @@ -172,7 +172,7 @@ func (c *Ctx) ButtonCol(r sdl.Rect, label string, bg, hoverBg, border, text sdl. } // A non-sharp chrome shape draws 9-sliced alpha masks and insets the label by shapeLabelInset so glyphs avoid the // corner curve. Sharp, or before the masks are resident, draws plain Fill+Border+label. - shaped := c.activeShape != shapeSharp && c.activeShape != "" && c.shapeMaskReady + shaped := !c.sharp() && c.shapeMaskReady if shaped { c.FillShaped(r, col) c.borderShaped(r, border) diff --git a/internal/ui/wardrobeadd.go b/internal/ui/wardrobeadd.go index 8e148080..060837a2 100644 --- a/internal/ui/wardrobeadd.go +++ b/internal/ui/wardrobeadd.go @@ -62,12 +62,12 @@ func (a *App) wardrobeAddNames() []string { func (a *App) drawWardrobeAdd(panel sdl.Rect) { c := a.ctx ward := &a.ward - c.FillRound(panel, wardRadPanel, wcOverlay) + c.FillRound(panel, a.wardRad(wardRadPanel), wcOverlay) h := min(wardAddH, panel.H-2*pad) dw := min(wardAddW, panel.W-2*pad) // the dialog narrows with a small window d := sdl.Rect{X: panel.X + (panel.W-dw)/2, Y: panel.Y + (panel.H-h)/2, W: dw, H: h} - c.RoundRect(d, wardRadDlg, 1, wcPanel, wcLineHi) - head := sdl.Rect{X: d.X + 2*wardPanelPad, Y: d.Y + 2*wardPanelPad, W: d.W - 4*wardPanelPad, H: wardSegH + 2*wardOutline + wardRadSeg} + c.RoundRect(d, a.wardRad(wardRadDlg), 1, wcPanel, wcLineHi) + head := sdl.Rect{X: d.X + 2*wardPanelPad, Y: d.Y + 2*wardPanelPad, W: d.W - 4*wardPanelPad, H: wardSegH + 2*wardOutline + a.wardRad(wardRadSeg)} c.LabelClippedFontWeight(c.chromeFace(), head.X, head.Y+(head.H-a.wardLineH())/2, head.W/2, "Add characters", wcText, true) // Close. closeR := sdl.Rect{X: head.X + head.W - wardBtnH + wardPanelPad/2, Y: head.Y + (head.H-wardBtnH+wardPanelPad)/2, W: wardBtnH - wardPanelPad/2, H: wardBtnH - wardPanelPad/2} @@ -152,7 +152,7 @@ func (a *App) drawWardrobeAddRows(r sdl.Rect, names []string, ticks bool) { if len(names) == 0 { return } - c.RoundRect(r, wardRadRow, 1, wcInset, wcLine) + c.RoundRect(r, a.wardRad(wardRadRow), 1, wcInset, wcLine) in := sdl.Rect{X: r.X + wardPanelPad/2, Y: r.Y + wardPanelPad/2, W: r.W - wardPanelPad, H: r.H - wardPanelPad} ward.addScroll -= c.WheelIn(in) * scrollStepPx track := sdl.Rect{X: in.X + in.W - scrollBarW, Y: in.Y, W: scrollBarW, H: in.H} @@ -165,7 +165,7 @@ func (a *App) drawWardrobeAddRows(r sdl.Rect, names []string, ticks bool) { } saved := ward.store.Has(n) if c.hovering(row) && !saved { - c.FillRound(row, wardRadSeg, wcHover) + c.FillRound(row, a.wardRad(wardRadSeg), wcHover) } x := row.X + wardPanelPad if ticks { @@ -194,7 +194,7 @@ func (a *App) drawWardrobeAddRows(r sdl.Rect, names []string, ticks bool) { // drawWardrobeAddIcon is a small initials box with the iniswap tag; the Add list shows names before any icon loads. func (a *App) drawWardrobeAddIcon(name string, r sdl.Rect) { c := a.ctx - c.FillRound(r, wardRadBadge, wcCard) + c.FillRound(r, a.wardRad(wardRadBadge), wcCard) initials := name if len(initials) > 2 { initials = initials[:2] diff --git a/internal/ui/wardrobedraw.go b/internal/ui/wardrobedraw.go index 73823e95..e04eb972 100644 --- a/internal/ui/wardrobedraw.go +++ b/internal/ui/wardrobedraw.go @@ -70,7 +70,7 @@ const ( wardOutline int32 = 2 wardGhostOffX int32 = 12 wardGhostOffY int32 = 8 - // Corner radii. + // Corner radii, applied through wardRad; badges use a.wardRad(wardRadBadge) directly and stay round. wardRadPanel int32 = 8 wardRadCard int32 = 8 wardRadRow int32 = 6 @@ -219,7 +219,7 @@ func (a *App) wardButton(r sdl.Rect, label string, look int) bool { if hover { fill = mixColor(fill, wcText, wardHoverMix) } - c.RoundRect(r, wardRadRow, 1, fill, edge) + c.RoundRect(r, a.wardRad(wardRadRow), 1, fill, edge) if label != "" { c.LabelClipped(r.X+(r.W-min(c.TextWidth(label), r.W))/2, r.Y+(r.H-a.wardLineH())/2, r.W, label, ink) } @@ -248,10 +248,10 @@ func (a *App) wardSegment(r sdl.Rect, label string, on, enabled bool) bool { case !enabled: ink = wcFaint case on: - c.FillRound(r, wardRadSeg, a.ward.accent) + c.FillRound(r, a.wardRad(wardRadSeg), a.ward.accent) ink = wcAccentInk case c.hovering(r): - c.FillRound(r, wardRadSeg, wcLine) + c.FillRound(r, a.wardRad(wardRadSeg), wcLine) } if label != "" { c.Label(r.X+(r.W-c.TextWidth(label))/2, r.Y+(r.H-a.wardLineH())/2, label, ink) @@ -261,7 +261,7 @@ func (a *App) wardSegment(r sdl.Rect, label string, on, enabled bool) bool { // wardPillGroup draws the inset track a run of segments sits in; inner is the segments' area. func (a *App) wardPillGroup(outer sdl.Rect) { - a.ctx.RoundRect(outer, wardRadPanel, 1, wcInset, wcLine) + a.ctx.RoundRect(outer, a.wardRad(wardRadPanel), 1, wcInset, wcLine) } // wardField is a rounded text field: the kit's field without its frame, inside a box that turns blue while focused. @@ -271,7 +271,7 @@ func (a *App) wardField(id string, r sdl.Rect, value, placeholder string) (strin if c.focusID == id { edge = a.ward.accent } - c.RoundRect(r, wardRadRow, 1, wcInset, edge) + c.RoundRect(r, a.wardRad(wardRadRow), 1, wcInset, edge) return c.TextFieldBare(id, sdl.Rect{X: r.X + wardRowGap, Y: r.Y + (r.H-fieldH)/2, W: r.W - 2*wardRowGap, H: fieldH}, value, placeholder) } @@ -289,7 +289,7 @@ func (a *App) drawWardrobePanel(w, h int32) { a.updateWardrobeDrag() chromeH := a.topChromeH() panel := sdl.Rect{X: pad * 3, Y: chromeH + pad*3, W: w - pad*6, H: h - chromeH - pad*6} - c.RoundRect(panel, wardRadPanel, 1, wcPanel, a.ward.accent) + c.RoundRect(panel, a.wardRad(wardRadPanel), 1, wcPanel, a.ward.accent) if ward.store == nil { c.Heading(panel.X+pad, panel.Y+pad, "Wardrobe", wcText) c.Label(panel.X+pad, panel.Y+wardBannerH, "Loading your Wardrobe…", wcDim) @@ -331,7 +331,7 @@ func (a *App) drawWardrobePanel(w, h int32) { label = a.wardrobeFolderName(ward.dragID) } g := sdl.Rect{X: c.mouseX + wardGhostOffX, Y: c.mouseY + wardGhostOffY, W: c.TextWidth(label) + 2*wardPanelPad + wardPanelPad, H: wardMenuRowH} - c.RoundRect(g, wardRadRow, 1, wcInset, a.ward.accent) + c.RoundRect(g, a.wardRad(wardRadRow), 1, wcInset, a.ward.accent) c.Label(g.X+wardPanelPad, g.Y+(g.H-a.wardLineH())/2, label, a.ward.accent) } } @@ -403,7 +403,7 @@ func (a *App) wardIconSegment(r sdl.Rect, icon int, on bool) bool { ink := wcDim if on { ink = wcText - c.FillRound(r, wardRadSeg, wcLine) + c.FillRound(r, a.wardRad(wardRadSeg), wcLine) } c.Icon(icon, sdl.Rect{X: r.X + (r.W-wardIconPx)/2, Y: r.Y + (r.H-wardIconPx)/2, W: wardIconPx, H: wardIconPx}, ink) return hit @@ -543,14 +543,14 @@ func (a *App) drawWardrobeDrawerRow(row wardrobeDrawerRow, r sdl.Rect) int32 { dropping := canDrop && a.offerWardrobeDrop(r, wardDragFolder, f.ID) switch { case dropping: - c.RoundRect(r, wardRadRow, wardOutline, mixColor(wcDrawer, col, wardSelectedTint), col) + c.RoundRect(r, a.wardRad(wardRadRow), wardOutline, mixColor(wcDrawer, col, wardSelectedTint), col) case active: - c.RoundRect(r, wardRadRow, 1, mixColor(wcDrawer, col, wardSelectedTint), mixColor(wcDrawer, col, wardSelectedEdge)) + c.RoundRect(r, a.wardRad(wardRadRow), 1, mixColor(wcDrawer, col, wardSelectedTint), mixColor(wcDrawer, col, wardSelectedEdge)) case hover && !(ward.dragging && ward.dragKind == wardDragFolder && ward.dragID == f.ID): - c.FillRound(r, wardRadRow, wcHover) + c.FillRound(r, a.wardRad(wardRadRow), wcHover) } if ward.dragging && ward.dragKind == wardDragFolder && ward.dragID == f.ID { - c.FillRound(r, wardRadRow, sdl.Color{R: wcDrawer.R, G: wcDrawer.G, B: wcDrawer.B, A: wardDimAlpha}) + c.FillRound(r, a.wardRad(wardRadRow), sdl.Color{R: wcDrawer.R, G: wcDrawer.G, B: wcDrawer.B, A: wardDimAlpha}) } if !row.builtin && hover && c.dropped != "" { a.importWardrobeImage(f.ID, c.dropped) @@ -627,10 +627,10 @@ func (a *App) drawWardrobeRowTools(f config.WardrobeFolder, r sdl.Rect) bool { if c.hovering(del) { delFill = wcDangerLine } - c.RoundRect(edit, wardRadSeg, 1, editFill, wcLineHi) + c.RoundRect(edit, a.wardRad(wardRadSeg), 1, editFill, wcLineHi) c.Icon(iconShapePencil, iconIn(edit), wcSoft) c.Tooltip(edit, "Name, icon and colour") - c.RoundRect(del, wardRadSeg, 1, delFill, wcDangerLine) + c.RoundRect(del, a.wardRad(wardRadSeg), 1, delFill, wcDangerLine) c.Icon(iconShapeCross, iconIn(del), wcDangerSoft) c.Tooltip(del, "Delete folder") switch { @@ -673,7 +673,7 @@ func (a *App) wardNameField(id string, r sdl.Rect, text *string, exceptID, okLab func (a *App) drawWardrobeRename(f config.WardrobeFolder, r sdl.Rect) int32 { ward := &a.ward box := sdl.Rect{X: r.X, Y: r.Y, W: r.W, H: wardFieldH + wardBtnH + 3*wardPanelPad} - a.ctx.RoundRect(box, wardRadRow, 1, wcCard, wcLineHi) + a.ctx.RoundRect(box, a.wardRad(wardRadRow), 1, wcCard, wcLineHi) bottom, ok, cancel := a.wardNameField("wardrename", sdl.Rect{X: r.X + wardPanelPad, Y: r.Y + wardPanelPad, W: r.W - 2*wardPanelPad}, &ward.renameText, f.ID, "Save") switch { case ok: @@ -692,7 +692,7 @@ func (a *App) drawWardrobeDeleteConfirm(f config.WardrobeFolder, count int, r sd btnH := wardBtnH - wardPanelPad/2 h := a.wardLineH() + 3*btnH + 5*wardPanelPad box := sdl.Rect{X: r.X + wardRowGap, Y: r.Y, W: r.W - 2*wardRowGap, H: h} - c.RoundRect(box, wardRadRow, 1, wcDangerBg, wcDangerLine) + c.RoundRect(box, a.wardRad(wardRadRow), 1, wcDangerBg, wcDangerLine) in := sdl.Rect{X: box.X + wardPanelPad + wardRowGap, Y: box.Y + wardPanelPad + wardRowGap, W: box.W - 2*wardPanelPad - 2*wardRowGap} c.LabelClipped(in.X, in.Y, in.W, "Delete "+f.Name+"?", wcText) y := in.Y + a.wardLineH() + wardPanelPad @@ -724,7 +724,7 @@ func (a *App) drawWardrobeLookPanel(f config.WardrobeFolder, r sdl.Rect) int32 { btnH := wardBtnH - wardPanelPad/2 h := 3*lh + wardFieldH + wardChoice + wardSwatch + 2*btnH + 9*wardPanelPad box := sdl.Rect{X: r.X + wardRowGap, Y: r.Y, W: r.W - 2*wardRowGap, H: h} - c.RoundRect(box, wardRadRow, 1, wcCard, wcLineHi) + c.RoundRect(box, a.wardRad(wardRadRow), 1, wcCard, wcLineHi) in := sdl.Rect{X: box.X + wardPanelPad + wardRowGap, Y: box.Y + wardPanelPad + wardRowGap, W: box.W - 2*wardPanelPad - 2*wardRowGap} y := in.Y c.Label(in.X, y, "NAME", wcDim) @@ -746,11 +746,11 @@ func (a *App) drawWardrobeLookPanel(f config.WardrobeFolder, r sdl.Rect) int32 { on := f.Image == "" && (f.Icon == ic.id || (f.Icon == "" && ic.id == wardrobeIcons[0].id)) switch { case on: - c.RoundRect(b, wardRadSeg, wardOutline, mixColor(wcCard, fcol, wardSelectedTint), fcol) + c.RoundRect(b, a.wardRad(wardRadSeg), wardOutline, mixColor(wcCard, fcol, wardSelectedTint), fcol) case c.hovering(b): - c.RoundRect(b, wardRadSeg, 1, wcHover, wcLineHi) + c.RoundRect(b, a.wardRad(wardRadSeg), 1, wcHover, wcLineHi) default: - c.RoundRect(b, wardRadSeg, 1, wcDrawer, wcLineHi) + c.RoundRect(b, a.wardRad(wardRadSeg), 1, wcDrawer, wcLineHi) } ink := wcSoft if on { @@ -814,7 +814,7 @@ func (a *App) drawWardrobeNewFolder(r sdl.Rect) { if c.hovering(b) { fill = wcHover } - c.RoundRect(b, wardRadRow, 1, fill, wcLineHi) + c.RoundRect(b, a.wardRad(wardRadRow), 1, fill, wcLineHi) label := "New folder" lw := c.TextWidth(label) ix := b.X + (b.W-lw-wardIconPx-wardPanelPad)/2 @@ -888,7 +888,7 @@ func (a *App) drawWardrobeToolbar(r sdl.Rect) { if c.focusID == "wardsearch" { edge = a.ward.accent } - c.RoundRect(box, wardRadRow, 1, wcInset, edge) + c.RoundRect(box, a.wardRad(wardRadRow), 1, wcInset, edge) c.Icon(iconShapeSearch, sdl.Rect{X: box.X + wardPanelPad + wardRowGap, Y: box.Y + (box.H-wardCheckIcon-wardOutline*2)/2, W: wardCheckIcon + wardOutline*2, H: wardCheckIcon + wardOutline*2}, wcDim) fieldX := box.X + wardPanelPad*3 + wardOutline ward.search, _ = c.TextFieldBare("wardsearch", sdl.Rect{X: fieldX, Y: box.Y + (box.H-fieldH)/2, W: box.X + box.W - fieldX - wardPanelPad/2, H: fieldH}, ward.search, "Search characters") @@ -898,7 +898,7 @@ func (a *App) drawWardrobeToolbar(r sdl.Rect) { if c.hovering(addR) { fill = wcLineHi } - c.RoundRect(addR, wardRadRow, 1, fill, wcLineHi) + c.RoundRect(addR, a.wardRad(wardRadRow), 1, fill, wcLineHi) c.Icon(iconShapePlus, sdl.Rect{X: addR.X + wardSegPad - wardRowGap, Y: addR.Y + (addR.H-wardCheckIcon-wardOutline)/2, W: wardCheckIcon + wardOutline, H: wardCheckIcon + wardOutline}, wcText) c.LabelClippedFontWeight(c.chromeFace(), addR.X+wardSegPad+wardIconPx-wardRowGap, addR.Y+(addR.H-a.wardLineH())/2, addR.W, label, wcText, true) if c.ClickedIn(addR) { @@ -1078,17 +1078,17 @@ func (a *App) drawWardrobeItem(idx int, it wardrobe.Item, r sdl.Rect) { hover := c.hovering(r) && !ward.dragging dropping := a.wardrobeReorderable() && ward.dragKind == wardDragChar && ward.dragID != it.Char && a.offerWardrobeDrop(r, wardDragChar, it.Char) if dropping { - c.FillRound(sdl.Rect{X: r.X - wardOutline*2, Y: r.Y - wardOutline*2, W: r.W + 4*wardOutline, H: r.H + 4*wardOutline}, wardRadCard+wardOutline, a.ward.accent) - c.FillRound(sdl.Rect{X: r.X - wardOutline, Y: r.Y - wardOutline, W: r.W + 2*wardOutline, H: r.H + 2*wardOutline}, wardRadCard, wcPanel) + c.FillRound(sdl.Rect{X: r.X - wardOutline*2, Y: r.Y - wardOutline*2, W: r.W + 4*wardOutline, H: r.H + 4*wardOutline}, a.wardRad(wardRadCard)+wardOutline, a.ward.accent) + c.FillRound(sdl.Rect{X: r.X - wardOutline, Y: r.Y - wardOutline, W: r.W + 2*wardOutline, H: r.H + 2*wardOutline}, a.wardRad(wardRadCard), wcPanel) } var icon sdl.Rect lh := a.wardLineH() if ward.listView { switch { case selected: - c.RoundRect(r, wardRadRow, 1, a.ward.selected, a.ward.accent) + c.RoundRect(r, a.wardRad(wardRadRow), 1, a.ward.selected, a.ward.accent) case hover: - c.FillRound(r, wardRadRow, wcHover) + c.FillRound(r, a.wardRad(wardRadRow), wcHover) } icon = sdl.Rect{X: r.X + wardPanelPad + wardOutline, Y: r.Y + (r.H-wardListIcon)/2, W: wardListIcon, H: wardListIcon} } else { @@ -1099,7 +1099,7 @@ func (a *App) drawWardrobeItem(idx int, it wardrobe.Item, r sdl.Rect) { case hover: fill = wcHover } - c.RoundRect(r, wardRadCard, wardOutline, fill, edge) + c.RoundRect(r, a.wardRad(wardRadCard), wardOutline, fill, edge) iconY := r.Y + wardPanelPad + wardOutline if ward.nameAbove { iconY = r.Y + r.H - wardPanelPad - wardOutline - ward.iconPx @@ -1141,9 +1141,9 @@ func (a *App) drawWardrobeItem(idx int, it wardrobe.Item, r sdl.Rect) { } } if ward.dragging && ward.dragKind == wardDragChar && ward.dragID == it.Char { - rad := wardRadCard + rad := a.wardRad(wardRadCard) if ward.listView { - rad = wardRadRow + rad = a.wardRad(wardRadRow) } c.FillRound(r, rad, sdl.Color{R: wcPanel.R, G: wcPanel.G, B: wcPanel.B, A: wardDimAlpha}) } @@ -1194,7 +1194,7 @@ func (a *App) wardrobeItemInput(it wardrobe.Item, r sdl.Rect) { func (a *App) drawWardrobeCharIcon(idx int, it wardrobe.Item, r sdl.Rect) { c := a.ctx ward := &a.ward - rad := wardRadBadge + rad := a.wardRad(wardRadBadge) c.FillRound(r, rad, wcInset) base := a.urls.CharIcon(it.Char) if page, ok := a.cachedPage(&ward.pages, &ward.pagesGen, len(ward.flat), idx, base); ok && len(page.Frames) > 0 { @@ -1394,11 +1394,11 @@ func (a *App) drawWardrobeMoreMenu() { } h := int32(ward.moreN)*wardMenuRowH + wardPanelPad menu := sdl.Rect{X: max(ward.moreAt.X+ward.moreAt.W-wardMenuW, 0), Y: ward.moreAt.Y - h - wardRowGap*2, W: wardMenuW, H: h} - c.RoundRect(menu, wardRadRow, 1, wcCard, wcLineHi) + c.RoundRect(menu, a.wardRad(wardRadRow), 1, wcCard, wcLineHi) for i := range ward.moreN { row := sdl.Rect{X: menu.X + wardPanelPad/2, Y: menu.Y + wardPanelPad/2 + int32(i)*wardMenuRowH, W: menu.W - wardPanelPad, H: wardMenuRowH} if c.hovering(row) { - c.FillRound(row, wardRadSeg, wcLine) + c.FillRound(row, a.wardRad(wardRadSeg), wcLine) } ink := wcText if ward.moreIDs[i] == wardActRemove { @@ -1505,20 +1505,20 @@ func (a *App) drawWardrobeMoveMenu(content sdl.Rect) { h := int32(len(rows))*wardMenuRowH + wardPanelPad menu := sdl.Rect{X: content.X + 2*wardPanelPad + wardFolderColW + 2*wardPanelPad, Y: content.Y + content.H - wardBarH - h - wardRowGap*2, W: wardMenuW, H: h} menu.Y = max(menu.Y, content.Y) - c.RoundRect(menu, wardRadRow, 1, wcCard, wcLineHi) + c.RoundRect(menu, a.wardRad(wardRadRow), 1, wcCard, wcLineHi) for i, mr := range rows { row := sdl.Rect{X: menu.X + wardPanelPad/2, Y: menu.Y + wardPanelPad/2 + int32(i)*wardMenuRowH, W: menu.W - wardPanelPad, H: wardMenuRowH} if c.hovering(row) { - c.FillRound(row, wardRadSeg, wcLine) + c.FillRound(row, a.wardRad(wardRadSeg), wcLine) } x := row.X + wardPanelPad if checklist { box := sdl.Rect{X: x, Y: row.Y + (row.H-wardCheckPx)/2, W: wardCheckPx, H: wardCheckPx} if mr.ticked { - c.FillRound(box, wardRadBadge, a.ward.accent) + c.FillRound(box, a.wardRad(wardRadBadge), a.ward.accent) c.Icon(iconShapeCheck, sdl.Rect{X: box.X + (box.W-wardCheckIcon)/2, Y: box.Y + (box.H-wardCheckIcon)/2, W: wardCheckIcon, H: wardCheckIcon}, wcAccentInk) } else { - c.RoundRect(box, wardRadBadge, 1, wcInset, wcLineHi) + c.RoundRect(box, a.wardRad(wardRadBadge), 1, wcInset, wcLineHi) } x += wardCheckPx + wardPanelPad } @@ -1545,3 +1545,11 @@ func (a *App) drawWardrobeMoveMenu(content sdl.Rect) { ward.moveMenu = false } } + +// wardRad is a Wardrobe corner radius under the chrome shape: square corners under Sharp. +func (a *App) wardRad(r int32) int32 { + if a.ctx.sharp() { + return 0 + } + return r +} diff --git a/internal/ui/wardrobewin_test.go b/internal/ui/wardrobewin_test.go index ff96d409..e9fc9b4a 100644 --- a/internal/ui/wardrobewin_test.go +++ b/internal/ui/wardrobewin_test.go @@ -286,3 +286,20 @@ func TestWardrobeClickOnlySelectsByDefault(t *testing.T) { t.Fatalf("a click switched to slot %d or didn't select (sel %q)", a.sess.MyCharID, a.ward.sel) } } + +// TestWardrobeCornersFollowSharp: under the Sharp chrome shape the Wardrobe's panels and controls are square; other +// shapes keep its rounded corners. +func TestWardrobeCornersFollowSharp(t *testing.T) { + a := wardrobeTestApp(t) + for _, shape := range []string{shapeSharp, shapeRounded, shapePillKey} { + a.d.Prefs.SetChromeShape(shape) + a.refreshShapeMasks() + want := wardRadRow + if shape == shapeSharp { + want = 0 + } + if got := a.wardRad(wardRadRow); got != want { + t.Errorf("shape %q: row radius %d, want %d", shape, got, want) + } + } +}