From 24f01f4988cfd96364a135c33bfeb9672a32794d Mon Sep 17 00:00:00 2001 From: Provessor <26803851+Provessor@users.noreply.github.com> Date: Tue, 1 Sep 2020 22:42:44 +1000 Subject: [PATCH] Replace termbox-go with tcell (#439) Fix colour construction issue This also has a test to mitigate it in the future Remove `colormode` option The original issue it was trying to solve is no longer present with tcell (it being a holdover from `color256` on termbox) so it is not needed. retire gitter channel in favor of irc/matrix Export options as environment variables (#448) * Export options as environment variables Any options from gOpts are available via lf_OPTION environment variables. For now it works only on booleans, integers and strings (no array support) * Do not export some of the options * Add support for arrays and fix numbers * Fix comments * Replace 1 and 0 with true and false * Export hidden,reverse,dirfirst and sortby options * Fix comments * Little fix * Simplify boolean conversion log readlink errors instead of fail Related #447 and #374 --- app.go | 6 +- client.go | 16 +- colors.go | 191 ++++++++++----------- colors_test.go | 98 ++++++----- complete.go | 3 - doc.go | 35 ++-- docstring.go | 31 ++-- eval.go | 21 +-- go.mod | 2 +- go.sum | 8 +- lf.1 | 7 +- main.go | 1 + opts.go | 2 - os.go | 13 +- os_windows.go | 5 + ui.go | 457 +++++++++++++++++++++++++++---------------------- 16 files changed, 477 insertions(+), 419 deletions(-) diff --git a/app.go b/app.go index 410ebaf2..06333752 100644 --- a/app.go +++ b/app.go @@ -14,6 +14,8 @@ import ( "strings" "syscall" "time" + + "github.com/gdamore/tcell" ) type cmdItem struct { @@ -34,8 +36,8 @@ type app struct { cmdHistoryInd int } -func newApp() *app { - ui := newUI() +func newApp(screen tcell.Screen) *app { + ui := newUI(screen) nav := newNav(ui.wins[0].h) quitChan := make(chan bool, 1) diff --git a/client.go b/client.go index 1c580bb9..1cdbd839 100644 --- a/client.go +++ b/client.go @@ -10,16 +10,17 @@ import ( "strings" "time" - "github.com/doronbehar/termbox-go" + "github.com/gdamore/tcell" ) func run() { - if err := termbox.Init(); err != nil { - log.Fatalf("initializing termbox: %s", err) + var screen tcell.Screen + var err error + if screen, err = tcell.NewScreen(); err != nil { + log.Fatalf("creating screen: %s", err) + } else if err = screen.Init(); err != nil { + log.Fatalf("initializing screen: %s", err) } - defer termbox.Close() - - setColorMode() f, err := os.Create(gLogPath) if err != nil { @@ -31,7 +32,7 @@ func run() { log.Print("hi!") - app := newApp() + app := newApp(screen) if err := app.nav.readMarks(); err != nil { app.ui.echoerrf("reading marks file: %s", err) @@ -42,6 +43,7 @@ func run() { } app.loop() + app.ui.screen.Fini() } func readExpr() <-chan expr { diff --git a/colors.go b/colors.go index 9d3ac83b..1c13457c 100644 --- a/colors.go +++ b/colors.go @@ -7,48 +7,18 @@ import ( "strconv" "strings" - "github.com/doronbehar/termbox-go" + "github.com/gdamore/tcell" ) -const gAnsiColorResetMask = termbox.AttrBold | termbox.AttrUnderline | termbox.AttrReverse +type styleMap map[string]tcell.Style -var gAnsiCodes = map[int]termbox.Attribute{ - 0: termbox.ColorDefault, - 1: termbox.AttrBold, - 4: termbox.AttrUnderline, - 7: termbox.AttrReverse, - 30: termbox.ColorBlack, - 31: termbox.ColorRed, - 32: termbox.ColorGreen, - 33: termbox.ColorYellow, - 34: termbox.ColorBlue, - 35: termbox.ColorMagenta, - 36: termbox.ColorCyan, - 37: termbox.ColorWhite, - 40: termbox.ColorBlack, - 41: termbox.ColorRed, - 42: termbox.ColorGreen, - 43: termbox.ColorYellow, - 44: termbox.ColorBlue, - 45: termbox.ColorMagenta, - 46: termbox.ColorCyan, - 47: termbox.ColorWhite, -} - -type colorEntry struct { - fg termbox.Attribute - bg termbox.Attribute -} - -type colorMap map[string]colorEntry - -func parseColors() colorMap { +func parseStyles() styleMap { if env := os.Getenv("LS_COLORS"); env != "" { - return parseColorsGNU(env) + return parseStylesGNU(env) } if env := os.Getenv("LSCOLORS"); env != "" { - return parseColorsBSD(env) + return parseStylesBSD(env) } // default values from dircolors with removed background colors @@ -73,10 +43,10 @@ func parseColors() colorMap { "ex=01;32", } - return parseColorsGNU(strings.Join(defaultColors, ":")) + return parseStylesGNU(strings.Join(defaultColors, ":")) } -func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, termbox.Attribute) { +func applyAnsiCodes(s string, st tcell.Style) tcell.Style { toks := strings.Split(s, ";") var nums []int @@ -93,43 +63,63 @@ func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, term nums = append(nums, n) } + // ECMA-48 details the standard for i := 0; i < len(nums); i++ { n := nums[i] switch { - case n == 38 && i+2 < len(nums) && nums[i+1] == 5: - fg &= gAnsiColorResetMask - fg |= termbox.Attribute(nums[i+2] + 1) - i += 2 - continue - case n == 48 && i+2 < len(nums) && nums[i+1] == 5: - bg = termbox.Attribute(nums[i+2] + 1) - i += 2 - continue - } - attr, ok := gAnsiCodes[n] - if !ok { - log.Printf("unknown ansi code: %d", n) - continue - } - switch { case n == 0: - fg, bg = attr, attr - case n == 1 || n == 4 || n == 7: - fg |= attr - case 30 <= n && n <= 37: - fg &= gAnsiColorResetMask - fg |= attr - case 40 <= n && n <= 47: - bg = attr + st = tcell.StyleDefault + case n == 1: + st = st.Bold(true) + case n == 2: + st = st.Dim(true) + case n == 4: + st = st.Underline(true) + case n == 5 || n == 6: + st = st.Blink(true) + case n == 7: + st = st.Reverse(true) + case n >= 30 && n <= 37: + st = st.Foreground(tcell.Color(n - 30)) + case n == 38: + if i+3 <= len(nums) && nums[i+1] == 5 { + st = st.Foreground(tcell.Color(nums[i+2])) + i += 2 + } else if i+5 <= len(nums) && nums[i+1] == 2 { + st = st.Foreground(tcell.NewRGBColor( + int32(nums[i+2]), + int32(nums[i+3]), + int32(nums[i+4]))) + i += 4 + } else { + log.Printf("unknown ansi code or incorrect form: %d", n) + } + case n >= 40 && n <= 47: + st = st.Background(tcell.Color(n - 40)) + case n == 48: + if i+3 <= len(nums) && nums[i+1] == 5 { + st = st.Background(tcell.Color(nums[i+2])) + i += 2 + } else if i+5 <= len(nums) && nums[i+1] == 2 { + st = st.Background(tcell.NewRGBColor( + int32(nums[i+2]), + int32(nums[i+3]), + int32(nums[i+4]))) + i += 4 + } else { + log.Printf("unknown ansi code or incorrect form: %d", n) + } + default: + log.Printf("unknown ansi code: %d", n) } } - return fg, bg + return st } // This function parses $LS_COLORS environment variable. -func parseColorsGNU(env string) colorMap { - colors := make(colorMap) +func parseStylesGNU(env string) styleMap { + styles := make(styleMap) entries := strings.Split(env, ":") for _, entry := range entries { @@ -139,63 +129,62 @@ func parseColorsGNU(env string) colorMap { pair := strings.Split(entry, "=") if len(pair) != 2 { log.Printf("invalid $LS_COLORS entry: %s", entry) - return colors + return styles } key, val := pair[0], pair[1] - fg, bg := applyAnsiCodes(val, termbox.ColorDefault, termbox.ColorDefault) - colors[key] = colorEntry{fg: fg, bg: bg} + styles[key] = applyAnsiCodes(val, tcell.StyleDefault) } - return colors + return styles } // This function parses $LSCOLORS environment variable. -func parseColorsBSD(env string) colorMap { - colors := make(colorMap) +func parseStylesBSD(env string) styleMap { + styles := make(styleMap) if len(env) != 22 { log.Printf("invalid $LSCOLORS variable: %s", env) - return colors + return styles } colorNames := []string{"di", "ln", "so", "pi", "ex", "bd", "cd", "su", "sg", "tw", "ow"} - colorCodes := map[byte]termbox.Attribute{ - 'a': termbox.ColorBlack, - 'b': termbox.ColorRed, - 'c': termbox.ColorGreen, - 'd': termbox.ColorYellow, // brown - 'e': termbox.ColorBlue, - 'f': termbox.ColorMagenta, - 'g': termbox.ColorCyan, - 'h': termbox.ColorWhite, // light grey - 'A': termbox.AttrBold | termbox.ColorBlack, - 'B': termbox.AttrBold | termbox.ColorRed, - 'C': termbox.AttrBold | termbox.ColorGreen, - 'D': termbox.AttrBold | termbox.ColorYellow, // brown - 'E': termbox.AttrBold | termbox.ColorBlue, - 'F': termbox.AttrBold | termbox.ColorMagenta, - 'G': termbox.AttrBold | termbox.ColorCyan, - 'H': termbox.AttrBold | termbox.ColorWhite, // light grey - 'x': termbox.ColorDefault, - } - getColor := func(r byte) termbox.Attribute { - if color, ok := colorCodes[r]; ok { - return color + getStyle := func(r1, r2 byte) tcell.Style { + st := tcell.StyleDefault + + switch { + case r1 == 'x': + st = st.Foreground(tcell.ColorDefault) + case 'A' <= r1 && r1 <= 'H': + st = st.Foreground(tcell.Color(r1 - 'A')).Bold(true) + case 'a' <= r1 && r1 <= 'h': + st = st.Foreground(tcell.Color(r1 - 'a')) + default: + log.Printf("invalid $LSCOLORS entry: %c", r1) + return tcell.StyleDefault } - log.Printf("invalid $LSCOLORS entry: %c", r) - return termbox.ColorDefault + switch { + case r2 == 'x': + st = st.Background(tcell.ColorDefault) + case 'a' <= r2 && r2 <= 'h': + st = st.Background(tcell.Color(r2 - 'a')) + default: + log.Printf("invalid $LSCOLORS entry: %c", r2) + return tcell.StyleDefault + } + + return st } for i, key := range colorNames { - colors[key] = colorEntry{fg: getColor(env[i*2]), bg: getColor(env[i*2+1])} + styles[key] = getStyle(env[i*2], env[i*2+1]) } - return colors + return styles } -func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) { +func (cm styleMap) get(f *file) tcell.Style { var key string switch { @@ -230,12 +219,12 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) { } if val, ok := cm[key]; ok { - return val.fg, val.bg + return val } if val, ok := cm["fi"]; ok { - return val.fg, val.bg + return val } - return termbox.ColorDefault, termbox.ColorDefault + return tcell.StyleDefault } diff --git a/colors_test.go b/colors_test.go index 2d4b8682..e9fd74f3 100644 --- a/colors_test.go +++ b/colors_test.go @@ -3,75 +3,79 @@ package main import ( "testing" - "github.com/doronbehar/termbox-go" + "github.com/gdamore/tcell" ) func TestApplyAnsiCodes(t *testing.T) { - none := termbox.ColorDefault + none := tcell.StyleDefault tests := []struct { s string - fg termbox.Attribute - bg termbox.Attribute - fgExp termbox.Attribute - bgExp termbox.Attribute + st tcell.Style + stExp tcell.Style }{ - {"", none, none, none, none}, - {"", termbox.ColorRed, termbox.ColorRed, none, none}, - {"", termbox.AttrBold, none, none, none}, - {"", termbox.ColorRed | termbox.AttrBold, none, none, none}, + {"", none, none}, + {"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none}, + {"", none.Bold(true), none}, + {"", none.Foreground(tcell.ColorMaroon).Bold(true), none}, - {"0", none, none, none, none}, - {"0", termbox.ColorRed, termbox.ColorRed, none, none}, - {"0", termbox.AttrBold, none, none, none}, - {"0", termbox.ColorRed | termbox.AttrBold, none, none, none}, + {"0", none, none}, + {"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none}, + {"0", none.Bold(true), none}, + {"0", none.Foreground(tcell.ColorMaroon).Bold(true), none}, - {"1", none, none, termbox.AttrBold, none}, - {"4", none, none, termbox.AttrUnderline, none}, - {"7", none, none, termbox.AttrReverse, none}, + {"1", none, none.Bold(true)}, + {"4", none, none.Underline(true)}, + {"7", none, none.Reverse(true)}, - {"1", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrBold, none}, - {"4", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrUnderline, none}, - {"7", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrReverse, none}, + {"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)}, + {"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)}, + {"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)}, - {"4", termbox.AttrBold, none, termbox.AttrBold | termbox.AttrUnderline, none}, - {"4", termbox.ColorRed | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold | termbox.AttrUnderline, none}, + {"4", none.Bold(true), none.Bold(true).Underline(true)}, + {"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)}, - {"31", none, none, termbox.ColorRed, none}, - {"31", termbox.ColorGreen, none, termbox.ColorRed, none}, - {"31", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none}, + {"31", none, none.Foreground(tcell.ColorMaroon)}, + {"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)}, + {"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)}, - {"41", none, none, none, termbox.ColorRed}, - {"41", none, termbox.ColorGreen, none, termbox.ColorRed}, + {"41", none, none.Background(tcell.ColorMaroon)}, + {"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)}, - {"1;31", none, none, termbox.ColorRed | termbox.AttrBold, none}, - {"1;31", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none}, + {"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)}, + {"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)}, - {"38;5;0", none, none, termbox.ColorBlack, none}, - {"38;5;1", none, none, termbox.ColorRed, none}, - {"38;5;8", none, none, termbox.Attribute(9), none}, - {"38;5;16", none, none, termbox.Attribute(17), none}, - {"38;5;232", none, none, termbox.Attribute(233), none}, + {"38;5;0", none, none.Foreground(tcell.ColorBlack)}, + {"38;5;1", none, none.Foreground(tcell.ColorMaroon)}, + {"38;5;8", none, none.Foreground(tcell.Color(8))}, + {"38;5;16", none, none.Foreground(tcell.Color(16))}, + {"38;5;232", none, none.Foreground(tcell.Color(232))}, - {"38;5;1", termbox.ColorGreen, none, termbox.ColorRed, none}, - {"38;5;1", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none}, + {"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)}, + {"38;5;1", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)}, - {"48;5;0", none, none, none, termbox.ColorBlack}, - {"48;5;1", none, none, none, termbox.ColorRed}, - {"48;5;8", none, none, none, termbox.Attribute(9)}, - {"48;5;16", none, none, none, termbox.Attribute(17)}, - {"48;5;232", none, none, none, termbox.Attribute(233)}, + {"48;5;0", none, none.Background(tcell.ColorBlack)}, + {"48;5;1", none, none.Background(tcell.ColorMaroon)}, + {"48;5;8", none, none.Background(tcell.Color(8))}, + {"48;5;16", none, none.Background(tcell.Color(16))}, + {"48;5;232", none, none.Background(tcell.Color(232))}, - {"48;5;1", none, termbox.ColorGreen, none, termbox.ColorRed}, + {"48;5;1", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)}, - {"1;38;5;1", none, none, termbox.ColorRed | termbox.AttrBold, none}, - {"1;38;5;1", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none}, + {"1;38;5;1", none, none.Foreground(tcell.ColorMaroon).Bold(true)}, + {"1;38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)}, + + {"38;2;5;102;8", none, none.Foreground(tcell.NewRGBColor(5, 102, 8))}, + {"48;2;0;48;143", none, none.Background(tcell.NewRGBColor(0, 48, 143))}, + + // Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446 + {"38;5;34;1", none, none.Foreground(tcell.Color(34)).Bold(true)}, } for _, test := range tests { - if fgGot, bgGot := applyAnsiCodes(test.s, test.fg, test.bg); fgGot != test.fgExp || bgGot != test.bgExp { - t.Errorf("at input '%s' with '%d' and '%d' expected '%d' and '%d' but got '%d' and '%d'", - test.s, test.fg, test.bg, test.fgExp, test.bgExp, fgGot, bgGot) + if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp { + t.Errorf("at input '%s' with '%d' expected '%d' but got '%d'", + test.s, test.st, test.stExp, stGot) } } } diff --git a/complete.go b/complete.go index 5cb24dd2..ae5cf68b 100644 --- a/complete.go +++ b/complete.go @@ -70,9 +70,6 @@ var ( "anchorfind", "noanchorfind", "anchorfind!", - "color256", - "nocolor256", - "color256!", "dircounts", "nodircounts", "dircounts!", diff --git a/doc.go b/doc.go index 1fc172ac..224e0df1 100644 --- a/doc.go +++ b/doc.go @@ -97,7 +97,6 @@ The following command line commands are provided by lf: The following options can be used to customize the behavior of lf: anchorfind boolean (default on) - color256 boolean (default off) dircounts boolean (default off) dirfirst boolean (default on) drawbox boolean (default off) @@ -929,25 +928,29 @@ If both of these environment variables are not set, then lf fallbacks to its default colorscheme. Default lf colors are taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute. -You should also note that lf uses 8 color mode by default which uses sgr 3-bit -color escapes (e.g. '\033[34m'). If you want to use 256 colors, you need to -enable 'color256' option which then makes lf use sgr 8-bit color escapes (e.g. -'\033[38;5;4m'). This option is intended to eliminate differences between -default colors used by ls and lf since terminals may render 3-bit and 8-bit -escapes differently even for the same color. +It is worth noting that lf uses as many colors are advertised by your terminal's +entry in your systems terminfo or infocmp database, if this is not present lf +will default to an internal database. For terminals supporting 24-bit (or +"true") color that do not have a database entry (or one that does not advertise +all capabilities), support can be enabled by either setting the '$COLORTERM' +variable to "truecolor" or ensuring '$TERM' is set to a value that ends with +"-truecolor". -Keeping this mechanism in mind, you can configure lf colors in two different -ways. First, you can configure 8 basic colors used by your terminal and lf -should pick up those colors automatically. Depending on your terminal, you -should be able to select your colors from a 24-bit palette. This is the -recommended approach as colors used by other programs will also match each -other. +Keeping this in mind, you can configure lf colors in two different ways. First, +you can configure 8 basic colors used by your terminal and lf should pick up +those colors automatically. Depending on your terminal, you should be able to +select your colors from a 24-bit palette. This is the recommended approach as +colors used by other programs will also match each other. Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different -file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and -it can be used even when GNU programs are not installed on the system. You can -combine this second method with the first method for best results. +file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it +can be used even when GNU programs are not installed on the system. You can +combine this second method with the first method for best results. lf can also +be configured to ignore your terminal theme and output colors "as they were +intended" by translating all numbered colors into a 24-bit output that matches +the description; this can be enabled by setting the environment variable +'$TCELL_TRUECOLOR' to "on" (or any text except ""/nothing or "disable"). Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the diff --git a/docstring.go b/docstring.go index 53b87d00..e4a8924a 100644 --- a/docstring.go +++ b/docstring.go @@ -100,7 +100,6 @@ The following command line commands are provided by lf: The following options can be used to customize the behavior of lf: anchorfind boolean (default on) - color256 boolean (default off) dircounts boolean (default off) dirfirst boolean (default on) drawbox boolean (default off) @@ -978,26 +977,30 @@ If both of these environment variables are not set, then lf fallbacks to its default colorscheme. Default lf colors are taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute. -You should also note that lf uses 8 color mode by default which uses sgr -3-bit color escapes (e.g. '\033[34m'). If you want to use 256 colors, you -need to enable 'color256' option which then makes lf use sgr 8-bit color -escapes (e.g. '\033[38;5;4m'). This option is intended to eliminate -differences between default colors used by ls and lf since terminals may -render 3-bit and 8-bit escapes differently even for the same color. +It is worth noting that lf uses as many colors are advertised by your +terminal's entry in your systems terminfo or infocmp database, if this is +not present lf will default to an internal database. For terminals +supporting 24-bit (or "true") color that do not have a database entry (or +one that does not advertise all capabilities), support can be enabled by +either setting the '$COLORTERM' variable to "truecolor" or ensuring '$TERM' +is set to a value that ends with "-truecolor". -Keeping this mechanism in mind, you can configure lf colors in two different -ways. First, you can configure 8 basic colors used by your terminal and lf -should pick up those colors automatically. Depending on your terminal, you -should be able to select your colors from a 24-bit palette. This is the -recommended approach as colors used by other programs will also match each -other. +Keeping this in mind, you can configure lf colors in two different ways. +First, you can configure 8 basic colors used by your terminal and lf should +pick up those colors automatically. Depending on your terminal, you should +be able to select your colors from a 24-bit palette. This is the recommended +approach as colors used by other programs will also match each other. Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for -best results. +best results. lf can also be configured to ignore your terminal theme and +output colors "as they were intended" by translating all numbered colors +into a 24-bit output that matches the description; this can be enabled by +setting the environment variable '$TCELL_TRUECOLOR' to "on" (or any text +except ""/nothing or "disable"). Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured diff --git a/eval.go b/eval.go index 95a0e146..9d6ba969 100644 --- a/eval.go +++ b/eval.go @@ -21,20 +21,11 @@ func (e *setExpr) eval(app *app, args []string) { case "anchorfind!": gOpts.anchorfind = !gOpts.anchorfind case "color256": - gOpts.color256 = true - setColorMode() - app.ui.pause() - app.ui.resume() + app.ui.echoerr("option color256 is depreciated") case "nocolor256": - gOpts.color256 = false - setColorMode() - app.ui.pause() - app.ui.resume() + app.ui.echoerr("option nocolor256 is depreciated") case "color256!": - gOpts.color256 = !gOpts.color256 - setColorMode() - app.ui.pause() - app.ui.resume() + app.ui.echoerr("option color256! is depreciated") case "dircounts": gOpts.dircounts = true case "nodircounts": @@ -284,7 +275,7 @@ func (e *setExpr) eval(app *app, args []string) { return } gOpts.ratios = rats - app.ui.wins = getWins() + app.ui.wins = getWins(app.ui.screen) app.ui.loadFile(app.nav) case "shell": gOpts.shell = e.val @@ -793,8 +784,8 @@ func (e *callExpr) eval(app *app, args []string) { app.ui.loadFileInfo(app.nav) case "draw": case "redraw": - app.ui.sync() app.ui.renew() + app.ui.screen.Sync() app.nav.height = app.ui.wins[0].h app.ui.loadFile(app.nav) app.ui.loadFileInfo(app.nav) @@ -1056,7 +1047,7 @@ func (e *callExpr) eval(app *app, args []string) { } app.ui.draw(app.nav) if len(matches) > 1 { - app.ui.menuBuf = listMatches(matches) + app.ui.menuBuf = listMatches(app.ui.screen, matches) } else { app.ui.menuBuf = nil } diff --git a/go.mod b/go.mod index 98ab9709..96a33fe9 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/gokcehan/lf go 1.12 require ( - github.com/doronbehar/termbox-go v0.0.0-20200711071547-71407e3bfa14 + github.com/gdamore/tcell v1.3.0 github.com/mattn/go-runewidth v0.0.9 gopkg.in/djherbis/times.v1 v1.2.0 ) diff --git a/go.sum b/go.sum index 7a8bcc22..b94b2e5c 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,10 @@ -github.com/doronbehar/termbox-go v0.0.0-20200711071547-71407e3bfa14 h1:KKPl27Vj3HRF384G7jW7K8uCRv0Ks+GuAOkGsz4qWAs= -github.com/doronbehar/termbox-go v0.0.0-20200711071547-71407e3bfa14/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk= +github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= +github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg= +github.com/gdamore/tcell v1.3.0/go.mod h1:Hjvr+Ofd+gLglo7RYKxxnzCBmev3BzsS67MebKS4zMM= +github.com/lucasb-eyer/go-colorful v1.0.2/go.mod h1:0MS4r+7BZKSJ5mw4/S5MPN+qHFF1fYclkSPilDOKW0s= github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= gopkg.in/djherbis/times.v1 v1.2.0 h1:UCvDKl1L/fmBygl2Y7hubXCnY7t4Yj46ZrBFNUipFbM= gopkg.in/djherbis/times.v1 v1.2.0/go.mod h1:AQlg6unIsrsCEdQYhTzERy542dz6SFdQFZFv6mUY0P8= diff --git a/lf.1 b/lf.1 index 2ae91542..b39e3522 100644 --- a/lf.1 +++ b/lf.1 @@ -111,7 +111,6 @@ The following options can be used to customize the behavior of lf: .PP .EX anchorfind boolean (default on) - color256 boolean (default off) dircounts boolean (default off) dirfirst boolean (default on) drawbox boolean (default off) @@ -924,10 +923,10 @@ If '$LS_COLORS' variable is not set, '$LSCOLORS' variable is checked instead. Th .PP If both of these environment variables are not set, then lf fallbacks to its default colorscheme. Default lf colors are taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute. .PP -You should also note that lf uses 8 color mode by default which uses sgr 3-bit color escapes (e.g. '\e033[34m'). If you want to use 256 colors, you need to enable 'color256' option which then makes lf use sgr 8-bit color escapes (e.g. '\e033[38;5;4m'). This option is intended to eliminate differences between default colors used by ls and lf since terminals may render 3-bit and 8-bit escapes differently even for the same color. +It is worth noting that lf uses as many colors are advertised by your terminal's entry in your systems terminfo or infocmp database, if this is not present lf will default to an internal database. For terminals supporting 24-bit (or "true") color that do not have a database entry (or one that does not advertise all capabilities), support can be enabled by either setting the '$COLORTERM' variable to "truecolor" or ensuring '$TERM' is set to a value that ends with "-truecolor". .PP -Keeping this mechanism in mind, you can configure lf colors in two different ways. First, you can configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other. +Keeping this in mind, you can configure lf colors in two different ways. First, you can configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other. .PP -Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results. +Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results. lf can also be configured to ignore your terminal theme and output colors "as they were intended" by translating all numbered colors into a 24-bit output that matches the description; this can be enabled by setting the environment variable '$TCELL_TRUECOLOR' to "on" (or any text except ""/nothing or "disable"). .PP Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the 'promptfmt' option which can include hardcoded colors as ansi escapes. See the default value of this option to have an idea about how to color this line. diff --git a/main.go b/main.go index b394ecef..d25918ee 100644 --- a/main.go +++ b/main.go @@ -50,6 +50,7 @@ func exportEnvVars() { os.Setenv("EDITOR", envEditor) os.Setenv("PAGER", envPager) os.Setenv("SHELL", envShell) + os.Setenv("TCELL_TRUECOLOR", envTcellTruecolor) level, err := strconv.Atoi(envLevel) if err != nil { diff --git a/opts.go b/opts.go index db8e6b8a..e3fd6849 100644 --- a/opts.go +++ b/opts.go @@ -29,7 +29,6 @@ type sortType struct { var gOpts struct { anchorfind bool - color256 bool dircounts bool drawbox bool globsearch bool @@ -68,7 +67,6 @@ var gOpts struct { func init() { gOpts.anchorfind = true - gOpts.color256 = false gOpts.dircounts = false gOpts.drawbox = false gOpts.globsearch = false diff --git a/os.go b/os.go index ca8ab509..1476a06e 100644 --- a/os.go +++ b/os.go @@ -15,10 +15,11 @@ import ( ) var ( - envOpener = os.Getenv("OPENER") - envEditor = os.Getenv("EDITOR") - envPager = os.Getenv("PAGER") - envShell = os.Getenv("SHELL") + envOpener = os.Getenv("OPENER") + envEditor = os.Getenv("EDITOR") + envPager = os.Getenv("PAGER") + envShell = os.Getenv("SHELL") + envTcellTruecolor = os.Getenv("TCELL_TRUECOLOR") ) var ( @@ -55,6 +56,10 @@ func init() { envShell = "sh" } + if envTcellTruecolor == "" { + envTcellTruecolor = "disable" + } + u, err := user.Current() if err != nil { log.Printf("user: %s", err) diff --git a/os_windows.go b/os_windows.go index 45d099d7..b0fd32b4 100644 --- a/os_windows.go +++ b/os_windows.go @@ -16,6 +16,7 @@ var ( envEditor = os.Getenv("EDITOR") envPager = os.Getenv("PAGER") envShell = os.Getenv("SHELL") + envTcellTruecolor = os.Getenv("TCELL_TRUECOLOR") ) var envPathExt = os.Getenv("PATHEXT") @@ -50,6 +51,10 @@ func init() { envShell = "cmd" } + if envTcellTruecolor == "" { + envTcellTruecolor = "disable" + } + u, err := user.Current() if err != nil { log.Printf("user: %s", err) diff --git a/ui.go b/ui.go index 97b36fbf..689bff2b 100644 --- a/ui.go +++ b/ui.go @@ -15,75 +15,75 @@ import ( "unicode" "unicode/utf8" - "github.com/doronbehar/termbox-go" + "github.com/gdamore/tcell" "github.com/mattn/go-runewidth" ) const gEscapeCode = 27 -var gKeyVal = map[termbox.Key]string{ - termbox.KeyF1: "", - termbox.KeyF2: "", - termbox.KeyF3: "", - termbox.KeyF4: "", - termbox.KeyF5: "", - termbox.KeyF6: "", - termbox.KeyF7: "", - termbox.KeyF8: "", - termbox.KeyF9: "", - termbox.KeyF10: "", - termbox.KeyF11: "", - termbox.KeyF12: "", - termbox.KeyInsert: "", - termbox.KeyDelete: "", - termbox.KeyHome: "", - termbox.KeyEnd: "", - termbox.KeyPgup: "", - termbox.KeyPgdn: "", - termbox.KeyArrowUp: "", - termbox.KeyArrowDown: "", - termbox.KeyArrowLeft: "", - termbox.KeyArrowRight: "", - termbox.KeyCtrlSpace: "", - termbox.KeyCtrlA: "", - termbox.KeyCtrlB: "", - termbox.KeyCtrlC: "", - termbox.KeyCtrlD: "", - termbox.KeyCtrlE: "", - termbox.KeyCtrlF: "", - termbox.KeyCtrlG: "", - termbox.KeyBackspace: "", - termbox.KeyTab: "", - termbox.KeyCtrlJ: "", - termbox.KeyCtrlK: "", - termbox.KeyCtrlL: "", - termbox.KeyEnter: "", - termbox.KeyCtrlN: "", - termbox.KeyCtrlO: "", - termbox.KeyCtrlP: "", - termbox.KeyCtrlQ: "", - termbox.KeyCtrlR: "", - termbox.KeyCtrlS: "", - termbox.KeyCtrlT: "", - termbox.KeyCtrlU: "", - termbox.KeyCtrlV: "", - termbox.KeyCtrlW: "", - termbox.KeyCtrlX: "", - termbox.KeyCtrlY: "", - termbox.KeyCtrlZ: "", - termbox.KeyEsc: "", - termbox.KeyCtrlBackslash: "", - termbox.KeyCtrlRsqBracket: "", - termbox.KeyCtrl6: "", - termbox.KeyCtrlSlash: "", - termbox.KeySpace: "", - termbox.KeyBackspace2: "", +var gKeyVal = map[tcell.Key]string{ + tcell.KeyF1: "", + tcell.KeyF2: "", + tcell.KeyF3: "", + tcell.KeyF4: "", + tcell.KeyF5: "", + tcell.KeyF6: "", + tcell.KeyF7: "", + tcell.KeyF8: "", + tcell.KeyF9: "", + tcell.KeyF10: "", + tcell.KeyF11: "", + tcell.KeyF12: "", + tcell.KeyInsert: "", + tcell.KeyDelete: "", + tcell.KeyHome: "", + tcell.KeyEnd: "", + tcell.KeyPgUp: "", + tcell.KeyPgDn: "", + tcell.KeyUp: "", + tcell.KeyDown: "", + tcell.KeyLeft: "", + tcell.KeyRight: "", + tcell.KeyCtrlSpace: "", + tcell.KeyCtrlA: "", + tcell.KeyCtrlB: "", + tcell.KeyCtrlC: "", + tcell.KeyCtrlD: "", + tcell.KeyCtrlE: "", + tcell.KeyCtrlF: "", + tcell.KeyCtrlG: "", + tcell.KeyBackspace: "", + tcell.KeyTab: "", + tcell.KeyCtrlJ: "", + tcell.KeyCtrlK: "", + tcell.KeyCtrlL: "", + tcell.KeyEnter: "", + tcell.KeyCtrlN: "", + tcell.KeyCtrlO: "", + tcell.KeyCtrlP: "", + tcell.KeyCtrlQ: "", + tcell.KeyCtrlR: "", + tcell.KeyCtrlS: "", + tcell.KeyCtrlT: "", + tcell.KeyCtrlU: "", + tcell.KeyCtrlV: "", + tcell.KeyCtrlW: "", + tcell.KeyCtrlX: "", + tcell.KeyCtrlY: "", + tcell.KeyCtrlZ: "", + tcell.KeyEsc: "", + tcell.KeyCtrlBackslash: "", + tcell.KeyCtrlRightSq: "", + // TODO: compatability only, they are discouraged + tcell.KeyCtrlCarat: "", + tcell.KeyCtrlUnderscore: "", + tcell.KeyBackspace2: "", } -var gValKey map[string]termbox.Key +var gValKey map[string]tcell.Key func init() { - gValKey = make(map[string]termbox.Key) + gValKey = make(map[string]tcell.Key) for k, v := range gKeyVal { gValKey[v] = k } @@ -129,7 +129,7 @@ func printLength(s string) int { return ind } -func (win *win) print(x, y int, fg, bg termbox.Attribute, s string) (termbox.Attribute, termbox.Attribute) { +func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) tcell.Style { off := x for i := 0; i < len(s); i++ { r, w := utf8.DecodeRuneInString(s[i:]) @@ -140,14 +140,14 @@ func (win *win) print(x, y int, fg, bg termbox.Attribute, s string) (termbox.Att continue } - fg, bg = applyAnsiCodes(s[i+2:i+j], fg, bg) + st = applyAnsiCodes(s[i+2:i+j], st) i += j continue } if x < win.w { - termbox.SetCell(win.x+x, win.y+y, r, fg, bg) + screen.SetContent(win.x+x, win.y+y, r, nil, st) } i += w - 1 @@ -155,7 +155,7 @@ func (win *win) print(x, y int, fg, bg termbox.Attribute, s string) (termbox.Att if r == '\t' { s := gOpts.tabstop - (x-off)%gOpts.tabstop for i := 0; i < s && x+i < win.w; i++ { - termbox.SetCell(win.x+x+i, win.y+y, ' ', fg, bg) + screen.SetContent(win.x+x+i, win.y+y, ' ', nil, st) } x += s } else { @@ -163,36 +163,40 @@ func (win *win) print(x, y int, fg, bg termbox.Attribute, s string) (termbox.Att } } - return fg, bg + return st } -func (win *win) printf(x, y int, fg, bg termbox.Attribute, format string, a ...interface{}) { - win.print(x, y, fg, bg, fmt.Sprintf(format, a...)) +func (win *win) printf(screen tcell.Screen, x, y int, st tcell.Style, format string, a ...interface{}) { + win.print(screen, x, y, st, fmt.Sprintf(format, a...)) } -func (win *win) printLine(x, y int, fg, bg termbox.Attribute, s string) { - win.printf(x, y, fg, bg, "%s%*s", s, win.w-len(s), "") +func (win *win) printLine(screen tcell.Screen, x, y int, st tcell.Style, s string) { + win.printf(screen, x, y, st, "%s%*s", s, win.w-len(s), "") } -func (win *win) printRight(y int, fg, bg termbox.Attribute, s string) { - win.print(win.w-len(s), y, fg, bg, s) +func (win *win) printRight(screen tcell.Screen, y int, st tcell.Style, s string) { + win.print(screen, win.w-len(s), y, st, s) } -func (win *win) printReg(reg *reg) { +func (win *win) printReg(screen tcell.Screen, reg *reg) { if reg == nil { return } - fg, bg := termbox.ColorDefault, termbox.ColorDefault + st := tcell.StyleDefault if reg.loading { - fg = termbox.AttrReverse - win.print(2, 0, fg, bg, "loading...") + st = st.Reverse(true) + win.print(screen, 2, 0, st, "loading...") return } for i, l := range reg.lines { - fg, bg = win.print(2, i, fg, bg, l) + if i > win.h-1 { + break + } + + st = win.print(screen, 2, i, st, l) } } @@ -247,23 +251,23 @@ func fileInfo(f *file, d *dir) string { return info } -func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]bool, colors colorMap, icons iconMap) { +func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]int, saves map[string]bool, colors styleMap, icons iconMap) { if win.w < 5 || dir == nil { return } if dir.loading { - win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "loading...") + win.print(screen, 2, 0, tcell.StyleDefault.Reverse(true), "loading...") return } if dir.noPerm { - win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "permission denied") + win.print(screen, 2, 0, tcell.StyleDefault.Reverse(true), "permission denied") return } if len(dir.files) == 0 { - win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "empty") + win.print(screen, 2, 0, tcell.StyleDefault.Reverse(true), "empty") return } @@ -289,7 +293,7 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b } for i, f := range dir.files[beg:end] { - fg, bg := colors.get(f) + st := colors.get(f) if lnwidth > 0 { var ln string @@ -309,23 +313,23 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b } } - win.print(0, i, termbox.ColorYellow, bg, ln) + win.print(screen, 0, i, st.Foreground(tcell.ColorOlive), ln) } path := filepath.Join(dir.path, f.Name()) if _, ok := selections[path]; ok { - win.print(lnwidth, i, fg, termbox.ColorMagenta, " ") + win.print(screen, lnwidth, i, st.Background(tcell.ColorPurple), " ") } else if cp, ok := saves[path]; ok { if cp { - win.print(lnwidth, i, fg, termbox.ColorYellow, " ") + win.print(screen, lnwidth, i, st.Background(tcell.ColorOlive), " ") } else { - win.print(lnwidth, i, fg, termbox.ColorRed, " ") + win.print(screen, lnwidth, i, st.Background(tcell.ColorMaroon), " ") } } if i == dir.pos { - fg |= termbox.AttrReverse + st = st.Reverse(true) } var s []rune @@ -368,11 +372,12 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b s = append(s, ' ') - win.print(lnwidth+1, i, fg, bg, string(s)) + win.print(screen, lnwidth+1, i, st, string(s)) } } type ui struct { + screen tcell.Screen wins []*win promptWin *win msgWin *win @@ -382,7 +387,7 @@ type ui struct { dirPrev *dir exprChan chan expr keyChan chan string - evChan chan termbox.Event + evChan chan tcell.Event menuBuf *bytes.Buffer cmdPrefix string cmdAccLeft []rune @@ -390,7 +395,7 @@ type ui struct { cmdYankBuf []rune keyAcc []rune keyCount []rune - colors colorMap + styles styleMap icons iconMap } @@ -417,8 +422,8 @@ func getWidths(wtot int) []int { return widths } -func getWins() []*win { - wtot, htot := termbox.Size() +func getWins(screen tcell.Screen) []*win { + wtot, htot := screen.Size() var wins []*win @@ -438,47 +443,76 @@ func getWins() []*win { return wins } -func newUI() *ui { - wtot, htot := termbox.Size() - - evQueue := make(chan termbox.Event) +func startEventListening(screen tcell.Screen) chan tcell.Event { + evQueue := make(chan tcell.Event) go func() { + var ev tcell.Event for { - evQueue <- termbox.PollEvent() + ev = screen.PollEvent() + evQueue <- ev + + if ev == nil { + return + } } }() - evChan := make(chan termbox.Event) + evChan := make(chan tcell.Event) go func() { for { ev := <-evQueue - if ev.Type == termbox.EventKey && ev.Key == termbox.KeyEsc { - select { - case ev2 := <-evQueue: - ev2.Mod = termbox.ModAlt - evChan <- ev2 - continue - case <-time.After(100 * time.Millisecond): + // .(type) can't be used outside a switch + switch tev := ev.(type) { + case *tcell.EventKey: + // tcell.KeyESC is one of the few cases we don't need Rune() for + if tev.Key() == tcell.KeyESC { + select { + case ev2 := <-evQueue: + switch tev2 := ev2.(type) { + case *tcell.EventKey: + evChan <- tcell.NewEventKey(tev2.Key(), tev2.Rune(), tcell.ModAlt) + default: + evChan <- ev2 + } + + if ev2 == nil { + return + } + + continue + case <-time.After(100 * time.Millisecond): + } } } evChan <- ev + + if ev == nil { + return + } } }() + return evChan +} + +func newUI(screen tcell.Screen) *ui { + wtot, htot := screen.Size() + return &ui{ - wins: getWins(), + screen: screen, + wins: getWins(screen), promptWin: newWin(wtot, 1, 0, 0), msgWin: newWin(wtot, 1, 0, htot-1), menuWin: newWin(wtot, 1, 0, htot-2), keyChan: make(chan string, 1000), - evChan: evChan, - colors: parseColors(), + evChan: startEventListening(screen), + styles: parseStyles(), icons: parseIcons(), } } func (ui *ui) renew() { - wtot, htot := termbox.Size() + wtot, htot := ui.screen.Size() widths := getWidths(wtot) @@ -571,7 +605,7 @@ func (ui *ui) loadFileInfo(nav *nav) { } func (ui *ui) drawPromptLine(nav *nav) { - fg, bg := termbox.ColorDefault, termbox.ColorDefault + st := tcell.StyleDefault pwd := nav.currDir().path @@ -614,15 +648,15 @@ func (ui *ui) drawPromptLine(nav *nav) { prompt = strings.Replace(prompt, "%w", pwd, -1) - ui.promptWin.print(0, 0, fg, bg, prompt) + ui.promptWin.print(ui.screen, 0, 0, st, prompt) } func (ui *ui) drawStatLine(nav *nav) { - fg, bg := termbox.ColorDefault, termbox.ColorDefault + st := tcell.StyleDefault dir := nav.currDir() - ui.msgWin.print(0, 0, fg, bg, ui.msg) + ui.msgWin.print(ui.screen, 0, 0, st, ui.msg) tot := len(dir.files) ind := min(dir.ind+1, tot) @@ -645,44 +679,49 @@ func (ui *ui) drawStatLine(nav *nav) { ruler := fmt.Sprintf("%s%s %d/%d", acc, progress, ind, tot) - ui.msgWin.printRight(0, fg, bg, ruler) + ui.msgWin.printRight(ui.screen, 0, st, ruler) } func (ui *ui) drawBox() { - fg, bg := termbox.ColorDefault, termbox.ColorDefault + st := tcell.StyleDefault - w, h := termbox.Size() + w, h := ui.screen.Size() for i := 1; i < w-1; i++ { - termbox.SetCell(i, 1, '─', fg, bg) - termbox.SetCell(i, h-2, '─', fg, bg) + ui.screen.SetContent(i, 1, '─', nil, st) + ui.screen.SetContent(i, h-2, '─', nil, st) } for i := 2; i < h-2; i++ { - termbox.SetCell(0, i, '│', fg, bg) - termbox.SetCell(w-1, i, '│', fg, bg) + ui.screen.SetContent(0, i, '│', nil, st) + ui.screen.SetContent(w-1, i, '│', nil, st) } - termbox.SetCell(0, 1, '┌', fg, bg) - termbox.SetCell(w-1, 1, '┐', fg, bg) - termbox.SetCell(0, h-2, '└', fg, bg) - termbox.SetCell(w-1, h-2, '┘', fg, bg) + ui.screen.SetContent(0, 1, '┌', nil, st) + ui.screen.SetContent(w-1, 1, '┐', nil, st) + ui.screen.SetContent(0, h-2, '└', nil, st) + ui.screen.SetContent(w-1, h-2, '┘', nil, st) wacc := 0 for wind := 0; wind < len(ui.wins)-1; wind++ { wacc += ui.wins[wind].w - termbox.SetCell(wacc, 1, '┬', fg, bg) + ui.screen.SetContent(wacc, 1, '┬', nil, st) for i := 2; i < h-2; i++ { - termbox.SetCell(wacc, i, '│', fg, bg) + ui.screen.SetContent(wacc, i, '│', nil, st) } - termbox.SetCell(wacc, h-2, '┴', fg, bg) + ui.screen.SetContent(wacc, h-2, '┴', nil, st) } } func (ui *ui) draw(nav *nav) { - fg, bg := termbox.ColorDefault, termbox.ColorDefault + st := tcell.StyleDefault - termbox.Clear(fg, bg) + wtot, htot := ui.screen.Size() + for i := 0; i < wtot; i++ { + for j := 0; j < htot; j++ { + ui.screen.SetContent(i, j, ' ', nil, st) + } + } ui.drawPromptLine(nav) @@ -696,24 +735,24 @@ func (ui *ui) draw(nav *nav) { doff := len(nav.dirs) - length for i := 0; i < length; i++ { - ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.selections, nav.saves, ui.colors, ui.icons) + ui.wins[woff+i].printDir(ui.screen, nav.dirs[doff+i], nav.selections, nav.saves, ui.styles, ui.icons) } switch ui.cmdPrefix { case "": ui.drawStatLine(nav) - termbox.HideCursor() + ui.screen.HideCursor() case ">": - ui.msgWin.printLine(0, 0, fg, bg, ui.cmdPrefix) - ui.msgWin.print(len(ui.cmdPrefix), 0, fg, bg, ui.msg) - ui.msgWin.print(len(ui.cmdPrefix)+len(ui.msg), 0, fg, bg, string(ui.cmdAccLeft)) - ui.msgWin.print(len(ui.cmdPrefix)+len(ui.msg)+runeSliceWidth(ui.cmdAccLeft), 0, fg, bg, string(ui.cmdAccRight)) - termbox.SetCursor(ui.msgWin.x+len(ui.cmdPrefix)+len(ui.msg)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y) + ui.msgWin.printLine(ui.screen, 0, 0, st, ui.cmdPrefix) + ui.msgWin.print(ui.screen, len(ui.cmdPrefix), 0, st, ui.msg) + ui.msgWin.print(ui.screen, len(ui.cmdPrefix)+len(ui.msg), 0, st, string(ui.cmdAccLeft)) + ui.msgWin.print(ui.screen, len(ui.cmdPrefix)+len(ui.msg)+runeSliceWidth(ui.cmdAccLeft), 0, st, string(ui.cmdAccRight)) + ui.screen.ShowCursor(ui.msgWin.x+len(ui.cmdPrefix)+len(ui.msg)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y) default: - ui.msgWin.printLine(0, 0, fg, bg, ui.cmdPrefix) - ui.msgWin.print(len(ui.cmdPrefix), 0, fg, bg, string(ui.cmdAccLeft)) - ui.msgWin.print(len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), 0, fg, bg, string(ui.cmdAccRight)) - termbox.SetCursor(ui.msgWin.x+len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y) + ui.msgWin.printLine(ui.screen, 0, 0, st, ui.cmdPrefix) + ui.msgWin.print(ui.screen, len(ui.cmdPrefix), 0, st, string(ui.cmdAccLeft)) + ui.msgWin.print(ui.screen, len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), 0, st, string(ui.cmdAccRight)) + ui.screen.ShowCursor(ui.msgWin.x+len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y) } if gOpts.preview { @@ -722,9 +761,9 @@ func (ui *ui) draw(nav *nav) { preview := ui.wins[len(ui.wins)-1] if curr.IsDir() { - preview.printDir(ui.dirPrev, nav.selections, nav.saves, ui.colors, ui.icons) + preview.printDir(ui.screen, ui.dirPrev, nav.selections, nav.saves, ui.styles, ui.icons) } else if curr.Mode().IsRegular() { - preview.printReg(ui.regPrev) + preview.printReg(ui.screen, ui.regPrev) } } } @@ -745,14 +784,14 @@ func (ui *ui) draw(nav *nav) { ui.menuWin.y += 2 } - ui.menuWin.printLine(0, 0, termbox.AttrBold, termbox.AttrBold, lines[0]) + ui.menuWin.printLine(ui.screen, 0, 0, st.Bold(true), lines[0]) for i, line := range lines[1:] { - ui.menuWin.printLine(0, i+1, fg, bg, "") - ui.menuWin.print(0, i+1, fg, bg, line) + ui.menuWin.printLine(ui.screen, 0, i+1, st, "") + ui.menuWin.print(ui.screen, 0, i+1, st, line) } } - termbox.Flush() + ui.screen.Show() } func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) { @@ -809,34 +848,36 @@ func listMarks(marks map[string]string) *bytes.Buffer { return b } -func (ui *ui) pollEvent() termbox.Event { +func (ui *ui) pollEvent() tcell.Event { select { case key := <-ui.keyChan: - ev := termbox.Event{Type: termbox.EventKey} + var ch rune + var mod tcell.ModMask + var Key tcell.Key if utf8.RuneCountInString(key) == 1 { - ev.Ch, _ = utf8.DecodeRuneInString(key) + ch, _ = utf8.DecodeRuneInString(key) } else { switch { case key == "": - ev.Ch = '<' + ch = '<' case key == "": - ev.Ch = '>' + ch = '>' case reAltKey.MatchString(key): match := reAltKey.FindStringSubmatch(key)[1] - ev.Ch, _ = utf8.DecodeRuneInString(match) - ev.Mod = termbox.ModAlt + ch, _ = utf8.DecodeRuneInString(match) + mod = tcell.ModMask(tcell.ModAlt) default: if val, ok := gValKey[key]; ok { - ev.Key = val + Key = val } else { - ev.Key = termbox.KeyEsc + Key = tcell.KeyESC ui.echoerrf("unknown key: %s", key) } } } - return ev + return tcell.NewEventKey(Key, ch, mod) case ev := <-ui.evChan: return ev } @@ -845,27 +886,34 @@ func (ui *ui) pollEvent() termbox.Event { // This function is used to read a normal event on the client side. For keys, // digits are interpreted as command counts but this is only done for digits // preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k"). -func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) { +func (ui *ui) readEvent(ch chan<- expr, ev tcell.Event) { + if ev == nil { + return + } + draw := &callExpr{"draw", nil, 1} count := 1 - switch ev.Type { - case termbox.EventKey: - if ev.Ch != 0 { + switch tev := ev.(type) { + case *tcell.EventKey: + // KeyRune is a regular character + if tev.Key() == tcell.KeyRune { switch { - case ev.Ch == '<': + case tev.Rune() == '<': ui.keyAcc = append(ui.keyAcc, []rune("")...) - case ev.Ch == '>': + case tev.Rune() == '>': ui.keyAcc = append(ui.keyAcc, []rune("")...) - case ev.Mod == termbox.ModAlt: - ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', ev.Ch, '>') - case unicode.IsDigit(ev.Ch) && len(ui.keyAcc) == 0: - ui.keyCount = append(ui.keyCount, ev.Ch) + case tev.Rune() == ' ': + ui.keyAcc = append(ui.keyAcc, []rune("")...) + case tev.Modifiers() == tcell.ModAlt: + ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', tev.Rune(), '>') + case unicode.IsDigit(tev.Rune()) && len(ui.keyAcc) == 0: + ui.keyCount = append(ui.keyCount, tev.Rune()) default: - ui.keyAcc = append(ui.keyAcc, ev.Ch) + ui.keyAcc = append(ui.keyAcc, tev.Rune()) } } else { - val := gKeyVal[ev.Key] + val := gKeyVal[tev.Key()] if val == "" { ch <- draw ui.keyAcc = nil @@ -914,25 +962,34 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) { ch <- draw } } - case termbox.EventResize: + case *tcell.EventResize: ch <- &callExpr{"redraw", nil, 1} + case *tcell.EventError: + log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When()) + return + case *tcell.EventInterrupt: + log.Printf("Got EventInterrupt: at %s", tev.When()) + return } } -func readCmdEvent(ch chan<- expr, ev termbox.Event) { - if ev.Ch != 0 { - if ev.Mod == termbox.ModAlt { - val := string([]rune{'<', 'a', '-', ev.Ch, '>'}) +func readCmdEvent(ch chan<- expr, ev tcell.Event) { + switch tev := ev.(type) { + case *tcell.EventKey: + if tev.Key() == tcell.KeyRune { + if tev.Modifiers() == tcell.ModMask(tcell.ModAlt) { + val := string([]rune{'<', 'a', '-', tev.Rune(), '>'}) + if expr, ok := gOpts.cmdkeys[val]; ok { + ch <- expr + } + } else { + ch <- &callExpr{"cmd-insert", []string{string(tev.Rune())}, 1} + } + } else { + val := gKeyVal[tev.Key()] if expr, ok := gOpts.cmdkeys[val]; ok { ch <- expr } - } else { - ch <- &callExpr{"cmd-insert", []string{string(ev.Ch)}, 1} - } - } else { - val := gKeyVal[ev.Key] - if expr, ok := gOpts.cmdkeys[val]; ok { - ch <- expr } } } @@ -948,9 +1005,12 @@ func (ui *ui) readExpr() <-chan expr { for { ev := ui.pollEvent() - if ui.cmdPrefix != "" && ev.Type == termbox.EventKey { - readCmdEvent(ch, ev) - continue + switch ev.(type) { + case *tcell.EventKey: + if ui.cmdPrefix != "" { + readCmdEvent(ch, ev) + continue + } } ui.readEvent(ch, ev) @@ -960,34 +1020,29 @@ func (ui *ui) readExpr() <-chan expr { return ch } -func setColorMode() { - if gOpts.color256 { - termbox.SetOutputMode(termbox.Output256) - } else { - termbox.SetOutputMode(termbox.OutputNormal) - } -} - func (ui *ui) pause() { - termbox.Close() + ui.screen.Fini() } func (ui *ui) resume() { - if err := termbox.Init(); err != nil { - log.Fatalf("initializing termbox: %s", err) + var err error + + if ui.screen, err = tcell.NewScreen(); err != nil { + log.Fatalf("creating screen: %s", err) + } else if err = ui.screen.Init(); err != nil { + log.Fatalf("initializing screen: %s", err) } + + close(ui.evChan) + ui.evChan = startEventListening(ui.screen) + + ui.renew() } -func (ui *ui) sync() { - if err := termbox.Sync(); err != nil { - log.Printf("syncing termbox: %s", err) - } -} - -func listMatches(matches []string) *bytes.Buffer { +func listMatches(screen tcell.Screen, matches []string) *bytes.Buffer { b := new(bytes.Buffer) - wtot, _ := termbox.Size() + wtot, _ := screen.Size() wcol := 0 for _, m := range matches {