desktop

package module
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: GPL-3.0 Imports: 53 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

eblitui-desktop

Full-featured desktop application UI for eblitui emulator cores. Built on Ebiten and ebitenui, it provides a complete desktop experience with a game library, settings, shader effects, save states, rewind, cheats, RetroAchievements, and gamepad navigation.

Usage

package main

import (
    "log"

    "github.com/user-none/eblitui/coreif"
    "github.com/user-none/eblitui/desktop"
)

func main() {
    var factory coreif.CoreFactory = myFactory()
    emu := desktop.Emulator{
        Name:        "myemu",
        Version:     "1.0.0",
        DataDirName: "myemu",
    }
    if err := desktop.Run(factory, emu); err != nil {
        log.Fatal(err)
    }
}

Run is the single entry point. It initializes storage, configures the Ebiten window, and starts the application loop. The CoreFactory supplies the core: the emulation and the facts about it in coreif.SystemInfo. The Emulator describes the application built around the core:

Field Description
Name, Version Window title, About, and the RetroAchievements client name
DataDirName Data directory name (see Data Storage)
Icon PNG, JPEG, or WebP icon for the window and About
RetroAchievementsConsoleID The console's RetroAchievements ID; 0 turns achievements off
CheatFormat The cheats system whose code formats the emulator's cheats use (e.g. "saturn"); empty turns cheats off
Update Where releases are published, the running version, and the update signing public keys (algorithm:base64); nil or no keys turns update checks off
Artwork The artwork site's HTTPS base URL and the public keys (algorithm:base64) trusted to sign its index; nil turns artwork downloads off
Metadata Source of game metadata (content.MetadataSource); nil shows file names only
Cheats Source of database cheats (content.CheatsSource); nil offers custom cheats only
Rumble Source of .erumble rumble files (content.RumbleSource); nil turns rumble off

Application States

The app is a state machine that transitions between screens:

State Screen Description
StateLibrary Library Game grid/list with artwork, search, and sorting
StateDetail Detail Box art over the page sidebar: Overview (game info, discs, achievement progress), Artwork (covers, discs, flyers and posters on disk), Cheats, Settings, and Screenshots
StateSettings Settings Tabbed configuration (Library, Appearance, Video, Audio, Rewind, RetroAchievements)
StateScanProgress Scan Progress ROM scanning with discovery and artwork phases
StateError Error Startup error handling (corrupted config recovery)
StatePlaying Gameplay Active emulation with pause menu overlay
StateFilePicker File Picker Full-screen file and folder selection

Features

Game Library
  • Scan directories for ROMs, keyed by CRC32 for cartridges and the disc's product number for disc games
  • Game metadata (title, region, developer, and more) from the emulator's Metadata source, looked up when shown; the library stores none of it, and a game without metadata shows its file name
  • Artwork downloaded during library scans from the emulator's artwork site (Emulator.Artwork): the site's index.json lists each game ID's images (front and back covers, discs, flyers, posters) with the values that tell images of one type apart (disc number, region, variant letter), and their size, CRC-32, and SHA-256. The index is used only when index.sig holds a valid signature by one of the artwork Keys; otherwise no artwork is downloaded. A scan downloads the images that are missing or whose size or CRC-32 differs from the index, and keeps a download only when its size and SHA-256 match. The Library setting "Artwork Download" limits which images a scan downloads (all artwork, front cover, both covers, or none); with none the index is not fetched. It never removes artwork already on disk. Images are stored under names built from the index values, such as disc_2_eu.webp or flyer_b.webp. Images larger than 4096x4096 are not decoded
  • The library and the detail sidebar show the front cover: one without a region first, then USA, Japan, Europe, and any other region. The detail Artwork page shows every image on disk, in order front, back, discs, flyers, posters, by disc number, region and variant. A game without boxart.webp shows its older boxart.png, which Clean Library removes once boxart.webp is present
  • Grid (icon) and list view modes
  • Sort by title, last played, or play time
  • Favorites filter
  • Search overlay with keyboard filter
Gameplay
  • Dedicated emulation goroutine with audio-driven timing (ADT)
  • Double-buffered framebuffer for thread-safe rendering
  • Aspect-ratio-correct scaling with optional display cropping
  • Keyboard input: WASD for D-pad, JKL/UIO for buttons
  • Gamepad input: standard layout with 2-player support
  • Gamepad rumble/haptic feedback via .erumble rumble files
  • Pause menu with resume, return to library, and exit options
  • Play time tracking per game
Save States
  • 10 save slots per game
  • Auto-save on exit, auto-resume on launch
  • SRAM battery save persistence
  • Resume state (separate from manual slots)
Rewind
  • Configurable buffer size and frame step
  • Hold-to-rewind with acceleration curve
  • Requires SaveStater interface from the core
Fast Forward
  • 1x / 2x / 3x speed toggle
  • Audio averaging for downsampled playback
  • Optional mute during fast forward
Rumble

Gamepad rumble support using .erumble rumble files (see the rumble module), supplied by the emulator's Rumble source and looked up by game ID when a game starts. A disc game uses a file for the disc being played (<gameid>.disc<n>) when the source has one, otherwise the game's shared file. Rumble needs the core to expose memory.

Rumble files define memory addresses to monitor and the conditions that trigger haptic feedback. The rumble engine evaluates these conditions each frame and drives the gamepad motors.

Rumble intensity is set per controller profile as a multiplier from 0 (off) to 3x in 0.05 steps. The authored motor levels are multiplied by it and clamped to the gamepad maximum.

Requires the core to implement coreif.Memory.

Note The number of games with rumble support is severely limited. Very few games have rumble files and the number of events that trigger a rumble is also sparse. The intensity and duration of rumble can be inconsistent between games.

Cheats

The detail screen's Cheats page lists a game's cheats with an On/Off toggle each. Cheats are applied between emulated frames through the core's memory interface, so they take effect without changing the core.

Database cheats come from the emulator's Cheats source, looked up by the game's ID: a name and a code string per cheat, decoded the same way as custom cheats. Cheats whose code cannot be decoded or converted to the core's memory byte order are hidden, and the master code is not applied. Every cheat starts off.

Custom cheats are added on the Cheats page with a name and a code string. Codes can be pasted with several codes separated by spaces, "+", or new lines. Duplicate codes are rejected, and a custom cheat whose code no longer parses shows why in place of its code.

Cheat support is available when the core implements coreif.Memory and the emulator's CheatFormat names a system the cheats package knows. Currently that is "saturn" (Action Replay codes).

Per-Game Settings

The detail screen's Settings page overrides global settings for one game. It lists the core options the core marks PerGame (Bool and Select options) under the name of the settings page each is on, and the preprocessing shader effects under Video. Each setting cycles through Inherit, which uses the global setting, then the setting's values. Reset All to Global removes every override of the game.

Overrides are stored in the game's settings file and apply when the game launches.

Shader Effects

Shader effects can be enabled independently for the UI and gameplay contexts. Multiple shaders can be active simultaneously and are applied in weight-based order.

Preprocessing effects:

  • xBR - Pixel art edge smoothing
  • Phosphor Persistence - CRT phosphor decay ghosting

