forked from gokcehan/lf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
358 lines (294 loc) · 7.02 KB
/
app.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
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
type cmdItem struct {
prefix string
value string
}
type app struct {
ui *ui
nav *nav
ticker *time.Ticker
quitChan chan bool
cmd *exec.Cmd
cmdIn io.WriteCloser
cmdOutBuf []byte
cmdHistory []cmdItem
cmdHistoryBeg int
cmdHistoryInd int
}
func newApp() *app {
ui := newUI()
nav := newNav(ui.wins[0].h)
return &app{
ui: ui,
nav: nav,
ticker: new(time.Ticker),
quitChan: make(chan bool, 1),
}
}
func (app *app) readFile(path string) {
log.Printf("reading file: %s", path)
f, err := os.Open(path)
if err != nil {
app.ui.printf("opening file: %s", err)
return
}
defer f.Close()
p := newParser(f)
for p.parse() {
p.expr.eval(app, nil)
}
if p.err != nil {
app.ui.printf("%s", p.err)
}
}
func (app *app) readHistory() error {
f, err := os.Open(gHistoryPath)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("opening history file: %s", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), " ", 2)
app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]})
}
app.cmdHistoryBeg = len(app.cmdHistory)
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading history file: %s", err)
}
return nil
}
func (app *app) writeHistory() error {
if len(app.cmdHistory) == 0 {
return nil
}
local := make([]cmdItem, len(app.cmdHistory)-app.cmdHistoryBeg)
copy(local, app.cmdHistory[app.cmdHistoryBeg:])
app.cmdHistory = nil
if err := app.readHistory(); err != nil {
return fmt.Errorf("reading history file: %s", err)
}
app.cmdHistory = append(app.cmdHistory, local...)
if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err)
}
f, err := os.Create(gHistoryPath)
if err != nil {
return fmt.Errorf("creating history file: %s", err)
}
defer f.Close()
if len(app.cmdHistory) > 1000 {
app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:]
}
for _, cmd := range app.cmdHistory {
_, err = f.WriteString(fmt.Sprintf("%s %s\n", cmd.prefix, cmd.value))
if err != nil {
return fmt.Errorf("writing history file: %s", err)
}
}
return nil
}
// This is the main event loop of the application. Expressions are read from
// the client and the server on separate goroutines and sent here over channels
// for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update.
func (app *app) loop() {
clientChan := app.ui.readExpr()
serverChan := readExpr()
for {
select {
case <-app.quitChan:
log.Print("bye!")
if err := app.nav.writeMarks(); err != nil {
log.Printf("writing marks file: %s", err)
}
if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err)
}
if gLastDirPath != "" {
f, err := os.Create(gLastDirPath)
if err != nil {
log.Printf("opening last dir file: %s", err)
}
defer f.Close()
dir := app.nav.currDir()
_, err = f.WriteString(dir.path)
if err != nil {
log.Printf("writing last dir file: %s", err)
}
}
return
case d := <-app.nav.dirChan:
prev, ok := app.nav.dirCache[d.path]
if ok {
d.ind = prev.ind
d.sel(prev.name(), app.nav.height)
}
app.nav.dirCache[d.path] = d
for i := range app.nav.dirs {
if app.nav.dirs[i].path == d.path {
app.nav.dirs[i] = d
}
}
app.nav.position()
curr, err := app.nav.currFile()
if err == nil {
if d.path == app.nav.currDir().path {
app.ui.loadFile(app.nav)
}
if d.path == curr.path {
app.ui.dirPrev = d
}
}
app.ui.draw(app.nav)
case r := <-app.nav.regChan:
app.nav.regCache[r.path] = r
curr, err := app.nav.currFile()
if err == nil {
if r.path == curr.path {
app.ui.regPrev = r
}
}
app.ui.draw(app.nav)
case e := <-clientChan:
e.eval(app, nil)
app.ui.draw(app.nav)
case e := <-serverChan:
e.eval(app, nil)
app.ui.draw(app.nav)
case <-app.ticker.C:
app.nav.renew()
app.ui.loadFile(app.nav)
app.ui.draw(app.nav)
}
}
}
func (app *app) exportVars() {
var envFile string
if f, err := app.nav.currFile(); err == nil {
envFile = f.path
}
selections := app.nav.currSelections()
envFiles := strings.Join(selections, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(selections) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
level, err := strconv.Atoi(envLevel)
if err != nil {
log.Printf("reading lf level: %s", err)
}
level++
os.Setenv("LF_LEVEL", strconv.Itoa(level))
}
func waitKey() error {
cmd := pauseCommand()
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("waiting key: %s", err)
}
return nil
}
// This function is used to run a shell command. Modes are as follows:
//
// Prefix Wait Async Stdin Stdout Stderr UI action
// $ No No Yes Yes Yes Pause and then resume
// % No No Yes Yes Yes Statline for input/output
// ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing
func (app *app) runShell(s string, args []string, prefix string) {
app.exportVars()
cmd := shellCommand(s, args)
var out io.Reader
switch prefix {
case "$", "!":
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
app.ui.pause()
defer app.ui.resume()
defer app.nav.renew()
case "%":
stdin, err := cmd.StdinPipe()
if err != nil {
log.Printf("writing stdin: %s", err)
}
app.cmdIn = stdin
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Printf("reading stdout: %s", err)
}
out = stdout
cmd.Stderr = cmd.Stdout
}
var err error
switch prefix {
case "$", "!":
err = cmd.Run()
case "%", "&":
err = cmd.Start()
}
if err != nil {
app.ui.printf("running shell: %s", err)
}
switch prefix {
case "!":
if err := waitKey(); err != nil {
app.ui.printf("waiting key: %s", err)
}
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
switch prefix {
case "%":
go func() {
app.cmd = cmd
app.cmdOutBuf = nil
app.ui.msg = ""
app.ui.cmdPrefix = ">"
reader := bufio.NewReader(out)
for {
b, err := reader.ReadByte()
if err == io.EOF {
break
}
app.cmdOutBuf = append(app.cmdOutBuf, b)
app.ui.exprChan <- &callExpr{"echo", []string{string(app.cmdOutBuf)}, 1}
if b == '\n' || b == '\r' {
app.cmdOutBuf = nil
}
}
if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err)
}
app.cmd = nil
app.ui.cmdPrefix = ""
app.ui.exprChan <- &callExpr{"load", nil, 1}
}()
}
}