platform

package
v0.0.0-...-863c820 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2019 License: BSD-3-Clause Imports: 23 Imported by: 4

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsReplayDone

func IsReplayDone(err error) bool

IsReplayDone returns true if the error was due to a replay session finishing.

func IsReplayStop

func IsReplayStop(err error) bool

IsReplayStop returns true if the error was due to the user canceling a replay.

func MustRun

func MustRun(in, out *os.File, run func(*Platform) error, opts ...Option)

MustRun call Run, calling os.Exit(1) if it returns a non-nil error.

func Run

func Run(in, out *os.File, run func(*Platform) error, opts ...Option) error

Run is a convenience wrapper that calls the run function with a newly created Platform activated under a newly constructed anansi.Term.

Types

type BackgroundWorker

type BackgroundWorker interface {
	Start() error
	Stop() error
	Notify() error
}

BackgroundWorker supports doing deferred work in between frames of a platform run loop. The Start() and Stop() methods are called before/after the run loop. The Notify() method is called at the end of the run loop, before going back to sleep to wait for the next frame tick.

The astute reader will note that BackgroundWorker itself provides no support for synchronizing with the background work. Any such needs must be implemented in-situ by the BackgroundWorker; no generic support is provided to block the start of the next frame to wait for prior triggered work to finish.

type BackgroundWorkers

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

BackgroundWorkers implements an anansi.Context-ually managed collection of background workers.

func (BackgroundWorkers) Enter

func (bg BackgroundWorkers) Enter(term *anansi.Term) error

Enter starts the background workers, stopping on and returning first error.

func (BackgroundWorkers) Exit

func (bg BackgroundWorkers) Exit(term *anansi.Term) (err error)

Exit stops all background workers, returning the first error, but stopping all regardless.

func (BackgroundWorkers) Notify

func (bg BackgroundWorkers) Notify() error

Notify all background workers, stopping on and returning the first error.

type Client

type Client interface {
	Update(*Context) error
}

Client runs under a platform, processing input and generating output within each frame Context.

type ClientFunc

type ClientFunc func(*Context) error

ClientFunc is a convenient way to implement a Client (e.g. for testing).

func (ClientFunc) Update

func (f ClientFunc) Update(ctx *Context) error

Update runs the aliased function.

type Config

type Config struct {
	LogFileName    string
	CPUProfileName string
	TraceFileName  string
	MemProfileName string

	StartTiming bool // Whether to start and
	LogTiming   bool // log timing right away

	TelemetryLogFileName string // log telemetry to file
	// contains filtered or unexported fields
}

Config uration for a Platform; populated from -platform.* flags; it implements Option, so applications may unmarshal it from some file and pass it to New().

TODO hud manipulable / dynamic

func (*Config) AddFlags

func (cfg *Config) AddFlags(f *flag.FlagSet, prefix string)

AddFlags adds flag variables to the given flag set that will allow the user to set various log and profiling files from the outset. If a non-empty prefix is given, then timing variables are also wired up.

func (*Config) Enter

func (cfg *Config) Enter(term *anansi.Term) error

Enter starts any CPU or Trace profiling.

func (*Config) Exit

func (cfg *Config) Exit(term *anansi.Term) error

Exit stops any CPU or Trace profiling, and writes any configured pprof profiles (like memory).

func (*Config) Merge

func (cfg *Config) Merge(other Config)

Merge an other config value into the receiver.

type Context

type Context struct {
	*Platform
	Time   time.Time
	Err    error
	Redraw bool
	Input  *Events
	Output *anansi.TermScreen
}

Context manages frame input and output state within a Platform.

func (*Context) Update

func (ctx *Context) Update()

Update runs a client round: - resets screen buffer - hides cursor (TODO) - processes user Ctrl-L to implement redraw flag - hands off to any active replay - re-reads terminal size on redraw - processes user Ctrl-R to toggle recording / replaying - runs the Platform client Update, under HUD Update - flushes screen buffer

type EditLine

type EditLine struct {
	State EditLineState
	Box   ansi.Rectangle
	Buf   []byte
	Cur   int
	View  int
	// contains filtered or unexported fields
}

EditLine provides basic line-editing .

func (*EditLine) Active

func (edl *EditLine) Active() bool

Active returns true if the edit line is accepting user input.

func (*EditLine) Canceled

func (edl *EditLine) Canceled() bool

Canceled returns true if the user canceled editing (e.g. hit <Esc>).

func (*EditLine) Done

func (edl *EditLine) Done() bool

Done returns true if the user submitted input (e.g. hit <Enter>).

func (*EditLine) Reset

func (edl *EditLine) Reset()

Reset state.

func (*EditLine) Update

func (edl *EditLine) Update(ctx *Context)

Update processes user input and draws the edit line.

type EditLineState

type EditLineState uint8

EditLineState code.