Post-processing shaders:

  • CRT - Curved screen with RGB separation and vignette
  • Scanlines - Horizontal scanline effect
  • Phosphor Glow - Bright pixel bloom
  • LCD Grid - Visible pixel grid with RGB subpixels
  • Color Bleed - Composite video color bleeding
  • Dot Matrix - Circular CRT phosphor dots
  • NTSC - NTSC composite signal artifacts
  • Rainbow - Rainbow banding interference
  • Gamma - Gamma correction
  • Halation - CRT internal light scattering
  • RF Noise - RF signal noise
  • Rolling Band - CRT rolling band interference
  • VHS - VHS tape distortion
  • Interlace - Interlaced display simulation
  • Horizontal Soften - Horizontal blur
  • Vertical Blur - Vertical blur
  • Monochrome - Grayscale conversion
  • Sepia - Sepia tone

Shaders are written in Ebiten's Kage shading language.

RetroAchievements
  • Login with RetroAchievements account
  • Achievement tracking and unlock notifications with sound
  • Badge and image caching
  • Auto-screenshot on achievement unlock
  • Encore mode (re-trigger unlocked achievements)
  • Spectator mode (track without submitting)
  • In-game achievement overlay
  • Per-game and library-wide progress tracking

Requires the core to implement coreif.Memory.

Themes

Supports a variety of built-in themes. The UI, font included, scales with the window size so it stays readable from a desktop window up to a TV.

Settings

Organized in tabbed sections:

  • Library - Add/remove folders, scan, clean missing games
  • Appearance - Theme
  • Video - Shader effects for UI and gameplay
  • Audio - Volume, mute, fast-forward mute
  • Input - Button bindings, rumble level
  • Rewind - Enable/disable, buffer size, frame step
  • RetroAchievements - Login, notification preferences, modes

Data Storage

Application data is stored per-emulator using Emulator.DataDirName:

Platform Path
macOS ~/Library/Application Support/<DataDirName>/
Linux ~/.local/share/<DataDirName>/ (or $XDG_DATA_HOME)
Windows %APPDATA%/<DataDirName>/

Directory structure:

<DataDirName>/
    config.json      - Application settings
    library.json     - Game library and scan state
    removed.json     - User data of games removed from the library
    gamesettings/    - Per-game settings (save state slot, cheat choices, setting overrides)
    artwork/         - Game artwork images, a directory per game (<type>[_<disc>][_<region>][_<variant>].webp)
    saves/           - SRAM and save state files
    screenshots/     - Screenshot captures

Per-game settings live in one JSON file per game under gamesettings/, with a section per feature. The library file holds no per-game settings; a version 1 library's save slots are moved there on first load. Library entries hold a game's ID, files, and user data only; a version 2 library's metadata fields are dropped on first load.

Scanning never removes games. The detail screen offers Remove Disc when the selected disc's file is missing and Remove from Library when every file of the game is missing. Clean Library in settings does both for the whole library. A removed game's entry, without its file locations and added time, moves to removed.json, and a scan that finds the game again restores its play time, favorite, and other user data. An unreadable removed.json is treated as empty and overwritten on the next removal.

All JSON writes are atomic (write to temp, rename) to prevent corruption.

Sub-packages

Package Description
screens UI screens (library, detail, settings, scan, error, file picker)
screens/detail Detail screen pages: Overview, Cheats, Settings, and Screenshots
screens/settings Settings screen sections
cheats Cheat code string decoding into memory operations (standard library only)
gamecheats A game's database and custom cheats, shared by the Cheats page and the cheat engine
storage Config, library, and per-game settings persistence with validation
widgets Shared ebitenui widget builders, the scroll view, sidebar, and multi-line text input
widgets/textedit Text, caret, and selection model behind the multi-line text input
shader Shader registry, compilation, and effect pipeline
style Themes, DPI-aware layout constants, widget builders
types Shared interfaces for cross-package use
achievements RetroAchievements manager and unlock sounds
filebrowser Directory listing, path input parsing and sidebar places for the file picker
scanner Background ROM scanning and artwork downloads
artwork The artwork index format, which artwork files to download, local artwork listing and captions, and box art lookup
signing Signing key parsing and detached signature verification for the update manifest and the artwork index
metadata The emulator's game metadata, and title and region resolution
content The game metadata and cheat types, and the source interfaces an emulator supplies metadata, cheats, and rumble files through
netutil HTTP download helpers
display Aspect ratio sizing, scaling, and DPI helpers for the game image

Dependencies

Key external dependencies:

  • github.com/hajimehoshi/ebiten/v2 - Game engine and rendering
  • github.com/ebitenui/ebitenui - UI widget framework
  • github.com/ebitengine/oto/v3 - Audio output
  • github.com/user-none/eblitui/coreif - Core interfaces
  • github.com/user-none/eblitui/romloader - ROM loading
  • github.com/user-none/go-rcheevos - RetroAchievements client
  • golang.design/x/clipboard - Clipboard access
  • golang.org/x/image - Font rendering
  • golang.org/x/sys - Windows drive and known folder lookup for the file picker

Testing

go test ./...

Test coverage includes state management, audio buffering, save states, rewind, turbo, pause menu, achievement overlay, search, scanning, storage validation, shader ordering, themes, rumble engine, cheat decoding and the cheat engine, the Cheats page, the text edit model, and game metadata resolution.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoCreateFirstProfile added in v0.5.0

func AutoCreateFirstProfile(input *storage.InputConfig, pads []PadInfo) bool

AutoCreateFirstProfile creates a profile for the first connected pad and assigns it to player 1. This happens exactly once: only when no controller profiles of any kind exist and no player has an assignment. All other profile creation is explicit through settings. Returns true if input was modified (the caller applies the change to the config).

func FireMotorStates added in v0.5.0

func FireMotorStates(states []rumble.MotorState, scales [maxPlayers]float64, active map[int]bool) map[int]bool

FireMotorStates applies the rumble engine's per-frame motor levels to the gamepads, scaled by each player's profile rumble scale. Levels are applied as authored with no minimum floors. A player whose scale is 0 (or who has no profile) gets no rumble. active is the set of players vibrating from the previous frame; players absent from states are stopped. Returns the new active set. Must run on the Ebiten thread.

func GenerateBaselineMapping added in v0.5.0

func GenerateBaselineMapping(sdlID, name string, buttonCount int, restingAxes []float64) string

GenerateBaselineMapping builds a standard-layout mapping line for a controller with the given SDL GUID, display name, raw button count, and per-axis resting values. Axes resting at -1 are assigned as triggers, the rest as stick axes in leftx/lefty/rightx/righty order. Raw buttons fill the remaining standard slots in order. The d-pad is mapped to hat 0 with the conventional direction bits, since raw hats are not observable. Returns "" if sdlID is empty.

func IsReservedKey

func IsReservedKey(k ebiten.Key) bool

IsReservedKey returns true if the key is reserved for UI functions.

func KeyToName

func KeyToName(k ebiten.Key) (string, bool)

KeyToName converts an ebiten.Key to its name string. Returns the name and true if the key has a name, or "" and false otherwise.

func PadToName

func PadToName(b ebiten.StandardGamepadButton) (string, bool)

PadToName converts an ebiten.StandardGamepadButton to its name string. Returns the name and true if the button has a name, or "" and false otherwise.

func ParseKey

func ParseKey(name string) (ebiten.Key, bool)

ParseKey converts a key name string to an ebiten.Key. Returns the key and true if the name is valid, or 0 and false otherwise.

func ParsePad

func ParsePad(name string) (ebiten.StandardGamepadButton, bool)

ParsePad converts a gamepad button name string to an ebiten.StandardGamepadButton. Returns the button and true if the name is valid, or 0 and false otherwise.

func PollButtons

func PollButtons(mapping InputMapping, gamepadID ebiten.GamepadID, hasGamepad bool) uint32

