// Package tcelllivepage provides a tcell screen which renders to a browser as // HTML streamed by livepage. DOM input events are mapped back to tcell cell // coordinates.
package tcelllivepage import ( am lp ) const ( // DefaultCols and DefaultRows are the initial grid dimensions, used until // the browser reports its viewport. DefaultCols = 80 DefaultRows = 25 // DefaultFontSize is the cell font size in CSS pixels. DefaultFontSize = 14 // maxDim guards against abusive resize messages. maxDim = 4096 screenID = "tcell-screen" ) // Theme defines the default colors of the screen. type Theme struct { Fg tcell.Color Bg tcell.Color Cursor tcell.Color } // DefaultTheme is a dark theme. func () Theme { return Theme{ Fg: tcell.NewHexColor(0xD4D4D4), Bg: tcell.NewHexColor(0x101014), Cursor: tcell.NewHexColor(0x56B6C2), } } // Opts configures a [Screen]. type Opts struct { // Cols and Rows are the initial grid dimensions before the browser reports // the viewport. Defaults to [DefaultCols] and [DefaultRows]. Cols, Rows int // FontSize is the CSS font size in pixels. Defaults to [DefaultFontSize]. FontSize int // FontFamily is the CSS font family. Defaults to a monospace stack. FontFamily string // Theme defines the default colors. Defaults to [DefaultTheme]. Theme Theme // Title is the title of the default HTML page. Optional. Title string // RefreshInterval coalesces [Screen.Show] refreshes to at most this rate, // using a trailing refresh. Zero means no throttling. Use it for // applications which draw frequently, e.g. 100ms for ~10fps. RefreshInterval time.Duration // Live holds the livepage options. HtmlPage is wrapped to inject the // screen's CSS and JS. Debounce defaults to 20ms. Live lp.Opts } // Screen is a tcell screen which streams its grid to the browser as HTML using // livepage. It embeds a [tcell.SimulationScreen], so it can be passed to // [cview.Application.SetScreen] or used by any tcell application. // // The screen is initialized by [NewScreen]; [tcell.Screen.Init] is a no-op. type Screen struct { tcell.SimulationScreen ctx context.Context cancel context.CancelFunc page *lp.Page[*compo] compo *compo mach *am.Machine theme Theme fontSize int fontFamily string refreshInterval time.Duration // primed is set after the first refresh, so the initial frame is rendered // even without any clients. primed bool lastRefresh time.Time refreshTimer *time.Timer mu sync.Mutex dirty bool html string styles map[tcell.Style]string // gen is incremented on every screen update. gen uint64 // sizesMx guards the per-browser viewports. sizesMx sync.Mutex sizes map[string][2]int finiOnce sync.Once } // NewScreen creates an initialized screen. The page lives as long as ctx; the // returned screen disposes it on [Screen.Fini]. func ( context.Context, Opts) (*Screen, error) { if .Cols <= 0 { .Cols = DefaultCols } if .Rows <= 0 { .Rows = DefaultRows } if .FontSize <= 0 { .FontSize = DefaultFontSize } if .FontFamily == "" { .FontFamily = `ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace` } := DefaultTheme() if !.Theme.Fg.Valid() { .Theme.Fg = .Fg } if !.Theme.Bg.Valid() { .Theme.Bg = .Bg } if !.Theme.Cursor.Valid() { .Theme.Cursor = .Cursor } if .Live.Debounce <= 0 { .Live.Debounce = 20 * time.Millisecond } := tcell.NewSimulationScreen("UTF-8") if := .Init(); != nil { return nil, } // The default fill char of a simulation screen is 'X'; emulate a blank // terminal before the first draw. .SetSize(.Cols, .Rows) .Clear() .Show() .EnableMouse() , := context.WithCancel() := &Screen{ SimulationScreen: , ctx: , cancel: , theme: .Theme, fontSize: .FontSize, fontFamily: .FontFamily, refreshInterval: .RefreshInterval, dirty: true, styles: map[tcell.Style]string{}, sizes: map[string][2]int{}, } // Wrap the page template to inject the screen's CSS and JS. When no // template is provided, use a full-page one. := .Live.HtmlPage == nil := .Live.HtmlPage if == nil { := .Title if == "" { = "livepage" } = func( string) string { return "<!DOCTYPE html><html><head><meta charset=\"utf-8\">" + "<title>" + html.EscapeString() + "</title></head><body>" + + "</body></html>" } } .Live.HtmlPage = func( string) string { return injectHead((), .headTags()) } // Keep a user-provided custom event hook. := .Live.OnEvent .Live.OnEvent = func( *lp.DomEvent) { .handleEvent() if != nil { () } } // Keep a user-provided client hook. := .Live.OnClient .Live.OnClient = func( string, bool) { .handleClient(, ) if != nil { (, ) } } .compo = &compo{s: } := am.New(, am.Schema{am.StateReady: {}}, nil) .mach = , := lp.New(, .compo, .Live) if != nil { () .Fini() .Dispose() return nil, } .page = return , nil } // Init is a no-op, the screen is initialized by [NewScreen]. func ( *Screen) () error { return nil } // Fini stops the screen and disposes the page. func ( *Screen) () { .finiOnce.Do(func() { .mu.Lock() if .refreshTimer != nil { .refreshTimer.Stop() .refreshTimer = nil } .mu.Unlock() .SimulationScreen.Fini() .page.Dispose() .cancel() .mach.Dispose() }) } // Show marks the screen as dirty and renders/pushes the HTML. Rendering is // skipped while no browser is connected, and coalesced according to // [Opts.RefreshInterval]. func ( *Screen) () { .SimulationScreen.Show() .mu.Lock() .dirty = true .gen++ := !.primed .primed = true .mu.Unlock() // Snapshot the completed frame for the async page renderer. Rendering from // the live simulation screen would tear while the app draws the next frame. .renderNow() // Prime the first frame, so clients connecting later get a full page even // before their first resize event. if { .refreshNow() return } // Lazy: pushing is only useful while at least one browser is connected. // A client forces a refresh via its initial resize event. if .page.Clients() == 0 { return } .scheduleRefresh() } // Sync renders and pushes the current state immediately. func ( *Screen) () { .SimulationScreen.Show() .mu.Lock() .dirty = true .gen++ .mu.Unlock() .renderNow() .refreshNow() } // renderNow snapshots the completed grid into HTML on the drawing goroutine. // The page renderer reads this snapshot, so it never sees a partially drawn // frame (fast input used to flicker because of that). func ( *Screen) () { .mu.Lock() defer .mu.Unlock() .html = .renderGrid() .dirty = false } // scheduleRefresh coalesces refreshes according to [Opts.RefreshInterval], // using a trailing refresh. func ( *Screen) () { .mu.Lock() if .refreshTimer != nil { .mu.Unlock() return } := time.Duration(0) if .refreshInterval > 0 { = .refreshInterval - time.Since(.lastRefresh) } if <= 0 { .mu.Unlock() .refreshNow() return } .refreshTimer = time.AfterFunc(, func() { .mu.Lock() .refreshTimer = nil .mu.Unlock() .refreshNow() }) .mu.Unlock() } // refreshNow renders the component and pushes the HTML on the screen's machine // queue. func ( *Screen) () { if .ctx.Err() != nil { return } .mu.Lock() .lastRefresh = time.Now() .mu.Unlock() // Refresh serializes the component update on the screen's machine queue. // It is safe to call from any goroutine. .page.Refresh(.ctx) } // ResizeGrid resizes the grid, typically from the browser viewport. It posts a // [tcell.EventResize] to the application and reports whether the size changed. func ( *Screen) (, int) bool { if <= 0 || <= 0 || > maxDim || > maxDim { return false } if , := .Size(); == && == { return false } .SimulationScreen.SetSize(, ) _ = .PostEvent(tcell.NewEventResize(, )) .mu.Lock() .dirty = true .gen++ .mu.Unlock() return true } // Handler serves the page, the livepage scripts and the WebSocket. func ( *Screen) () http.Handler { return .page.NewHandler() } // Machine returns the machine used to serialize rendering and DOM events. func ( *Screen) () *am.Machine { return .mach }