const (
	EditLineReady EditLineState = iota
	EditLineDone
	EditLineCanceled
)

EditLineState constants.

type Escape

type Escape struct {
	ID  ansi.Escape
	Arg []byte
}

Escape represents ansi escape sequence data stored in an Events queue.

func (Escape) String

func (e Escape) String() string

type EventType

type EventType uint8

EventType is the type of an entry in Events.

const (
	EventNone EventType = iota
	EventEscape
	EventRune
	EventMouse
)

Type constants for Events.

type Events

type Events struct {
	Type []EventType
	// contains filtered or unexported fields
}

Events holds a queue of input events that were available at the start of the current frame's time window.

func (*Events) AnyPressesOutside

func (es *Events) AnyPressesOutside(box ansi.Rectangle) bool

AnyPressesOutside returns true if there are any mouse presses outside the given rectangle.

func (*Events) Clear

func (es *Events) Clear()

Clear the event queue.

func (*Events) CountPressesIn

func (es *Events) CountPressesIn(box ansi.Rectangle, buttonID uint8) (n int)

CountPressesIn counts mouse presses of the given button within the given rectangle, striking them out.

func (*Events) CountRune

func (es *Events) CountRune(rs ...rune) (n int)

CountRune counts occurrences of any of the given runes, striking them out.

func (*Events) DecodeBytes

func (es *Events) DecodeBytes(b []byte)

DecodeBytes parses from the given byte slice; useful for replays and testing.

func (*Events) DecodeInput

func (es *Events) DecodeInput(in *anansi.Input)

DecodeInput decodes all input currently read into the given input.

func (*Events) Empty

func (es *Events) Empty() bool

Empty returns true if there are non-EventNone typed events left.

func (*Events) Escape

func (es *Events) Escape(id int) Escape

Escape returns any ansi escape sequence data for the given event id.

func (*Events) HasTerminal

func (es *Events) HasTerminal(r rune) bool

HasTerminal returns true if the given terminal rune is in the event queue, striking it and truncating any events after it.

func (*Events) LastMouse

func (es *Events) LastMouse(consume bool) (m Mouse, have bool)

LastMouse returns the last mouse event, striking all mouse events out (including the last!) only if consume is true.

func (*Events) Mouse

func (es *Events) Mouse(id int) Mouse

Mouse returns any mouse event data for the given event id.

func (*Events) Rune

func (es *Events) Rune(id int) rune

Rune returns the event's rune (maybe an ansi.Escape PUA range rune).

func (*Events) TotalCursorMovement

func (es *Events) TotalCursorMovement() (move image.Point)

TotalCursorMovement returns the total cursor movement delta (e.g. from arrow keys) striking out all such cursor movement events. Does not recognize cursor line movements (CNL and CPL).

func (*Events) TotalScrollIn

func (es *Events) TotalScrollIn(box ansi.Rectangle) (n int)

TotalScrollIn counts total mouse scroll delta within the given rectangle, striking out all such events.

type FPSEstimate

type FPSEstimate struct {
	Value float64
	// contains filtered or unexported fields
}

FPSEstimate keep a running Frames Per Second estimate based on a windowed average.

type HUD

type HUD struct {
	HUDState
	// contains filtered or unexported fields
}

HUD implements a toggle-able debug overlay.

func (*HUD) Update

func (hud *HUD) Update(ctx *Context, client Client) error

Update the HUD (only if visible).

type HUDState

type HUDState struct {
	// last mouse for status display
	Mouse Mouse

	// structural state
	Visible    bool
	TimeDetail bool
	ProfDetail bool
	FPSControl bool
	FPSDetail  bool

	// theme
	SelectAttr ansi.SGRAttr
	ButtonAttr ansi.SGRAttr

	// user interaction state
	Active UIID
	EdLin  EditLine
}

HUDState contains serializable HUD state.

type LogSink

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

LogSink implements an in-memory log buffer.

var Logs LogSink

Logs is the LogSink installed as the output for the standard "logs" package.

func (*LogSink) Contents

func (logs *LogSink) Contents() ([]byte, []int)

Contents all in-memory buffered bytes and a slice containing the index of all newlines within those bytes.

func (*LogSink) Error

func (core *LogSink) Error() error

func (*LogSink) Notify

func (core *LogSink) Notify() error

func (*LogSink) Read

func (logs *LogSink) Read(p []byte) (n int, err error)

func (*LogSink) SetFile

func (logs *LogSink) SetFile(f *os.File) error

SetFile sets the sink's file destination, starting or stopping a background goroutine as needed.

func (*LogSink) Start

func (logs *LogSink) Start() error

Start a background goroutine to defer file writing, transitioning to such deferred writing model; file writes will not be performed until Notify() or Stop() is next called.

func (*LogSink) Stop

func (logs *LogSink) Stop() error