PollButtons reads P1 input from keyboard and gamepad (including D-pad and analog stick). All buttons including D-pad are in the mapping. Returns a button bitmask.

func PollGamepadButtons

func PollGamepadButtons(mapping InputMapping, gamepadID ebiten.GamepadID) uint32

PollGamepadButtons reads P2 input from gamepad only (D-pad + analog stick + mapped buttons). No keyboard since that belongs to P1. All D-pad buttons are expected in the mapping.

func ResolveKeyDisplay

func ResolveKeyDisplay(buttonName string, defaultKey string, overrides map[string]string) string

ResolveKeyDisplay returns the display string for a button's current keyboard binding, checking overrides first then falling back to the provided default.

func ResolvePadDisplay

func ResolvePadDisplay(buttonName string, defaultPad string, overrides map[string]string) string

ResolvePadDisplay returns the display string for a button's current controller binding, checking overrides first then falling back to the provided default.

func Run

func Run(factory coreif.CoreFactory, emu Emulator) error

Run is the public entry point for the standalone UI. It initializes storage, configures the window, creates the app, and starts the Ebiten game loop. factory supplies the core; emu describes the application built around it.

Types

type AchievementOverlay

type AchievementOverlay struct {
	// contains filtered or unexported fields
}

AchievementOverlay shows achievements during gameplay

func NewAchievementOverlay

func NewAchievementOverlay(manager *achievements.Manager) *AchievementOverlay

NewAchievementOverlay creates a new achievement overlay

func (*AchievementOverlay) Draw

func (o *AchievementOverlay) Draw(screen *ebiten.Image)

Draw renders the overlay

func (*AchievementOverlay) Hide

func (o *AchievementOverlay) Hide()

Hide hides the achievement overlay

func (*AchievementOverlay) InitForGame

func (o *AchievementOverlay) InitForGame()

InitForGame prepares the overlay for a new game session. The manager already caches achievements on LoadGame, so this just resets overlay state.

func (*AchievementOverlay) IsVisible

func (o *AchievementOverlay) IsVisible() bool

IsVisible returns whether the overlay is visible

func (*AchievementOverlay) Reset

func (o *AchievementOverlay) Reset()

Reset clears session state when the game ends

func (*AchievementOverlay) Show

func (o *AchievementOverlay) Show()

Show displays the achievement overlay

func (*AchievementOverlay) Update

func (o *AchievementOverlay) Update(nav UINavigation)

Update handles input for the overlay. Navigation (keyboard arrows, D-pad, left analog stick) and close (ESC/B/Start) come from the shared InputManager via nav. Page/Home/End and the mouse wheel are handled directly since they are not part of UINavigation.

type App

type App struct {
	// contains filtered or unexported fields
}

App is the main application struct that implements ebiten.Game

func (*App) Draw

func (a *App) Draw(screen *ebiten.Image)

Draw implements ebiten.Game

func (*App) Exit

func (a *App) Exit()

Exit closes the application

func (*App) GameInfo added in v0.8.0

func (a *App) GameInfo(game *storage.GameEntry) storage.GameKeys

GameInfo returns the keys a library entry is sorted and searched by: its title and supported region codes.

func (*App) GameMetadata added in v0.8.0

func (a *App) GameMetadata(gameID string) (content.GameMetadata, bool)

GameMetadata returns the emulator's metadata for a game ID and true, or false when it has none for it.

func (*App) GameTitle added in v0.8.0

func (a *App) GameTitle(game *storage.GameEntry) string

GameTitle returns the title to show for a library entry.

func (*App) GetExtensions

func (a *App) GetExtensions() []string

GetExtensions returns the file extensions for the core's content: the disc image formats for a disc core, or the declared ROM extensions otherwise.

func (*App) GetMissingArtImageData

func (a *App) GetMissingArtImageData() []byte

GetMissingArtImageData returns the raw embedded missing-art image data shown for games that have no artwork file.

func (*App) GetPlaceholderImageData

func (a *App) GetPlaceholderImageData() []byte

GetPlaceholderImageData returns the raw embedded placeholder image data used as the loading indicator while artwork is being loaded asynchronously.

func (*App) GetWindowConfig

func (a *App) GetWindowConfig() (width, height int, x, y *int, fullscreen bool)

GetWindowConfig returns the saved window dimensions, position, and fullscreen state from config. This should be called before RunGame to set the initial window size.

func (*App) GetWindowWidth

func (a *App) GetWindowWidth() int

GetWindowWidth returns the current window width for responsive layouts

func (*App) LaunchGame

func (a *App) LaunchGame(gameID string, resume bool, discIndex int)

LaunchGame starts the emulator with the specified game. discIndex selects the disc of a multi-disc game; -1 uses the remembered SelectedDisc. Ignored for single-disc and cartridge games.

func (*App) Layout

func (a *App) Layout(outsideWidth, outsideHeight int) (int, int)

Layout implements ebiten.Game

func (*App) OpenFilePicker added in v0.7.0

func (a *App) OpenFilePicker(req types.FilePickerRequest)

OpenFilePicker shows the full-screen file/folder picker. The current state is restored when the picker closes.

func (*App) RequestRebuild

func (a *App) RequestRebuild()

RequestRebuild triggers a UI rebuild for the current screen. This is safe to call from goroutines - the rebuild happens on the main thread. Focus restoration is handled in the Update loop after ui.Update()

func (*App) SaveAndClose

func (a *App) SaveAndClose()

SaveAndClose saves config and library before exit

func (*App) ShowNotification

func (a *App) ShowNotification(msg string)

ShowNotification shows a brief notification message

func (*App) SwitchToCleanProgress added in v0.7.0

func (a *App) SwitchToCleanProgress()

SwitchToCleanProgress transitions to the progress screen and starts Clean Library

func (*App) SwitchToDetail

func (a *App) SwitchToDetail(gameID string)

SwitchToDetail transitions to the detail screen

func (*App) SwitchToLibrary

func (a *App) SwitchToLibrary()

SwitchToLibrary transitions to the library screen

func (*App) SwitchToScanProgress

func (a *App) SwitchToScanProgress()

SwitchToScanProgress transitions to the scan progress screen

func (*App) SwitchToSettings

func (a *App) SwitchToSettings()

SwitchToSettings transitions to the settings screen

func (*App) SwitchToSettingsSection added in v0.7.0

func (a *App) SwitchToSettingsSection(focusKey string)

SwitchToSettingsSection transitions to the settings screen with the given section selected

func (*App) Update

func (a *App) Update() error

Update implements ebiten.Game

type AppState

type AppState int

AppState represents the current state of the application

const (
	// StateLibrary is the main library screen showing all games
	StateLibrary AppState = iota
	// StateDetail shows information about a selected game
	StateDetail
	// StateSettings shows application settings
	StateSettings
	// StateScanProgress shows ROM scanning progress
	StateScanProgress
	// StateCleanProgress shows Clean Library progress
	StateCleanProgress
	// StateError shows a startup error (corrupted config)
	StateError
	// StatePlaying is active gameplay
	StatePlaying
	// StateFilePicker shows the full-screen file and folder picker
	StateFilePicker
)

func (AppState) String

func (s AppState) String() string

String returns the string representation of the state

type ArtworkConfig added in v0.8.0

type ArtworkConfig struct {
	// URL is the HTTPS base URL of the artwork site, which serves
	// index.json, index.sig, and the images the index lists.
	URL string

	// Keys are the public keys, as algorithm:base64, trusted to sign the
	// artwork index. Without them no artwork is downloaded.
	Keys []string
}

