Skip to content
Myr

feat: print unmanaged output above the application (#249)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* merge Adjective-Object/tea_log_renderer into standard renderer * rename queuedMessages -> queuedMessageLines & break apart strings during message processing * delete cursorDownBy * += 1 -> ++ to make the linter happy * add skipLines[] tracking back to standard renderer, and add rename skippedLines local to jumpedLines to clarify they are separate comments * request repaint when a message is recieved * Convert Println and Printf to commands * Add package manager example demonstrating tea.Printf * Use Unix instead of UnixMicro for Go 1.13 support in CI * fix off by one in std renderer * add Printf/Println to tea.go * revert attempt at sequence compression + cursorUpBy

authored by Max · committed by GitHub · parent a2d0ac9 · Browse files · 4 files+289 added−18 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Maxwell Huang-Hobbs <mahuangh@microsoft.com>
  • Co-authored-by: Christian Rocha <christian@rocha.is>

Diff stats

4 files+289 added−18 removed

  • other:+289 added−18 removed

4 files+289 added−18 removed

added:examples/package-manager/main.go+139 added
1package main23import (4 "fmt"5 "math/rand"6 "os"7 "strings"8 "time"910 "github.com/charmbracelet/bubbles/progress"11 "github.com/charmbracelet/bubbles/spinner"12 tea "github.com/charmbracelet/bubbletea"13 "github.com/charmbracelet/lipgloss"14)1516type model struct {17 packages []string18 index int19 width int20 height int21 spinner spinner.Model22 progress progress.Model23 done bool24}2526var (27 currentPkgNameStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("211"))28 subtleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("239"))29 doneStyle = lipgloss.NewStyle().Margin(1, 2)30 checkMark = lipgloss.NewStyle().Foreground(lipgloss.Color("42")).SetString("✓")31)3233func newModel() model {34 p := progress.New(35 progress.WithDefaultGradient(),36 progress.WithWidth(40),37 progress.WithoutPercentage(),38 )39 s := spinner.New()40 s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("63"))41 return model{42 packages: getPackages(),43 spinner: s,44 progress: p,45 }46}4748func (m model) Init() tea.Cmd {49 return tea.Batch(downloadAndInstall(m.packages[m.index]), m.spinner.Tick)50}5152func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {53 switch msg := msg.(type) {54 case tea.WindowSizeMsg:55 m.width, m.height = msg.Width, msg.Height56 case tea.KeyMsg:57 switch msg.String() {58 case "ctrl+c", "esc", "q":59 return m, tea.Quit60 }61 case installedPkgMsg:62 if m.index >= len(m.packages)-1 {63 // Everything's been installed. We're done!64 m.done = true65 return m, tea.Quit66 }6768 // Update progress bar69 progressCmd := m.progress.SetPercent(float64(m.index) / float64(len(m.packages)-1))7071 m.index++72 return m, tea.Batch(73 progressCmd,74 tea.Printf("%s %s", checkMark, m.packages[m.index]), // print success message above our program75 downloadAndInstall(m.packages[m.index]), // download the next package76 )77 case spinner.TickMsg:78 var cmd tea.Cmd79 m.spinner, cmd = m.spinner.Update(msg)80 return m, cmd81 case progress.FrameMsg:82 newModel, cmd := m.progress.Update(msg)83 if newModel, ok := newModel.(progress.Model); ok {84 m.progress = newModel85 }86 return m, cmd87 }88 return m, nil89}9091func (m model) View() string {92 n := len(m.packages)93 w := lipgloss.Width(fmt.Sprintf("%d", n))9495 if m.done {96 return doneStyle.Render(fmt.Sprintf("Done! Installed %d packages.\n", n))97 }9899 pkgCount := fmt.Sprintf(" %*d/%*d", w, m.index, w, n-1)100101 spin := m.spinner.View() + " "102 prog := m.progress.View()103 cellsAvail := max(0, m.width-lipgloss.Width(spin+prog+pkgCount))104105 pkgName := currentPkgNameStyle.Render(m.packages[m.index])106 info := lipgloss.NewStyle().MaxWidth(cellsAvail).Render("Installing " + pkgName)107108 cellsRemaining := max(0, m.width-lipgloss.Width(spin+info+prog+pkgCount))109 gap := strings.Repeat(" ", cellsRemaining)110111 return spin + info + gap + prog + pkgCount112}113114type installedPkgMsg string115116func downloadAndInstall(pkg string) tea.Cmd {117 // This is where you'd do i/o stuff to download and install packages. In118 // our case we're just pausing for a moment to simulate the process.119 d := time.Millisecond * time.Duration(rand.Intn(500))120 return tea.Tick(d, func(t time.Time) tea.Msg {121 return installedPkgMsg(pkg)122 })123}124125func max(a, b int) int {126 if a > b {127 return a128 }129 return b130}131132func main() {133 rand.Seed(time.Now().Unix())134135 if err := tea.NewProgram(newModel()).Start(); err != nil {136 fmt.Println("Error running program:", err)137 os.Exit(1)138 }139}
added:examples/package-manager/packages.go+52 added
1package main23import (4 "fmt"5 "math/rand"6)78var packages = []string{9 "vegeutils",10 "libgardening",11 "currykit",12 "spicerack",13 "fullenglish",14 "eggy",15 "bad-kitty",16 "chai",17 "hojicha",18 "libtacos",19 "babys-monads",20 "libpurring",21 "currywurst-devel",22 "xmodmeow",23 "licorice-utils",24 "cashew-apple",25 "rock-lobster",26 "standmixer",27 "coffee-CUPS",28 "libesszet",29 "zeichenorientierte-benutzerschnittstellen",30 "schnurrkit",31 "old-socks-devel",32 "jalapeño",33 "molasses-utils",34 "xkohlrabi",35 "party-gherkin",36 "snow-peas",37 "libyuzu",38}3940func getPackages() []string {41 pkgs := packages42 copy(pkgs, packages)4344 rand.Shuffle(len(pkgs), func(i, j int) {45 pkgs[i], pkgs[j] = pkgs[j], pkgs[i]46 })4748 for k := range pkgs {49 pkgs[k] += fmt.Sprintf("-%d.%d.%d", rand.Intn(10), rand.Intn(10), rand.Intn(10))50 }51 return pkgs52}
modified:standard_renderer.go+71 added-18 removed
1package tea23import (4 "bytes"5 "fmt"6 "io"7 "strings"8 "sync"9 "time"
13 unmodified lines
23//24// In cases where very high performance is needed the renderer can be told25// to exclude ranges of lines, allowing them to be written to directly.26type standardRenderer struct {27 out io.Writer26 out io.Writer27 buf bytes.Buffer28 framerate time.Duration29 ticker *time.Ticker30 mtx *sync.Mutex31 done chan struct{}32 lastRender string33 linesRendered int34 useANSICompressor bool35 once sync.Once28 buf bytes.Buffer29 queuedMessageLines []string30 framerate time.Duration31 ticker *time.Ticker32 mtx *sync.Mutex33 done chan struct{}34 lastRender string35 linesRendered int36 useANSICompressor bool37 once sync.Once3839 // essentially whether or not we're using the full size of the terminal40 altScreenActive bool41
8 unmodified lines
50// newRenderer creates a new renderer. Normally you'll want to initialize it51// with os.Stdout as the first argument.52func newRenderer(out io.Writer, mtx *sync.Mutex, useANSICompressor bool) renderer {53 r := &standardRenderer{52 out: out,53 mtx: mtx,54 framerate: defaultFramerate,55 useANSICompressor: useANSICompressor,54 out: out,55 mtx: mtx,56 framerate: defaultFramerate,57 useANSICompressor: useANSICompressor,58 queuedMessageLines: []string{},59 }60 if r.useANSICompressor {61 r.out = &compressor.Writer{Forward: out}62 }
61 unmodified lines
124 // Output buffer125 out := new(bytes.Buffer)126127 newLines := strings.Split(r.buf.String(), "\n")128 numLinesThisFlush := len(newLines)129 oldLines := strings.Split(r.lastRender, "\n")130 skipLines := make(map[int]struct{})131 flushQueuedMessages := len(r.queuedMessageLines) > 0 && !r.altScreenActive132133 // Add any queued messages to this render134 if flushQueuedMessages {135 newLines = append(r.queuedMessageLines, newLines...)136 r.queuedMessageLines = []string{}137 }138139 // Clear any lines we painted in the last render.140 if r.linesRendered > 0 {141 for i := r.linesRendered - 1; i > 0; i-- {142 // If the number of lines we want to render hasn't increased and
30 unmodified lines
173 skipLines[k] = v174 }175 }176166 r.linesRendered = 0167177 // Paint new lines178 for i := 0; i < len(newLines); i++ {170 if _, skip := skipLines[r.linesRendered]; skip {179 if _, skip := skipLines[i]; skip {180 // Unless this is the last line, move the cursor down.181 if i < len(newLines)-1 {182 cursorDown(out)183 }
16 unmodified lines
200 if i < len(newLines)-1 {201 _, _ = io.WriteString(out, "\r\n")202 }203 }195 r.linesRendered++204 }205 r.linesRendered = numLinesThisFlush206207 // Make sure the cursor is at the start of the last line to keep rendering208 // behavior consistent.209 if r.altScreenActive {
181 unmodified lines
391 r.insertTop(msg.lines, msg.topBoundary, msg.bottomBoundary)392393 case scrollDownMsg:394 r.insertBottom(msg.lines, msg.topBoundary, msg.bottomBoundary)395396 case printLineMessage:397 if !r.altScreenActive {398 lines := strings.Split(msg.messageBody, "\n")399 r.mtx.Lock()400 r.queuedMessageLines = append(r.queuedMessageLines, lines...)401 r.repaint()402 r.mtx.Unlock()403 }404 }405}406407// HIGH-PERFORMANCE RENDERING STUFF
69 unmodified lines
477 bottomBoundary: bottomBoundary,478 }479 }480}481482type printLineMessage struct {483 messageBody string484}485486// Printf prints above the Program. This output is unmanaged by the program and487// will persist across renders by the Program.488//489// Unlike fmt.Printf (but similar to log.Printf) the message will be print on490// its own line.491//492// If the altscreen is active no output will be printed.493func Println(args ...interface{}) Cmd {494 return func() Msg {495 return printLineMessage{496 messageBody: fmt.Sprint(args...),497 }498 }499}500501// Printf prints above the Program. It takes a format template followed by502// values similar to fmt.Printf. This output is unmanaged by the program and503// will persist across renders by the Program.504//505// Unlike fmt.Printf (but similar to log.Printf) the message will be print on506// its own line.507//508// If the altscreen is active no output will be printed.509func Printf(template string, args ...interface{}) Cmd {510 return func() Msg {511 return printLineMessage{512 messageBody: fmt.Sprintf(template, args...),513 }514 }515}
modified:tea.go+27 added
707 unmodified lines
708 go p.Send(repaintMsg{})709710 return nil711}712713// Printf prints above the Program. This output is unmanaged by the program and714// will persist across renders by the Program.715//716// Unlike fmt.Printf (but similar to log.Printf) the message will be print on717// its own line.718//719// If the altscreen is active no output will be printed.720func (p *Program) Println(args ...interface{}) {721 p.msgs <- printLineMessage{722 messageBody: fmt.Sprint(args...),723 }724}725726// Printf prints above the Program. It takes a format template followed by727// values similar to fmt.Printf. This output is unmanaged by the program and728// will persist across renders by the Program.729//730// Unlike fmt.Printf (but similar to log.Printf) the message will be print on731// its own line.732//733// If the altscreen is active no output will be printed.734func (p *Program) Printf(template string, args ...interface{}) {735 p.msgs <- printLineMessage{736 messageBody: fmt.Sprintf(template, args...),737 }738}