forked from charmbracelet/vhs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeylogger.go
More file actions
86 lines (72 loc) 路 2.09 KB
/
Copy pathkeylogger.go
File metadata and controls
86 lines (72 loc) 路 2.09 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
package main
import (
"encoding/json"
"log"
"os"
"sync/atomic"
)
// KeyEvent represents a single key press and timing information.
type KeyEvent struct {
// Ms is the number of milliseconds relative to the recording start.
Ms int64 `json:"ms"`
// Key is the string representation of the key pressed.
Key string `json:"key"`
}
// KeyLogger tracks key events during tape execution.
type KeyLogger struct {
events []KeyEvent
paused bool
frame *int64 // pointer to shared frame counter
framerate int
}
// NewKeyLogger creates a new KeyLogger.
func NewKeyLogger() *KeyLogger {
return &KeyLogger{
events: make([]KeyEvent, 0),
}
}
// Start begins key recording.
//
// The first parameter is a pointer to the shared frame counter that is being
// incremented asynchronously by VHS as captures are being made. This is used
// with the framerate parameter to compute when a key event was made.
func (l *KeyLogger) Start(frame *int64, framerate int) {
l.frame = frame
l.framerate = framerate
}
// Pause suspends key logging until Resume is called.
func (l *KeyLogger) Pause() {
l.paused = true
}
// Resume enables key logging after Pause is called.
func (l *KeyLogger) Resume() {
l.paused = false
}
// LogKey records the current key and time at which it occurred with respect
// to the current frame being captured. If key logging has not been started or
// if it has been paused, this does nothing.
func (l *KeyLogger) LogKey(key string) {
if l.frame == nil || l.paused {
return
}
frameNum := atomic.LoadInt64(l.frame)
timeMs := frameNum * 1000 / int64(l.framerate)
event := KeyEvent{
Ms: timeMs,
Key: key,
}
l.events = append(l.events, event)
}
// Save writes the recorded key events to logFile as JSON. If logFile is an
// empty string or if there are no events, this does nothing.
func (l *KeyLogger) Save(logFile string) error {
if logFile == "" || len(l.events) == 0 {
return nil
}
log.Println(GrayStyle.Render("Saving keylog to " + logFile + "..."))
data, err := json.MarshalIndent(l.events, "", " ")
if err != nil {
return err
}
return os.WriteFile(logFile, data, 0o644)
}