ArtworkConfig is where an emulator's artwork is published.

type AssignEvent added in v0.5.0

type AssignEvent struct {
	Player     int    // player slot index (0-based)
	Controller string // controller display name
	Bound      bool   // true = controller bound, false = unbound
}

AssignEvent reports a change to a player's controller binding.

type AudioPlayer

type AudioPlayer struct {
	// contains filtered or unexported fields
}

AudioPlayer is audio output only: it converts int16 stereo samples to bytes, writes them into a ring buffer that oto pulls from, and runs a silent fallback when no device is available. It does NOT pace the emulation loop - the framePacer does that, reading Buffered() as its rate-lock reference. The ring's block-on-full path remains as a backpressure safety net against pathological over-production.

When the host has no usable audio device (headless, permission denied, device busy) oto initialization fails and a timer-driven drain goroutine pulls bytes at the nominal rate a real device would, so the ring still drains and the producer's writes do not block indefinitely.

func NewAudioPlayer

func NewAudioPlayer(volume float64, ringCapacity, silentFrameBytes int) *AudioPlayer

NewAudioPlayer creates audio output with a ring of ringCapacity bytes and a silent-pad frame of silentFrameBytes (both supplied by the framePacer, which owns the rate-derived sizing). volume sets the initial volume before playback starts, preventing audio pops when muted.

If the audio device is unavailable, a silent fallback drains the ring on a timer instead of the hardware clock. The returned player is always usable.

func (*AudioPlayer) Buffered added in v0.4.4

func (a *AudioPlayer) Buffered() int

Buffered returns the current ring fill in bytes. The framePacer reads this as its rate-lock reference.

func (*AudioPlayer) ClearQueue

func (a *AudioPlayer) ClearQueue()

ClearQueue flushes all buffered audio from the ring buffer. Used across state transitions (rewind enter, save state load) to prevent stale audio from playing once the new state takes over. Callers must pause the emulation goroutine first so no producer write races the clear.

func (*AudioPlayer) Close

func (a *AudioPlayer) Close()

Close cleans up audio resources.

func (*AudioPlayer) QueueSamples

func (a *AudioPlayer) QueueSamples(samples []int16)

QueueSamples converts int16 stereo samples to bytes and writes them to the ring buffer for oto to consume. Blocks when the ring is full as a backpressure safety net; real-time pacing comes from the framePacer, not from this Write.

Empty input is replaced with one frame of silence so oto always has bytes to drain and does not underrun on cold-start frames where the core produces no audio. Short non-empty frames are passed through unchanged - only zero-length input is padded.

func (*AudioPlayer) SetVolume

func (a *AudioPlayer) SetVolume(vol float64)

SetVolume sets the playback volume (0.0 = silent, 1.0 = normal, 2.0 = max). Values are clamped to [0.0, 2.0]. No-op on the silent fallback.

type AudioRingBuffer

type AudioRingBuffer struct {
	// contains filtered or unexported fields
}

AudioRingBuffer is a thread-safe ring buffer implementing io.Reader. The emulation goroutine writes samples via Write(), and oto's player reads them via Read(). Write blocks when the buffer is full until Read frees space. Read never blocks, returning silence on underrun.

func NewAudioRingBuffer

func NewAudioRingBuffer(capacity int) *AudioRingBuffer

NewAudioRingBuffer creates a ring buffer with the given capacity in bytes.

func (*AudioRingBuffer) Buffered

func (rb *AudioRingBuffer) Buffered() int

Buffered returns the number of bytes currently in the buffer.

func (*AudioRingBuffer) Clear

func (rb *AudioRingBuffer) Clear()

Clear resets the buffer, discarding all data. Any writer parked on a full ring is woken so it can complete its Write against the now-empty buffer.

func (*AudioRingBuffer) Close

func (rb *AudioRingBuffer) Close()

Close signals shutdown. Subsequent Reads return io.EOF when the buffer is empty. Unblocks any goroutines waiting in Read or Write.

func (*AudioRingBuffer) Read

func (rb *AudioRingBuffer) Read(p []byte) (int, error)

Read implements io.Reader. It never blocks: on underrun (the ring is open but empty) it returns a full buffer of silence. because the Returns io.EOF only when the buffer is closed and empty.

func (*AudioRingBuffer) Write

func (rb *AudioRingBuffer) Write(p []byte)

Write copies data into the buffer, blocking on a full ring until Read frees space. If the input is larger than the buffer's capacity the leading portion is dropped and only the tail is written, because the audio device would only ever consume the most recent samples anyway.

type CheatEngine added in v0.7.0

type CheatEngine struct {
	// contains filtered or unexported fields
}

CheatEngine applies a game's enabled cheats to memory. Apply runs once per emulated frame, between frames, while the emulation is stopped.

func NewCheatEngine added in v0.7.0

func NewCheatEngine(list []cheats.Cheat) *CheatEngine

NewCheatEngine creates an engine for the given cheats' ops.

func (*CheatEngine) Apply added in v0.7.0

func (e *CheatEngine) Apply(mem coreif.Memory)

Apply runs every cheat's ops in order. A compare op that fails skips the next op of the same cheat.

type CleanManager added in v0.7.0

type CleanManager struct {
	// contains filtered or unexported fields
}

CleanManager runs Clean Library. The game files are checked in the background while the progress screen shows how far the check is, then the missing discs and games are removed on the UI thread together with the library games' superseded boxart.png files. Clean Library works on local files only. A cancelled clean changes nothing.

func NewCleanManager added in v0.7.0

func NewCleanManager(library *storage.Library, screen *screens.ScanProgressScreen, onProgress func(), onComplete func(msg string)) *CleanManager

NewCleanManager creates a new clean manager

func (*CleanManager) Start added in v0.7.0

func (cm *CleanManager) Start()

Start begins checking the library's files in the background

func (*CleanManager) Update added in v0.7.0

func (cm *CleanManager) Update()

Update polls for clean progress and completion. Should be called each frame while cleaning.

type EmuControl

type EmuControl struct {
	// contains filtered or unexported fields
}

EmuControl manages pause/resume/stop coordination between the Ebiten thread and the emulation goroutine. Both sides share one lock and wait on one condition, which is signaled whenever the state changes.

func NewEmuControl

func NewEmuControl() *EmuControl

NewEmuControl creates a new emulation control.

func (*EmuControl) CheckPause

func (ec *EmuControl) CheckPause() bool

CheckPause is called by the emulation goroutine between frames. While a pause is requested it marks itself paused and waits. Returns false if the goroutine should exit.

func (*EmuControl) IsPaused

func (ec *EmuControl) IsPaused() bool

IsPaused returns true if the emulation goroutine is currently paused.

func (*EmuControl) RequestPause

func (ec *EmuControl) RequestPause()

RequestPause asks the emulation goroutine to pause and blocks until it is paused or stopped.

func (*EmuControl) RequestResume

func (ec *EmuControl) RequestResume()

RequestResume lets the emulation goroutine continue. It does not wait for the goroutine to leave its pause.

func (*EmuControl) Stop

func (ec *EmuControl) Stop()

Stop signals the emulation goroutine to exit and releases a pending RequestPause.

type Emulator added in v0.8.0