Stop the any background file-writing goroutine, transitioning back to direct file writes.

func (*LogSink) Write

func (logs *LogSink) Write(p []byte) (n int, _ error)

type LogView

type LogView struct {
	LogViewState
	// contains filtered or unexported fields
}

LogView is a scrollable log viewer.

TODO currently anchored to bottom of screen, and hardcoded to 10 lines high.

func NewLogView

func NewLogView(logs *LogSink) *LogView

NewLogView creates a new log view attached to the given log buffer.

func (*LogView) Update

func (lv *LogView) Update(ctx *Context) error

Update the log view, processing input, and drawing.

type LogViewState

type LogViewState struct {
	ViewLines int
	Expanded  bool
	Line      int
}

LogViewState contains serializable LogView state.

type Mouse

type Mouse struct {
	State ansi.MouseState
	ansi.Point
}

Mouse represents mouse data stored in an Events queue.

var ZM Mouse

ZM is a convenience name for the zero value of Mouse.

func (Mouse) String

func (m Mouse) String() string

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option customizes Platform's behavior.

func FrameRate

func FrameRate(fps int) Option

FrameRate changes the platform's Frames-Per-Second rate, which defaults to 60.

type Platform

type Platform struct {
	Config

	State
	Time time.Time // internal time (rewinds during replay)

	Telemetry

	HUD HUD
	// contains filtered or unexported fields
}

Platform is a high level abstraction for implementing frame-oriented interactive fullscreen terminal programs.

func New

func New(in, out *os.File, opts ...Option) (*Platform, error)

New creates a platform layer for running interactive fullscreen terminal applications.

func (*Platform) Context

func (p *Platform) Context() Context

Context returns a new Context bound to the platform.

func (*Platform) Run

func (p *Platform) Run(client Client) (err error)

Run a client under a platform. It loads client state from any active replay buffer, and then runs the client under a ticker loop.

func (*Platform) RunWith

func (p *Platform) RunWith(run func(*Platform) error) error

RunWith runs the given function under the platform anansi.Term; such function should call Platform.Run one or more times.

func (*Platform) SetStallTracking

func (p *Platform) SetStallTracking(enabled bool)

SetStallTracking sets whether output stall tracking is enabled.

func (*Platform) SetTimingEnabled

func (p *Platform) SetTimingEnabled(enabled bool)

SetTimingEnabled sets whether frame timing data collection is enabled.

func (*Platform) Suspend

func (p *Platform) Suspend() error

Suspend restores terminal context to pre-platform-run settings, suspends the current process, and then restores platform terminal context once resumed; returns any error preventing any of that.

type StallsData

type StallsData struct {
	Stats StallsStats
}

StallsData stores output stall data.

type StallsStats

type StallsStats struct {
	N    int
	Time time.Time
	Min  time.Duration
	Max  time.Duration
	Sum  time.Duration
	Pct  float64
}

StallsStats stores stats computed from the last round of output StallsData.

type State

type State struct {
	Paused   bool
	LastTime time.Time
	LastSize image.Point
}

State contains serializable Platform state.

type Telemetry

type Telemetry struct {
	TelemetryState

	FPSEstimate FPSEstimate
	Timing      TimingData
	Stalls      StallsData
	// contains filtered or unexported fields
}

Telemetry contains platform runtime performance data.

func (*Telemetry) FPS

func (tel *Telemetry) FPS() float64

FPS returns the measured FPS rate if timing collection is enabled, or the current FPSEstimate value otherwise.

type TelemetryState

type TelemetryState struct {
	TimingEnabled    bool
	StallDataEnabled bool
	LogTiming        bool
	LogStallData     bool
}

TelemetryState contains serializable Telemetry state.

type Ticker

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

Ticker implements a contextual time.Ticker, start/stopping it during terminal enter/exit.

func (*Ticker) Enter

func (ct *Ticker) Enter(term *anansi.Term) error

Enter starts a new ticker, after stopping any prior one for good measure; always returns nil error.

func (*Ticker) Exit

func (ct *Ticker) Exit(term *anansi.Term) error

Exit stops any running ticker; always returns nil error.

func (*Ticker) Wait

func (ct *Ticker) Wait() time.Time

Wait blocks for the next ticker time, returning zero time if the Ticker isn't active, or is Exit-ed first.

type TimingData

type TimingData struct {
	// state
	Stats TimingStats
	// contains filtered or unexported fields
}

TimingData stores inter-frame timing data.

type TimingStats

type TimingStats struct {
	Time time.Time

	FPS        float64
	Elapsed    time.Duration
	Min, Max   time.Duration
	Q1, Q2, Q3 time.Duration
}

TimingStats stores stats computed from the last round of frame TimingData.

type UIID

type UIID int

UIID identifies a user interface component

Jump to

Keyboard shortcuts

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