This repository was archived by the owner on Aug 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathui.go
533 lines (485 loc) · 14.6 KB
/
ui.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// Copyright (c) 2020 Yon <anaseto@bardinflor.perso.aquilenet.fr>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// ----
//
// Some code from the core gruid package relative to models and commands in ui.go
// is strongly inspired from github.com/charmbracelet/bubbletea, which uses the
// following license:
//
// MIT License
//
// Copyright (c) 2020 Charmbracelet, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Package gruid provides a model for building grid-based applications. The
// interface abstracts rendering and input for different platforms. There are
// drivers for terminal apps (gruid-tcell), native graphical apps (gruid-sdl)
// and browser apps (gruid-js).
//
// The package uses an architecture of updating a model in response to messages
// strongly inspired from the bubbletea module for building terminal apps
// (https://github.com/charmbracelet/bubbletea), which in turn is based on the
// Elm Architecture (https://guide.elm-lang.org/architecture/).
//
// The typical usage looks like this:
//
// // model implements gruid.Model interface and represents the
// // application's state.
// type model struct {
// grid gruid.Grid // user interface grid
// // other fields with the state of the application
// }
//
// func (m *model) Update(msg gruid.Msg) gruid.Effect {
// // Update your application's state in response to messages.
// }
//
// func (m *model) Draw() gruid.Grid {
// // Write your rendering into the grid and return it.
// }
//
// func main() {
// gd := gruid.NewGrid(80, 24)
// m := &model{grid: gd, ...}
// // Specify a driver among the provided ones.
// driver := tcell.NewDriver(...)
// app := gruid.NewApp(gruid.AppConfig{
// Driver: driver,
// Model: m,
// })
// // Start the main loop of the application.
// if err := app.Start(context.Background()); err != nil {
// log.Fatal(err)
// }
// }
//
// The values of type gruid.Effect returned by Update are optional and
// represent concurrently executed functions that produce messages. The
// gruid.Grid type is a convenient 2-dimensional slice type representing the
// screen's logical contents. See the relevant types documentation for details
// and usage.
package gruid
import (
"context"
"fmt"
"io"
"log"
"runtime/debug"
"time"
)
// Model contains the application's state.
type Model interface {
// Update is called when a message is received. Use it to update your
// model in response to messages and/or send commands or subscriptions.
// It is always called the first time with a MsgInit message.
Update(Msg) Effect
// Draw is called after every Update. Use this function to draw the UI
// elements in a grid to be returned. If only parts of the grid are to
// be updated, you can return a smaller grid slice, or an empty grid
// slice to skip any drawing work. Note that the contents of the grid
// slice are then compared to the previous state at the same bounds,
// and only the changes are sent to the driver anyway.
Draw() Grid
}
// Driver handles both user input and rendering. When creating an App and using
// the Start main loop, you will not have to call those methods directly. You
// may reuse the same driver for another application after the current
// application's Start loop ends.
type Driver interface {
// Init initializes the driver, so that you can then call its other
// methods.
Init() error
// PollMsgs is a subscription for input messages. It returns an error
// in case the driver input loop suffered a non recoverable error. It
// should handle cancellation of the passed context and return as
// appropriate.
PollMsgs(context.Context, chan<- Msg) error
// Flush sends grid's last frame changes to the driver.
Flush(Frame)
// Close may execute needed code to finalize the screen and release
// resources. Redundant Close() calls are ignored. After Close() it is
// possible to call Init() again.
Close()
}
// DriverPollMsg is an optional interface that can be satisfied by drivers.
// Such drivers will be run such that the message polling is executed in the
// same thread as main using a non-blocking polling message method, instead of
// PollMsgs. This may be necessary with drivers whose input system is not
// thread safe.
type DriverPollMsg interface {
// The PollMsg returns an input message if any, in a non-blocking way.
// If no message can be retrieved, nil should be returned. If a non
// recoverable input error happens, an error can be returned.
PollMsg() (Msg, error)
}
// Msg represents an action and triggers the Update function of the model. Note
// that nil messages are discarded and do not trigger Update.
type Msg interface{}
// Effect is an interface type for representing either command or subscription
// functions. Those functions generally represent IO operations, either
// producing a single message or several. They are executed on their own
// goroutine after being returned by the Update method of the model. A nil
// effect is discarded and does nothing.
//
// The types Cmd and Sub implement the Effect interface. See their respective
// documentation for specific usage details.
type Effect interface {
implementsEffect()
}
// Cmd is an Effect that returns a message. Commands returned by Update are
// executed on their own goroutine. You can use them for things like single
// event timers and short-lived IO operations with a single result. A nil
// command is discarded and does nothing.
//
// Cmd implements the Effect interface.
type Cmd func() Msg
// Sub is similar to Cmd, but instead of returning a message, it sends messages
// to a channel. Subscriptions should only be used for long running functions
// where more than one message will be produced, for example to send messages
// delivered by a time.Ticker, or to report messages from listening on a
// socket. The function should handle the context and terminate as appropriate.
//
// Sub implements the Effect interface.
type Sub func(context.Context, chan<- Msg)
// implementsEffect makes Cmd satisfy Effect interface.
func (cmd Cmd) implementsEffect() {}
// implementsEffect makes Sub satisfy Effect interface.
func (sub Sub) implementsEffect() {}
// End returns a special command that signals the application to end its Start
// loop. Note that the application does not wait for pending effects to
// complete before exiting the Start loop, so you may have to wait for any of
// those commands messages before using End.
func End() Cmd {
return func() Msg {
return msgEnd{}
}
}
// Batch peforms a bunch of effects concurrently with no ordering guarantees
// about the potential results.
func Batch(effs ...Effect) Effect {
if len(effs) == 0 {
return nil
}
return Cmd(func() Msg {
return msgBatch(effs)
})
}
// App represents a message and model-driven application with a grid-based user
// interface.
type App struct {
// CatchPanics ensures that Close is called on the driver before ending
// the Start loop. When a panic occurs, it will be recovered, the stack
// trace will be printed and an error will be returned. It defaults to
// true.
CatchPanics bool
driver Driver
model Model
enc *frameEncoder
logger *log.Logger
grid Grid
frame Frame
effects chan Effect
errs chan error
inputs chan Msg
msgs chan Msg
polldone chan struct{}
t *time.Timer
}
// AppConfig contains the configuration options for creating a new App.
type AppConfig struct {
Model Model // application state
Driver Driver // input and rendering driver
// FrameWriter is an optional io.Writer for recording frames. They can
// be decoded after a successful Start session with a FrameDecoder. If
// nil, no frame recording will be done. It is your responsibility to
// call Close on the Writer after Start returns.
FrameWriter io.Writer
// Logger is optional and is used to log non-fatal IO errors.
Logger *log.Logger
}
// NewApp creates a new App with the given configuration options.
func NewApp(cfg AppConfig) *App {
app := &App{
model: cfg.Model,
driver: cfg.Driver,
logger: cfg.Logger,
CatchPanics: true,
}
if cfg.FrameWriter != nil {
app.enc = newFrameEncoder(cfg.FrameWriter)
}
return app
}
// Start initializes the application and runs its main loop. The context
// argument can be used as a means to prematurely cancel the loop. You can
// usually use an empty context here.
func (app *App) Start(ctx context.Context) (err error) {
app.msgs = make(chan Msg, 4)
app.errs = make(chan error) // for driver input errors
app.polldone = make(chan struct{}) // PollMsgs subscription finished
app.effects = make(chan Effect, 4)
pollMsgNonBlocking := false
switch app.driver.(type) {
case DriverPollMsg:
pollMsgNonBlocking = true
app.inputs = make(chan Msg, 4)
}
// frame encoder finalization
defer func() {
if app.enc != nil {
nerr := app.enc.gzw.Close()
if err == nil {
err = nerr
} else if app.logger != nil {
app.logger.Printf("error closing gzip encoder: %v", err)
}
}
}()
// driver and context initialization
err = app.driver.Init()
if err != nil {
return err
}
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithCancel(ctx)
if app.CatchPanics {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
cancel()
<-app.polldone
app.driver.Close()
log.Printf("Caught panic: %v\nStack Trace:\n", r)
debug.PrintStack()
} else {
<-app.polldone
app.driver.Close()
}
}()
} else {
defer func() {
<-app.polldone
app.driver.Close()
}()
}
defer cancel()
// initialization message (non-blocking, buffered)
app.msgs <- MsgInit{}
// input messages queueing
if pollMsgNonBlocking {
go app.startPollMsgSub(ctx)
} else {
go app.startPollMsgs(ctx)
}
// effect processing
go app.processEffects(ctx)
// start Update on message then Draw main loop
if pollMsgNonBlocking {
err = app.startWithPollMsg(ctx, cancel)
} else {
err = app.start(ctx, cancel)
}
return err
}
func (app *App) start(ctx context.Context, cancel context.CancelFunc) error {
for {
select {
case <-ctx.Done():
return nil
case err := <-app.errs:
cancel()
return err
case msg := <-app.msgs:
if msg == nil {
continue
}
// Handle quit message
if _, ok := msg.(msgEnd); ok {
cancel()
return nil
}
app.handleMsg(ctx, msg)
}
}
}
func (app *App) startWithPollMsg(ctx context.Context, cancel context.CancelFunc) error {
for {
select {
case <-ctx.Done():
return nil
case err := <-app.errs:
cancel()
return err
case msg := <-app.msgs:
if msg == nil {
continue
}
// Handle quit message
if _, ok := msg.(msgEnd); ok {
cancel()
return nil
}
app.handleMsg(ctx, msg)
default:
err := app.pollMsg(ctx)
if err != nil {
cancel()
return err
}
}
}
}
func (app *App) pollMsg(ctx context.Context) error {
if len(app.inputs) >= cap(app.inputs) {
return nil
}
dr := app.driver.(DriverPollMsg)
msg, err := dr.PollMsg()
if err != nil {
return err
}
if msg != nil {
select {
case app.msgs <- msg:
// if there is room
return nil
default:
// otherwise
select {
case <-ctx.Done():
case app.inputs <- msg:
return nil
}
}
}
if len(app.msgs) > 0 || len(app.inputs) > 0 {
return nil
}
if app.t == nil {
app.t = time.NewTimer(2 * time.Millisecond)
} else {
app.t.Reset(2 * time.Millisecond)
}
select {
case <-ctx.Done():
case <-app.t.C:
}
return nil
}
func (app *App) startPollMsgSub(ctx context.Context) {
defer func() {
close(app.polldone)
}()
for {
select {
case <-ctx.Done():
return
case msg := <-app.inputs:
select {
case <-ctx.Done():
case app.msgs <- msg:
}
}
}
}
func (app *App) startPollMsgs(ctx context.Context) {
defer func() {
close(app.polldone)
}()
err := app.driver.PollMsgs(ctx, app.msgs)
if err != nil {
select {
case app.errs <- err:
case <-ctx.Done():
}
}
}
func (app *App) handleMsg(ctx context.Context, msg Msg) {
// Process batched effects
if batchedEffects, ok := msg.(msgBatch); ok {
for _, eff := range batchedEffects {
if eff != nil {
select {
case app.effects <- eff:
case <-ctx.Done():
break
}
}
}
return
}
// force redraw on screen message
_, exposed := msg.(MsgScreen)
eff := app.model.Update(msg)
if eff != nil {
select {
case app.effects <- eff: // process effect (if any)
case <-ctx.Done():
return
}
}
gd := app.model.Draw()
frame := app.computeFrame(gd, exposed)
if len(frame.Cells) > 0 {
app.flush(frame)
}
}
func (app *App) flush(frame Frame) {
app.driver.Flush(frame)
if app.enc != nil {
err := app.enc.encode(frame)
if err != nil && app.logger != nil {
app.logger.Printf("frame encoding: %v", err)
}
}
}
func (app *App) processEffects(ctx context.Context) {
for {
select {
case eff := <-app.effects:
switch eff := eff.(type) {
case Cmd:
go func(ctx context.Context, cmd Cmd) {
select {
case app.msgs <- cmd():
case <-ctx.Done():
}
}(ctx, eff)
case Sub:
go eff(ctx, app.msgs)
}
case <-ctx.Done():
return
}
}
}