type Emulator struct {
	Name        string // window title and RetroAchievements client name
	Version     string // running version
	DataDirName string // data directory name under the platform data folder
	Icon        []byte // PNG, JPEG, or WebP application icon; nil for none

	// RetroAchievementsConsoleID identifies the emulated console to
	// RetroAchievements; 0 turns achievements off.
	RetroAchievementsConsoleID int

	// CheatFormat names the cheats package system whose code formats the
	// emulator's cheats use, such as "saturn"; "" turns cheats off.
	CheatFormat string

	Update  *UpdateConfig  // where releases are published; nil or no keys turns update checks off
	Artwork *ArtworkConfig // where artwork is published; nil turns artwork downloads off

	Metadata content.MetadataSource // game metadata; nil shows file names only
	Cheats   content.CheatsSource   // database cheats; nil offers custom cheats only
	Rumble   content.RumbleSource   // rumble files; nil turns rumble off
}

Emulator describes the application built around a core: its identity, where it keeps its data, the content it supplies or downloads, and the keys that verify what it downloads. The core itself is described by coreif.SystemInfo. A nil source or config turns that feature off.

type FramebufferRenderer

type FramebufferRenderer struct {
	// contains filtered or unexported fields
}

FramebufferRenderer owns the ebiten offscreen buffer and handles pixel rendering with scaling. Replaces the emulator-specific DrawCachedFramebuffer/GetCachedFramebufferImage methods that were previously on the bridge emulator.

func NewFramebufferRenderer

func NewFramebufferRenderer(par float64) *FramebufferRenderer

NewFramebufferRenderer creates a renderer for the given native screen width and pixel aspect ratio.

func (*FramebufferRenderer) DrawFramebuffer

func (r *FramebufferRenderer) DrawFramebuffer(screen *ebiten.Image, pixels []byte, stride, activeHeight int) shader.Picture

DrawFramebuffer renders pixel data to the screen with PAR-corrected aspect ratio scaling. It returns the picture's placement in screen, zero when nothing was drawn.

func (*FramebufferRenderer) GetFramebufferImage

func (r *FramebufferRenderer) GetFramebufferImage(pixels []byte, stride, activeHeight int) *ebiten.Image

GetFramebufferImage returns pixel data as an ebiten.Image at native resolution. Used for shader processing.

func (*FramebufferRenderer) Release added in v0.7.0

func (r *FramebufferRenderer) Release()

Release frees the offscreen image and the downscale buffers. Call when gameplay ends.

func (*FramebufferRenderer) SetAspectRatioMode

func (r *FramebufferRenderer) SetAspectRatioMode(mode string)

SetAspectRatioMode sets the aspect ratio scaling mode ("dar", "4:3", "1:1", "stretch").

func (*FramebufferRenderer) SetPAR added in v0.3.0

func (r *FramebufferRenderer) SetPAR(par float64)

SetPAR updates the pixel aspect ratio used for "dar" scaling. Called per frame with the value delivered alongside the framebuffer so cores whose PAR changes with video mode render correctly.

type GameplayManager

type GameplayManager struct {
	// contains filtered or unexported fields
}

GameplayManager handles all gameplay-related state and logic. This includes emulator control, input handling, save states, play time tracking, and the pause menu.

The emulator runs on a dedicated goroutine paced by the framePacer: an absolute-deadline timer at the frame interval, slowly corrected from the audio ring fill so long-term rate stays locked to the device. The Ebiten thread handles UI, input polling, and reads the shared framebuffer.

func NewGameplayManager

func NewGameplayManager(
	factory coreif.CoreFactory,
	systemInfo coreif.SystemInfo,
	inputManager *InputManager,
	assignment *PlayerAssignment,
	saveStateManager *SaveStateManager,
	screenshotManager *ScreenshotManager,
	notification *Notification,
	library *storage.Library,
	config *storage.Config,
	achievementManager *achievements.Manager,
	cheatSystem cheats.System,
	cheatsSource content.CheatsSource,
	rumbleSource content.RumbleSource,
	raConsoleID int,
	onExitToLibrary func(),
	onExitApp func(),
) *GameplayManager

NewGameplayManager creates a new gameplay manager

func (*GameplayManager) CurrentGameID added in v0.8.0

func (gm *GameplayManager) CurrentGameID() string

CurrentGameID returns the game ID of the currently loaded game, or empty string if none

func (*GameplayManager) Draw

func (gm *GameplayManager) Draw(screen *ebiten.Image) shader.Picture

Draw renders the gameplay screen from the shared framebuffer and returns the picture's placement in screen, zero when nothing was drawn.

func (*GameplayManager) DrawAchievementOverlay

func (gm *GameplayManager) DrawAchievementOverlay(screen *ebiten.Image)

DrawAchievementOverlay draws the achievement overlay

func (*GameplayManager) DrawFramebuffer

func (gm *GameplayManager) DrawFramebuffer() (*ebiten.Image, float64)

DrawFramebuffer returns the native-resolution framebuffer and the pixel aspect ratio delivered with that frame, for the effects pipeline. Reads from the shared framebuffer rather than directly from the emulator.

func (*GameplayManager) DrawPauseMenu

func (gm *GameplayManager) DrawPauseMenu(screen *ebiten.Image)

DrawPauseMenu draws the pause menu overlay

func (*GameplayManager) DrawPerfOverlay added in v0.6.0

func (gm *GameplayManager) DrawPerfOverlay(screen *ebiten.Image)

DrawPerfOverlay draws the performance overlay when it is on.

func (*GameplayManager) Exit

func (gm *GameplayManager) Exit(saveResume bool)

Exit cleans up when exiting gameplay

func (*GameplayManager) GameShaders added in v0.7.0

func (gm *GameplayManager) GameShaders() []string

GameShaders returns the game shaders of the running game: the global game shaders with the game's overrides applied

func (*GameplayManager) IsPaused

func (gm *GameplayManager) IsPaused() bool

IsPaused returns whether the pause menu is visible

func (*GameplayManager) IsPlaying

func (gm *GameplayManager) IsPlaying() bool

IsPlaying returns true if a game is currently being played

func (*GameplayManager) Launch

func (gm *GameplayManager) Launch(gameID string, resume bool, discIndex int) bool

Launch starts the emulator with the specified game. discIndex selects which disc of a multi-disc game to launch; -1, or any index out of range, uses the entry's remembered SelectedDisc. Ignored for single-disc and cartridge games.

func (*GameplayManager) Resume

func (gm *GameplayManager) Resume()

Resume resumes gameplay after the pause menu.

func (*GameplayManager) Update

func (gm *GameplayManager) Update() (pauseMenuOpened bool, err error)

Update handles the gameplay update loop. Returns true if pause menu was opened. This runs on the Ebiten thread — it polls input and manages UI state. The emulator itself runs on a separate goroutine.

type InputManager

type InputManager struct {
	// contains filtered or unexported fields
}

InputManager handles all input for UI navigation. It tracks gamepad state, handles repeat navigation, and provides a clean interface for UI code to query input state.

func NewInputManager

func NewInputManager() *InputManager

NewInputManager creates a new input manager

func (*InputManager) GetUINavigation

func (im *InputManager) GetUINavigation() UINavigation

GetUINavigation returns the current UI navigation state. This handles keyboard arrow keys and gamepad D-pad/analog stick with repeat navigation, and A/B/Start button presses.

func (*InputManager) Update

func (im *InputManager) Update() (screenshotRequested, fullscreenToggle bool)

Update polls input state. Should be called once per frame. Returns global key states: F12 screenshot and F11 fullscreen toggle. The app acts on the screenshot request during gameplay only.

type InputMapping

type InputMapping struct {
	Keys    map[int]ebiten.Key                   // bit ID -> keyboard key
	Gamepad map[int]ebiten.StandardGamepadButton // bit ID -> gamepad button
}

