Debian Codegraph @

ui.go

raw
1 package main
2
3 import (
4 "bytes"
5 "cmp"
6 "fmt"
7 "log"
8 "maps"
9 "os"
10 "path/filepath"
11 "reflect"
12 "slices"
13 "strconv"
14 "strings"
15 "text/tabwriter"
16 "text/template"
17 "time"
18 "unicode/utf8"
19
20 "github.com/clipperhouse/displaywidth"
21 "github.com/gdamore/tcell/v3"
22 "golang.org/x/term"
23 )
24
25 const previewLoadingDelay = 100 * time.Millisecond
26
27 type win struct {
28 w, h, x, y int
29 }
30
31 func newWin(w, h, x, y int) *win {
32 return &win{w, h, x, y}
33 }
34
35 func (win *win) renew(w, h, x, y int) {
36 win.w, win.h, win.x, win.y = w, h, x, y
37 }
38
39 // firstGrapheme returns the first grapheme cluster in s and its display width.
40 func firstGrapheme(s string) (string, int) {
41 gr := displaywidth.StringGraphemes(s)
42 if !gr.Next() {
43 return "", 0
44 }
45 return gr.Value(), gr.Width()
46 }
47
48 // printLength returns the display width of s in terminal cells.
49 //
50 // It ignores supported terminal control sequences (see [readTermSequence])
51 // and accounts for tab expansions using the `tabstop` option.
52 func printLength(s string) int {
53 length := 0
54
55 slen := len(s)
56 for i := 0; i < slen; {
57 seq := readTermSequence(s[i:])
58 if seq != "" {
59 i += len(seq)
60 continue
61 }
62
63 gc, w := firstGrapheme(s[i:])
64 i += len(gc)
65
66 if gc == "\t" {
67 length += gOpts.tabstop - length%gOpts.tabstop
68 } else if isPrintable(gc) {
69 length += w
70 } else {
71 length++ // U+FFFD replacement has width 1
72 }
73 }
74
75 return length
76 }
77
78 func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) tcell.Style {
79 var b strings.Builder
80 off := 0
81 put := func() {
82 if b.Len() > 0 {
83 s := b.String()
84 screen.PutStrStyled(win.x+x+off, win.y+y, s, st)
85 off += printLength(s)
86 b.Reset()
87 }
88 }
89
90 slen := len(s)
91 for i := 0; i < slen; {
92 seq := readTermSequence(s[i:])
93 if seq != "" {
94 put()
95 st = applyTermSequence(seq, st)
96 i += len(seq)
97 continue
98 }
99
100 gc := firstGraphemeCluster(s[i:])
101 if gc == "\t" {
102 w := gOpts.tabstop - (x+off+printLength(b.String()))%gOpts.tabstop
103 b.WriteString(strings.Repeat(" ", w))
104 } else if isPrintable(gc) {
105 b.WriteString(gc)
106 } else {
107 b.WriteString("\uFFFD")
108 }
109
110 i += len(gc)
111 }
112
113 put()
114 return st
115 }
116
117 func (win *win) printf(screen tcell.Screen, x, y int, st tcell.Style, format string, a ...any) {
118 win.print(screen, x, y, st, fmt.Sprintf(format, a...))
119 }
120
121 func (win *win) printLine(screen tcell.Screen, x, y int, st tcell.Style, s string) {
122 win.printf(screen, x, y, st, "%s%*s", s, win.w-printLength(s), "")
123 }
124
125 func (win *win) printRight(screen tcell.Screen, y int, st tcell.Style, s string) {
126 win.print(screen, win.w-printLength(s), y, st, s)
127 }
128
129 func (win *win) printMsg(screen tcell.Screen, s string) {
130 pad := 1
131 if gOpts.mergeindicators {
132 pad--
133 }
134 st := tcell.StyleDefault.Reverse(true)
135 win.print(screen, pad, 0, st, s)
136 }
137
138 func (win *win) printReg(screen tcell.Screen, reg *reg, sxs *sixelScreen, previewTimer *time.Timer) {
139 switch {
140 case reg.loading:
141 if time.Since(reg.loadTime) > previewLoadingDelay {
142 win.printMsg(screen, "loading...")
143 } else {
144 previewTimer.Reset(previewLoadingDelay)
145 }
146 case reg.sixel:
147 sxs.printSixel(win, screen, reg)
148 default:
149 st := tcell.StyleDefault
150 for i, l := range reg.lines {
151 if i > win.h-1 {
152 break
153 }
154
155 st = win.print(screen, 0, i, st, l)
156 }
157 }
158
159 if !reg.sixel {
160 sxs.lastFile = ""
161 }
162 }
163
164 var gThisYear = time.Now().Year()
165
166 func infotimefmt(t time.Time) string {
167 if t.Year() == gThisYear {
168 return t.Format(gOpts.infotimefmtnew)
169 }
170 return t.Format(gOpts.infotimefmtold)
171 }
172
173 func fileInfo(f *file, d *dir, userWidth, groupWidth, customWidth int) (string, string, int) {
174 var info strings.Builder
175 var custom string
176 var off int
177
178 for _, s := range getInfo(d.path) {
179 switch s {
180 case "size":
181 if f.IsDir() && getDirCounts(d.path) {
182 switch {
183 case f.dirCount < 0:
184 info.WriteString(" !")
185 case f.dirCount < 10000:
186 fmt.Fprintf(&info, " %5d", f.dirCount)
187 default:
188 info.WriteString(" 9999+")
189 }
190 } else {
191 switch {
192 case f.dirSize >= 0:
193 fmt.Fprintf(&info, " %5s", humanize(f.dirSize))
194 case f.IsDir():
195 info.WriteString(" -")
196 default:
197 fmt.Fprintf(&info, " %5s", humanize(f.Size()))
198 }
199 }
200 case "time":
201 fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime()))
202 case "atime":
203 fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.accessTime))
204 case "btime":
205 fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.birthTime))
206 case "ctime":
207 fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.changeTime))
208 case "perm":
209 info.WriteString(" " + permString(f.Mode()))
210 case "user":
211 fmt.Fprintf(&info, " %-*s", userWidth, userName(f.FileInfo))
212 case "group":
213 fmt.Fprintf(&info, " %-*s", groupWidth, groupName(f.FileInfo))
214 case "custom":
215 // Prevent useless spacers, as `custom` allows empty values
216 if customWidth < 1 {
217 continue
218 }
219 // To allow for the usage of escape sequences, store `custom`
220 // separately and print it later using the offset.
221 off = info.Len()
222 fmt.Fprintf(&info, " %*s", customWidth, "")
223 custom = fmt.Sprintf(" %s%*s", f.customInfo, customWidth-printLength(f.customInfo), "")
224 default:
225 log.Printf("unknown info type: %s", s)
226 }
227 }
228
229 return info.String(), custom, off
230 }
231
232 type dirContext struct {
233 selections map[string]int
234 clipboard clipboard
235 tags map[string]string
236 }
237
238 // dirRole describes what kind of directory pane is being drawn.
239 type dirRole byte
240
241 const (
242 Active dirRole = iota // Current directory pane.
243 Parent // Parent or ancestor directory pane.
244 Preview // Preview pane when it shows a directory listing.
245 )
246
247 type dirStyle struct {
248 colors styleMap
249 icons iconMap
250 role dirRole
251 }
252
253 func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirStyle, previewTimer *time.Timer) {
254 if win.w < 5 || dir == nil {
255 return
256 }
257
258 fileslen := len(dir.files)
259
260 switch {
261 case dir.loading && fileslen == 0:
262 if time.Since(dir.loadTime) > previewLoadingDelay {
263 win.printMsg(ui.screen, "loading...")
264 } else {
265 previewTimer.Reset(previewLoadingDelay)
266 }
267 return
268 case dir.noPerm:
269 win.printMsg(ui.screen, "permission denied")
270 return
271 case fileslen == 0:
272 win.printMsg(ui.screen, "empty")
273 return
274 }
275
276 beg := max(dir.ind-dir.pos, 0)
277 end := min(beg+win.h, fileslen)
278
279 if beg > end {
280 return
281 }
282
283 var lnwidth int
284
285 if dirStyle.role == Active && (gOpts.number || gOpts.relativenumber) {
286 lnwidth = 1
287 for j := 10; j <= fileslen; j *= 10 {
288 lnwidth++
289 }
290 if gOpts.number && gOpts.relativenumber {
291 lnwidth = max(lnwidth, 2)
292 }
293 }
294
295 var userWidth, groupWidth, customWidth int
296 var fetchedCustom bool
297
298 // Only fetch user/group/custom widths if configured to display them
299 for _, s := range getInfo(dir.path) {
300 switch s {
301 case "user":
302 userWidth = getUserWidth(dir, beg, end)
303 case "group":
304 groupWidth = getGroupWidth(dir, beg, end)
305 case "custom":
306 customWidth = getCustomWidth(dir, beg, end)
307 fetchedCustom = true // Can have a length of 0
308 }
309
310 if userWidth > 0 && groupWidth > 0 && fetchedCustom {
311 break
312 }
313 }
314
315 indOff, tagOff, nameOff := lnwidth, lnwidth, lnwidth+1
316 if !gOpts.mergeindicators {
317 tagOff++
318 nameOff++
319 }
320
321 visualSelections := dir.visualSelections()
322 for i, f := range dir.files[beg:end] {
323 st := dirStyle.colors.get(f)
324
325 if lnwidth > 0 {
326 var ln string
327
328 if gOpts.number && !gOpts.relativenumber {
329 ln = fmt.Sprintf("%*d", lnwidth, i+1+beg)
330 } else if gOpts.relativenumber {
331 switch {
332 case i < dir.pos:
333 ln = fmt.Sprintf("%*d", lnwidth, dir.pos-i)
334 case i > dir.pos:
335 ln = fmt.Sprintf("%*d", lnwidth, i-dir.pos)
336 case gOpts.number:
337 ln = fmt.Sprintf("%-*d", lnwidth, i+1+beg)
338 default:
339 ln = fmt.Sprintf("%*d", lnwidth, 0)
340 }
341 }
342
343 fmtStr := optionToFmtstr(gOpts.numberfmt)
344 if i == dir.pos && gOpts.numbercursorfmt != "" {
345 fmtStr = optionToFmtstr(gOpts.numbercursorfmt)
346 }
347 win.print(ui.screen, 0, i, tcell.StyleDefault, fmt.Sprintf(fmtStr, ln))
348 }
349
350 path := filepath.Join(dir.path, f.Name())
351
352 var fmtStr string
353 if slices.Contains(visualSelections, path) {
354 fmtStr = gOpts.visualfmt
355 } else if _, ok := context.selections[path]; ok {
356 fmtStr = gOpts.selectfmt
357 } else if slices.Contains(context.clipboard.paths, path) {
358 if context.clipboard.mode == clipboardCopy {
359 fmtStr = gOpts.copyfmt
360 } else {
361 fmtStr = gOpts.cutfmt
362 }
363 }
364
365 tag := " "
366 if val, ok := context.tags[path]; ok && len(val) > 0 {
367 tag = val
368 }
369
370 if fmtStr != "" {
371 ind := " "
372 if gOpts.mergeindicators {
373 ind = tag
374 }
375 win.print(ui.screen, indOff, i, parseEscapeSequence(fmtStr), ind)
376 }
377
378 // make space for select marker, and leave another space at the end
379 maxWidth := win.w - lnwidth - 2
380
381 var icon string
382 var iconDef iconDef
383 if gOpts.icons {
384 iconDef = dirStyle.icons.get(f)
385 icon = iconDef.icon + " "
386 }
387
388 // subtract space for icon
389 maxFilenameWidth := maxWidth - displaywidth.String(icon)
390 // subtract space for tag if not merged with selection marker
391 if !gOpts.mergeindicators {
392 maxFilenameWidth--
393 }
394
395 info, custom, customOff := fileInfo(f, dir, userWidth, groupWidth, customWidth)
396 infolen := len(info)
397 showInfo := infolen > 0 && 2*infolen < maxWidth
398 if showInfo {
399 maxFilenameWidth -= infolen
400 }
401
402 filename := truncateFilename(f, maxFilenameWidth, gOpts.truncatepct, gOpts.truncatechar)
403 spacing := maxFilenameWidth - displaywidth.String(filename)
404 if spacing > 0 {
405 filename += strings.Repeat(" ", spacing)
406 }
407
408 if showInfo {
409 filename += info
410 customOff += nameOff + displaywidth.String(icon) + maxFilenameWidth
411 }
412
413 if i == dir.pos {
414 var cursorFmt string
415 switch dirStyle.role {
416 case Active:
417 cursorFmt = optionToFmtstr(gOpts.cursoractivefmt)
418 case Parent:
419 cursorFmt = optionToFmtstr(gOpts.cursorparentfmt)
420 case Preview:
421 cursorFmt = optionToFmtstr(gOpts.cursorpreviewfmt)
422 }
423
424 // print tag separately as it can contain color escape sequences
425 if !gOpts.mergeindicators || fmtStr == "" {
426 win.print(ui.screen, tagOff, i, st, fmt.Sprintf(cursorFmt, tag))
427 }
428
429 win.print(ui.screen, nameOff, i, st, fmt.Sprintf(cursorFmt, icon+filename+" "))
430
431 // print over the empty space we reserved for the custom info
432 if showInfo && custom != "" {
433 win.print(ui.screen, customOff, i, st, fmt.Sprintf(cursorFmt, stripTermSequence(custom)))
434 }
435 } else {
436 if !gOpts.mergeindicators || fmtStr == "" {
437 if tag == " " {
438 win.print(ui.screen, tagOff, i, st, " ")
439 } else {
440 tagStr := fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag)
441 win.print(ui.screen, tagOff, i, tcell.StyleDefault, tagStr)
442 }
443 }
444
445 if len(icon) > 0 {
446 iconStyle := st
447 if iconDef.hasStyle {
448 iconStyle = iconDef.style
449 }
450 win.print(ui.screen, nameOff, i, iconStyle, icon)
451 }
452
453 win.print(ui.screen, nameOff+displaywidth.String(icon), i, st, filename+" ")
454
455 // print over the empty space we reserved for the custom info
456 if showInfo && custom != "" {
457 win.print(ui.screen, customOff, i, st, custom)
458 }
459 }
460 }
461 }
462
463 func getUserWidth(dir *dir, beg, end int) int {
464 maxw := 0
465
466 for _, f := range dir.files[beg:end] {
467 maxw = max(len(userName(f.FileInfo)), maxw)
468 }
469
470 return maxw
471 }
472
473 func getGroupWidth(dir *dir, beg, end int) int {
474 maxw := 0
475
476 for _, f := range dir.files[beg:end] {
477 maxw = max(len(groupName(f.FileInfo)), maxw)
478 }
479
480 return maxw
481 }
482
483 func getCustomWidth(dir *dir, beg, end int) int {
484 maxw := 0
485
486 for _, f := range dir.files[beg:end] {
487 maxw = max(printLength(f.customInfo), maxw)
488 }
489
490 return maxw
491 }
492
493 func getWins(screen tcell.Screen) []*win {
494 wtot, htot := screen.Size()
495
496 h := max(htot-2, 0)
497 x, y := 0, 1
498 if gOpts.drawbox && gOpts.borderstyle&borderOutline != 0 {
499 h = max(htot-4, 0)
500 x, y = 1, 2
501 }
502
503 widths := getWidths(wtot, gOpts.ratios, gOpts.drawbox, gOpts.borderstyle)
504 wins := make([]*win, 0, len(widths))
505 for _, w := range widths {
506 wins = append(wins, newWin(w, h, x, y))
507 x += w + 1
508 }
509
510 return wins
511 }
512
513 type menuSelect struct {
514 x, y int // selection position in menuWin (cells)
515 s string // selected entry text to draw with `menuselectfmt`
516 }
517
518 type ui struct {
519 screen tcell.Screen // primary screen used for drawing and event polling
520 sxScreen sixelScreen // sixel preview state
521 wins []*win // pane windows from `ratios` (last is `preview` when enabled)
522 promptWin *win // prompt line window
523 msgWin *win // status line window
524 menuWin *win // menu window
525 msg string // message/output shown in msgWin
526 exprChan chan expr // expr queue
527 evChan chan tcell.Event // merged event queue (keyChan + tevChan)
528 menu string // rendered (multiline) menu text (i.e. completions, binds, marks)
529 menuSelect *menuSelect // selected menu entry (completion menu only)
530 cmdPrefix string // command prefix/prompt (empty: Normal mode)
531 cmdAccLeft string // command buffer left of cursor
532 cmdAccRight string // command buffer right of cursor
533 cmdYankBuf string // yank buffer for command line editing
534 keyAcc string // keys typed so far for mapping lookup
535 keyCount string // count prefix for next command
536 styles styleMap // parsed styles
537 icons iconMap // parsed icons
538 ruler *template.Template // compiled `rulerfile`
539 rulerErr error // `rulerfile` parse error (if any)
540 currentFile string // last path passed to `on-select`
541 pasteEvent bool // whether paste event is active (to ignore pasted input in Normal mode)
542 }
543
544 func newUI(screen tcell.Screen) *ui {
545 wtot, htot := screen.Size()
546
547 ui := &ui{
548 screen: screen,
549 wins: getWins(screen),
550 promptWin: newWin(wtot, 1, 0, 0),
551 msgWin: newWin(wtot, 1, 0, htot-1),
552 menuWin: newWin(wtot, 1, 0, htot-2),
553 exprChan: make(chan expr, 1000),
554 evChan: make(chan tcell.Event, 1000),
555 styles: parseStyles(),
556 icons: parseIcons(),
557 currentFile: "",
558 sxScreen: sixelScreen{},
559 }
560 ui.ruler, ui.rulerErr = parseRuler(gOpts.rulerfile)
561
562 return ui
563 }
564
565 func (ui *ui) winAt(x, y int) (int, *win) {
566 for i, w := range slices.Backward(ui.wins) {
567 if x >= w.x && y >= w.y && y < w.y+w.h {
568 return i, w
569 }
570 }
571 return -1, nil
572 }
573
574 func (ui *ui) renew() {
575 ui.wins = getWins(ui.screen)
576
577 wtot, htot := ui.screen.Size()
578 ui.promptWin.renew(wtot, 1, 0, 0)
579 ui.msgWin.renew(wtot, 1, 0, htot-1)
580 ui.menuWin.renew(wtot, 1, 0, htot-2)
581 }
582
583 func (ui *ui) echo(msg string) {
584 ui.msg = msg
585 }
586
587 func (ui *ui) echomsg(msg string) {
588 ui.echo(sanitizeMessage(msg))
589 log.Print(msg)
590 }
591
592 func (ui *ui) echoerr(msg string) {
593 ui.echo(fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), sanitizeName(msg)))
594 log.Printf("error: %s", msg)
595 }
596
597 func (ui *ui) echoerrf(format string, a ...any) {
598 ui.echoerr(fmt.Sprintf(format, a...))
599 }
600
601 // reg represents the preview for a file.
602 // This can also be used to represent the preview of a directory if
603 // `dirpreviews` is enabled.
604 //
605 // Note: the name `reg` is historical. It originally meant "regular"
606 // file preview, but `previewer` now also supports non-regular files.
607 type reg struct {
608 loading bool
609 volatile bool
610 loadTime time.Time
611 path string
612 lines []string
613 sixel bool
614 height int
615 }
616
617 func (ui *ui) loadFile(app *app, volatile bool) {
618 if volatile {
619 app.nav.previewChan <- ""
620 }
621
622 curr := app.nav.currFile()
623 if curr == nil {
624 return
625 }
626
627 if curr.path != ui.currentFile {
628 ui.currentFile = curr.path
629 onSelect(app)
630 }
631
632 if !gOpts.preview {
633 return
634 }
635
636 if curr.isPreviewable() {
637 app.nav.loadReg(curr.path, volatile)
638 } else if curr.IsDir() {
639 dir := app.nav.getDir(curr.path)
640 app.nav.checkDir(dir)
641 }
642 }
643
644 func (ui *ui) drawPromptLine(nav *nav) {
645 st := tcell.StyleDefault
646
647 dir := nav.currDir()
648 pwd := sanitizeName(dir.path)
649
650 if after, ok := strings.CutPrefix(pwd, gUser.HomeDir); ok {
651 pwd = filepath.Join("~", after)
652 }
653
654 sep := string(filepath.Separator)
655
656 var fname string
657 if curr := nav.currFile(); curr != nil {
658 fname = sanitizeName(filepath.Base(curr.path))
659 }
660
661 var prompt string
662
663 prompt = strings.ReplaceAll(gOpts.promptfmt, "%u", gUser.Username)
664 prompt = strings.ReplaceAll(prompt, "%h", gHostname)
665 prompt = strings.ReplaceAll(prompt, "%f", fname)
666
667 if printLength(strings.ReplaceAll(strings.ReplaceAll(prompt, "%w", pwd), "%d", pwd)) > ui.promptWin.w {
668 names := strings.Split(pwd, sep)
669 for i := range names {
670 if names[i] == "" {
671 continue
672 }
673 r, _ := utf8.DecodeRuneInString(names[i])
674 names[i] = string(r)
675 if printLength(strings.ReplaceAll(strings.ReplaceAll(prompt, "%w", strings.Join(names, sep)), "%d", strings.Join(names, sep))) <= ui.promptWin.w {
676 break
677 }
678 }
679 pwd = strings.Join(names, sep)
680 }
681
682 prompt = strings.ReplaceAll(prompt, "%w", pwd)
683 if !strings.HasSuffix(pwd, sep) {
684 pwd += sep
685 }
686 prompt = strings.ReplaceAll(prompt, "%d", pwd)
687
688 if len(dir.filter) != 0 {
689 prompt = strings.ReplaceAll(prompt, "%F", fmt.Sprint(dir.filter))
690 } else {
691 prompt = strings.ReplaceAll(prompt, "%F", "")
692 }
693
694 // spacer
695 avail := ui.promptWin.w - printLength(prompt) + 2
696 if avail > 0 {
697 prompt = strings.Replace(prompt, "%S", strings.Repeat(" ", avail), 1)
698 }
699 prompt = strings.ReplaceAll(prompt, "%S", "")
700
701 ui.promptWin.print(ui.screen, 0, 0, st, prompt)
702 }
703
704 // Deprecated: Only called by drawRuler, which will eventually be replaced by drawRulerFile
705 func formatRulerOpt(name, val string) string {
706 // handle escape character so it doesn't mess up the ruler
707 val = strings.ReplaceAll(val, "\033", "\033[7m\\033\033[0m")
708
709 // display name of builtin options for clarity
710 if !strings.HasPrefix(name, "lf_user_") {
711 return strings.TrimPrefix(name, "lf_") + "=" + val
712 }
713
714 return val
715 }
716
717 // Deprecated: Will eventually be replaced by drawRulerFile
718 func (ui *ui) drawStat(nav *nav) {
719 if ui.msg != "" {
720 ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, ui.msg)
721 return
722 }
723
724 curr := nav.currFile()
725 if curr == nil {
726 return
727 }
728
729 if curr.err != nil {
730 ui.echoerrf("stat: %s", curr.err)
731 ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, ui.msg)
732 return
733 }
734
735 statfmt := strings.ReplaceAll(gOpts.statfmt, "|", "\x1f")
736 replace := func(s, val string) {
737 if val == "" {
738 val = "\x00"
739 }
740 statfmt = strings.ReplaceAll(statfmt, s, val)
741 }
742 if nav.isVisualMode() {
743 replace("%m", "VISUAL")
744 replace("%M", "VISUAL")
745 } else {
746 replace("%m", "")
747 replace("%M", "NORMAL")
748 }
749 replace("%p", permString(curr.Mode()))
750 replace("%c", linkCount(curr))
751 replace("%u", userName(curr))
752 replace("%g", groupName(curr))
753 replace("%s", humanize(curr.Size()))
754 replace("%S", fmt.Sprintf("%5s", humanize(curr.Size())))
755 replace("%t", curr.ModTime().Format(gOpts.timefmt))
756 replace("%l", sanitizeName(curr.linkTarget))
757
758 var fileInfo strings.Builder
759 for section := range strings.SplitSeq(statfmt, "\x1f") {
760 if !strings.Contains(section, "\x00") {
761 fileInfo.WriteString(section)
762 }
763 }
764
765 ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, fileInfo.String())
766 }
767
768 // Deprecated: Will eventually be replaced by drawRulerFile
769 func (ui *ui) drawRuler(nav *nav) {
770 st := tcell.StyleDefault
771
772 dir := nav.currDir()
773
774 tot := len(dir.files)
775 ind := min(dir.ind+1, tot)
776 hid := len(dir.allFiles) - tot
777 acc := ui.keyCount + ui.keyAcc
778
779 var percentage string
780 beg := max(dir.ind-dir.pos, 0)
781 switch {
782 case tot <= nav.height:
783 percentage = "All"
784 case beg == 0:
785 percentage = "Top"
786 case beg == tot-nav.height:
787 percentage = "Bot"
788 default:
789 percentage = fmt.Sprintf("%2d%%", beg*100/(tot-nav.height))
790 }
791
792 numClipCopy := 0
793 numClipMove := 0
794 if nav.clipboard.mode == clipboardCopy {
795 numClipCopy = len(nav.clipboard.paths)
796 } else {
797 numClipMove = len(nav.clipboard.paths)
798 }
799
800 numCurrSelections := len(nav.currSelections())
801 numCurrVSelections := len(nav.currDir().visualSelections())
802
803 var progress strings.Builder
804
805 if nav.copyJobs > 0 {
806 if nav.copyTotal == 0 {
807 progress.WriteString("[0%] ")
808 } else {
809 progress.WriteString("[" + strconv.FormatInt(nav.copyBytes*100/nav.copyTotal, 10) + "%] ")
810 }
811 }
812
813 if nav.moveTotal > 0 {
814 progress.WriteString("[" + strconv.Itoa(nav.moveCount) + "/" + strconv.Itoa(nav.moveTotal) + "] ")
815 }
816
817 if nav.deleteTotal > 0 {
818 progress.WriteString("[" + strconv.Itoa(nav.deleteCount) + "/" + strconv.Itoa(nav.deleteTotal) + "] ")
819 }
820
821 opts := getOptsMap()
822
823 rulerfmt := strings.ReplaceAll(gOpts.rulerfmt, "|", "\x1f")
824 rulerfmt = reRulerSub.ReplaceAllStringFunc(rulerfmt, func(s string) string {
825 empty := "\x00"
826 switch s {
827 case "%a":
828 return cmp.Or(acc, empty)
829 case "%p":
830 return cmp.Or(strings.TrimSuffix(progress.String(), " "), empty)
831 case "%m":
832 if numClipMove == 0 {
833 return empty
834 }
835 return strconv.Itoa(numClipMove)
836 case "%c":
837 if numClipCopy == 0 {
838 return empty
839 }
840 return strconv.Itoa(numClipCopy)
841 case "%s":
842 if numCurrSelections == 0 {
843 return empty
844 }
845 return strconv.Itoa(numCurrSelections)
846 case "%v":
847 if numCurrVSelections == 0 {
848 return empty
849 }
850 return strconv.Itoa(numCurrVSelections)
851 case "%f":
852 return cmp.Or(strings.Join(dir.filter, " "), empty)
853 case "%i":
854 return strconv.Itoa(ind)
855 case "%t":
856 return strconv.Itoa(tot)
857 case "%h":
858 return strconv.Itoa(hid)
859 case "%P":
860 return percentage
861 case "%d":
862 return cmp.Or(diskFree(dir.path), empty)
863 default:
864 s = strings.TrimSuffix(strings.TrimPrefix(s, "%{"), "}")
865 if val, ok := opts[s]; ok {
866 return cmp.Or(formatRulerOpt(s, val), empty)
867 }
868 return empty
869 }
870 })
871 var ruler strings.Builder
872 for section := range strings.SplitSeq(rulerfmt, "\x1f") {
873 if !strings.Contains(section, "\x00") {
874 ruler.WriteString(section)
875 }
876 }
877 ui.msgWin.printRight(ui.screen, 0, st, ruler.String())
878 }
879
880 func (ui *ui) drawRulerFile(nav *nav) {
881 if ui.rulerErr != nil {
882 err := fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), sanitizeName(fmt.Sprintf("parsing ruler: %s", ui.rulerErr)))
883 ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, err)
884 return
885 }
886
887 var stat *statData
888 curr := nav.currFile()
889 if curr != nil {
890 if curr.err == nil {
891 stat = &statData{
892 Path: sanitizeName(curr.path),
893 Name: sanitizeName(curr.Name()),
894 Extension: sanitizeName(curr.ext),
895 Size: curr.Size(),
896 DirSize: curr.dirSize,
897 DirCount: curr.dirCount,
898 Permissions: permString(curr.Mode()),
899 ModTime: curr.ModTime().Format(gOpts.timefmt),
900 AccessTime: curr.accessTime.Format(gOpts.timefmt),
901 BirthTime: curr.birthTime.Format(gOpts.timefmt),
902 ChangeTime: curr.changeTime.Format(gOpts.timefmt),
903 LinkCount: linkCount(curr),
904 User: userName(curr),
905 Group: groupName(curr),
906 Target: sanitizeName(curr.linkTarget),
907 CustomInfo: curr.customInfo,
908 }
909 } else {
910 ui.echoerrf("stat: %s", curr.err)
911 }
912 }
913
914 dir := nav.currDir()
915 tot := len(dir.files)
916 ind := min(dir.ind+1, tot)
917 all := len(dir.allFiles)
918 hid := all - tot
919
920 var linePercentage string
921 if tot == 0 {
922 linePercentage = "100%"
923 } else {
924 linePercentage = fmt.Sprintf("%d%%", ind*100/tot)
925 }
926
927 var scrollPercentage string
928 beg := max(dir.ind-dir.pos, 0)
929 switch {
930 case tot <= nav.height:
931 scrollPercentage = "All"
932 case beg == 0:
933 scrollPercentage = "Top"
934 case beg == tot-nav.height:
935 scrollPercentage = "Bot"
936 default:
937 scrollPercentage = fmt.Sprintf("%2d%%", beg*100/(tot-nav.height))
938 }
939
940 var copiedPaths []string
941 var cutPaths []string
942 if nav.clipboard.mode == clipboardCopy {
943 copiedPaths = nav.clipboard.paths
944 } else {
945 cutPaths = nav.clipboard.paths
946 }
947
948 currSelections := nav.currSelections()
949 currVSelections := nav.currDir().visualSelections()
950
951 progress := []string{}
952
953 if nav.copyJobs > 0 {
954 if nav.copyTotal == 0 {
955 progress = append(progress, fmt.Sprintf("[0%%]"))
956 } else {
957 progress = append(progress, fmt.Sprintf("[%d%%]", nav.copyBytes*100/nav.copyTotal))
958 }
959 }
960
961 if nav.moveTotal > 0 {
962 progress = append(progress, fmt.Sprintf("[%d/%d]", nav.moveCount, nav.moveTotal))
963 }
964
965 if nav.deleteTotal > 0 {
966 progress = append(progress, fmt.Sprintf("[%d/%d]", nav.deleteCount, nav.deleteTotal))
967 }
968
969 mode := "NORMAL"
970 if nav.isVisualMode() {
971 mode = "VISUAL"
972 }
973
974 v := reflect.ValueOf(gOpts)
975 t := v.Type()
976 options := make(map[string]string, v.NumField())
977 for i := range v.NumField() {
978 name := t.Field(i).Name
979 switch name {
980 case "nkeys", "vkeys", "cmdkeys", "cmds", "user":
981 continue
982 default:
983 options[name] = fieldToString(v.Field(i))
984 }
985 }
986
987 data := rulerData{
988 SPACER: "\x1f",
989 Message: ui.msg,
990 Keys: ui.keyCount + ui.keyAcc,
991 Progress: progress,
992 Copy: copiedPaths,
993 Cut: cutPaths,
994 Select: currSelections,
995 Visual: currVSelections,
996 Index: ind,
997 Total: tot,
998 Hidden: hid,
999 All: all,
1000 LinePercentage: linePercentage,
1001 ScrollPercentage: scrollPercentage,
1002 Filter: dir.filter,
1003 Mode: mode,
1004 Options: options,
1005 UserOptions: gOpts.user,
1006 Stat: stat,
1007 }
1008
1009 left, right, err := renderRuler(ui.ruler, data, ui.msgWin.w)
1010 if err != nil {
1011 err := fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), sanitizeName(fmt.Sprintf("rendering ruler: %s", err)))
1012 ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, err)
1013 return
1014 }
1015
1016 ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, left)
1017 ui.msgWin.printRight(ui.screen, 0, tcell.StyleDefault, right)
1018 }
1019
1020 func (ui *ui) drawPreview(nav *nav, context *dirContext) {
1021 curr := nav.currFile()
1022 if curr == nil {
1023 return
1024 }
1025
1026 win := ui.wins[len(ui.wins)-1]
1027 ui.sxScreen.clearSixel(win, ui.screen, curr.path)
1028
1029 if gOpts.preview {
1030 if curr.isPreviewable() {
1031 reg, ok := nav.regCache[curr.path]
1032 if !ok {
1033 // the shown file can lose its cache entry, e.g. a save that deletes and recreates it
1034 reg = nav.loadReg(curr.path, false)
1035 }
1036 win.printReg(ui.screen, reg, &ui.sxScreen, nav.previewTimer)
1037 } else if curr.IsDir() {
1038 ui.sxScreen.lastFile = ""
1039 dir := nav.getDir(curr.path)
1040 dirStyle := &dirStyle{colors: ui.styles, icons: ui.icons, role: Preview}
1041 win.printDir(ui, dir, context, dirStyle, nav.previewTimer)
1042 }
1043 }
1044 }
1045
1046 func (ui *ui) drawBox() {
1047 st := parseEscapeSequence(gOpts.borderfmt)
1048
1049 w, h := ui.screen.Size()
1050 style := gOpts.borderstyle
1051
1052 if style&borderOutline != 0 {
1053 for i := 1; i < w-1; i++ {
1054 ui.screen.PutStrStyled(i, 1, string(tcell.RuneHLine), st)
1055 ui.screen.PutStrStyled(i, h-2, string(tcell.RuneHLine), st)
1056 }
1057
1058 for i := 2; i < h-2; i++ {
1059 ui.screen.PutStrStyled(0, i, string(tcell.RuneVLine), st)
1060 ui.screen.PutStrStyled(w-1, i, string(tcell.RuneVLine), st)
1061 }
1062
1063 if style&borderRound != 0 {
1064 ui.screen.PutStrStyled(0, 1, "╭", st)
1065 ui.screen.PutStrStyled(w-1, 1, "╮", st)
1066 ui.screen.PutStrStyled(0, h-2, "╰", st)
1067 ui.screen.PutStrStyled(w-1, h-2, "╯", st)
1068 } else {
1069 ui.screen.PutStrStyled(0, 1, string(tcell.RuneULCorner), st)
1070 ui.screen.PutStrStyled(w-1, 1, string(tcell.RuneURCorner), st)
1071 ui.screen.PutStrStyled(0, h-2, string(tcell.RuneLLCorner), st)
1072 ui.screen.PutStrStyled(w-1, h-2, string(tcell.RuneLRCorner), st)
1073 }
1074 }
1075
1076 if style&borderSeparators == 0 {
1077 return
1078 }
1079
1080 top, bot := 1, h-1
1081 if style&borderOutline != 0 {
1082 top, bot = 2, h-2
1083 }
1084
1085 for wind := range len(ui.wins) - 1 {
1086 x := ui.wins[wind].x + ui.wins[wind].w
1087 if style&borderOutline != 0 {
1088 ui.screen.PutStrStyled(x, 1, string(tcell.RuneTTee), st)
1089 }
1090 for y := top; y < bot; y++ {
1091 ui.screen.PutStrStyled(x, y, string(tcell.RuneVLine), st)
1092 }
1093 if style&borderOutline != 0 {
1094 ui.screen.PutStrStyled(x, h-2, string(tcell.RuneBTee), st)
1095 }
1096 }
1097 }
1098
1099 func (ui *ui) drawMenu() {
1100 if ui.menu == "" {
1101 return
1102 }
1103
1104 lines := strings.Split(ui.menu, "\n")
1105 lines = lines[:len(lines)-1]
1106
1107 ui.menuWin.h = len(lines)
1108 ui.menuWin.y = ui.msgWin.y - ui.menuWin.h
1109
1110 // clear sixel image if it overlaps with the menu
1111 ui.screen.LockRegion(ui.menuWin.x, ui.menuWin.y, ui.menuWin.w, ui.menuWin.h, false)
1112 ui.sxScreen.forceClear = true
1113
1114 for i, line := range lines {
1115 var st tcell.Style
1116 if i == 0 {
1117 st = parseEscapeSequence(gOpts.menuheaderfmt)
1118 } else {
1119 st = parseEscapeSequence(gOpts.menufmt)
1120 }
1121
1122 ui.menuWin.printLine(ui.screen, 0, i, st, line)
1123 }
1124
1125 if ui.menuSelect != nil {
1126 st := parseEscapeSequence(gOpts.menuselectfmt)
1127 ui.menuWin.print(ui.screen, ui.menuSelect.x, ui.menuSelect.y, st, ui.menuSelect.s)
1128 }
1129 }
1130
1131 func (ui *ui) dirOfWin(nav *nav, wind int) *dir {
1132 wins := len(ui.wins)
1133 if gOpts.preview {
1134 wins--
1135 }
1136 ind := len(nav.dirPaths) - wins + wind
1137 if ind < 0 {
1138 return nil
1139 }
1140 return nav.getDir(nav.dirPaths[ind])
1141 }
1142
1143 func (ui *ui) draw(nav *nav) {
1144 st := tcell.StyleDefault
1145 context := dirContext{selections: nav.selections, clipboard: nav.clipboard, tags: nav.tags}
1146
1147 ui.screen.Clear()
1148
1149 ui.drawPromptLine(nav)
1150
1151 wins := len(ui.wins)
1152 if gOpts.preview {
1153 wins--
1154 }
1155 for i := range wins {
1156 role := Parent
1157 if i == wins-1 {
1158 role = Active
1159 }
1160 if dir := ui.dirOfWin(nav, i); dir != nil {
1161 dirStyle := &dirStyle{colors: ui.styles, icons: ui.icons, role: role}
1162 ui.wins[i].printDir(ui, dir, &context, dirStyle, nav.previewTimer)
1163 }
1164 }
1165
1166 // sanitize cmd-line buffers at render time
1167 cmdPrefix := sanitizeName(ui.cmdPrefix)
1168 cmdAccLeft := sanitizeName(ui.cmdAccLeft)
1169 cmdAccRight := sanitizeName(ui.cmdAccRight)
1170
1171 switch ui.cmdPrefix {
1172 case "":
1173 if gOpts.rulerfmt == "" {
1174 ui.drawRulerFile(nav)
1175 } else {
1176 ui.drawStat(nav)
1177 ui.drawRuler(nav)
1178 }
1179 ui.screen.HideCursor()
1180 case ">":
1181 maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end
1182 prefix := truncateRight(cmdPrefix, maxWidth)
1183 left := truncateLeft(cmdAccLeft, maxWidth-displaywidth.String(prefix)-printLength(ui.msg))
1184 ui.msgWin.printLine(ui.screen, 0, 0, st, prefix+ui.msg)
1185 ui.msgWin.print(ui.screen, displaywidth.String(prefix)+printLength(ui.msg), 0, st, left+cmdAccRight)
1186 ui.screen.ShowCursor(ui.msgWin.x+displaywidth.String(prefix)+printLength(ui.msg)+displaywidth.String(left), ui.msgWin.y)
1187 default:
1188 maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end
1189 prefix := truncateRight(cmdPrefix, maxWidth)
1190 left := truncateLeft(cmdAccLeft, maxWidth-displaywidth.String(prefix))
1191 ui.msgWin.printLine(ui.screen, 0, 0, st, prefix+left+cmdAccRight)
1192 ui.screen.ShowCursor(ui.msgWin.x+displaywidth.String(prefix)+displaywidth.String(left), ui.msgWin.y)
1193 }
1194
1195 ui.drawPreview(nav, &context)
1196
1197 if gOpts.drawbox {
1198 ui.drawBox()
1199 }
1200
1201 ui.drawMenu()
1202
1203 ui.screen.Show()
1204 }
1205
1206 func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, exact bool) {
1207 binds = make(map[string]expr)
1208 for key, expr := range keys {
1209 if !strings.HasPrefix(key, prefix) {
1210 continue
1211 }
1212 binds[key] = expr
1213 if key == prefix {
1214 exact = true
1215 }
1216 }
1217 return binds, exact
1218 }
1219
1220 func listBinds(binds map[string]map[string]expr) string {
1221 t := new(tabwriter.Writer)
1222 b := new(bytes.Buffer)
1223
1224 // merge keys by command across modes
1225 m := make(map[string]map[string]string)
1226 for mode, keys := range binds {
1227 for key, expr := range keys {
1228 if _, ok := m[key]; !ok {
1229 m[key] = make(map[string]string)
1230 }
1231 m[key][expr.String()] += mode
1232 }
1233 }
1234
1235 type entry struct {
1236 mode, key, cmd string
1237 }
1238
1239 // collect normalized entries
1240 var entries []entry
1241 for key, cmds := range m {
1242 for cmd, modes := range cmds {
1243 tmp := []rune(modes)
1244 slices.Sort(tmp)
1245 entries = append(entries, entry{string(tmp), key, cmd})
1246 }
1247 }
1248
1249 slices.SortFunc(entries, func(a, b entry) int {
1250 if c := cmp.Compare(a.key, b.key); c != 0 {
1251 return c
1252 }
1253 return cmp.Compare(a.mode, b.mode)
1254 })
1255
1256 t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
1257 fmt.Fprintln(t, "mode\tkey\tcommand")
1258 for _, e := range entries {
1259 fmt.Fprintf(t, "%s\t%s\t%s\n", e.mode, e.key, e.cmd)
1260 }
1261 t.Flush()
1262
1263 return b.String()
1264 }
1265
1266 func listMatchingBinds(binds map[string]expr, prefix string) string {
1267 t := new(tabwriter.Writer)
1268 b := new(bytes.Buffer)
1269
1270 t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
1271 fmt.Fprintln(t, "key\tcommand")
1272 for _, k := range slices.Sorted(maps.Keys(binds)) {
1273 remain, _ := strings.CutPrefix(k, prefix)
1274 fmt.Fprintf(t, "%s\t%v\n", sanitizeName(remain), binds[k])
1275 }
1276 t.Flush()
1277
1278 return b.String()
1279 }
1280
1281 func listCmds(cmds map[string]expr) string {
1282 t := new(tabwriter.Writer)
1283 b := new(bytes.Buffer)
1284
1285 t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
1286 fmt.Fprintln(t, "name\tcommand")
1287 for _, k := range slices.Sorted(maps.Keys(cmds)) {
1288 fmt.Fprintf(t, "%s\t%v\n", k, cmds[k])
1289 }
1290 t.Flush()
1291
1292 return b.String()
1293 }
1294
1295 func listJumps(jumps []string, ind int) string {
1296 t := new(tabwriter.Writer)
1297 b := new(bytes.Buffer)
1298
1299 maxlength := len(strconv.Itoa(max(ind, len(jumps)-1-ind)))
1300
1301 t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
1302 fmt.Fprintln(t, " jump\tpath")
1303 // print jumps in order of most recent, Vim uses the opposite order
1304 for i, path := range slices.Backward(jumps) {
1305 switch {
1306 case i < ind:
1307 fmt.Fprintf(t, " %*d\t%s\n", maxlength, ind-i, path)
1308 case i > ind:
1309 fmt.Fprintf(t, " %*d\t%s\n", maxlength, i-ind, path)
1310 default:
1311 fmt.Fprintf(t, "> %*d\t%s\n", maxlength, 0, path)
1312 }
1313 }
1314 t.Flush()
1315
1316 return b.String()
1317 }
1318
1319 func listHistory(history []string) string {
1320 t := new(tabwriter.Writer)
1321 b := new(bytes.Buffer)
1322
1323 maxlength := len(strconv.Itoa(len(history)))
1324
1325 t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
1326 fmt.Fprintln(t, "number\tcommand")
1327 for i, cmd := range history {
1328 fmt.Fprintf(t, "%*d\t%s\n", maxlength, i+1, cmd)
1329 }
1330 t.Flush()
1331
1332 return b.String()
1333 }
1334
1335 func listMarks(marks map[string]string) string {
1336 t := new(tabwriter.Writer)
1337 b := new(bytes.Buffer)
1338
1339 t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
1340 fmt.Fprintln(t, "mark\tpath")
1341 for _, k := range slices.Sorted(maps.Keys(marks)) {
1342 fmt.Fprintf(t, "%s\t%s\n", sanitizeName(k), sanitizeName(marks[k]))
1343 }
1344 t.Flush()
1345
1346 return b.String()
1347 }
1348
1349 func listFilesInCurrDir(nav *nav) string {
1350 dir := nav.currDir()
1351 if dir.loading {
1352 log.Printf("listFilesInCurrDir(): %s is still loading, `files` isn't ready for remote query", dir.path)
1353 return ""
1354 }
1355
1356 b := new(strings.Builder)
1357 for _, file := range dir.files {
1358 if strings.ContainsAny(file.path, "\n\r") {
1359 continue
1360 }
1361 fmt.Fprintln(b, file.path)
1362 }
1363
1364 return b.String()
1365 }
1366
1367 // readNormalEvent is used to read a normal event on the client side. For keys,
1368 // digits are interpreted as command counts but this is only done for digits
1369 // preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k").
1370 func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
1371 draw := &callExpr{"draw", nil, 1}
1372
1373 keys := gOpts.nkeys
1374 if nav.isVisualMode() {
1375 keys = gOpts.vkeys
1376 }
1377
1378 switch tev := ev.(type) {
1379 case *tcell.EventKey:
1380 if ui.pasteEvent {
1381 return nil
1382 }
1383
1384 isDigitKey := func(*tcell.EventKey) bool {
1385 if tev.Key() != tcell.KeyRune || tev.Modifiers() != tcell.ModNone {
1386 return false
1387 }
1388
1389 s := tev.Str()
1390 return len(s) == 1 && s[0] >= '0' && s[0] <= '9'
1391 }
1392
1393 switch {
1394 case tev.Key() == tcell.KeyEsc && ui.keyAcc != "":
1395 ui.keyAcc = ""
1396 ui.keyCount = ""
1397 ui.menu = ""
1398 return draw
1399 case isDigitKey(tev) && ui.keyAcc == "":
1400 ui.keyCount += tev.Str()
1401 return draw
1402 default:
1403 ui.keyAcc += readKey(tev)
1404 }
1405
1406 binds, exact := findBinds(keys, ui.keyAcc)
1407 if len(binds) == 0 {
1408 ui.echoerrf("unknown mapping: %s", ui.keyAcc)
1409 ui.keyAcc = ""
1410 ui.keyCount = ""
1411 ui.menu = ""
1412 return draw
1413 }
1414 if !exact {
1415 if gOpts.showbinds {
1416 // mode and already typed keys are obvious here; no need to clutter the menu
1417 ui.menu = listMatchingBinds(binds, ui.keyAcc)
1418 }
1419 return draw
1420 }
1421
1422 expr := keys[ui.keyAcc]
1423 if ui.keyCount != "" {
1424 if count, err := strconv.Atoi(ui.keyCount); err != nil {
1425 log.Printf("converting command count: %s", err)
1426 } else if count > 0 {
1427 switch e := expr.(type) {
1428 case *callExpr:
1429 expr = &callExpr{name: e.name, args: e.args, count: count}
1430 case *listExpr:
1431 expr = &listExpr{exprs: e.exprs, count: count}
1432 }
1433 }
1434 }
1435
1436 ui.keyAcc = ""
1437 ui.keyCount = ""
1438 ui.menu = ""
1439 return expr
1440
1441 case *tcell.EventMouse:
1442 if ui.cmdPrefix != "" {
1443 return nil
1444 }
1445
1446 var button string
1447
1448 switch tev.Buttons() {
1449 case tcell.Button1:
1450 button = "<m-1>"
1451 case tcell.Button2:
1452 button = "<m-2>"
1453 case tcell.Button3:
1454 button = "<m-3>"
1455 case tcell.Button4:
1456 button = "<m-4>"
1457 case tcell.Button5:
1458 button = "<m-5>"
1459 case tcell.Button6:
1460 button = "<m-6>"
1461 case tcell.Button7:
1462 button = "<m-7>"
1463 case tcell.Button8:
1464 button = "<m-8>"
1465 case tcell.WheelUp:
1466 button = "<m-up>"
1467 case tcell.WheelDown:
1468 button = "<m-down>"
1469 case tcell.WheelLeft:
1470 button = "<m-left>"
1471 case tcell.WheelRight:
1472 button = "<m-right>"
1473 case tcell.ButtonNone:
1474 return nil
1475 }
1476 if tev.Modifiers() == tcell.ModCtrl {
1477 button = "<c-" + button[1:]
1478 }
1479 if expr, ok := keys[button]; ok {
1480 return expr
1481 }
1482 if button != "<m-1>" && button != "<m-2>" {
1483 ui.echoerrf("unknown mapping: %s", button)
1484 ui.keyAcc = ""
1485 ui.keyCount = ""
1486 ui.menu = ""
1487 return draw
1488 }
1489
1490 x, y := tev.Position()
1491 wind, w := ui.winAt(x, y)
1492 if wind == -1 {
1493 return nil
1494 }
1495
1496 var dir *dir
1497 if gOpts.preview && wind == len(ui.wins)-1 {
1498 curr := nav.currFile()
1499 if curr == nil {
1500 return nil
1501 } else if !curr.IsDir() || gOpts.dirpreviews {
1502 if tev.Buttons() != tcell.Button2 {
1503 return nil
1504 }
1505 return &callExpr{"open", nil, 1}
1506 }
1507
1508 dir = nav.getDir(curr.path)
1509 } else {
1510 dir = ui.dirOfWin(nav, wind)
1511 if dir == nil {
1512 return nil
1513 }
1514 }
1515
1516 var file *file
1517 ind := dir.ind - dir.pos + y - w.y
1518 if ind < len(dir.files) {
1519 file = dir.files[ind]
1520 }
1521
1522 if file != nil {
1523 sel := &callExpr{"select", []string{file.path}, 1}
1524
1525 if tev.Buttons() == tcell.Button1 {
1526 return sel
1527 }
1528 if file.IsDir() {
1529 return &callExpr{"cd", []string{file.path}, 1}
1530 }
1531 return &listExpr{[]expr{sel, &callExpr{"open", nil, 1}}, 1}
1532 }
1533 if tev.Buttons() == tcell.Button1 {
1534 return &callExpr{"cd", []string{dir.path}, 1}
1535 }
1536 case *tcell.EventResize:
1537 return &callExpr{"redraw", nil, 1}
1538 case *tcell.EventError:
1539 log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When())
1540 case *tcell.EventInterrupt:
1541 log.Printf("Got EventInterrupt: at %s", tev.When())
1542 case *tcell.EventFocus:
1543 if tev.Focused {
1544 return &callExpr{"on-focus-gained", nil, 1}
1545 } else {
1546 return &callExpr{"on-focus-lost", nil, 1}
1547 }
1548 case *tcell.EventPaste:
1549 if tev.Start() {
1550 ui.pasteEvent = true
1551 } else if tev.End() {
1552 ui.pasteEvent = false
1553 }
1554 }
1555 return nil
1556 }
1557
1558 func readCmdEvent(ev tcell.Event) expr {
1559 if tev, ok := ev.(*tcell.EventKey); ok {
1560 if tev.Key() == tcell.KeyRune && tev.Modifiers()&tcell.ModAlt == 0 {
1561 return &callExpr{"cmd-insert", []string{tev.Str()}, 1}
1562 }
1563
1564 if expr, ok := gOpts.cmdkeys[readKey(tev)]; ok {
1565 return expr
1566 }
1567 }
1568 return nil
1569 }
1570
1571 func (ui *ui) readEvent(ev tcell.Event, nav *nav) expr {
1572 if ev == nil {
1573 return nil
1574 }
1575
1576 if _, ok := ev.(*tcell.EventKey); ok && ui.cmdPrefix != "" {
1577 return readCmdEvent(ev)
1578 }
1579
1580 return ui.readNormalEvent(ev, nav)
1581 }
1582
1583 func (ui *ui) readEvents() {
1584 for ev := range ui.screen.EventQ() {
1585 ui.evChan <- ev
1586 }
1587 }
1588
1589 func (ui *ui) suspend() error {
1590 ui.sxScreen.forceClear = true
1591 return ui.screen.Suspend()
1592 }
1593
1594 func (ui *ui) resume() error {
1595 return ui.screen.Resume()
1596 }
1597
1598 func (ui *ui) exportSizes() {
1599 w, h := ui.screen.Size()
1600 os.Setenv("lf_width", strconv.Itoa(w))
1601 os.Setenv("lf_height", strconv.Itoa(h))
1602 }
1603
1604 func anyKey() {
1605 fmt.Fprint(os.Stderr, gOpts.waitmsg)
1606 defer fmt.Fprintln(os.Stderr)
1607 oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
1608 if err != nil {
1609 panic(err)
1610 }
1611 defer func() {
1612 if err := term.Restore(int(os.Stdin.Fd()), oldState); err != nil {
1613 panic(err)
1614 }
1615 }()
1616
1617 b := make([]byte, 8)
1618 if _, err := os.Stdin.Read(b); err != nil {
1619 log.Printf("Failed to read key press: %s", err)
1620 }
1621 }
1622
1623 func listMatches(screen tcell.Screen, matches []compMatch, selectedInd int) (string, *menuSelect) {
1624 if len(matches) < 2 {
1625 return "", nil
1626 }
1627
1628 names := make([]string, len(matches))
1629 for i, m := range matches {
1630 names[i] = sanitizeName(m.name)
1631 }
1632
1633 wtot, _ := screen.Size()
1634 wcol := 0
1635 for _, n := range names {
1636 wcol = max(wcol, printLength(n))
1637 }
1638 wcol += gOpts.tabstop - wcol%gOpts.tabstop
1639 ncol := max(wtot/wcol, 1)
1640
1641 var b strings.Builder
1642 b.WriteString("possible matches")
1643
1644 for i, n := range names {
1645 if i%ncol == 0 {
1646 b.WriteByte('\n')
1647 }
1648 w := printLength(n)
1649 fmt.Fprintf(&b, "%s%*s", n, wcol-w, "")
1650 }
1651
1652 b.WriteByte('\n')
1653
1654 var selection *menuSelect
1655 if selectedInd != -1 {
1656 selection = &menuSelect{selectedInd % ncol * wcol, selectedInd/ncol + 1, names[selectedInd]}
1657 }
1658
1659 return b.String(), selection
1660 }