gizak / termui

Golang terminal dashboard
MIT License
13.23k stars 786 forks source link

Crash on resize when resize handler func calls termui.Clear() #137

Closed christophberger closed 5 years ago

christophberger commented 7 years ago

When the resize handler func calls termui.Clear(), resizing the terminal window can cause a crash.

This is the test code:

package main

import ui "github.com/gizak/termui"

func main() {
    ui.Init()
    defer ui.Close()
    p := ui.NewPar("Hey")
    p.Height = ui.TermHeight()
    ui.Body.AddRows(
        ui.NewRow(
            ui.NewCol(12, 0, p)))
    ui.Body.Align()
    ui.Render(ui.Body)

    ui.Handle("/sys/wnd/resize", func(ui.Event) {
        ui.Body.Width = ui.TermWidth()
        ui.Body.Align()
        ui.Clear()  // Delete this line to avoid the crash
        ui.Render(ui.Body)
    })
    ui.Handle("/sys/kbd/C-c", func(ui.Event) {
        ui.StopLoop()
    })

    ui.Loop()
}

BTW, the resize handler appears to work fine without Clear().

cjbassi commented 5 years ago

Hi, I (roughly) converted your code based on the latest api:

package main

import (
    ui "github.com/gizak/termui"
    "github.com/gizak/termui/widgets"
)

func main() {
    ui.Init()
    defer ui.Close()

    p := widgets.NewParagraph()
    p.Text = "Hey"

    grid := ui.NewGrid()
    termWidth, termHeight := ui.TerminalDimensions()
    grid.SetRect(0, 0, termWidth, termHeight)

    grid.Set(
        ui.NewRow(1.0/2,
            ui.NewCol(1.0/2, p),
        ),
    )

    ui.Render(grid)

    uiEvents := ui.PollEvents()
    for {
        select {
        case e := <-uiEvents:
            switch e.ID {
            case "q", "<C-c>":
                return
            case "<Resize>":
                payload := e.Payload.(ui.Resize)
                grid.SetRect(0, 0, payload.Width, 0)
                ui.Clear()
                ui.Render(grid)
            }
        }
    }
}

And it seems to work for me with or without the ui.Clear() line. I just rewrote most of termui in 958a285 on master, so that may have fixed it, but let me know if you still get issues. Do note that termui has been heavily reworked in that commit, so there's a lot of breaking changes.