InputMapping maps button bit IDs to ebiten input types. Keyed by the Button.ID (bit position in the uint32 bitmask).

func BuildMappingFromConfig

func BuildMappingFromConfig(buttons []coreif.Button, kbOverrides, padOverrides map[string]string) InputMapping

BuildMappingFromConfig creates an InputMapping using config overrides with adaptor defaults as fallback. D-pad defaults are WASD (keyboard) and DpadUp/Down/Left/Right (controller). For each button, the override map is checked first; if absent or invalid, the adaptor default is used.

type Notification

type Notification struct {
	// contains filtered or unexported fields
}

Notification displays temporary messages on screen

func NewNotification

func NewNotification() *Notification

NewNotification creates a new notification system

func (*Notification) Clear

func (n *Notification) Clear()

Clear removes the current notification

func (*Notification) Close

func (n *Notification) Close()

Close cleans up audio resources

func (*Notification) Draw

func (n *Notification) Draw(screen *ebiten.Image)

Draw renders the notification

func (*Notification) IsVisible

func (n *Notification) IsVisible() bool

IsVisible returns whether the notification is currently visible

func (*Notification) PlaySound

func (n *Notification) PlaySound(soundData []byte)

PlaySound plays sound data through a one-shot oto player. Sound data should be 48kHz stereo S16LE format.

func (*Notification) SetBadge

func (n *Notification) SetBadge(badge *ebiten.Image)

SetBadge updates the badge image for the current notification (thread-safe)

func (*Notification) Show

func (n *Notification) Show(message string, duration time.Duration)

Show displays a notification message

func (*Notification) ShowAchievementWithBadge

func (n *Notification) ShowAchievementWithBadge(title, description string, badge *ebiten.Image)

ShowAchievementWithBadge displays a prominent achievement notification with a badge image

func (*Notification) ShowDefault

func (n *Notification) ShowDefault(message string)

ShowDefault displays a notification with default 3 second duration

func (*Notification) ShowShort

func (n *Notification) ShowShort(message string)

ShowShort displays a notification with 1 second duration (for gameplay)

type NotificationType

type NotificationType int

NotificationType determines the visual style of the notification

const (
	NotificationTypeDefault     NotificationType = iota // Small, bottom-right
	NotificationTypeAchievement                         // Large, top-center, prominent
)

type PadInfo added in v0.5.0

type PadInfo struct {
	ID    ebiten.GamepadID
	SDLID string
	Name  string
}

PadInfo identifies a connected gamepad for player assignment.

func SnapshotPads added in v0.5.0

func SnapshotPads() []PadInfo

SnapshotPads returns the currently connected gamepads in ID order.

type PauseMenu

type PauseMenu struct {
	// contains filtered or unexported fields
}

PauseMenu handles the in-game pause menu

func NewPauseMenu

func NewPauseMenu(onResume, onLibrary, onExit func()) *PauseMenu

NewPauseMenu creates a new pause menu

func (*PauseMenu) Draw

func (m *PauseMenu) Draw(screen *ebiten.Image)

Draw renders the pause menu

func (*PauseMenu) Hide

func (m *PauseMenu) Hide()

Hide hides the pause menu

func (*PauseMenu) IsVisible

func (m *PauseMenu) IsVisible() bool

IsVisible returns whether the menu is visible

func (*PauseMenu) Show

func (m *PauseMenu) Show()

Show displays the pause menu

func (*PauseMenu) Update

func (m *PauseMenu) Update(nav UINavigation)

Update handles input for the pause menu. Navigation (keyboard arrows, gamepad D-pad, and left analog stick) and the activate/back/start actions are supplied by the shared InputManager via nav, keeping behavior identical to the rest of the UI. Mouse and keyboard Enter/Space are handled directly.

type PauseMenuOption

type PauseMenuOption int

PauseMenuOption represents a menu option

const (
	PauseMenuResume PauseMenuOption = iota
	PauseMenuLibrary
	PauseMenuExit
	PauseMenuOptionCount
)

type PerfOverlay added in v0.6.0

type PerfOverlay struct {
	// contains filtered or unexported fields
}

PerfOverlay draws performance statistics in the top-left corner of the screen. Its mode cycles off, basic, extended, off, and persists across games; its statistics reset per game.

func (*PerfOverlay) Cycle added in v0.6.0

func (o *PerfOverlay) Cycle()

Cycle advances the mode: off, basic, extended, off. Ebiten thread.

func (*PerfOverlay) Draw added in v0.6.0

func (o *PerfOverlay) Draw(screen *ebiten.Image)

Draw renders the overlay when its mode is on. Ebiten thread.

func (*PerfOverlay) Stats added in v0.6.0

func (o *PerfOverlay) Stats() *PerfStats

Stats is the overlay's statistics, reset for each game and fed by the emulation goroutine.

type PerfStats added in v0.6.0

type PerfStats struct {
	// contains filtered or unexported fields
}

PerfStats accumulates per-frame measurements on the emulation goroutine and publishes their averages over the window once per bucket for the Ebiten thread to read.

func (*PerfStats) AddFrame added in v0.6.0

func (p *PerfStats) AddFrame(d time.Duration, gameFrames uint64, now time.Time)

AddFrame records one emulator frame that took d to run and finished at now, with gameFrames the core's game frame count after it. A frame that starts a window, the first or one after a gap, is not counted, so the window's counts and its game frame count start together. When the current bucket has spanned perfBucketSpan, the averages over the buckets in use are published and a new bucket starts at this frame, replacing the oldest once the window is full. The core's render info is read with each publish, so a renderer change shows by the next one.

func (*PerfStats) Reset added in v0.6.0

func (p *PerfStats) Reset(provider coreif.RenderInfoProvider)

Reset clears the published values and the window for a new game and takes the core's render info provider, or nil. The render info is first published with the first bucket. Called before the emulation goroutine starts.

func (*PerfStats) Snapshot added in v0.6.0

func (p *PerfStats) Snapshot() (emuFPS, gameFPS, frameTimeMS float64, info *coreif.RenderInfo)

Snapshot returns the last published emulator frames per second, game frames per second, average frame time in milliseconds, and render info, nil when the core does not report it.

type PlayTimeTracker

type PlayTimeTracker struct {
	// contains filtered or unexported fields
}

PlayTimeTracker tracks play time during gameplay

type PlayerAssignment added in v0.5.0

type PlayerAssignment struct {
	// contains filtered or unexported fields
}

PlayerAssignment tracks which connected gamepad is bound to each player slot. Pads are matched to players by the controller model key (SDL ID + name) of the player's assigned profile. Identity is model-level only, so with two identical controllers connection order decides which unit fills which slot.

func NewPlayerAssignment added in v0.5.0

func NewPlayerAssignment(players int) *PlayerAssignment

NewPlayerAssignment creates an assignment tracker for the given number of player slots, clamped to [1, maxPlayers].

func (*PlayerAssignment) PadFor added in v0.5.0

func (pa *PlayerAssignment) PadFor(player int) (ebiten.GamepadID, bool)

PadFor returns the gamepad bound to the player slot, if any.

func (*PlayerAssignment) Update added in v0.5.0

func (pa *PlayerAssignment) Update(pads []PadInfo, input *storage.InputConfig) []AssignEvent

Update reconciles player bindings with the currently connected pads and the player profile assignments in input. pads must be in ebiten gamepad ID order so startup binding follows enumeration order and later binds follow connection order. Returns bind/unbind events for notifications.

type RewindBuffer

