Debian Codegraph @

app.go

raw
1 package main
2
3 import (
4 "bufio"
5 "cmp"
6 "errors"
7 "fmt"
8 "io"
9 "io/fs"
10 "log"
11 "os"
12 "os/exec"
13 "os/signal"
14 "path/filepath"
15 "slices"
16 "strings"
17 "syscall"
18 "time"
19 )
20
21 type app struct {
22 ui *ui // ui state (screen, windows, input)
23 nav *nav // navigation state (dirs, cursor, selections, preview, caches)
24 ticker *time.Ticker // refresh ticker if `period` > 0
25 quitChan chan struct{} // signals main loop to exit
26 cmd *exec.Cmd // currently running % (shell-pipe) command
27 cmdIn io.WriteCloser // stdin writer for running % command
28 cmdOutBuf []byte // output of running % command
29 cmdHistory []string // command history entries
30 cmdHistoryBeg int // index where commands from this session start in cmdHistory
31 cmdHistoryInd int // history navigation offset from most recent
32 cmdHistoryInput *string // initial input used as prefix filter while browsing history
33 menuCompActive bool // whether completion cycling is active
34 menuCompTmp []string // token snapshot taken when completion cycling starts, used for `cmd-menu-discard`
35 menuComps []compMatch // completion candidates for active prompt
36 menuCompInd int // index of selected completion candidate (-1: none selected)
37 selectionOut []string // paths to output on exit, used for `-print-selection` and `-selection-path`
38 watch *watch // fs watcher if `watch` is enabled
39 quitting bool // guard to prevent re-entering quit logic
40 }
41
42 func newApp(ui *ui, nav *nav) *app {
43 quitChan := make(chan struct{}, 1)
44
45 app := &app{
46 ui: ui,
47 nav: nav,
48 ticker: new(time.Ticker),
49 quitChan: quitChan,
50 watch: newWatch(nav.dirChan, nav.fileChan, nav.delChan),
51 }
52
53 sigChan := make(chan os.Signal, 1)
54 signal.Notify(sigChan, os.Interrupt, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM)
55 go func() {
56 for {
57 switch <-sigChan {
58 case os.Interrupt:
59 case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM:
60 app.quit()
61 os.Exit(3)
62 return
63 }
64 }
65 }()
66
67 return app
68 }
69
70 func (app *app) quit() {
71 // Using synchronous shell commands for `on-quit` can cause this to be
72 // called again, so a guard variable is introduced here to prevent an
73 // infinite loop.
74 if app.quitting {
75 return
76 }
77 app.quitting = true
78
79 onQuit(app)
80
81 if gOpts.history {
82 if err := app.writeHistory(); err != nil {
83 log.Printf("writing history file: %s", err)
84 }
85 }
86 if !gSingleMode {
87 if _, err := remote(fmt.Sprintf("drop %d", gClientID)); err != nil {
88 log.Printf("dropping connection: %s", err)
89 }
90 if gOpts.autoquit {
91 if _, err := remote("quit"); err != nil {
92 log.Printf("auto quitting server: %s", err)
93 }
94 }
95 }
96 }
97
98 func (app *app) readFile(path string) {
99 log.Printf("reading file: %s", path)
100
101 f, err := os.Open(path)
102 if err != nil {
103 app.ui.echoerrf("opening file: %s", err)
104 return
105 }
106 defer f.Close()
107
108 p := newParser(f)
109
110 for p.parse() {
111 p.expr.eval(app, nil)
112 }
113
114 if p.err != nil {
115 app.ui.echoerrf("%s", p.err)
116 }
117 }
118
119 func loadFiles() (clipboard clipboard, err error) {
120 files, err := os.Open(gFilesPath)
121 if os.IsNotExist(err) {
122 err = nil
123 return
124 }
125 if err != nil {
126 err = fmt.Errorf("opening file selections file: %w", err)
127 return
128 }
129 defer files.Close()
130
131 s := bufio.NewScanner(files)
132
133 if !s.Scan() {
134 err = fmt.Errorf("scanning file list: %w", cmp.Or(s.Err(), io.EOF))
135 return
136 }
137
138 switch s.Text() {
139 case "copy":
140 clipboard.mode = clipboardCopy
141 case "move":
142 clipboard.mode = clipboardCut
143 default:
144 err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text())
145 return
146 }
147
148 for s.Scan() && s.Text() != "" {
149 clipboard.paths = append(clipboard.paths, s.Text())
150 }
151
152 if s.Err() != nil {
153 err = fmt.Errorf("scanning file list: %w", s.Err())
154 return
155 }
156
157 log.Printf("loading clipboard: %v", clipboard.paths)
158
159 return
160 }
161
162 func saveFiles(clipboard clipboard) error {
163 for _, path := range clipboard.paths {
164 // the clipboard file stores one path per line so a newline cannot be saved
165 if strings.ContainsAny(path, "\n\r") {
166 return fmt.Errorf("cannot copy %s because the name contains a newline", path)
167 }
168 }
169
170 if err := os.MkdirAll(filepath.Dir(gFilesPath), 0o700); err != nil {
171 return fmt.Errorf("creating data directory: %w", err)
172 }
173
174 files, err := os.OpenFile(gFilesPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
175 if err != nil {
176 return fmt.Errorf("opening file selections file: %w", err)
177 }
178 defer files.Close()
179
180 log.Printf("saving files: %v", clipboard.paths)
181
182 var clipboardModeStr string
183 if clipboard.mode == clipboardCopy {
184 clipboardModeStr = "copy"
185 } else {
186 clipboardModeStr = "move"
187 }
188 if _, err := fmt.Fprintln(files, clipboardModeStr); err != nil {
189 return fmt.Errorf("write clipboard mode to file: %w", err)
190 }
191
192 for _, path := range clipboard.paths {
193 if _, err := fmt.Fprintln(files, path); err != nil {
194 return fmt.Errorf("write path to file: %w", err)
195 }
196 }
197
198 return files.Sync()
199 }
200
201 func (app *app) readHistory() error {
202 f, err := os.Open(gHistoryPath)
203 if os.IsNotExist(err) {
204 return nil
205 }
206 if err != nil {
207 return fmt.Errorf("opening history file: %w", err)
208 }
209 defer f.Close()
210
211 scanner := bufio.NewScanner(f)
212 for scanner.Scan() {
213 cmd := scanner.Text()
214 if len(cmd) < 1 || !slices.Contains([]string{":", "$", "!", "%", "&"}, cmd[:1]) {
215 continue
216 }
217 app.cmdHistory = append(app.cmdHistory, cmd)
218 }
219
220 app.cmdHistoryBeg = len(app.cmdHistory)
221
222 if err := scanner.Err(); err != nil {
223 return fmt.Errorf("reading history file: %w", err)
224 }
225
226 return nil
227 }
228
229 func (app *app) writeHistory() error {
230 if len(app.cmdHistory) == 0 {
231 return nil
232 }
233
234 local := slices.Clone(app.cmdHistory[app.cmdHistoryBeg:])
235 app.cmdHistory = nil
236
237 if err := app.readHistory(); err != nil {
238 return fmt.Errorf("reading history file: %w", err)
239 }
240
241 app.cmdHistory = append(app.cmdHistory, local...)
242 if len(app.cmdHistory) > 1000 {
243 app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:]
244 }
245
246 if err := os.MkdirAll(filepath.Dir(gHistoryPath), 0o700); err != nil {
247 return fmt.Errorf("creating data directory: %w", err)
248 }
249
250 f, err := os.OpenFile(gHistoryPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
251 if err != nil {
252 return fmt.Errorf("creating history file: %w", err)
253 }
254 defer f.Close()
255
256 for _, cmd := range app.cmdHistory {
257 if _, err = fmt.Fprintln(f, cmd); err != nil {
258 return fmt.Errorf("writing history file: %w", err)
259 }
260 }
261
262 return nil
263 }
264
265 // loop is the main event loop of the application. Expressions are read from
266 // the client and the server on separate goroutines and sent here over channels
267 // for evaluation. Similarly directories and regular files are also read in
268 // separate goroutines and sent here for update.
269 func (app *app) loop() {
270 go app.nav.preloadLoop(app.ui)
271 go app.nav.previewLoop(app.ui)
272
273 var serverChan <-chan expr
274 if !gSingleMode {
275 serverChan = readExpr()
276 }
277
278 go app.ui.readEvents()
279
280 if gConfigPath != "" {
281 if _, err := os.Stat(gConfigPath); !os.IsNotExist(err) {
282 app.readFile(gConfigPath)
283 } else {
284 log.Printf("config file does not exist: %s", err)
285 }
286 } else {
287 for _, path := range gConfigPaths {
288 if _, err := os.Stat(path); !os.IsNotExist(err) {
289 app.readFile(path)
290 }
291 }
292 }
293
294 for _, cmd := range gCommands {
295 p := newParser(strings.NewReader(cmd))
296
297 for p.parse() {
298 p.expr.eval(app, nil)
299 }
300
301 if p.err != nil {
302 app.ui.echoerrf("%s", p.err)
303 }
304 }
305
306 app.nav.addJumpList()
307
308 if gSelect != "" {
309 go func() {
310 lstat, err := os.Lstat(gSelect)
311 if err != nil {
312 app.ui.exprChan <- &callExpr{"echoerr", []string{err.Error()}, 1}
313 } else if lstat.IsDir() {
314 app.ui.exprChan <- &callExpr{"cd", []string{gSelect}, 1}
315 } else {
316 app.ui.exprChan <- &callExpr{"select", []string{gSelect}, 1}
317 }
318 }()
319 }
320
321 for {
322 select {
323 case <-app.quitChan:
324 if app.nav.copyJobs > 0 {
325 app.ui.echoerr("quit: copy operation in progress")
326 continue
327 }
328
329 if app.nav.moveTotal > 0 {
330 app.ui.echoerr("quit: move operation in progress")
331 continue
332 }
333
334 if app.nav.deleteTotal > 0 {
335 app.ui.echoerr("quit: delete operation in progress")
336 continue
337 }
338
339 app.quit()
340
341 app.nav.previewChan <- ""
342
343 log.Printf("*************** closing client, PID: %d ***************", gClientID)
344
345 return
346 case n := <-app.nav.copyJobsChan:
347 app.nav.copyJobs += n
348 app.ui.draw(app.nav)
349 case n := <-app.nav.copyBytesChan:
350 app.nav.copyBytes += n
351 // n is usually 32*1024B (default io.Copy() buffer) so update roughly per 32KB x 128 = 4MB copied
352 if app.nav.copyUpdate++; app.nav.copyUpdate >= 128 {
353 app.nav.copyUpdate = 0
354 app.ui.draw(app.nav)
355 }
356 case n := <-app.nav.copyTotalChan:
357 app.nav.copyTotal += n
358 if n < 0 {
359 app.nav.copyBytes += n
360 }
361 if app.nav.copyTotal == 0 {
362 app.nav.copyUpdate = 0
363 }
364 app.ui.draw(app.nav)
365 case n := <-app.nav.moveCountChan:
366 app.nav.moveCount += n
367 if app.nav.moveUpdate++; app.nav.moveUpdate >= 1000 {
368 app.nav.moveUpdate = 0
369 app.ui.draw(app.nav)
370 }
371 case n := <-app.nav.moveTotalChan:
372 app.nav.moveTotal += n
373 if n < 0 {
374 app.nav.moveCount += n
375 }
376 if app.nav.moveTotal == 0 {
377 app.nav.moveUpdate = 0
378 }
379 app.ui.draw(app.nav)
380 case n := <-app.nav.deleteCountChan:
381 app.nav.deleteCount += n
382 if app.nav.deleteUpdate++; app.nav.deleteUpdate >= 1000 {
383 app.nav.deleteUpdate = 0
384 app.ui.draw(app.nav)
385 }
386 case n := <-app.nav.deleteTotalChan:
387 app.nav.deleteTotal += n
388 if n < 0 {
389 app.nav.deleteCount += n
390 }
391 if app.nav.deleteTotal == 0 {
392 app.nav.deleteUpdate = 0
393 }
394 app.ui.draw(app.nav)
395 case d := <-app.nav.dirChan:
396 var oldCurrPath string
397 if curr := app.nav.currFile(); curr != nil {
398 oldCurrPath = curr.path
399 }
400
401 if prev, ok := app.nav.dirCache[d.path]; ok {
402 d.ind = prev.ind
403 d.pos = prev.pos
404 d.visualAnchor = min(prev.visualAnchor, len(d.files)-1)
405 d.visualWrap = prev.visualWrap
406 d.filter = prev.filter
407 d.sort()
408 d.sel(prev.name(), app.nav.height)
409 } else {
410 d.sort()
411 }
412 app.nav.dirCache[d.path] = d
413
414 app.nav.position()
415
416 if curr := app.nav.currFile(); curr != nil {
417 if curr.path != oldCurrPath {
418 app.ui.loadFile(app, true)
419 }
420 }
421
422 app.watchDir(d)
423
424 // Avoid flickering UI and multiple, unnecessary `on-load` calls
425 // triggered by Git commands executed inside the users `on-load`
426 // command (often used to add git symbols using `addcustominfo`).
427 // TODO: Should `watch` also ignore `.git` directories?
428 if filepath.Base(d.path) != ".git" {
429 paths := make([]string, len(d.allFiles))
430 for i, file := range d.allFiles {
431 paths[i] = file.path
432 }
433 onLoad(app, paths)
434 }
435
436 if d.path == app.nav.currDir().path {
437 app.nav.preload()
438 }
439
440 app.ui.draw(app.nav)
441 case r := <-app.nav.regChan:
442 if r.height != app.nav.height {
443 delete(app.nav.regCache, r.path)
444 continue
445 }
446 app.nav.regCache[r.path] = r
447
448 if curr := app.nav.currFile(); curr != nil {
449 if r.path == curr.path {
450 app.ui.sxScreen.forceClear = true
451 if gOpts.preload && r.volatile {
452 app.ui.loadFile(app, true)
453 }
454 }
455 }
456
457 app.ui.draw(app.nav)
458 case f := <-app.nav.fileChan:
459 if dir, ok := app.nav.dirCache[filepath.Dir(f.path)]; ok {
460 for i := range dir.allFiles {
461 if dir.allFiles[i].path == f.path {
462 dir.allFiles[i] = f
463 break
464 }
465 }
466
467 name := dir.name()
468 dir.sort()
469 dir.sel(name, app.nav.height)
470 }
471
472 if r, ok := app.nav.regCache[f.path]; ok {
473 app.nav.checkReg(r)
474 }
475 onLoad(app, []string{f.path})
476 app.ui.draw(app.nav)
477 case path := <-app.nav.delChan:
478 deletePathRecursive(app.nav.selections, path)
479 if len(app.nav.selections) == 0 {
480 app.nav.selectionInd = 0
481 }
482
483 deletePathRecursive(app.nav.regCache, path)
484 deletePathRecursive(app.nav.dirCache, path)
485
486 if slices.Contains(app.nav.dirPaths, path) {
487 if err := app.nav.cd(filepath.Dir(path)); err != nil {
488 log.Print(err)
489 }
490 }
491 case ev := <-app.ui.evChan:
492 e := app.ui.readEvent(ev, app.nav)
493 if e == nil {
494 continue
495 }
496 e.eval(app, nil)
497 loop:
498 for {
499 select {
500 case ev := <-app.ui.evChan:
501 e = app.ui.readEvent(ev, app.nav)
502 if e == nil {
503 continue
504 }
505 e.eval(app, nil)
506 default:
507 break loop
508 }
509 }
510 app.ui.draw(app.nav)
511 case e := <-app.ui.exprChan:
512 e.eval(app, nil)
513 app.ui.draw(app.nav)
514 case e := <-serverChan:
515 e.eval(app, nil)
516 app.ui.draw(app.nav)
517 case <-app.ticker.C:
518 app.nav.renew()
519 app.ui.loadFile(app, false)
520 case <-app.nav.previewTimer.C:
521 app.ui.draw(app.nav)
522 case <-app.nav.preloadTimer.C:
523 app.nav.preload()
524 }
525 }
526 }
527
528 func (app *app) runCmdSync(cmd *exec.Cmd, pauseAfter bool) {
529 app.nav.previewChan <- ""
530
531 if err := app.ui.suspend(); err != nil {
532 log.Printf("suspend: %s", err)
533 }
534 defer func() {
535 if err := app.ui.resume(); err != nil {
536 app.quit()
537 os.Exit(3)
538 }
539 }()
540
541 if err := cmd.Run(); err != nil {
542 app.ui.echoerrf("running shell: %s", err)
543 }
544 if pauseAfter {
545 anyKey()
546 }
547
548 app.ui.loadFile(app, true)
549 app.nav.renew()
550 }
551
552 // runShell is used to run a shell command. Modes are as follows:
553 //
554 // Prefix Wait Async Stdin Stdout Stderr UI action
555 // $ No No Yes Yes Yes Pause and then resume
556 // % No No Yes Yes Yes Statline for input/output
557 // ! Yes No Yes Yes Yes Pause and then resume
558 // & No Yes No No No Do nothing
559 func (app *app) runShell(s string, args []string, prefix string) {
560 app.nav.exportFiles()
561 app.ui.exportSizes()
562 app.exportMode()
563 exportLfPath()
564 exportOpts()
565
566 gState.mutex.Lock()
567 gState.data["maps"] = listBinds(map[string]map[string]expr{
568 "n": gOpts.nkeys,
569 "v": gOpts.vkeys,
570 })
571 gState.data["nmaps"] = listBinds(map[string]map[string]expr{
572 "n": gOpts.nkeys,
573 })
574 gState.data["vmaps"] = listBinds(map[string]map[string]expr{
575 "v": gOpts.vkeys,
576 })
577 gState.data["cmaps"] = listBinds(map[string]map[string]expr{
578 "c": gOpts.cmdkeys,
579 })
580 gState.data["cmds"] = listCmds(gOpts.cmds)
581 gState.data["jumps"] = listJumps(app.nav.jumpList, app.nav.jumpListInd)
582 gState.data["history"] = listHistory(app.cmdHistory)
583 gState.data["files"] = listFilesInCurrDir(app.nav)
584 gState.mutex.Unlock()
585
586 cmd := shellCommand(s, args)
587
588 switch prefix {
589 case "$", "!":
590 cmd.Stdin = os.Stdin
591 cmd.Stdout = os.Stderr
592 cmd.Stderr = os.Stderr
593
594 app.runCmdSync(cmd, prefix == "!")
595 return
596 }
597
598 // We are running the command asynchronously
599 var inReader, inWriter, outReader, outWriter *os.File
600 if prefix == "%" {
601 if app.ui.cmdPrefix == ">" {
602 return
603 }
604
605 // [exec.Cmd.StdoutPipe] cannot be used as it requires the output to be fully
606 // read before calling [exec.Cmd.Wait], however in this case Cmd.Wait should
607 // only wait for the command to finish executing regardless of whether the
608 // output has been fully read or not.
609 var err error
610 inReader, inWriter, err = os.Pipe()
611 if err != nil {
612 log.Printf("creating input pipe: %s", err)
613 return
614 }
615 cmd.Stdin = inReader
616 app.cmdIn = inWriter
617
618 outReader, outWriter, err = os.Pipe()
619 if err != nil {
620 log.Printf("creating output pipe: %s", err)
621 return
622 }
623 cmd.Stdout = outWriter
624 cmd.Stderr = outWriter
625 }
626
627 shellSetPG(cmd)
628 if err := cmd.Start(); err != nil {
629 app.ui.echoerrf("running shell: %s", err)
630 }
631
632 switch prefix {
633 case "%":
634 normal(app)
635 app.cmd = cmd
636 app.cmdOutBuf = nil
637 app.ui.cmdPrefix = ">"
638 app.ui.echo("")
639
640 go func() {
641 reader := bufio.NewReader(outReader)
642 for {
643 b, err := reader.ReadByte()
644 if err != nil {
645 if !errors.Is(err, io.EOF) && !errors.Is(err, fs.ErrClosed) {
646 log.Printf("reading command output: %s", err)
647 }
648 break
649 }
650
651 app.cmdOutBuf = append(app.cmdOutBuf, b)
652 if reader.Buffered() == 0 {
653 app.ui.exprChan <- &callExpr{"echo", []string{string(app.cmdOutBuf)}, 1}
654 }
655
656 if b == '\n' || b == '\r' {
657 app.cmdOutBuf = nil
658 }
659 }
660 }()
661
662 go func() {
663 if err := cmd.Wait(); err != nil {
664 log.Printf("running shell: %s", err)
665 }
666 inReader.Close()
667 inWriter.Close()
668 outReader.Close()
669 outWriter.Close()
670
671 app.cmd = nil
672 app.ui.cmdPrefix = ""
673 app.ui.exprChan <- &callExpr{"load", nil, 1}
674 }()
675 case "&":
676 go func() {
677 if err := cmd.Wait(); err != nil {
678 log.Printf("running shell: %s", err)
679 }
680 app.ui.exprChan <- &callExpr{"load", nil, 1}
681 }()
682 }
683 }
684
685 func (app *app) doComplete() (matches []compMatch) {
686 var longest string
687
688 switch app.ui.cmdPrefix {
689 case ":":
690 matches, longest = completeCmd(app.ui.cmdAccLeft)
691 case "$", "%", "!", "&":
692 matches, longest = completeShell(app.ui.cmdAccLeft)
693 case "/", "?":
694 matches, longest = completeSearch(app.ui.cmdAccLeft)
695 }
696
697 app.ui.cmdAccLeft = longest
698 app.ui.menu, app.ui.menuSelect = listMatches(app.ui.screen, matches, -1)
699 return
700 }
701
702 func (app *app) menuComplete(direction int) {
703 if !app.menuCompActive {
704 app.menuCompTmp = tokenize(app.ui.cmdAccLeft)
705 app.menuComps = app.doComplete()
706 if len(app.menuComps) > 1 {
707 app.menuCompInd = -1
708 app.menuCompActive = true
709 }
710 } else {
711 app.menuCompInd += direction
712 if app.menuCompInd == len(app.menuComps) {
713 app.menuCompInd = 0
714 } else if app.menuCompInd < 0 {
715 app.menuCompInd = len(app.menuComps) - 1
716 }
717
718 toks := slices.Clone(app.menuCompTmp)
719 toks[len(toks)-1] = app.menuComps[app.menuCompInd].result
720 app.ui.cmdAccLeft = strings.Join(toks, " ")
721 }
722 app.ui.menu, app.ui.menuSelect = listMatches(app.ui.screen, app.menuComps, app.menuCompInd)
723 }
724
725 func (app *app) watchDir(dir *dir) {
726 if !gOpts.watch {
727 return
728 }
729
730 app.watch.add(dir.path)
731
732 // ensure dircounts are updated for child directories
733 for _, file := range dir.allFiles {
734 if file.IsDir() {
735 app.watch.add(file.path)
736 }
737 }
738 }
739
740 func (app *app) exportMode() {
741 getMode := func() string {
742 if app.menuCompActive {
743 return "compmenu"
744 }
745
746 if strings.HasPrefix(app.ui.cmdPrefix, "delete") {
747 return "delete"
748 }
749
750 if strings.HasPrefix(app.ui.cmdPrefix, "replace") || strings.HasPrefix(app.ui.cmdPrefix, "create") {
751 return "rename"
752 }
753
754 switch app.ui.cmdPrefix {
755 case "filter: ":
756 return "filter"
757 case "find: ", "find-back: ":
758 return "find"
759 case "mark-save: ", "mark-load: ", "mark-remove: ":
760 return "mark"
761 case "rename: ":
762 return "rename"
763 case "/", "?":
764 return "search"
765 case ":":
766 return "command"
767 case "$", "%", "!", "&":
768 return "shell"
769 case ">":
770 return "pipe"
771 case "":
772 if app.nav.isVisualMode() {
773 return "visual"
774 }
775 return "normal"
776 default:
777 return "unknown"
778 }
779 }
780
781 os.Setenv("lf_mode", getMode())
782 }