-
Notifications
You must be signed in to change notification settings - Fork 18
/
state.go
290 lines (244 loc) · 6.16 KB
/
state.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
package main
import (
"bytes"
"encoding/hex"
"io"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"time"
"github.com/fatih/color"
"github.com/gorilla/websocket"
"github.com/jroimartin/gocui"
)
// State is the central function managing the information of claws.
type State struct {
// important to running the application as a whole
ActionIndex int
Mode UIMode
ConnectionStarted time.Time
wsConn WebSocket
Writer io.Writer
writerLock sync.RWMutex
// important for drawing
FirstDrawDone bool
ShouldQuit bool
HideHelp bool
KeepAutoscrolling bool
// functions
ExecuteFunc func(func(*gocui.Gui) error)
Settings Settings
}
// PushAction adds an action to LastActions
func (s *State) PushAction(act string) error {
return s.Settings.PushAction(act)
}
// BrowseActions changes the ActionIndex and returns the value at the specified index.
// move is the number of elements to move (negatives go into more recent history,
// 0 returns the current element, positives go into older history)
func (s *State) BrowseActions(move int) string {
oSet := s.Settings.Clone()
nActions := len(oSet.LastActions)
s.ActionIndex += move
if s.ActionIndex >= nActions {
s.ActionIndex = nActions - 1
} else if s.ActionIndex < -1 {
s.ActionIndex = -1
}
// -1 always indicates the "next" element, thus empty
if s.ActionIndex == -1 {
return ""
}
return oSet.LastActions[s.ActionIndex]
}
// StartConnection begins a WebSocket connection to url.
func (s *State) StartConnection(url string) {
var err error
defer func() {
if err != nil {
s.PrintError(err)
}
}()
url = strings.TrimSpace(url)
if len(url) > 0 {
s.Settings.LastWebsocketURL = url
s.Settings.Update("LastWebsocketURL")
}
if len(s.Settings.LastWebsocketURL) == 0 {
return
}
// TODO: channel into editor message pump?
s.wsConn.FnDebug = func(v string) {
s.PrintDebug(v)
}
fnWsReadmsg := func(msg *WsMsg, err error) {
if err != nil {
s.PrintError(err)
}
if msg != nil {
s.PrintFromPeer(*msg)
}
}
oSet := s.Settings.Clone()
sErrs := s.wsConn.WsOpen(
s.Settings.LastWebsocketURL,
oSet.PingSeconds,
fnWsReadmsg,
)
for _, err := range sErrs {
s.PrintError(err)
}
s.ConnectionStarted = time.Now()
}
func (s *State) SetPingInterval(nSecs int) {
s.Settings.PingSeconds = nSecs
s.Settings.Update("PingSeconds")
s.wsConn.SetPingInterval(nSecs)
}
func (s *State) WsSendMsg(msg string) bool {
return s.wsConn.Write(WsMsg{
Type: websocket.TextMessage,
Msg: []byte(msg),
})
}
type WsInfo struct {
IsOpen bool
Url string
Settings SettingsBase
}
func (s *State) GetWsInfo() WsInfo {
return WsInfo{
IsOpen: s.wsConn.IsOpen(),
Url: s.wsConn.URL(),
Settings: s.Settings.Clone(),
}
}
func (s *State) WsClose() []error {
return s.wsConn.WsClose()
}
var (
printDebug = color.New(color.FgCyan).Fprint
printError = color.New(color.FgRed).Fprint
printUser = color.New(color.FgGreen).Fprint
printServer = color.New(color.FgWhite).Fprint
)
// PrintDebug prints debug information to the Writer, using light blue.
func (s *State) PrintDebug(x string) {
s.printToOut(x, s.getTimestamp("=="), false, printDebug)
}
// PrintError prints an error to the Writer, using red.
func (s *State) PrintError(x error) {
if x != nil {
s.printToOut(x.Error(), s.getTimestamp("!!"), false, printError)
}
}
// prints user-provided messages to the Writer, using green.
func (s *State) PrintFromUser(x string) {
oSet := s.Settings.Clone()
res, err := s.pipe([]byte(x), "out", oSet.Pipe.Out)
if err != nil {
s.PrintError(err)
if len(bytes.TrimSpace(res)) == 0 {
return
}
}
s.printToOut(string(res), s.getTimestamp("=>"), true, printUser)
}
// prints server-returned messages to the Writer, using white.
func (s *State) PrintFromPeer(msg WsMsg) {
switch msg.Type {
case websocket.PingMessage:
s.PrintDebug("<PING MSG>")
return
case websocket.PongMessage:
s.PrintDebug("<PONG MSG>")
return
case websocket.CloseMessage:
s.PrintDebug("<CLOSE MSG>")
return
}
// TODO: cmdline flags for HTTP headers to send with websocket connect
// TODO: persistent pipes?
oSet := s.Settings.Clone()
res, err := s.pipe(msg.Msg, "in", oSet.Pipe.In)
if err != nil {
s.PrintError(err)
if len(bytes.TrimSpace(res)) == 0 {
return
}
}
var szText string
switch msg.Type {
case websocket.BinaryMessage:
szText = strings.TrimSuffix(hex.Dump(res), "\n")
case websocket.TextMessage:
if oSet.JSONFormatting {
res = attemptJSONFormatting(res)
}
szText = strings.TrimSuffix(string(res), "\n")
}
s.printToOut(szText, s.getTimestamp("<="), true, printServer)
}
// getTimestamp returns the settings' timestamp,
// replacing "=>" with symbol
func (s *State) getTimestamp(symbol string) string {
return strings.Replace(s.Settings.Clone().Timestamp, "=>", symbol, -1)
}
var (
sessionStarted = time.Now()
)
func (s *State) pipe(data []byte, t string, command []string) ([]byte, error) {
if len(command) < 1 {
return data, nil
}
// prepare the command: create it, set up env variables
c := exec.Command(command[0], command[1:]...)
c.Env = append(
os.Environ(),
"CLAWS_PIPE_TYPE="+t,
"CLAWS_SESSION="+strconv.FormatInt(sessionStarted.UnixNano()/1000, 10),
"CLAWS_CONNECTION="+strconv.FormatInt(s.ConnectionStarted.UnixNano()/1000, 10),
"CLAWS_WS_URL="+s.wsConn.URL(),
)
// set up stdin
stdin := bytes.NewReader(data)
c.Stdin = stdin
// run the command
return c.Output()
}
func (s *State) printToOut(
str string,
ts string,
bIndent bool,
f func(io.Writer, ...interface{}) (int, error),
) {
// NOTE: mutexed to sequentialize whole writes between
// UI goroutine, read pump, & write pump
s.writerLock.Lock()
defer s.writerLock.Unlock()
var szTs string
if len(ts) > 0 {
szTs = time.Now().Format(ts)
}
s.ExecuteFunc(func(*gocui.Gui) error {
if s.Writer == nil {
return nil
}
// Timestamp, not indented.
bHasTs := len(szTs) > 0
if bHasTs {
if _, e := f(s.Writer, szTs); e != nil {
return e
}
if bIndent {
const indentPrefix = " "
_, e := f(s.Writer, "\n"+indentPrefix+strings.ReplaceAll(str, "\n", "\n"+indentPrefix)+"\n")
return e
}
}
_, e := f(s.Writer, str+"\n")
return e
})
}