type RewindBuffer struct {
	// contains filtered or unexported fields
}

RewindBuffer stores serialized emulator states in a ring buffer for rewinding gameplay. States are captured every frameStep frames and can be popped in reverse order (LIFO) to step backwards.

func NewRewindBuffer

func NewRewindBuffer(bufferSizeMB, frameStep, stateSize int) *RewindBuffer

NewRewindBuffer allocates a ring buffer sized to fit bufferSizeMB worth of serialized states, each stateSize bytes.

func (*RewindBuffer) Capacity

func (rb *RewindBuffer) Capacity() int

Capacity returns the maximum number of entries the buffer can hold.

func (*RewindBuffer) Capture

func (rb *RewindBuffer) Capture(saveStater coreif.SaveStater) error

Capture serializes the emulator state and stores it in the ring buffer. Only captures every frameStep frames. Should be called after RunFrame.

func (*RewindBuffer) Count

func (rb *RewindBuffer) Count() int

Count returns the number of valid entries in the buffer.

func (*RewindBuffer) IsRewinding

func (rb *RewindBuffer) IsRewinding() bool

IsRewinding returns whether the buffer is currently in rewind mode.

func (*RewindBuffer) Reset

func (rb *RewindBuffer) Reset()

Reset clears the buffer. Call on game launch or save state load.

func (*RewindBuffer) Rewind

func (rb *RewindBuffer) Rewind(emu coreif.Emulator, saveStater coreif.SaveStater, count int) bool

Rewind pops count states from the buffer and deserializes the last one. After deserializing, RunFrame is called to regenerate the framebuffer since the serialized state doesn't include rendered pixels. Returns false if the buffer is empty.

func (*RewindBuffer) SetRewinding

func (rb *RewindBuffer) SetRewinding(v bool)

SetRewinding sets the rewind mode flag.

type SaveStateManager

type SaveStateManager struct {
	// contains filtered or unexported fields
}

SaveStateManager handles save state operations

func NewSaveStateManager

func NewSaveStateManager(notification *Notification) *SaveStateManager

NewSaveStateManager creates a new save state manager

func (*SaveStateManager) GetCurrentSlot

func (m *SaveStateManager) GetCurrentSlot() int

GetCurrentSlot returns the current save slot

func (*SaveStateManager) HasResumeState

func (m *SaveStateManager) HasResumeState() bool

HasResumeState checks if a resume state exists

func (*SaveStateManager) Load

func (m *SaveStateManager) Load(saveStater coreif.SaveStater) error

Load loads the state from the current slot

func (*SaveStateManager) LoadResume

func (m *SaveStateManager) LoadResume(saveStater coreif.SaveStater) error

LoadResume loads the resume state

func (*SaveStateManager) LoadSRAM

func (m *SaveStateManager) LoadSRAM(batterySaver coreif.BatterySaver) error

LoadSRAM loads the cartridge SRAM

func (*SaveStateManager) NextSlot

func (m *SaveStateManager) NextSlot()

NextSlot cycles to the next save slot

func (*SaveStateManager) PreviousSlot

func (m *SaveStateManager) PreviousSlot()

PreviousSlot cycles to the previous save slot

func (*SaveStateManager) ResumePath added in v0.8.0

func (m *SaveStateManager) ResumePath() (string, error)

ResumePath returns the path of the current game's resume state. The auto-save resolves it before writing in the background, so the write is not affected by a game change made meanwhile.

func (*SaveStateManager) Save

func (m *SaveStateManager) Save(saveStater coreif.SaveStater) error

Save saves the current state to the current slot

func (*SaveStateManager) SaveResume

func (m *SaveStateManager) SaveResume(saveStater coreif.SaveStater) error

SaveResume saves the resume state

func (*SaveStateManager) SaveSRAM

func (m *SaveStateManager) SaveSRAM(batterySaver coreif.BatterySaver) error

SaveSRAM saves the cartridge SRAM

func (*SaveStateManager) SetGame

func (m *SaveStateManager) SetGame(gameID string)

SetGame sets the current game for save states Restores the last-used slot from the game's settings file

type ScanManager

type ScanManager struct {
	// contains filtered or unexported fields
}

ScanManager handles ROM scanning orchestration. This includes creating and running scanners, tracking progress, and merging results into the library.

func NewScanManager

func NewScanManager(
	library *storage.Library,
	scanScreen *screens.ScanProgressScreen,
	extensions []string,
	defaultConsoleID int,
	disc bool,
	discID coreif.DiscIdentifier,
	sources func() scanner.Sources,
	onProgress func(),
	onComplete func(msg string),
) *ScanManager

NewScanManager creates a new scan manager

func (*ScanManager) IsScanning

func (sm *ScanManager) IsScanning() bool

IsScanning returns true if a scan is in progress

func (*ScanManager) Start

func (sm *ScanManager) Start()

Start begins a new scan operation

func (*ScanManager) Update

func (sm *ScanManager) Update()

Update polls for scan progress and completion. Should be called each frame while scanning.

type ScreenshotManager

type ScreenshotManager struct {
	// contains filtered or unexported fields
}

ScreenshotManager saves screenshots of gameplay. Captures are queued from anywhere, including the emulation thread. Flush, at the end of Draw, copies the final drawn frame out of the screen and hands it to an encoder goroutine, which encodes and writes the files off the draw thread.

func NewScreenshotManager

func NewScreenshotManager() *ScreenshotManager

NewScreenshotManager creates a screenshot manager with its encoder running. Close stops it.

func (*ScreenshotManager) Close added in v0.7.0

func (m *ScreenshotManager) Close()

Close stops the encoder once the queued frames are written. Captures after Close are dropped.

func (*ScreenshotManager) Flush added in v0.7.0

func (m *ScreenshotManager) Flush(screen *ebiten.Image, picture image.Rectangle, gameID string)

Flush copies the picture region of screen for the queued captures and empties the queue, so letterbox and pillarbox bars are left out. The frame is encoded and written later, once per capture, in the game's screenshot directory. Captures queued while no game is loaded are dropped. Capture is silent, with no notification; failures are logged.

func (*ScreenshotManager) Queue added in v0.7.0

func (m *ScreenshotManager) Queue(tag string)

Queue requests a screenshot of the next drawn frame. tag is the filename tag of the capture: the result of achievementTag for an achievement unlock, or "" for a manual capture.

type SearchOverlay

type SearchOverlay struct {
	// contains filtered or unexported fields
}

SearchOverlay displays a search filter at the bottom-left of the screen

func NewSearchOverlay

func NewSearchOverlay(onChanged func(text string)) *SearchOverlay

NewSearchOverlay creates a new search overlay with the given change callback

func (*SearchOverlay) Activate

func (s *SearchOverlay) Activate()

Activate starts capturing keyboard input

func (*SearchOverlay) Clear

func (s *SearchOverlay) Clear()

Clear removes all search text and deactivates

func (*SearchOverlay) Draw

func (s *SearchOverlay) Draw(screen *ebiten.Image)

Draw renders the search overlay at bottom-left. The overlay is never wider than the screen less its margins.

func (*SearchOverlay) HandleInput

func (s *SearchOverlay) HandleInput() bool

HandleInput processes keyboard input when active. Returns true if input was handled (should not propagate to navigation).

func (*SearchOverlay) IsActive

func (s *SearchOverlay) IsActive() bool

IsActive returns true if the overlay is capturing keyboard input

func (*SearchOverlay) IsVisible

func (s *SearchOverlay) IsVisible() bool

IsVisible returns true if the search has text (overlay should be shown)

