forked from kungfusheep/glyph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
1171 lines (1020 loc) · 31.6 KB
/
app.go
File metadata and controls
1171 lines (1020 loc) · 31.6 KB
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package glyph
import (
"fmt"
"os"
"sync"
"sync/atomic"
"time"
"github.com/kungfusheep/riffkey"
)
// Debug timing
var (
DebugTiming bool
DebugFullRedraw bool // force full redraws instead of diff-based (set TUI_FULL_REDRAW=1 to enable)
DebugFlush bool // dump flush debug info (set TUI_DEBUG_FLUSH=1 to enable)
lastBuildTime time.Duration
lastLayoutTime time.Duration
lastRenderTime time.Duration
lastFlushTime time.Duration
// fine-grained post-processing phase timings (only populated when DebugTiming=true)
lastEffectTime time.Duration // resolveColor16 + all Effect passes
lastDiffTime time.Duration // Flush(): diff + escape-sequence building
lastWriteTime time.Duration // FlushBuffer(): Write() syscall to terminal
)
func init() {
if os.Getenv("TUI_FULL_REDRAW") != "" {
DebugFullRedraw = true
}
if os.Getenv("TUI_DEBUG_FLUSH") != "" {
DebugFlush = true
}
}
// App is a TUI application with integrated input handling via riffkey.
type App struct {
screen *Screen
// riffkey integration
router *riffkey.Router
input *riffkey.Input
reader *riffkey.Reader
// Template + BufferPool (for SetView single-view mode)
template *Template
pool *BufferPool
// Multi-view routing
viewTemplates map[string]*Template
viewRouters map[string]*riffkey.Router
currentView string
viewStack []string // pushed views (for modal overlays)
// State
running bool
renderMu sync.Mutex
renderChan chan struct{}
frameFlushed atomic.Bool // set when input renders directly, cleared by debounce timer
forceFullFlush bool // set by Go() to force full redraw on next frame
// Cursor state
cursorX, cursorY int
cursorVisible bool
cursorShape CursorShape
cursorColor Color
cursorColorSet bool
// default style for all cells (set via SetDefaultStyle)
defaultStyle Style
// Resize callback
onResize func(width, height int)
// Before-render callback (for syncing state before layout)
onBeforeRender func()
// After-render callback (for cursor updates after layout is known)
onAfterRender func()
// Active layer for cursor (set during template render)
activeLayer *Layer
// Inline mode
inline bool
clearOnExit bool
linesUsed int
viewHeight int16 // Height of the view for inline mode
nonInteractive bool // True when running via RunNonInteractive
// Jump labels
jumpMode *JumpMode
jumpStyle JumpStyle
// Post-processing pipeline
postProcess []Effect
frameCount uint64
startTime time.Time
lastFrameTime time.Time
defaultFG Color // terminal's default FG (detected via OSC 10)
defaultBG Color // terminal's default BG (detected via OSC 11)
// SetView limit (for catching anti-patterns)
setViewCount int
setViewLimit int // 0 = unlimited
}
// NewApp creates a new TUI application (fullscreen, alternate buffer).
func NewApp() *App {
screen := NewScreen(nil)
router := riffkey.NewRouter()
input := riffkey.NewInput(router)
reader := riffkey.NewReader(os.Stdin).SetUTF8(true)
app := &App{
screen: screen,
router: router,
input: input,
reader: reader,
renderChan: make(chan struct{}, 1),
jumpMode: &JumpMode{},
jumpStyle: DefaultJumpStyle,
}
return app
}
// NewInlineApp creates a new inline TUI application.
// Inline apps render at the current cursor position without taking over the screen.
// Use this for progress bars, selection menus, spinners, etc.
func NewInlineApp() *App {
app := NewApp()
app.inline = true
return app
}
// Ref provides access to the component for external references.
func (a *App) Ref(f func(*App)) *App { f(a); return a }
// ClearOnExit sets whether the inline app should clear its content on exit.
// If true, the rendered content disappears when the app stops.
// If false (default), the content remains visible and cursor moves below it.
func (a *App) ClearOnExit(clear bool) *App {
a.clearOnExit = clear
return a
}
// IsInline returns true if this is an inline app.
func (a *App) IsInline() bool {
return a.inline
}
// Height sets the height for inline apps.
// This determines how many lines the inline view will use.
// If not set, defaults to 1.
func (a *App) Height(h int16) *App {
a.viewHeight = h
return a
}
// RunNonInteractive runs an inline app without an input loop.
// Use this for progress bars, spinners, etc. that don't need keyboard input.
// Call Stop() when done to clean up and exit.
func (a *App) RunNonInteractive() error {
if !a.inline {
return fmt.Errorf("RunNonInteractive only works with inline apps")
}
a.running = true
a.nonInteractive = true
// Clean up buffer pool on exit
if a.pool != nil {
defer a.pool.Stop()
}
// Enter inline mode (raw mode without alternate buffer)
if err := a.screen.EnterInlineMode(); err != nil {
return err
}
// Initial render
a.render()
// frame debounce: render at most once per 16ms (~60fps)
frameTimer := time.NewTimer(0)
if !frameTimer.Stop() {
<-frameTimer.C
}
framePending := false
for a.running {
select {
case <-a.renderChan:
if !framePending {
framePending = true
frameTimer.Reset(16 * time.Millisecond)
}
case <-frameTimer.C:
framePending = false
// drain any render request that arrived during the frame window
select {
case <-a.renderChan:
default:
}
a.render()
case <-time.After(50 * time.Millisecond):
// check running flag periodically
}
}
// Clean up
a.screen.ExitInlineMode(a.linesUsed, a.clearOnExit)
return nil
}
// SetViewLimit sets the maximum number of times SetView can be called.
// Panics if exceeded. Use this to catch anti-patterns where SetView is called
// repeatedly instead of using reactive updates via pointers.
//
// Example:
//
// app.SetViewLimit(1) // Panic if SetView called more than once
// app.SetView(myView) // OK
// app.SetView(other) // PANIC: SetView called 2 times, limit is 1
//
// Set to 0 (default) for unlimited calls.
func (a *App) SetViewLimit(n int) *App {
a.setViewLimit = n
return a
}
// SetView sets a declarative view for fast rendering.
// Pointers in the view are captured at compile time - just mutate your state.
//
// Example:
//
// state := &MyState{Title: "Hello", Progress: 50}
// app.SetView(
// Col{Children: []any{
// Text{Content: &state.Title},
// Progress{Value: &state.Progress},
// }},
// )
func (a *App) SetView(view any) *App {
a.setViewCount++
if a.setViewLimit > 0 && a.setViewCount > a.setViewLimit {
panic(fmt.Sprintf("SetView called %d times, limit is %d. Use reactive updates via pointers instead of calling SetView repeatedly.", a.setViewCount, a.setViewLimit))
}
a.template = Build(view)
a.template.SetApp(a) // Link for jump mode support
a.template.requestRender = a.RequestRender
a.wireBindings(a.template, a.router)
// Create buffer pool for async clearing (or reuse existing)
size := a.screen.Size()
if a.pool == nil {
a.pool = NewBufferPool(size.Width, size.Height)
} else if a.pool.Width() != size.Width || a.pool.Height() != size.Height {
a.pool.Resize(size.Width, size.Height)
}
if a.defaultStyle.FG.Mode != ColorDefault || a.defaultStyle.BG.Mode != ColorDefault {
for _, buf := range a.pool.buffers {
buf.defaultStyle = a.defaultStyle
buf.Clear()
}
}
return a
}
// wireBindings registers all declarative component bindings on the given router.
func (a *App) wireBindings(tmpl *Template, router *riffkey.Router) {
for _, b := range tmpl.pendingBindings {
switch h := b.handler.(type) {
case func(riffkey.Match):
pattern := b.pattern
router.Handle(pattern, func(m riffkey.Match) { h(m); a.RequestRender() })
case func(any):
pattern := b.pattern
router.Handle(pattern, func(_ riffkey.Match) { h(nil); a.RequestRender() })
case func():
pattern := b.pattern
router.Handle(pattern, func(_ riffkey.Match) { h(); a.RequestRender() })
}
}
// focus manager takes precedence over single pendingTIB
if fm := tmpl.pendingFocusManager; fm != nil {
// wire focus manager bindings (Tab/Shift-Tab) on the base router
for _, b := range fm.bindings() {
if h, ok := b.handler.(func(riffkey.Match)); ok {
pattern := b.pattern
router.Handle(pattern, func(m riffkey.Match) { h(m); a.RequestRender() })
}
}
// build a sub-router per focusable item.
// each gets pushed on focus and popped on blur.
fm.push = func(r *riffkey.Router) { a.Push(r) }
fm.pop = func() { a.Pop() }
fm.routers = make([]*riffkey.Router, len(fm.items))
for i, item := range fm.items {
sub := riffkey.NewRouter()
// common: Tab/Shift-Tab to cycle, Escape to blur
sub.Handle(fm.nextKey, func(_ riffkey.Match) { fm.Next(); a.RequestRender() })
if fm.prevKey != "" {
sub.Handle(fm.prevKey, func(_ riffkey.Match) { fm.Prev(); a.RequestRender() })
}
sub.Handle("<Escape>", func(_ riffkey.Match) { fm.BlurCurrent(); a.RequestRender() })
// sub-bindings (e.g., Enter for form submit)
for _, sb := range fm.subBindings {
switch h := sb.handler.(type) {
case func():
pattern := sb.pattern
sub.Handle(pattern, func(_ riffkey.Match) { h(); a.RequestRender() })
case func(riffkey.Match):
pattern := sb.pattern
sub.Handle(pattern, func(m riffkey.Match) { h(m); a.RequestRender() })
}
}
// per-item bindings (e.g., j/k for Radio, Space for Checkbox)
for _, cb := range item.bindings {
switch h := cb.handler.(type) {
case func():
pattern := cb.pattern
sub.Handle(pattern, func(_ riffkey.Match) { h(); a.RequestRender() })
case func(riffkey.Match):
pattern := cb.pattern
sub.Handle(pattern, func(m riffkey.Match) { h(m); a.RequestRender() })
}
}
if item.tib != nil {
// text input: route unmatched keys to TextHandler
th := fm.handlers[i]
sub.HandleUnmatched(th.HandleKey)
sub.NoCounts()
}
fm.routers[i] = sub
}
fm.initialPush()
} else if tmpl.pendingTIB != nil {
th := riffkey.NewTextHandler(tmpl.pendingTIB.value, tmpl.pendingTIB.cursor)
th.OnChange = tmpl.pendingTIB.onChange
router.HandleUnmatched(th.HandleKey)
router.NoCounts()
}
// wire Log invalidation
for _, lv := range tmpl.pendingLogs {
lv.onUpdate = a.RequestRender
}
}
// ViewBuilder allows chaining Handle() calls after View().
type ViewBuilder struct {
app *App
name string
router *riffkey.Router
}
// View registers a named view for multi-view routing.
// Returns a builder for chaining Handle() calls.
//
// Example:
//
// app.View("home", homeView).
// Handle("j", moveDown).
// Handle("s", func(_ riffkey.Match) { app.Go("settings") })
func (a *App) View(name string, view any) *ViewBuilder {
// Initialize maps if needed
if a.viewTemplates == nil {
a.viewTemplates = make(map[string]*Template)
}
if a.viewRouters == nil {
a.viewRouters = make(map[string]*riffkey.Router)
}
// Create buffer pool if not exists (shared across all views)
if a.pool == nil {
size := a.screen.Size()
a.pool = NewBufferPool(size.Width, size.Height)
if a.defaultStyle.FG.Mode != ColorDefault || a.defaultStyle.BG.Mode != ColorDefault {
for _, buf := range a.pool.buffers {
buf.defaultStyle = a.defaultStyle
}
}
}
// Compile template and create router for this view
tmpl := Build(view)
tmpl.SetApp(a) // Link for jump mode support
router := riffkey.NewRouter()
a.wireBindings(tmpl, router)
a.viewTemplates[name] = tmpl
a.viewRouters[name] = router
return &ViewBuilder{
app: a,
name: name,
router: router,
}
}
// Ref provides access to the component for external references.
func (vb *ViewBuilder) Ref(f func(*ViewBuilder)) *ViewBuilder { f(vb); return vb }
// NoCounts disables vim-style count prefixes (e.g., 5j) for this view.
// Use this when the view has text input so digits can be typed.
func (vb *ViewBuilder) NoCounts() *ViewBuilder {
vb.router.NoCounts()
return vb
}
// Handle registers a key handler for this view.
// Accepts func(riffkey.Match), func(any), or func() for convenience.
// Automatically requests a re-render after the handler runs.
func (vb *ViewBuilder) Handle(pattern string, handler any) *ViewBuilder {
switch h := handler.(type) {
case func(riffkey.Match):
vb.router.Handle(pattern, func(m riffkey.Match) { h(m); vb.app.RequestRender() })
case func(any):
vb.router.Handle(pattern, func(_ riffkey.Match) { h(nil); vb.app.RequestRender() })
case func():
vb.router.Handle(pattern, func(_ riffkey.Match) { h(); vb.app.RequestRender() })
}
return vb
}
// UpdateView recompiles a view with a new view definition.
// Use this when the view's structure changes and needs re-compilation.
func (a *App) UpdateView(name string, view any) {
if a.viewTemplates == nil {
return
}
tmpl := Build(view)
tmpl.SetApp(a) // Link for jump mode support
if router, ok := a.viewRouters[name]; ok {
a.wireBindings(tmpl, router)
}
a.viewTemplates[name] = tmpl
}
// Go switches to a different view.
// Swaps the template and input handlers.
func (a *App) Go(name string) {
if _, ok := a.viewTemplates[name]; !ok {
return // View doesn't exist
}
a.currentView = name
a.input.SetRouter(a.viewRouters[name])
// diff flush handles view switches correctly — every changed cell gets
// emitted. FlushFull issues \x1b[2J (clear) which can produce a visible
// microflash on some terminals (Ghostty) during a sync-wrapped update.
// a.forceFullFlush = true
a.RequestRender()
}
// Back returns to the previous view.
// Currently an alias for Pop().
func (a *App) Back() {
a.input.Pop()
a.RequestRender()
}
// PushView pushes a view as a modal overlay.
// The modal's handlers take precedence until PopView() is called.
// The pushed view becomes the active rendered view until popped.
func (a *App) PushView(name string) {
if router, ok := a.viewRouters[name]; ok {
a.viewStack = append(a.viewStack, name)
a.input.Push(router)
a.RequestRender()
}
}
// PopView removes the top modal overlay.
// Returns to the previous view in the stack.
func (a *App) PopView() {
if len(a.viewStack) > 0 {
a.viewStack = a.viewStack[:len(a.viewStack)-1]
}
a.input.Pop()
a.RequestRender()
}
// ViewRouter returns the router for a named view, if it exists.
// Useful for advanced configuration like HandleUnmatched.
func (a *App) ViewRouter(name string) (*riffkey.Router, bool) {
if a.viewRouters == nil {
return nil, false
}
router, ok := a.viewRouters[name]
return router, ok
}
// Screen returns the screen.
func (a *App) Screen() *Screen {
return a.screen
}
// Router returns the riffkey router for advanced configuration.
func (a *App) Router() *riffkey.Router {
return a.router
}
// Input returns the riffkey input for modal handling (push/pop).
func (a *App) Input() *riffkey.Input {
return a.input
}
// Handle registers a key binding with a vim-style pattern.
// Examples: "j", "gg", "<C-c>", "<C-w>j", "<Up>"
// Accepts func(riffkey.Match), func(any), or func() for convenience.
// Automatically requests a re-render after the handler runs.
func (a *App) Handle(pattern string, handler any) *App {
switch h := handler.(type) {
case func(riffkey.Match):
a.router.Handle(pattern, func(m riffkey.Match) { h(m); a.RequestRender() })
case func(any):
a.router.Handle(pattern, func(_ riffkey.Match) { h(nil); a.RequestRender() })
case func():
a.router.Handle(pattern, func(_ riffkey.Match) { h(); a.RequestRender() })
}
return a
}
// HandleNamed registers a named key binding (for rebinding support).
// Automatically requests a re-render after the handler runs.
func (a *App) HandleNamed(name, pattern string, handler func(riffkey.Match)) *App {
a.router.HandleNamed(name, pattern, func(m riffkey.Match) { handler(m); a.RequestRender() })
return a
}
// BindField routes unmatched keys to a text input field.
func (a *App) BindField(f *InputState) *App {
a.router.TextInput(&f.Value, &f.Cursor)
return a
}
// UnbindField clears the text input field binding.
func (a *App) UnbindField() *App {
a.router.HandleUnmatched(nil)
return a
}
// Push pushes a new router onto the input stack (for modal input).
func (a *App) Push(r *riffkey.Router) {
a.input.Push(r)
}
// Pop pops the current router from the input stack.
func (a *App) Pop() {
a.input.Pop()
}
// SetCursor sets the cursor position (0-indexed screen coordinates).
// The cursor will be positioned here after each render.
func (a *App) SetCursor(x, y int) {
a.cursorX = x
a.cursorY = y
}
// SetCursorStyle sets the cursor visual style.
func (a *App) SetCursorStyle(style CursorShape) {
a.cursorShape = style
}
// ShowCursor makes the cursor visible.
func (a *App) ShowCursor() {
a.cursorVisible = true
}
// HideCursor hides the cursor.
func (a *App) HideCursor() {
a.cursorVisible = false
}
// SetCursorColor sets the cursor color using OSC 12 escape sequence.
// This changes the actual cursor color in supporting terminals.
// SetDefaultStyle sets the default style for all cells. Any cell not explicitly
// styled will use this FG/BG instead of the terminal default.
func (a *App) SetDefaultStyle(s Style) {
a.defaultStyle = s
if a.pool != nil {
for _, buf := range a.pool.buffers {
buf.defaultStyle = s
}
}
}
func (a *App) SetCursorColor(c Color) {
a.cursorColor = c
a.cursorColorSet = true
}
// Cursor returns the current cursor state.
func (a *App) Cursor() Cursor {
return Cursor{
X: a.cursorX,
Y: a.cursorY,
Style: a.cursorShape,
Visible: a.cursorVisible,
}
}
// OnResize sets a callback to be called when the terminal is resized.
// The callback receives the new width and height.
// Use this to update viewport dimensions, reinitialize layers, etc.
func (a *App) OnResize(fn func(width, height int)) {
a.onResize = fn
}
// OnBeforeRender sets a callback to be called before each render.
// Use this to sync state (e.g., filter updates) before layout runs.
func (a *App) OnBeforeRender(fn func()) {
a.onBeforeRender = fn
}
// OnAfterRender sets a callback to be called after each render completes.
// Use this to update cursor position after layout is known.
func (a *App) OnAfterRender(fn func()) {
a.onAfterRender = fn
}
// AddEffect appends a post-processing pass to the pipeline.
// Passes run in order after template rendering, before screen flush.
// Closures captured by the pass act as shader uniforms — mutate them to
// change behaviour next frame.
func (a *App) AddEffect(pp Effect) *App {
a.postProcess = append(a.postProcess, pp)
return a
}
// SetEffect replaces the entire post-processing pipeline.
// Call with no arguments to clear all passes.
func (a *App) SetEffect(passes ...Effect) *App {
a.postProcess = passes
return a
}
// Template returns the current template for debugging.
// Use with Template().DebugDump("") to inspect the op tree.
func (a *App) Template() *Template {
return a.template
}
// RequestRender marks that a render is needed.
// Safe to call from any goroutine.
func (a *App) RequestRender() {
select {
case a.renderChan <- struct{}{}:
default:
// Already a render pending
}
}
// RenderNow performs a render immediately without channel coordination.
// Use this from dedicated update goroutines to avoid scheduler overhead.
// The render is mutex-protected so it's safe to call concurrently.
func (a *App) RenderNow() {
a.render()
}
// render performs the actual render if needed.
func (a *App) render() {
a.renderMu.Lock()
defer a.renderMu.Unlock()
var t0, t1 time.Time
if DebugTiming {
t0 = time.Now()
}
if a.pool == nil {
return // No pool
}
// sync state before layout (e.g., filter updates)
if a.onBeforeRender != nil {
a.onBeforeRender()
}
// clear active layer before render (will be set if a layer has visible cursor)
a.activeLayer = nil
size := a.screen.Size()
buf := a.pool.Current()
// For inline mode, use view height instead of terminal height
renderHeight := int16(size.Height)
if a.inline && a.viewHeight > 0 {
renderHeight = a.viewHeight
} else if a.inline {
// auto-size: give layout full terminal height, then trim to content
renderHeight = int16(size.Height)
}
// Priority: pushed views > current view > base template
var activeTmpl *Template
if len(a.viewStack) > 0 {
topView := a.viewStack[len(a.viewStack)-1]
if a.viewTemplates != nil {
if tmpl, ok := a.viewTemplates[topView]; ok {
activeTmpl = tmpl
}
}
}
if activeTmpl == nil {
if a.currentView != "" && a.viewTemplates != nil {
if tmpl, ok := a.viewTemplates[a.currentView]; ok {
activeTmpl = tmpl
} else {
return // View not found
}
} else if a.template != nil {
activeTmpl = a.template
} else {
return // No view set
}
}
activeTmpl.Execute(buf, int16(size.Width), renderHeight)
// for inline auto-size, use content height instead of full terminal height
if a.inline && a.viewHeight == 0 {
if h := buf.ContentHeight(); h > 0 {
renderHeight = int16(h)
}
}
// apply layer cursor if one was set during template render
if a.activeLayer != nil {
if x, y, visible := a.activeLayer.ScreenCursor(); visible {
a.cursorX = x
a.cursorY = y
a.cursorVisible = true
a.cursorShape = a.activeLayer.cursor.Style
}
}
// call after-render callback (e.g., for additional cursor customization)
if a.onAfterRender != nil {
a.onAfterRender()
}
if DebugTiming {
t1 = time.Now()
lastBuildTime = 0
lastLayoutTime = 0
lastRenderTime = t1.Sub(t0)
}
// post-processing pipeline: tree-declared ScreenEffects first, then imperative
treeEffects := activeTmpl.ScreenEffects()
a.screen.forceRGB = len(treeEffects) > 0 || len(a.postProcess) > 0
if a.screen.forceRGB {
var tEffect time.Time
if DebugTiming {
tEffect = time.Now()
}
// resolve Color16 cells to detected palette RGB before effects run
resolveColor16(buf, size.Width, int(renderHeight))
now := time.Now()
if a.startTime.IsZero() {
a.startTime = now
}
var delta time.Duration
if !a.lastFrameTime.IsZero() {
delta = now.Sub(a.lastFrameTime)
}
a.lastFrameTime = now
ppCtx := PostContext{
Width: size.Width,
Height: int(renderHeight),
Frame: a.frameCount,
Delta: delta,
Time: now.Sub(a.startTime),
DefaultFG: a.defaultFG,
DefaultBG: a.defaultBG,
}
for _, pp := range treeEffects {
pp.Apply(buf, ppCtx)
}
for _, pp := range a.postProcess {
pp.Apply(buf, ppCtx)
}
a.frameCount++
if DebugTiming {
lastEffectTime = time.Since(tEffect)
}
}
// Copy to screen's back buffer for flush
a.copyToScreen(buf)
if a.inline {
// Inline mode: render at cursor position
a.linesUsed = a.screen.FlushInline(int(renderHeight), a.linesUsed)
a.pool.Swap() // Queue async clear
} else {
// Fullscreen mode
var tDiff time.Time
if DebugTiming {
tDiff = time.Now()
}
if DebugFullRedraw || a.forceFullFlush {
a.forceFullFlush = false
a.screen.FlushFull()
} else {
a.screen.Flush() // diff + escape-sequence building
}
if DebugTiming {
lastDiffTime = time.Since(tDiff)
}
a.pool.Swap()
// Add cursor ops to same buffer - one syscall for everything
if a.cursorColorSet {
a.screen.BufferCursorColor(a.cursorColor)
}
a.screen.BufferCursor(a.cursorX, a.cursorY, a.cursorVisible, a.cursorShape)
var tWrite time.Time
if DebugTiming {
tWrite = time.Now()
}
a.screen.FlushBuffer() // single Write() syscall to terminal
if DebugTiming {
lastWriteTime = time.Since(tWrite)
}
}
if DebugTiming {
lastFlushTime = time.Since(t1)
}
}
// copyToScreen copies pool buffer to screen's back buffer.
func (a *App) copyToScreen(src *Buffer) {
dst := a.screen.Buffer()
dst.CopyFrom(src) // Fast bulk copy
}
// TimingString returns a formatted timing string.
func TimingString() string {
return fmt.Sprintf("render:%v effect:%v diff:%v write:%v",
lastRenderTime.Round(time.Microsecond),
lastEffectTime.Round(time.Microsecond),
lastDiffTime.Round(time.Microsecond),
lastWriteTime.Round(time.Microsecond))
}
// Timings holds timing data for the last frame.
type Timings struct {
BuildUs float64 // Build time in microseconds
LayoutUs float64 // Layout time in microseconds
RenderUs float64 // Render time in microseconds
FlushUs float64 // Flush time in microseconds
// fine-grained post-processing breakdown (only valid when effects are active)
EffectUs float64 // resolveColor16 + all Effect passes (pure Go)
DiffUs float64 // Flush(): diff comparison + escape-sequence building (pure Go)
WriteUs float64 // FlushBuffer(): Write() syscall — time spent waiting on terminal
}
// GetTimings returns the timing data for the last frame.
func GetTimings() Timings {
return Timings{
BuildUs: float64(lastBuildTime.Microseconds()),
LayoutUs: float64(lastLayoutTime.Microseconds()),
RenderUs: float64(lastRenderTime.Microseconds()),
FlushUs: float64(lastFlushTime.Microseconds()),
EffectUs: float64(lastEffectTime.Microseconds()),
DiffUs: float64(lastDiffTime.Microseconds()),
WriteUs: float64(lastWriteTime.Microseconds()),
}
}
// Run starts the application. Blocks until Stop is called.
// For multi-view apps, use RunFrom(startView) instead.
func (a *App) Run() error {
return a.run("")
}
// RunFrom starts the application on the specified view.
// Use this for multi-view apps.
func (a *App) RunFrom(startView string) error {
return a.run(startView)
}
func (a *App) run(startView string) error {
a.running = true
// Set up starting view if specified
if startView != "" && a.viewTemplates != nil {
a.currentView = startView
if router, ok := a.viewRouters[startView]; ok {
a.input.SetRouter(router)
}
}
// Clean up buffer pool on exit if using fast path
if a.pool != nil {
defer a.pool.Stop()
}
// Enter raw mode (inline or fullscreen)
if a.inline {
if err := a.screen.EnterInlineMode(); err != nil {
return err
}
// Use closure so linesUsed is read at defer time, not now (when it's 0)
defer func() { a.screen.ExitInlineMode(a.linesUsed, a.clearOnExit) }()
} else {
if err := a.screen.EnterRawMode(); err != nil {
return err
}
defer a.screen.ExitRawMode()
// if a default style is set, paint the terminal background immediately
// before the first frame renders (avoids flash of terminal default colours).
// OSC 11 also tells the terminal to use this as its default bg, which
// covers unfilled areas (e.g. partial bottom row below our content).
if a.defaultStyle.BG.Mode == ColorRGB {
a.screen.SetTerminalBG(a.defaultStyle.BG)
bg := a.defaultStyle.BG
fmt.Fprintf(a.screen.writer, "\x1b[48;2;%d;%d;%dm\x1b[2J\x1b[H", bg.R, bg.G, bg.B)
}
}
// Handle resize
go a.handleResize()
// Handle async render requests (from timers, data updates, etc)
go a.handleRenderRequests()
// Render first so the screen is populated before we block on the color query.
// This eliminates the blank-screen flash between alternate buffer switch and first frame.
a.render()
// Detect terminal's default colours for post-processing.
// Runs after first render so the blank gap is gone; runs before input.Run so
// there's no race on stdin.
a.defaultFG, a.defaultBG = a.screen.QueryDefaultColors()
a.RequestRender()
// Run riffkey input loop
// render immediately on input for zero-latency response;
// signal debounce timer to skip its next frame since we just rendered
err := a.input.Run(a.reader, func(handled bool) {
if a.running {
a.frameFlushed.Store(true)
// drain any pending render request so the debounce timer won't double-render
select {
case <-a.renderChan:
default:
}
a.render()
}
})
// Normal termination via Stop() causes reader to return error
if !a.running {
// Reopen stdin for inline apps so subsequent apps can use it
if a.inline {
reopenStdin()
}
return nil
}
return err
}
// handleRenderRequests processes async render requests with frame debouncing.
// Renders at most once per 16ms (~60fps), coalescing multiple requests.
func (a *App) handleRenderRequests() {
frameTimer := time.NewTimer(0)
if !frameTimer.Stop() {
<-frameTimer.C
}
framePending := false
for {
select {
case <-a.renderChan:
if !a.running {
return
}
if !framePending {
framePending = true
frameTimer.Reset(8 * time.Millisecond)
}