Documentation
¶
Overview ¶
Package engine runs an app on a goroutine of its own and hands the platform one MountBatch per commit.
Performance monitoring: what a surface's frames and commits cost while it runs, for an on-screen monitor (`nsgo dev`) or the app's own tooling.
A PerfMonitor is shared by the two threads of a surface:
- the engine goroutine records every wake-up that produced a commit (the app's code and the core's work, CommitTiming) and how long it was busy at all;
- the main thread records the time it spends on the surface (RecordWork: applying batches, ticking animations, handling input) and closes a frame at every display refresh (Vsync): a refresh in which something changed is a frame the screen showed, and its cost is the main-thread work since the previous refresh. It also reports how long a batch waited between the engine handing it over and the main thread applying it (RecordLatency).
Snapshot turns what was recorded into readings (PerfSnapshot); Readings formats them for a monitor panel.
Nothing is measured while no monitor is installed (engine.Options.Perf is nil): the engine checks one pointer per wake-up, the platforms one per frame.
The readings follow NSH's (`nsh_engine::perf`): the headline rate counts frames that reached the screen, MAX is derived from what a frame cost rather than counted (so the monitor never drives frames to find it), and the first frames, the cold ones, are not counted.
Index ¶
- Constants
- Variables
- func AppDirs(id string) (data, cache, logs string)
- func LaunchFiles() []string
- func NewStorage(backend driver.StorageBackend) *core.Store
- func OpenFileStorage(dir string) *core.Store
- func SyncStorage()
- type App
- type CommitTiming
- type Engine
- func (e *Engine) Attach(id uint32, p Platform) *Engine
- func (e *Engine) Close()
- func (e *Engine) Dispatch(ev driver.Event)
- func (e *Engine) DispatchBeforeFrame(ev driver.Event)
- func (e *Engine) DispatchKeyDown(ev driver.Event) bool
- func (e *Engine) FontsChanged()
- func (e *Engine) Frame()
- func (e *Engine) Hide()
- func (e *Engine) InputModality(m uint32)
- func (e *Engine) Language() string
- func (e *Engine) PressAt(ev driver.Event)
- func (e *Engine) Repin()
- func (e *Engine) Resize(size driver.Size, g driver.Geometry)
- func (e *Engine) ResizeAndWait(size driver.Size, g driver.Geometry) <-chan struct{}
- func (e *Engine) ResizeWithEnvironment(size driver.Size, g driver.Geometry, env driver.Environment)
- func (e *Engine) SetEnvironment(env driver.Environment)
- func (e *Engine) SetHostEnvironment(h HostEnvironment)
- func (e *Engine) SetTokens(t core.Tokens)
- func (e *Engine) Sync()
- type Host
- type HostCall
- type HostEnvironment
- type HostOptions
- type HostSettings
- type Options
- type PerfBar
- type PerfMonitor
- func (m *PerfMonitor) RecordBusy(d time.Duration)
- func (m *PerfMonitor) RecordCommit(timing CommitTiming)
- func (m *PerfMonitor) RecordLatency(latency time.Duration)
- func (m *PerfMonitor) RecordWork(cost time.Duration, dirty bool)
- func (m *PerfMonitor) SetProcess(sample ProcessSample)
- func (m *PerfMonitor) Snapshot() PerfSnapshot
- func (m *PerfMonitor) Vsync(at time.Time, interval time.Duration)
- type PerfSnapshot
- type Platform
- type ProcessSample
- type SharedMounter
- type Stat
- type TestPin
- type Tokens
- type WindowOptions
Constants ¶
const ( PerfWidth = 262.0 PerfMargin = 10.0 PerfPadding = 8.0 PerfGraphHeight = 36.0 PerfFontSize = 10.5 PerfRadius = 8.0 )
The panel's width, its distance from the surface's edges, its padding, the trace's height and the text's size, in points.
const PerfInterval = 500 * time.Millisecond
PerfInterval is how often a panel shows new readings.
Variables ¶
var ( PerfPanelColor = driver.RGBA(0x121214, 0.86) PerfTextColor = driver.RGB(0xebedf2) PerfTraceFill = driver.RGBA(0xffffff, 0.08) PerfTraceBudget = driver.RGBA(0xffffff, 0.45) PerfTraceGood = driver.RGBA(0x4dd973, 0.9) PerfTraceWarn = driver.RGBA(0xfabf40, 0.9) PerfTraceBad = driver.RGBA(0xfa5954, 0.9) )
The panel's colors: its fill, its text, and the trace's fill, budget line and bars within half the budget, within it and over it.
var Trace func(b *driver.MountBatch, took time.Duration)
Trace, when set, hears each commit's batch, before the platform, and how long the commit took, on the engine goroutine of every engine the process starts from then on; it must not block. nsgo dev -trace's builds set it, as their dev client starts.
Functions ¶
func AppDirs ¶
AppDirs returns app id's data, cache and logs directories on this system: Application Support, Caches and, on macOS, Logs in Library on Apple platforms, %APPDATA%, %LOCALAPPDATA% and its Logs on Windows, XDG_DATA_HOME, XDG_CACHE_HOME and XDG_STATE_HOME elsewhere, each with a directory named by id, or "default" when id names no directory. On iOS and watchOS, which have no place for logs, they go in logs in the data directory. All are "" where only the platform knows them, on Android and the web.
func LaunchFiles ¶
func LaunchFiles() []string
LaunchFiles returns the files the command line names, as absolute paths: what Windows and Linux launch an app with to open, which their backends send it as EventOpenFiles. Other arguments are left to the app.
func NewStorage ¶
func NewStorage(backend driver.StorageBackend) *core.Store
NewStorage returns a store kept by backend, for platforms that keep the app's entries themselves, such as in the browser's localStorage.
func OpenFileStorage ¶
OpenFileStorage returns the store kept in dir/storage.json: the one already open in this process, so every engine of the app shares it, or a new one. The directory is made on the first write.
func SyncStorage ¶
func SyncStorage()
SyncStorage waits until every change made so far to the stores OpenFileStorage returned is written. Platforms call it as the process ends, which would otherwise cut the last write short.
Types ¶
type CommitTiming ¶
type CommitTiming struct {
// App is the app's code: event handlers, timers, effects and the other
// work of the wake-up less Core.
App time.Duration
// Core is the core: applying what changed, rendering components,
// typesetting text, layout and diffing into mount items.
Core time.Duration
// Items are the mount items the commit produced.
Items int
}
CommitTiming is what one engine wake-up that committed cost.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is one running app: one reactive graph, one goroutine, and a tree per surface. An Engine value is one surface's: Start returns the first's, and Attach another's, which the app opened. Its methods are safe to call from any goroutine and never block, so a platform's main thread can call them.
func (*Engine) Attach ¶
Attach attaches platform p to the surface the app opened as id (driver.ItemOpenSurface) and returns the surface's Engine, which p reports to as the first surface's platform does: its size and environment first. Closing it detaches p.
func (*Engine) Close ¶
func (e *Engine) Close()
Close stops the app, running its OnQuit handlers and disposing its graph, and waits for the engine goroutine to exit; an opened surface's Engine only detaches its platform. It must not be called from the engine goroutine.
func (*Engine) DispatchBeforeFrame ¶
DispatchBeforeFrame reports a platform event from a backend whose frame clock will call Frame next, as the app waits for a display frame: the event waits for that call to wake the engine, which then handles it and runs the frame in one pass, with one commit, instead of two.
func (*Engine) DispatchKeyDown ¶ added in v0.2.0
DispatchKeyDown reports EventKeyDown ev and waits for the engine to run the view's OnKeyDown, after what is queued before it, returning whether it consumed the key: the platform calls it on its main thread before matching the keymap, which a consumed key skips. It returns false once the engine has ended. It must not be called from the engine goroutine.
func (*Engine) FontsChanged ¶
func (e *Engine) FontsChanged()
FontsChanged prepares the app's text and records its canvases again, for fonts the platform loaded after they were registered (driver.FontRegistrar).
func (*Engine) Frame ¶
func (e *Engine) Frame()
Frame reports that the display frame the app asked for has begun. The engine runs the callbacks waiting for it on its goroutine, then commits.
func (*Engine) Hide ¶
func (e *Engine) Hide()
Hide runs the OnQuit handlers for an app the system hides and may end unheard (core.Scope.Hiding), keeping them and the engine for when it shows the app again, and waits for them as Close does.
func (*Engine) InputModality ¶
InputModality reports what the user gives the surface input with (driver.ModalityKeyboard or ModalityPointer), as it changes: a backend calls it for every key and press, before the focus moves they cause.
func (*Engine) Language ¶
Language returns the language the app shows on its first surface (core.Env.Language), "" for an app without catalogs. It waits for what is already queued on the engine, the app's mount included, so it sees a locale the app set as it mounted; it returns "" once the engine has ended.
func (*Engine) PressAt ¶
PressAt reports a press at ev.Page in surface points, with its Modifiers and click Count, for platforms that draw their own views and leave hit testing to the engine.
func (*Engine) Repin ¶
func (e *Engine) Repin()
Repin reports the platform's last environment again, for a pin that changed.
func (*Engine) Resize ¶
Resize sets the surface size and the fold geometry measured at it, the zero Geometry for a surface without a fold. A change of the geometry alone is a resize to the same size.
func (*Engine) ResizeAndWait ¶
ResizeAndWait sets the surface size and its fold geometry as Resize does and returns a channel closed once the commit laid out at it is mounted: a platform that shows a new size at once waits on it, briefly.
func (*Engine) ResizeWithEnvironment ¶ added in v0.2.0
ResizeWithEnvironment sets the surface size and geometry as Resize does and reports the environment that changed with them, as a rotation's safe area, as SetEnvironment does: the app sees both in one batch, never one without the other.
func (*Engine) SetEnvironment ¶
func (e *Engine) SetEnvironment(env driver.Environment)
SetEnvironment reports what the platform knows about where the app runs; only the latest report queued is applied.
func (*Engine) SetHostEnvironment ¶
func (e *Engine) SetHostEnvironment(h HostEnvironment)
SetHostEnvironment sets what an embedding host sets over the platform's environment, from now on.
type HostEnvironment ¶
type HostEnvironment struct {
// Locale is a BCP 47 tag ("de-CH") the app formats for instead of
// the system's language; the layout direction stays the system's.
Locale string
// FontScale is the text size multiplier, standing in for the
// system's.
FontScale float32
// Appearance light or dark stands in for the system's; an appearance
// the app forces still wins over it.
Appearance driver.Appearance
}
HostEnvironment is what an embedding host sets over the platform's environment for its view; zero values follow the platform's.
type HostOptions ¶
type HostOptions struct {
// Channel is the channel between the host and the app
// (core.RootOptions.Host).
Channel *Host
// Settings are the host's settings of the view.
Settings *HostSettings
// OnError hears each failure the app does not catch, after the log,
// on the engine goroutine; it must not block.
OnError func(error)
// DataDir is the app's data directory, its storage's, instead of the system's for the app's ID; its logs directory goes in DataDir/logs.
DataDir string
}
HostOptions are what an embedding host gives a view's engine.
type HostSettings ¶
type HostSettings struct {
Environment HostEnvironment
Tokens Tokens
// contains filtered or unexported fields
}
HostSettings are an embedding host's settings of one view: kept until the view's engine starts, which has them from its first frame, and sent to it after. Only the platform's main thread uses them.
func (*HostSettings) SetEnvironment ¶
func (h *HostSettings) SetEnvironment(env HostEnvironment)
SetEnvironment sets what the host sets over the platform's environment.
func (*HostSettings) SetTokens ¶
func (h *HostSettings) SetTokens(t Tokens)
SetTokens sets the values the host themes the app with.
type Options ¶
type Options struct {
// CheckCommits enables full-layout diagnostics for this engine only. In a test or development build it also checks that only the engine's goroutine touches its graph, and it re-panics an internal fault after the fault's cleanup, so a test fails rather than only reporting it.
CheckCommits bool
// Size is the surface's size at start.
Size driver.Size
// Geometry is the fold geometry measured at Size, which the first commit is laid out with (Engine.Resize); the zero Geometry is a surface without a fold.
Geometry driver.Geometry
// Environment is what the platform knows at start.
Environment driver.Environment
// Clock runs the app's timers; the system's when nil.
Clock core.Clock
// Storage keeps the app's entries; in memory for the engine's life
// when nil. Platforms pass OpenFileStorage in the data directory.
Storage *core.Store
// Secrets is the platform's secure store (core.Scope.Secrets); nil where it has none.
Secrets driver.SecretStore
// DataDir, CacheDir and LogsDir are the app's directories, made when the engine starts; "" where the target has none.
DataDir, CacheDir, LogsDir string
// Appearance is the appearance the app starts in, forced as
// Scope.SetAppearance forces it; the system's by default.
Appearance driver.Appearance
// Host is what an embedding host gives the view the app runs in.
Host HostOptions
// Windows, set where the platform opens windows, are the main
// window's options (core.RootOptions.Windows): the first surface is
// the app's own, which shows no view, and the platform attaches each
// surface the app opens.
Windows *WindowOptions
// HotKeys, set where the platform registers global shortcuts but opens no windows, has the first surface take the app's global shortcuts (core.RootOptions.HotKeys).
HotKeys bool
// Tray is set where the platform supports app-level tray icons without
// opening additional windows (core.RootOptions.Tray).
Tray bool
// Perf collects this app's commit timings; nil measures nothing.
Perf *PerfMonitor
// Thread runs first on the OS thread the engine keeps, before the
// app. The engine turns input into frames, as latency-critical as the
// main thread: a platform whose scheduler would put it on slower
// cores raises its priority here.
Thread func()
// Observe sees each batch before the platform does, and Event each
// event the platform reports, as a test host follows the app; Pin
// turns each environment the platform reports into the app's. None
// may block.
Observe func(*driver.MountBatch)
Event func(driver.Event)
Pin func(driver.Environment) driver.Environment
// Clipboard, with Observe, is the clipboard of a test's own, which
// the app's clipboard commands use instead of the platform's.
Clipboard *driver.MemoryClipboard
// LogPerf logs Perf's readings once a second while the engine runs.
LogPerf bool
}
Options configure an engine.
type PerfBar ¶
PerfBar is a rectangle of the trace, in its box's points with y down.
func PerfTrace ¶
func PerfTrace(s PerfSnapshot, w, h float64) []PerfBar
PerfTrace returns the trace of s's frames in a w × h box: its fill, a bar per frame, newest at the right, scaled so that twice the budget (one refresh) fills the box, and the budget's line at half height.
type PerfMonitor ¶
type PerfMonitor struct {
// contains filtered or unexported fields
}
PerfMonitor collects a surface's frame and commit timings. It is shared by its engine goroutine and its main thread, and safe for both.
func (*PerfMonitor) RecordBusy ¶
func (m *PerfMonitor) RecordBusy(d time.Duration)
RecordBusy records that an engine wake-up was busy for d.
func (*PerfMonitor) RecordCommit ¶
func (m *PerfMonitor) RecordCommit(timing CommitTiming)
RecordCommit records an engine wake-up that committed.
func (*PerfMonitor) RecordLatency ¶
func (m *PerfMonitor) RecordLatency(latency time.Duration)
RecordLatency records that a batch was applied latency after the engine handed it over.
func (*PerfMonitor) RecordWork ¶
func (m *PerfMonitor) RecordWork(cost time.Duration, dirty bool)
RecordWork records main-thread work on the surface: cost was spent, and dirty reports whether it changed what the screen shows (a batch was applied, an animation stepped, a scroll view moved).
func (*PerfMonitor) SetProcess ¶
func (m *PerfMonitor) SetProcess(sample ProcessSample)
SetProcess stores the process' latest resource use, shown with the next snapshots.
func (*PerfMonitor) Snapshot ¶
func (m *PerfMonitor) Snapshot() PerfSnapshot
Snapshot returns the readings as of now.
type PerfSnapshot ¶
type PerfSnapshot struct {
// FPS is frames shown per second over the last second: display
// refreshes in which the surface changed. Low while the app is idle,
// which is not slowness.
FPS float32
// MaxFPS is what the main thread could keep up with: one over the mean
// frame cost, capped at the display's rate when it is known.
MaxFPS float32
// RefreshRate is the rate the display link asks for (Hz), once it ran.
RefreshRate *float32
// TickInterval is the gaps between refreshes as they were delivered,
// over the last capacity: a mean above one period means refreshes came
// late or were skipped (a main thread busy when they were due).
TickInterval Stat
// FrameInterval is the gaps between shown frames over the last
// capacity (long while the app is idle, one period while it animates
// smoothly).
FrameInterval Stat
// Frame is main-thread time per shown frame (applying batches,
// animations, input), over the last capacity frames.
Frame Stat
// Dropped is the share of those frames that took longer than one
// refresh, in 0..=1.
Dropped float32
// Commits is commits per second over the last second.
Commits float32
// App is the app's code per commit.
App Stat
// Core is the core's work per commit.
Core Stat
// Items is the mean mount items per commit.
Items float32
// Latency is how long batches waited between the engine handing them
// over and the main thread applying them.
Latency Stat
// EngineBusy is the engine goroutine's busy time over the last second,
// in percent.
EngineBusy float32
// Passes is the engine's wake-ups per second over the last second: one
// a frame for an app that only changes in its frames.
Passes float32
// Frames are the main-thread costs of the retained frames, oldest
// first (for a trace).
Frames []time.Duration
// Process is the process' resource use, as last given to SetProcess.
Process ProcessSample
}
PerfSnapshot is what a PerfMonitor read, as of one moment.
func (PerfSnapshot) Readings ¶
func (s PerfSnapshot) Readings() string
Readings formats a snapshot as the performance monitor's panel shows it: milliseconds as mean and 95th percentile, CPU and GPU as percent of one core, memory in megabytes.
func (PerfSnapshot) String ¶
func (s PerfSnapshot) String() string
String is the snapshot as one line, as nsgo test -fps logs it.
type Platform ¶
type Platform interface {
driver.TextEngine
// Mount receives each commit on the engine goroutine. The platform
// applies it on its main thread, in one hop, without waiting.
Mount(batch *driver.MountBatch)
// RequestFrame asks for the next display frame. The platform calls
// Frame when that frame begins, once for each request, and only then.
// It is called from the engine goroutine, so it must not block. A
// platform with no display frame leaves it empty, and the app's frame
// callbacks wait.
RequestFrame()
}
Platform is what a backend gives the engine.
type ProcessSample ¶
type ProcessSample struct {
// CPU is CPU time over wall time since the previous sample, in percent
// of one core (as top and Activity Monitor show it: 150 is one and a
// half cores busy).
CPU *float32
// Memory is the memory the process owns, in bytes: the physical
// footprint on Apple platforms (Activity Monitor's Memory column), the
// resident set elsewhere.
Memory *uint64
// GPU is GPU time over wall time, in percent, where the platform tells
// it per process (macOS).
GPU *float32
}
ProcessSample is the process' resource use.
type SharedMounter ¶
type SharedMounter interface {
Platform
}
SharedMounter is a Platform that applies each batch within Mount, on the engine goroutine, as the web does: its batches are the tree's own items, not copies (core.Tree.CommitShared).
type TestPin ¶
type TestPin struct {
// contains filtered or unexported fields
}
TestPin is the environment a test pins over the platform's, which it may change while the app runs.
type WindowOptions ¶
type WindowOptions = core.WindowOptions
Host, Tokens and WindowOptions are core's, for backends.