type SharedFramebuffer

type SharedFramebuffer struct {
	// contains filtered or unexported fields
}

SharedFramebuffer holds pixel data written by the emulation goroutine and read by Ebiten's Draw() method. Uses separate write and read buffers so the emu goroutine can write new data while Draw uses the read copy.

func NewSharedFramebuffer

func NewSharedFramebuffer(width, height int) *SharedFramebuffer

NewSharedFramebuffer creates a framebuffer pre-allocated for the given screen dimensions (width and height in pixels, 4 bytes per pixel). The dimensions are the starting size, not a limit: a larger frame grows the buffers when it arrives.

func (*SharedFramebuffer) Read

func (sf *SharedFramebuffer) Read() (pixels []byte, stride, activeHeight int, par float64)

Read returns a snapshot of the current framebuffer state. Copies the write buffer into the read buffer under the lock, then returns the read buffer which is safe to use without holding the lock. The read buffer grows to the write buffer's size, so the returned pixels hold the whole frame whenever Update was given all of it.

func (*SharedFramebuffer) Update

func (sf *SharedFramebuffer) Update(pixels []byte, stride, activeHeight int, par float64)

Update copies framebuffer data from the emulation goroutine, or from the Ebiten thread while the emulation goroutine is paused (a state load, a rewind step). A frame larger than the write buffer, such as a core rendering above its native resolution or a loaded state in a larger video mode, grows the write buffer to hold it.

type SharedInput

type SharedInput struct {
	// contains filtered or unexported fields
}

SharedInput holds controller state as button bitmasks written by the Ebiten thread and read by the emulation goroutine.

func (*SharedInput) Read

func (si *SharedInput) Read() [maxPlayers]uint32

Read returns the current button bitmasks for all players.

func (*SharedInput) Set

func (si *SharedInput) Set(player int, buttons uint32)

Set updates button bitmask for a player from the Ebiten thread.

type TurboState

type TurboState struct {
	// contains filtered or unexported fields
}

TurboState holds fast-forward state shared between the Ebiten thread (which sets it from key input) and the emulation goroutine (which reads it).

func (*TurboState) CycleMultiplier

func (ts *TurboState) CycleMultiplier() int

CycleMultiplier advances through Off(1) → 2x → 3x → Off(1), returning the new value. Called from the Ebiten thread.

func (*TurboState) Read

func (ts *TurboState) Read() int

Read returns the current multiplier. Called from the emulation goroutine.

type UINavigation

type UINavigation struct {
	Direction    int  // 0=none, 1=up, 2=down, 3=left, 4=right
	Activate     bool // A/Cross button just pressed
	Back         bool // B/Circle button just pressed
	OpenSettings bool // Start button just pressed
	FocusChanged bool // True if navigation caused focus change this frame
}

UINavigation represents the result of UI input polling

type UpdateConfig added in v0.7.0

type UpdateConfig struct {
	ManifestURL    string   // The latest release's manifest, an HTTPS URL
	SignatureURL   string   // The latest release's manifest signature file, an HTTPS URL
	ReleasePageURL string   // A release's page, an HTTPS URL; {version} is replaced by the version
	Keys           []string // Update signing public keys, each algorithm:base64
}

UpdateConfig describes where an application's releases are published and how they are verified: the update signing public keys stamped into its release builds. The application's name and running version come from Emulator. Without usable keys, or with a URL that is not HTTPS, the update system is off: no network requests, no update bar, and no Updates area in About.

type UpdateManager added in v0.7.0

type UpdateManager struct {
	// contains filtered or unexported fields
}

UpdateManager checks for new releases and holds the update state shown by the update bar and Settings > About. Checks run in the background; the methods are safe to call from the UI thread while one runs.

func NewUpdateManager added in v0.7.0

func NewUpdateManager(cfg *UpdateConfig, appName, version string, config *storage.Config, onChange func()) *UpdateManager

NewUpdateManager returns the update manager for cfg and the application named appName running version, or nil when the update system is off: cfg is nil or has no usable keys or URLs, or appName is empty. appName is bound into the signed manifest. It loads the stored update state and manifest.

func (*UpdateManager) AppName added in v0.7.0

func (m *UpdateManager) AppName() string

AppName returns the application name shown in the update bar

func (*UpdateManager) BarVersion added in v0.7.0

func (m *UpdateManager) BarVersion() string

BarVersion returns the version the update bar offers, or "" when the bar is not shown. The bar is shown while automatic checks are on and an update is available that is newer than the ignored version and was not dismissed this session. It is not shown while a check runs, since the check may find a newer version.

func (*UpdateManager) CheckNow added in v0.7.0

func (m *UpdateManager) CheckNow()

CheckNow starts a manual background check unless one is running. An update it finds is treated as ignored for the update bar.

func (*UpdateManager) Dismiss added in v0.7.0

func (m *UpdateManager) Dismiss()

Dismiss hides the update bar for the rest of this session

func (*UpdateManager) Download added in v0.7.0

func (m *UpdateManager) Download()

Download opens the available version's release page in the browser and stops the update bar from showing that version.

func (*UpdateManager) IgnoreVersion added in v0.7.0

func (m *UpdateManager) IgnoreVersion()

IgnoreVersion stops the update bar from showing the available version. A newer version shows it again.

func (*UpdateManager) StartAutomaticCheck added in v0.7.0

func (m *UpdateManager) StartAutomaticCheck()

StartAutomaticCheck starts a background check when automatic checks are on and the last check is at least updateCheckInterval old.

func (*UpdateManager) Status added in v0.7.0

func (m *UpdateManager) Status() types.UpdateStatus

Status returns the update state for Settings > About

Directories

Path Synopsis
Package artwork reads a core's artwork index and decides which local artwork files to download.
Package artwork reads a core's artwork index and decides which local artwork files to download.
Package cheats decodes cheat code strings, such as Action Replay codes, into memory operations.
Package cheats decodes cheat code strings, such as Action Replay codes, into memory operations.
Package content defines the per-game data an emulator supplies to the desktop UI: game metadata and cheats.
Package content defines the per-game data an emulator supplies to the desktop UI: game metadata and cheats.
Package filebrowser provides the filesystem side of the in-app file and folder picker: listing, filtering, path input parsing and the sidebar places.
Package filebrowser provides the filesystem side of the in-app file and folder picker: listing, filtering, path input parsing and the sidebar places.
Package gamecheats loads a game's cheats: the database cheats from the emulator's cheats source and the custom cheats from its settings file.
Package gamecheats loads a game's cheats: the database cheats from the emulator's cheats source and the custom cheats from its settings file.
Package launch hands things to the operating system to open: a file in the file manager or a URL in the browser.
Package launch hands things to the operating system to open: a file in the file manager or a URL in the browser.
Package rating defines the game ratings the desktop shows: age ratings from rating boards and critic ratings from publications.
Package rating defines the game ratings the desktop shows: age ratings from rating boards and critic ratings from publications.
Package region defines the game regions the desktop supports: USA, Europe and Japan.
Package region defines the game regions the desktop supports: USA, Europe and Japan.
Package signing verifies detached signatures made with the project's signing keys.
Package signing verifies detached signatures made with the project's signing keys.
Package types provides shared interfaces used across UI packages.
Package types provides shared interfaces used across UI packages.
Package update checks for new application releases.
Package update checks for new application releases.
textedit
Package textedit holds the text, caret, and selection of a multi-line text field, with the editing operations on them.
Package textedit holds the text, caret, and selection of a multi-line text field, with the editing operations on them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL