jroimartin / gocui

Minimalist Go package aimed at creating Console User Interfaces.
BSD 3-Clause "New" or "Revised" License
9.92k stars 608 forks source link

Separate Gui event handler from main loop initialization #198

Closed trumpetx closed 10 months ago

trumpetx commented 5 years ago

I don't know if you want this change or if you'd rather handle this differently... I'm using gocui to "handle" the errors "thrown" at different points in the lifecycle (on keybind, etc) and I needed a common place to put them. Since gocui has its own lifecycle, I felt it was appropriate to handle the errors by returning them to their appropriate handlers. This posed a problem when I wanted to display an error in an "alert" (using gocui) instead of returning. My thought is that as my error handling gets better, some would exit (like now) and others would be gracefully recovered from.

Calling gui.MainLoop() after it exits doesn't work because the goroutine for termbox.PollEvent() is initialized more than once (causing multiple keypresses -- among other things). So, this PR separates that "initialization" from the actual main loop so that I can re-call the main loop after gracefully recovering after an error.

Ex:

    gui.MainLoopInit()

    for {
        err := gui.MainLoopEventHandler()
        if err == nil || err == gocui.ErrQuit {
            return
        } else if err != nil {
            gui.Update(func(gui *gocui.Gui) error {
                return views.AlertWithTitle(gui, "Error", err.Error()+"\n\n"+string(debug.Stack()))
            })
        }
    }