package debugger
import (
"fmt"
"log"
"regexp"
"slices"
"strings"
"time"
"github.com/gdamore/tcell/v2"
"github.com/pancsta/cview"
"github.com/pancsta/cview/cbind"
"github.com/pancsta/asyncmachine-go/tools/debugger/states"
amhelp "github.com/pancsta/asyncmachine-go/pkg/helpers"
am "github.com/pancsta/asyncmachine-go/pkg/machine"
)
var re = regexp .MustCompile (`\[(.*?)\]` )
func normalizeText(text string ) string {
return strings .ToLower (re .ReplaceAllString (text , "" ))
}
func (d *Debugger ) hBindKeyboard () {
inputHandler := d .hInitFocusManager ()
for key , fn := range d .getKeystrokes () {
err := inputHandler .Set (key , fn )
if err != nil {
log .Printf ("Error: binding keys %s" , err )
}
}
d .hSearchSchemaClients (inputHandler )
d .App .SetDrawOnKey (false )
d .App .SetInputCapture (func (ev *tcell .EventKey ) *tcell .EventKey {
var out *tcell .EventKey
isFilter := d .App .GetFocus () == d .treeFilterOut
if isFilter && ev .Key () != tcell .KeyTab &&
ev .Key () != tcell .KeyBacktab && ev .Key () != tcell .KeyCtrlQ {
out = ev
} else {
out = inputHandler .Capture (ev )
}
if out == nil {
if ev .Key () == tcell .KeyCtrlQ {
return nil
}
d .hDraw ()
return nil
}
if out .Key () == tcell .KeyCtrlC {
return out
}
oldFocus := d .App .GetFocus ()
if oldFocus == nil {
return out
}
handler := oldFocus .InputHandler ()
if handler == nil {
return out
}
handler (out , d .App .SetFocus )
d .hDraw (oldFocus , d .App .GetFocus ())
return nil
})
}
func (d *Debugger ) hInitFocusManager () *cbind .Configuration {
inputHandler := cbind .NewConfiguration ()
d .App .SetAfterFocusFunc (func (p cview .Primitive ) {
if !d .Mach .WillBe1 (ss .AfterFocus , am .PositionLast ) {
d .Mach .Add1 (ss .AfterFocus , Pass (&A {
FocusPrimitive : p ,
MouseFocus : d .mouseFocusChanged ,
}))
}
d .mouseFocusChanged = false
})
d .App .SetMouseCapture (func (
event *tcell .EventMouse , action cview .MouseAction ,
) (*tcell .EventMouse , cview .MouseAction ) {
if event .Buttons () == tcell .ButtonPrimary {
d .mouseFocusChanged = true
}
return event , action
})
focusChange := func (state string ) func (ev *tcell .EventKey ) *tcell .EventKey {
return func (ev *tcell .EventKey ) *tcell .EventKey {
defer d .Mach .PanicToErr (nil )
if d .Mach .Any1 (states .DebuggerGroups .Dialog ...) {
return ev
}
d .Mach .Add1 (state , nil )
return nil
}
}
err := inputHandler .Set ("Backtab" , focusChange (ss .FocusPrev ))
if err != nil {
log .Printf ("Error: binding keys %s" , err )
}
err = inputHandler .Set ("Tab" , focusChange (ss .FocusNext ))
if err != nil {
log .Printf ("Error: binding keys %s" , err )
}
return inputHandler
}
func (d *Debugger ) hSearchSchemaClients (inputHandler *cbind .Configuration ) {
var (
bufferStart time .Time
buffer string
keys = []string {"-" , "_" }
)
for i := 0 ; i < 26 ; i ++ {
keys = append (keys ,
fmt .Sprintf ("%c" , 'a' +i ))
}
for _ , key := range keys {
key := key
err := inputHandler .Set (key , func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Not (am .S {ss .ClientListFocused , ss .TreeFocused }) {
return ev
}
if bufferStart .Add (searchAsTypeWindow ).After (time .Now ()) {
buffer += key
} else {
bufferStart = time .Now ()
buffer = key
}
if d .Mach .Is1 (ss .ClientListFocused ) {
currIdx := d .clientList .GetCurrentItemIndex ()
for i , item := range d .clientList .GetItems () {
if i +1 <= currIdx {
continue
}
text := normalizeText (item .GetMainText ())
if strings .HasPrefix (text , buffer ) {
d .clientList .SetCurrentItem (i )
d .hUpdateClientList ()
d .hDraw (d .clientList )
break
}
}
} else if d .Mach .Is1 (ss .TreeFocused ) {
currNodePassed := false
currNode := d .tree .GetCurrentNode ()
var nodeMatch *cview .TreeNode
d .treeRoot .Walk (
func (node , parent *cview .TreeNode , depth int ) bool {
if nodeMatch != nil {
return false
}
if !currNodePassed && node != currNode {
return true
} else if !currNodePassed {
currNodePassed = true
}
text := normalizeText (node .GetText ())
p := parent
for p != nil {
if !p .IsExpanded () {
return true
}
p = p .GetParent ()
}
if strings .HasPrefix (text , buffer ) {
nodeMatch = node
return false
}
return true
},
)
if nodeMatch != nil {
ref , ok := nodeMatch .GetReference ().(*nodeRef )
if ok && ref != nil && ref .stateName != "" {
d .Mach .Add1 (ss .StateNameSelected , Pass (&A {
State : ref .stateName ,
}))
} else {
d .Mach .Remove1 (ss .StateNameSelected , nil )
}
d .hUpdateSchemaTree ()
d .hUpdateLogReader (nil )
d .hDraw ()
d .tree .SetCurrentNode (nodeMatch )
}
}
return nil
})
if err != nil {
log .Printf ("Error: binding keys %s" , err )
}
}
}
type tcellKeyFn = func (ev *tcell .EventKey ) *tcell .EventKey
func (d *Debugger ) getKeystrokes () map [string ]tcellKeyFn {
keys := tcell .KeyNames
return map [string ]func (ev *tcell .EventKey ) *tcell .EventKey {
"space" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Is1 (ss .Paused ) {
d .Mach .Add1 (ss .Playing , nil )
} else {
d .Mach .Add1 (ss .Paused , nil )
}
return nil
},
"left" : d .hPrevTxKey (),
"right" : d .hNextTxKey (),
"alt+h" : d .hJumpBackKey ,
"alt+l" : d .hJumpFwdKey ,
"alt+Left" : d .hJumpBackKey ,
"alt+Right" : d .hJumpFwdKey ,
"alt+i" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Is1 (ss .ClientSelected ) &&
d .Mach .Not (am .S {ss .ClientListFocused , ss .TreeFocused }) {
d .Mach .Add1 (ss .ToggleMark , nil )
return nil
}
return ev
},
"alt+j" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .Mach .Add1 (ss .UserBackMarker , nil )
return nil
},
"alt+k" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .Mach .Add1 (ss .UserFwdMarker , nil )
return nil
},
"alt+n" : func (ev *tcell .EventKey ) *tcell .EventKey {
return tcell .NewEventKey (tcell .KeyPgDn , ' ' , tcell .ModNone )
},
"alt+p" : func (ev *tcell .EventKey ) *tcell .EventKey {
return tcell .NewEventKey (tcell .KeyPgUp , ' ' , tcell .ModNone )
},
"alt+e" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .hToolExpand ()
return nil
},
"alt+o" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .Mach .Toggle1 (ss .LogReaderEnabled , nil )
return nil
},
"alt+v" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .Mach .Toggle1 (ss .TailMode , nil )
return nil
},
"alt+m" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .hToolMatrix ()
return nil
},
"alt+r" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .Mach .Add1 (ss .ToolRain , nil )
return nil
},
"home" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .hToolFirstTx (nil )
return nil
},
"end" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .hToolLastTx (nil )
return nil
},
"ctrl+q" : func (ev *tcell .EventKey ) *tcell .EventKey {
d .App .Stop ()
return nil
},
"?" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Not1 (ss .HelpDialog ) {
d .preModalFocus = d .Focused
d .Mach .Add1 (ss .HelpDialog , nil )
} else {
d .Mach .Remove (states .DebuggerGroups .Dialog , nil )
}
return ev
},
"alt+f" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Not1 (ss .Toolbar1Focused ) {
d .App .SetFocus (d .toolbars [0 ])
} else {
d .App .SetFocus (d .clientList )
}
d .hDraw ()
return ev
},
"alt+s" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Not1 (ss .ExportDialog ) {
d .Mach .Add1 (ss .ExportDialog , nil )
} else {
d .Mach .Remove (states .DebuggerGroups .Dialog , nil )
}
return ev
},
"esc" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Is1 (ss .Overlay ) {
d .Mach .Remove1 (ss .Overlay , nil )
return nil
} else if d .Mach .Any1 (states .DebuggerGroups .Dialog ...) {
d .Mach .Remove (states .DebuggerGroups .Dialog , nil )
return nil
}
d .hFocusDefault ()
return ev
},
keys [tcell .KeyBackspace ]: func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Not1 (ss .ClientListFocused ) {
return ev
}
d .hDeleteClient ()
return nil
},
"alt+d" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Not1 (ss .ClientListFocused ) {
return ev
}
d .hDeleteClient ()
return nil
},
"down" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Is (S {ss .ClientListFocused , ss .ClientListVisible }) {
d .updateClientList ()
} else if d .Mach .Is1 (ss .LogFocused ) {
d .Mach .Add1 (ss .LogUserScrolled , nil )
}
return ev
},
"up" : func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Is (S {ss .ClientListFocused , ss .ClientListVisible }) {
d .updateClientList ()
} else if d .Mach .Is1 (ss .LogFocused ) {
d .Mach .Add1 (ss .LogUserScrolled , nil )
}
return ev
},
}
}
func (d *Debugger ) hDeleteClient () {
sel := d .clientList .GetCurrentItem ()
if sel == nil || d .Mach .Not1 (ss .ClientListFocused ) {
return
}
ref := sel .GetReference ().(*clientListRef )
d .Mach .Add1 (ss .RemoveClient , Pass (&A {
ClientId : ref .name ,
}))
}
func (d *Debugger ) hFocusDefault () {
tick := false
if d .Mach .Is1 (ss .ClientListVisible ) {
if d .Mach .Not1 (ss .ClientListFocused ) {
d .Mach .Add1 (ss .ClientListFocused , nil )
tick = true
}
} else if d .Mach .Not1 (ss .TimelineTxHidden ) {
if d .Mach .Not1 (ss .TimelineTxsFocused ) {
d .Mach .Add1 (ss .TimelineTxsFocused , nil )
tick = true
}
} else if d .Mach .Not1 (ss .AddressFocused ) {
d .Mach .Add1 (ss .AddressFocused , nil )
tick = true
}
if tick {
d .Mach .Add1 (ss .UpdateFocus , nil )
}
}
var keyNavigable = am .S {
ss .AddressFocused , ss .Toolbar1Focused , ss .Toolbar2Focused , ss .Toolbar3Focused ,
ss .Toolbar4Focused ,
}
func (d *Debugger ) hNextTxKey () tcellKeyFn {
return func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Is1 (ss .LogFocused ) {
d .Mach .Add1 (ss .LogUserScrolled , nil )
return ev
} else if d .Mach .Any1 (keyNavigable ...) {
return ev
}
if d .Mach .Not1 (ss .ClientSelected ) {
return nil
}
if d .hThrottleArrow (ev ) {
return nil
}
if d .hShouldScrollCurrView () {
return ev
}
state := ss .UserFwd
if d .Mach .Is1 (ss .TimelineMarkersFocused ) {
state = ss .UserFwdMarker
}
if !d .Mach .IsQueuedAbove (scrollTxThrottle , am .MutationAdd , S {state }, false ,
false , 0 ) {
d .Mach .Add1 (state , nil )
}
return nil
}
}
func (d *Debugger ) hPrevTxKey () tcellKeyFn {
return func (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Is1 (ss .LogFocused ) {
d .Mach .Add1 (ss .LogUserScrolled , nil )
return ev
} else if d .Mach .Any1 (keyNavigable ...) {
return ev
}
if d .Mach .Not1 (ss .ClientSelected ) {
return nil
}
if d .hThrottleArrow (ev ) {
return nil
}
if d .hShouldScrollCurrView () {
return ev
}
state := ss .UserBack
if d .Mach .Is1 (ss .TimelineMarkersFocused ) {
state = ss .UserBackMarker
}
if !d .Mach .IsQueuedAbove (scrollTxThrottle , am .MutationAdd , S {state }, false ,
false , 0 ) {
d .Mach .Add1 (state , nil )
}
return nil
}
}
func (d *Debugger ) hJumpBackKey (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Not1 (ss .ClientSelected ) {
return nil
}
if ev != nil && d .hThrottleKey (ev , arrowThrottleMs ) {
return nil
}
ctx := d .Mach .Context ()
d .Mach .Remove (am .S {ss .Playing , ss .TailMode }, nil )
if d .Mach .Is1 (ss .StateNameSelected ) {
state := ss .ScrollToMutTx
args := Pass (&A {
State : d .C .SelectedState ,
Fwd : false ,
})
d .Mach .Go (ctx , func () {
amhelp .Add1Sync (ctx , d .Mach , state , args )
d .Mach .Eval ("hJumpBackKey" , func () {
d .hUpdateClientList ()
}, nil )
})
} else {
target := d .hFastJumpCursor1 (true )
if target == d .C .CursorTx1 {
return nil
}
amount := d .C .CursorTx1 - target
d .Mach .Go (ctx , func () {
amhelp .Add1Sync (ctx , d .Mach , ss .Back , Pass (&A {
Amount : amount ,
}))
})
}
return nil
}
func (d *Debugger ) hJumpFwdKey (ev *tcell .EventKey ) *tcell .EventKey {
if d .Mach .Not1 (ss .ClientSelected ) {
return nil
}
if ev != nil && d .hThrottleKey (ev , arrowThrottleMs ) {
return nil
}
ctx := d .Mach .Context ()
d .Mach .Remove (am .S {ss .Playing , ss .TailMode }, nil )
if d .Mach .Is1 (ss .StateNameSelected ) {
state := ss .ScrollToMutTx
args := Pass (&A {
State : d .C .SelectedState ,
Fwd : true ,
})
d .Mach .Go (ctx , func () {
amhelp .Add1Sync (ctx , d .Mach , state , args )
d .Mach .Eval ("hJumpFwdKey" , func () {
d .hUpdateClientList ()
}, nil )
})
} else {
target := d .hFastJumpCursor1 (false )
if target == d .C .CursorTx1 {
return nil
}
amount := target - d .C .CursorTx1
d .Mach .Go (ctx , func () {
amhelp .Add1Sync (ctx , d .Mach , ss .Fwd , Pass (&A {
Amount : amount ,
}))
})
}
return nil
}
func (d *Debugger ) hToolMatrix () {
is1 := d .Mach .Is1
not1 := d .Mach .Not1
switch {
case is1 (ss .TreeLogView ):
d .Mach .Add1 (ss .TreeMatrixView , nil )
case is1 (ss .TreeMatrixView ):
if not1 (ss .MatrixRain ) {
d .Mach .Add1 (ss .MatrixRain , nil )
} else {
d .Mach .Remove1 (ss .MatrixRain , nil )
d .Mach .Add1 (ss .MatrixView , nil )
}
case is1 (ss .MatrixView ):
if not1 (ss .MatrixRain ) {
d .Mach .Add1 (ss .MatrixRain , nil )
} else {
d .Mach .Add1 (ss .TreeLogView , nil )
}
}
}
func (d *Debugger ) hToolLastTx (e *am .Event ) {
if d .Mach .Not1 (ss .ClientSelected ) {
return
}
d .hSetCursor1 (e , &A {
Cursor1 : len (d .C .MsgTxs ),
FilterBack : true ,
})
d .Mach .EvRemove (e , am .S {ss .TailMode , ss .Playing }, nil )
d .hUpdateClientList ()
d .hRedrawFull (true )
}
func (d *Debugger ) hToolFirstTx (e *am .Event ) {
if d .Mach .Not1 (ss .ClientSelected ) {
return
}
d .hSetCursor1 (e , &A {Cursor1 : 0 })
d .Mach .EvRemove (e , am .S {ss .TailMode , ss .Playing }, nil )
d .hUpdateClientList ()
d .hRedrawFull (true )
}
func (d *Debugger ) hToolExpand () {
if d .Mach .Is1 (ss .LogReaderFocused ) {
root := d .logReader .GetRoot ()
children := root .GetChildren ()
expanded := false
for _ , child := range children {
if child .IsExpanded () {
expanded = true
break
}
child .Collapse ()
}
d .C .ReaderCollapsed = expanded
return
}
expanded := false
children := d .tree .GetRoot ().GetChildren ()
for _ , child := range children {
if child .IsExpanded () {
expanded = true
break
}
child .Collapse ()
}
for _ , child := range children {
if expanded {
child .Collapse ()
child .GetReference ().(*nodeRef ).expanded = false
} else {
child .Expand ()
child .GetReference ().(*nodeRef ).expanded = true
}
}
}
func (d *Debugger ) hShouldScrollCurrView () bool {
return d .Mach .Any1 (ss .MatrixFocused , ss .LogFocused )
}
func (d *Debugger ) hThrottleKey (ev *tcell .EventKey , ms int ) bool {
sameKey := d .lastKeystroke == ev .Key ()
elapsed := time .Since (d .lastKeystrokeTime )
if sameKey && elapsed < time .Duration (ms )*time .Millisecond {
return true
}
d .lastKeystroke = ev .Key ()
d .lastKeystrokeTime = time .Now ()
return false
}
func (d *Debugger ) hThrottleArrow (ev *tcell .EventKey ) bool {
now := time .Now ()
sameKey := d .lastKeystroke == ev .Key () &&
now .Sub (d .lastKeystrokeTime ) <= arrowHoldWindowMs *time .Millisecond
if !sameKey {
d .lastKeystroke = ev .Key ()
d .lastKeystrokeTime = now
return false
}
if now .Sub (d .lastKeystrokeTime ) < arrowRepeatMs *time .Millisecond {
return true
}
d .lastKeystrokeTime = now
return false
}
var _ = ss .FocusNext
func (d *Debugger ) FocusNextState (e *am .Event ) {
idx := slices .Index (d .focusablePrims , d .Focused )
idx ++
if idx >= len (d .focusablePrims ) {
idx = 0
}
prim := d .focusablePrims [idx ]
_ , state := d .hBoxFromPrimitive (prim )
d .Mach .EvAdd1 (e , state , nil )
d .App .SetFocus (prim )
}
var _ = ss .FocusPrev
func (d *Debugger ) FocusPrevState (e *am .Event ) {
idx := slices .Index (d .focusablePrims , d .Focused )
idx --
if idx < 0 {
idx = len (d .focusablePrims ) - 1
}
prim := d .focusablePrims [idx ]
_ , state := d .hBoxFromPrimitive (prim )
d .Mach .EvAdd1 (e , state , nil )
d .App .SetFocus (prim )
}
func (d *Debugger ) hUpdateFocusableOrder () {
var (
boxes []*cview .Box
prims []cview .Primitive
)
add := func (prim cview .Primitive , box *cview .Box ) {
prims = append (prims , prim )
boxes = append (boxes , box )
}
if d .Mach .Is1 (ss .ExportDialog ) {
add (d .exportDialog , d .exportDialog .Box )
d .focusable , d .focusablePrims = boxes , prims
return
} else if d .Mach .Is1 (ss .HelpDialog ) {
add (d .helpDialogLeft , d .helpDialogLeft .Box )
add (d .helpDialogRight , d .helpDialogRight .Box )
d .focusable , d .focusablePrims = boxes , prims
return
}
add (d .addressBar , d .addressBar .Box )
if d .Mach .Not1 (ss .NarrowLayout ) && d .Mach .Is1 (ss .ClientListVisible ) {
add (d .clientList , d .clientList .Box )
}
switch d .Mach .Switch (states .DebuggerGroups .Views ) {
case ss .MatrixView :
add (d .matrix , d .matrix .Box )
case ss .TreeMatrixView :
add (d .treeGroups , d .treeGroups .Box )
add (d .treeFilterOut , d .treeFilterOut .Box )
add (d .tree , d .tree .Box )
add (d .matrix , d .matrix .Box )
default :
add (d .treeGroups , d .treeGroups .Box )
add (d .treeFilterOut , d .treeFilterOut .Box )
add (d .tree , d .tree .Box )
if d .params .Filters .LogLevel != am .LogNothing {
add (d .log , d .log .Box )
}
if d .Mach .Is1 (ss .LogReaderVisible ) {
add (d .logReader , d .logReader .Box )
}
}
if d .Mach .Not1 (ss .TimelineTxHidden ) {
add (d .timelineTxs , d .timelineTxs .Box )
}
if d .Mach .Not1 (ss .TimelineMarkersHidden ) {
add (d .timelineMarkers , d .timelineMarkers .Box )
}
for i := range d .toolbars {
add (d .toolbars [i ], d .toolbars [i ].Box )
}
d .focusable = boxes
d .focusablePrims = prims
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .