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
This commit is contained in:
Provessor authored and GitHub committed 2020-09-01 15:42:44 +03:00
1 parent d25faf7186
commit 24f01f4988
16 files changed
+477 -419

No files matched your search

+4 -2
View File
@@ -14,6 +14,8 @@ import (
"strings" "strings"
"syscall" "syscall"
"time" "time"
"github.com/gdamore/tcell"
) )
type cmdItem struct { type cmdItem struct {
@@ -34,8 +36,8 @@ type app struct {
cmdHistoryInd int cmdHistoryInd int
} }
func newApp() *app { func newApp(screen tcell.Screen) *app {
ui := newUI() ui := newUI(screen)
nav := newNav(ui.wins[0].h) nav := newNav(ui.wins[0].h)
quitChan := make(chan bool, 1) quitChan := make(chan bool, 1)
+9 -7
View File
@@ -10,16 +10,17 @@ import (
"strings" "strings"
"time" "time"
"github.com/doronbehar/termbox-go" "github.com/gdamore/tcell"
) )
func run() { func run() {
if err := termbox.Init(); err != nil { var screen tcell.Screen
log.Fatalf("initializing termbox: %s", err) 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) f, err := os.Create(gLogPath)
if err != nil { if err != nil {
@@ -31,7 +32,7 @@ func run() {
log.Print("hi!") log.Print("hi!")
app := newApp() app := newApp(screen)
if err := app.nav.readMarks(); err != nil { if err := app.nav.readMarks(); err != nil {
app.ui.echoerrf("reading marks file: %s", err) app.ui.echoerrf("reading marks file: %s", err)
@@ -42,6 +43,7 @@ func run() {
} }
app.loop() app.loop()
app.ui.screen.Fini()
} }
func readExpr() <-chan expr { func readExpr() <-chan expr {
+90 -101
View File
@@ -7,48 +7,18 @@ import (
"strconv" "strconv"
"strings" "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{ func parseStyles() styleMap {
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 {
if env := os.Getenv("LS_COLORS"); env != "" { if env := os.Getenv("LS_COLORS"); env != "" {
return parseColorsGNU(env) return parseStylesGNU(env)
} }
if env := os.Getenv("LSCOLORS"); env != "" { if env := os.Getenv("LSCOLORS"); env != "" {
return parseColorsBSD(env) return parseStylesBSD(env)
} }
// default values from dircolors with removed background colors // default values from dircolors with removed background colors
@@ -73,10 +43,10 @@ func parseColors() colorMap {
"ex=01;32", "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, ";") toks := strings.Split(s, ";")
var nums []int var nums []int
@@ -93,43 +63,63 @@ func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, term
nums = append(nums, n) nums = append(nums, n)
} }
// ECMA-48 details the standard
for i := 0; i < len(nums); i++ { for i := 0; i < len(nums); i++ {
n := nums[i] n := nums[i]
switch { 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: case n == 0:
fg, bg = attr, attr st = tcell.StyleDefault
case n == 1 || n == 4 || n == 7: case n == 1:
fg |= attr st = st.Bold(true)
case 30 <= n && n <= 37: case n == 2:
fg &= gAnsiColorResetMask st = st.Dim(true)
fg |= attr case n == 4:
case 40 <= n && n <= 47: st = st.Underline(true)
bg = attr 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. // This function parses $LS_COLORS environment variable.
func parseColorsGNU(env string) colorMap { func parseStylesGNU(env string) styleMap {
colors := make(colorMap) styles := make(styleMap)
entries := strings.Split(env, ":") entries := strings.Split(env, ":")
for _, entry := range entries { for _, entry := range entries {
@@ -139,63 +129,62 @@ func parseColorsGNU(env string) colorMap {
pair := strings.Split(entry, "=") pair := strings.Split(entry, "=")
if len(pair) != 2 { if len(pair) != 2 {
log.Printf("invalid $LS_COLORS entry: %s", entry) log.Printf("invalid $LS_COLORS entry: %s", entry)
return colors return styles
} }
key, val := pair[0], pair[1] key, val := pair[0], pair[1]
fg, bg := applyAnsiCodes(val, termbox.ColorDefault, termbox.ColorDefault) styles[key] = applyAnsiCodes(val, tcell.StyleDefault)
colors[key] = colorEntry{fg: fg, bg: bg}
} }
return colors return styles
} }
// This function parses $LSCOLORS environment variable. // This function parses $LSCOLORS environment variable.
func parseColorsBSD(env string) colorMap { func parseStylesBSD(env string) styleMap {
colors := make(colorMap) styles := make(styleMap)
if len(env) != 22 { if len(env) != 22 {
log.Printf("invalid $LSCOLORS variable: %s", env) log.Printf("invalid $LSCOLORS variable: %s", env)
return colors return styles
} }
colorNames := []string{"di", "ln", "so", "pi", "ex", "bd", "cd", "su", "sg", "tw", "ow"} 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 { getStyle := func(r1, r2 byte) tcell.Style {
if color, ok := colorCodes[r]; ok { st := tcell.StyleDefault
return color
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) switch {
return termbox.ColorDefault 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 { 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 var key string
switch { switch {
@@ -230,12 +219,12 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) {
} }
if val, ok := cm[key]; ok { if val, ok := cm[key]; ok {
return val.fg, val.bg return val
} }
if val, ok := cm["fi"]; ok { if val, ok := cm["fi"]; ok {
return val.fg, val.bg return val
} }
return termbox.ColorDefault, termbox.ColorDefault return tcell.StyleDefault
} }
+51 -47
View File
@@ -3,75 +3,79 @@ package main
import ( import (
"testing" "testing"
"github.com/doronbehar/termbox-go" "github.com/gdamore/tcell"
) )
func TestApplyAnsiCodes(t *testing.T) { func TestApplyAnsiCodes(t *testing.T) {
none := termbox.ColorDefault none := tcell.StyleDefault
tests := []struct { tests := []struct {
s string s string
fg termbox.Attribute st tcell.Style
bg termbox.Attribute stExp tcell.Style
fgExp termbox.Attribute
bgExp termbox.Attribute
}{ }{
{"", none, none, none, none}, {"", none, none},
{"", termbox.ColorRed, termbox.ColorRed, none, none}, {"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"", termbox.AttrBold, none, none, none}, {"", none.Bold(true), none},
{"", termbox.ColorRed | termbox.AttrBold, none, none, none}, {"", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"0", none, none, none, none}, {"0", none, none},
{"0", termbox.ColorRed, termbox.ColorRed, none, none}, {"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"0", termbox.AttrBold, none, none, none}, {"0", none.Bold(true), none},
{"0", termbox.ColorRed | termbox.AttrBold, none, none, none}, {"0", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"1", none, none, termbox.AttrBold, none}, {"1", none, none.Bold(true)},
{"4", none, none, termbox.AttrUnderline, none}, {"4", none, none.Underline(true)},
{"7", none, none, termbox.AttrReverse, none}, {"7", none, none.Reverse(true)},
{"1", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrBold, none}, {"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"4", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrUnderline, none}, {"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)},
{"7", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrReverse, none}, {"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)},
{"4", termbox.AttrBold, none, termbox.AttrBold | termbox.AttrUnderline, none}, {"4", none.Bold(true), none.Bold(true).Underline(true)},
{"4", termbox.ColorRed | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold | termbox.AttrUnderline, none}, {"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)},
{"31", none, none, termbox.ColorRed, none}, {"31", none, none.Foreground(tcell.ColorMaroon)},
{"31", termbox.ColorGreen, none, termbox.ColorRed, none}, {"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"31", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none}, {"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"41", none, none, none, termbox.ColorRed}, {"41", none, none.Background(tcell.ColorMaroon)},
{"41", none, termbox.ColorGreen, none, termbox.ColorRed}, {"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;31", none, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;31", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;5;0", none, none, termbox.ColorBlack, none}, {"38;5;0", none, none.Foreground(tcell.ColorBlack)},
{"38;5;1", none, none, termbox.ColorRed, none}, {"38;5;1", none, none.Foreground(tcell.ColorMaroon)},
{"38;5;8", none, none, termbox.Attribute(9), none}, {"38;5;8", none, none.Foreground(tcell.Color(8))},
{"38;5;16", none, none, termbox.Attribute(17), none}, {"38;5;16", none, none.Foreground(tcell.Color(16))},
{"38;5;232", none, none, termbox.Attribute(233), none}, {"38;5;232", none, none.Foreground(tcell.Color(232))},
{"38;5;1", termbox.ColorGreen, none, termbox.ColorRed, none}, {"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"38;5;1", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none}, {"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;0", none, none.Background(tcell.ColorBlack)},
{"48;5;1", none, none, none, termbox.ColorRed}, {"48;5;1", none, none.Background(tcell.ColorMaroon)},
{"48;5;8", none, none, none, termbox.Attribute(9)}, {"48;5;8", none, none.Background(tcell.Color(8))},
{"48;5;16", none, none, none, termbox.Attribute(17)}, {"48;5;16", none, none.Background(tcell.Color(16))},
{"48;5;232", none, none, none, termbox.Attribute(233)}, {"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", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;38;5;1", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none}, {"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 { for _, test := range tests {
if fgGot, bgGot := applyAnsiCodes(test.s, test.fg, test.bg); fgGot != test.fgExp || bgGot != test.bgExp { if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp {
t.Errorf("at input '%s' with '%d' and '%d' expected '%d' and '%d' but got '%d' and '%d'", t.Errorf("at input '%s' with '%d' expected '%d' but got '%d'",
test.s, test.fg, test.bg, test.fgExp, test.bgExp, fgGot, bgGot) test.s, test.st, test.stExp, stGot)
} }
} }
} }
-3
View File
@@ -70,9 +70,6 @@ var (
"anchorfind", "anchorfind",
"noanchorfind", "noanchorfind",
"anchorfind!", "anchorfind!",
"color256",
"nocolor256",
"color256!",
"dircounts", "dircounts",
"nodircounts", "nodircounts",
"dircounts!", "dircounts!",
+19 -16
View File
@@ -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: The following options can be used to customize the behavior of lf:
anchorfind boolean (default on) anchorfind boolean (default on)
color256 boolean (default off)
dircounts boolean (default off) dircounts boolean (default off)
dirfirst boolean (default on) dirfirst boolean (default on)
drawbox boolean (default off) 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. default colorscheme. Default lf colors are taken from GNU dircolors defaults.
These defaults use 8 basic colors and bold attribute. 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 It is worth noting that lf uses as many colors are advertised by your terminal's
color escapes (e.g. '\033[34m'). If you want to use 256 colors, you need to entry in your systems terminfo or infocmp database, if this is not present lf
enable 'color256' option which then makes lf use sgr 8-bit color escapes (e.g. will default to an internal database. For terminals supporting 24-bit (or
'\033[38;5;4m'). This option is intended to eliminate differences between "true") color that do not have a database entry (or one that does not advertise
default colors used by ls and lf since terminals may render 3-bit and 8-bit all capabilities), support can be enabled by either setting the '$COLORTERM'
escapes differently even for the same color. 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 Keeping this in mind, you can configure lf colors in two different ways. First,
ways. First, you can configure 8 basic colors used by your terminal and lf you can configure 8 basic colors used by your terminal and lf should pick up
should pick up those colors automatically. Depending on your terminal, you those colors automatically. Depending on your terminal, you should be able to
should be able to select your colors from a 24-bit palette. This is the select your colors from a 24-bit palette. This is the recommended approach as
recommended approach as colors used by other programs will also match each colors used by other programs will also match each other.
other.
Second, you can set the values of environmental variables mentioned above for Second, you can set the values of environmental variables mentioned above for
fine grained customization. This is useful to change colors used for different fine grained customization. This is useful to change colors used for different
file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it
it can be used even when GNU programs are not installed on the system. You can 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. 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 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 the rest of the colors. Colors of the prompt line can be configured using the
+17 -14
View File
@@ -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: The following options can be used to customize the behavior of lf:
anchorfind boolean (default on) anchorfind boolean (default on)
color256 boolean (default off)
dircounts boolean (default off) dircounts boolean (default off)
dirfirst boolean (default on) dirfirst boolean (default on)
drawbox boolean (default off) 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 default colorscheme. Default lf colors are taken from GNU dircolors
defaults. These defaults use 8 basic colors and bold attribute. 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 It is worth noting that lf uses as many colors are advertised by your
3-bit color escapes (e.g. '\033[34m'). If you want to use 256 colors, you terminal's entry in your systems terminfo or infocmp database, if this is
need to enable 'color256' option which then makes lf use sgr 8-bit color not present lf will default to an internal database. For terminals
escapes (e.g. '\033[38;5;4m'). This option is intended to eliminate supporting 24-bit (or "true") color that do not have a database entry (or
differences between default colors used by ls and lf since terminals may one that does not advertise all capabilities), support can be enabled by
render 3-bit and 8-bit escapes differently even for the same color. 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 Keeping this in mind, you can configure lf colors in two different ways.
ways. First, you can configure 8 basic colors used by your terminal and lf First, you can configure 8 basic colors used by your terminal and lf should
should pick up those colors automatically. Depending on your terminal, you pick up those colors automatically. Depending on your terminal, you should
should be able to select your colors from a 24-bit palette. This is the be able to select your colors from a 24-bit palette. This is the recommended
recommended approach as colors used by other programs will also match each approach as colors used by other programs will also match each other.
other.
Second, you can set the values of environmental variables mentioned above Second, you can set the values of environmental variables mentioned above
for fine grained customization. This is useful to change colors used for for fine grained customization. This is useful to change colors used for
different file types and extensions. '$LS_COLORS' is more powerful than 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 '$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 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 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 match the rest of the colors. Colors of the prompt line can be configured
+6 -15
View File
@@ -21,20 +21,11 @@ func (e *setExpr) eval(app *app, args []string) {
case "anchorfind!": case "anchorfind!":
gOpts.anchorfind = !gOpts.anchorfind gOpts.anchorfind = !gOpts.anchorfind
case "color256": case "color256":
gOpts.color256 = true app.ui.echoerr("option color256 is depreciated")
setColorMode()
app.ui.pause()
app.ui.resume()
case "nocolor256": case "nocolor256":
gOpts.color256 = false app.ui.echoerr("option nocolor256 is depreciated")
setColorMode()
app.ui.pause()
app.ui.resume()
case "color256!": case "color256!":
gOpts.color256 = !gOpts.color256 app.ui.echoerr("option color256! is depreciated")
setColorMode()
app.ui.pause()
app.ui.resume()
case "dircounts": case "dircounts":
gOpts.dircounts = true gOpts.dircounts = true
case "nodircounts": case "nodircounts":
@@ -284,7 +275,7 @@ func (e *setExpr) eval(app *app, args []string) {
return return
} }
gOpts.ratios = rats gOpts.ratios = rats
app.ui.wins = getWins() app.ui.wins = getWins(app.ui.screen)
app.ui.loadFile(app.nav) app.ui.loadFile(app.nav)
case "shell": case "shell":
gOpts.shell = e.val gOpts.shell = e.val
@@ -793,8 +784,8 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
case "draw": case "draw":
case "redraw": case "redraw":
app.ui.sync()
app.ui.renew() app.ui.renew()
app.ui.screen.Sync()
app.nav.height = app.ui.wins[0].h app.nav.height = app.ui.wins[0].h
app.ui.loadFile(app.nav) app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
@@ -1056,7 +1047,7 @@ func (e *callExpr) eval(app *app, args []string) {
} }
app.ui.draw(app.nav) app.ui.draw(app.nav)
if len(matches) > 1 { if len(matches) > 1 {
app.ui.menuBuf = listMatches(matches) app.ui.menuBuf = listMatches(app.ui.screen, matches)
} else { } else {
app.ui.menuBuf = nil app.ui.menuBuf = nil
} }
+1 -1
View File
@@ -3,7 +3,7 @@ module github.com/gokcehan/lf
go 1.12 go 1.12
require ( 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 github.com/mattn/go-runewidth v0.0.9
gopkg.in/djherbis/times.v1 v1.2.0 gopkg.in/djherbis/times.v1 v1.2.0
) )
+6 -2
View File
@@ -1,6 +1,10 @@
github.com/doronbehar/termbox-go v0.0.0-20200711071547-71407e3bfa14 h1:KKPl27Vj3HRF384G7jW7K8uCRv0Ks+GuAOkGsz4qWAs= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/doronbehar/termbox-go v0.0.0-20200711071547-71407e3bfa14/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk= 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 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= 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 h1:UCvDKl1L/fmBygl2Y7hubXCnY7t4Yj46ZrBFNUipFbM=
gopkg.in/djherbis/times.v1 v1.2.0/go.mod h1:AQlg6unIsrsCEdQYhTzERy542dz6SFdQFZFv6mUY0P8= gopkg.in/djherbis/times.v1 v1.2.0/go.mod h1:AQlg6unIsrsCEdQYhTzERy542dz6SFdQFZFv6mUY0P8=
+3 -4
View File
@@ -111,7 +111,6 @@ The following options can be used to customize the behavior of lf:
.PP .PP
.EX .EX
anchorfind boolean (default on) anchorfind boolean (default on)
color256 boolean (default off)
dircounts boolean (default off) dircounts boolean (default off)
dirfirst boolean (default on) dirfirst boolean (default on)
drawbox boolean (default off) drawbox boolean (default off)
@@ -924,10 +923,10 @@ If '$LS_COLORS' variable is not set, '$LSCOLORS' variable is checked instead. Th
.PP .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. 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 .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 .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 .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 .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. 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.
+1
View File
@@ -50,6 +50,7 @@ func exportEnvVars() {
os.Setenv("EDITOR", envEditor) os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager) os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell) os.Setenv("SHELL", envShell)
os.Setenv("TCELL_TRUECOLOR", envTcellTruecolor)
level, err := strconv.Atoi(envLevel) level, err := strconv.Atoi(envLevel)
if err != nil { if err != nil {
-2
View File
@@ -29,7 +29,6 @@ type sortType struct {
var gOpts struct { var gOpts struct {
anchorfind bool anchorfind bool
color256 bool
dircounts bool dircounts bool
drawbox bool drawbox bool
globsearch bool globsearch bool
@@ -68,7 +67,6 @@ var gOpts struct {
func init() { func init() {
gOpts.anchorfind = true gOpts.anchorfind = true
gOpts.color256 = false
gOpts.dircounts = false gOpts.dircounts = false
gOpts.drawbox = false gOpts.drawbox = false
gOpts.globsearch = false gOpts.globsearch = false
+9 -4
View File
@@ -15,10 +15,11 @@ import (
) )
var ( var (
envOpener = os.Getenv("OPENER") envOpener = os.Getenv("OPENER")
envEditor = os.Getenv("EDITOR") envEditor = os.Getenv("EDITOR")
envPager = os.Getenv("PAGER") envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL") envShell = os.Getenv("SHELL")
envTcellTruecolor = os.Getenv("TCELL_TRUECOLOR")
) )
var ( var (
@@ -55,6 +56,10 @@ func init() {
envShell = "sh" envShell = "sh"
} }
if envTcellTruecolor == "" {
envTcellTruecolor = "disable"
}
u, err := user.Current() u, err := user.Current()
if err != nil { if err != nil {
log.Printf("user: %s", err) log.Printf("user: %s", err)
+5
View File
@@ -16,6 +16,7 @@ var (
envEditor = os.Getenv("EDITOR") envEditor = os.Getenv("EDITOR")
envPager = os.Getenv("PAGER") envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL") envShell = os.Getenv("SHELL")
envTcellTruecolor = os.Getenv("TCELL_TRUECOLOR")
) )
var envPathExt = os.Getenv("PATHEXT") var envPathExt = os.Getenv("PATHEXT")
@@ -50,6 +51,10 @@ func init() {
envShell = "cmd" envShell = "cmd"
} }
if envTcellTruecolor == "" {
envTcellTruecolor = "disable"
}
u, err := user.Current() u, err := user.Current()
if err != nil { if err != nil {
log.Printf("user: %s", err) log.Printf("user: %s", err)
+256 -201
View File
@@ -15,75 +15,75 @@ import (
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
"github.com/doronbehar/termbox-go" "github.com/gdamore/tcell"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
) )
const gEscapeCode = 27 const gEscapeCode = 27
var gKeyVal = map[termbox.Key]string{ var gKeyVal = map[tcell.Key]string{
termbox.KeyF1: "<f-1>", tcell.KeyF1: "<f-1>",
termbox.KeyF2: "<f-2>", tcell.KeyF2: "<f-2>",
termbox.KeyF3: "<f-3>", tcell.KeyF3: "<f-3>",
termbox.KeyF4: "<f-4>", tcell.KeyF4: "<f-4>",
termbox.KeyF5: "<f-5>", tcell.KeyF5: "<f-5>",
termbox.KeyF6: "<f-6>", tcell.KeyF6: "<f-6>",
termbox.KeyF7: "<f-7>", tcell.KeyF7: "<f-7>",
termbox.KeyF8: "<f-8>", tcell.KeyF8: "<f-8>",
termbox.KeyF9: "<f-9>", tcell.KeyF9: "<f-9>",
termbox.KeyF10: "<f-10>", tcell.KeyF10: "<f-10>",
termbox.KeyF11: "<f-11>", tcell.KeyF11: "<f-11>",
termbox.KeyF12: "<f-12>", tcell.KeyF12: "<f-12>",
termbox.KeyInsert: "<insert>", tcell.KeyInsert: "<insert>",
termbox.KeyDelete: "<delete>", tcell.KeyDelete: "<delete>",
termbox.KeyHome: "<home>", tcell.KeyHome: "<home>",
termbox.KeyEnd: "<end>", tcell.KeyEnd: "<end>",
termbox.KeyPgup: "<pgup>", tcell.KeyPgUp: "<pgup>",
termbox.KeyPgdn: "<pgdn>", tcell.KeyPgDn: "<pgdn>",
termbox.KeyArrowUp: "<up>", tcell.KeyUp: "<up>",
termbox.KeyArrowDown: "<down>", tcell.KeyDown: "<down>",
termbox.KeyArrowLeft: "<left>", tcell.KeyLeft: "<left>",
termbox.KeyArrowRight: "<right>", tcell.KeyRight: "<right>",
termbox.KeyCtrlSpace: "<c-space>", tcell.KeyCtrlSpace: "<c-space>",
termbox.KeyCtrlA: "<c-a>", tcell.KeyCtrlA: "<c-a>",
termbox.KeyCtrlB: "<c-b>", tcell.KeyCtrlB: "<c-b>",
termbox.KeyCtrlC: "<c-c>", tcell.KeyCtrlC: "<c-c>",
termbox.KeyCtrlD: "<c-d>", tcell.KeyCtrlD: "<c-d>",
termbox.KeyCtrlE: "<c-e>", tcell.KeyCtrlE: "<c-e>",
termbox.KeyCtrlF: "<c-f>", tcell.KeyCtrlF: "<c-f>",
termbox.KeyCtrlG: "<c-g>", tcell.KeyCtrlG: "<c-g>",
termbox.KeyBackspace: "<bs>", tcell.KeyBackspace: "<bs>",
termbox.KeyTab: "<tab>", tcell.KeyTab: "<tab>",
termbox.KeyCtrlJ: "<c-j>", tcell.KeyCtrlJ: "<c-j>",
termbox.KeyCtrlK: "<c-k>", tcell.KeyCtrlK: "<c-k>",
termbox.KeyCtrlL: "<c-l>", tcell.KeyCtrlL: "<c-l>",
termbox.KeyEnter: "<enter>", tcell.KeyEnter: "<enter>",
termbox.KeyCtrlN: "<c-n>", tcell.KeyCtrlN: "<c-n>",
termbox.KeyCtrlO: "<c-o>", tcell.KeyCtrlO: "<c-o>",
termbox.KeyCtrlP: "<c-p>", tcell.KeyCtrlP: "<c-p>",
termbox.KeyCtrlQ: "<c-q>", tcell.KeyCtrlQ: "<c-q>",
termbox.KeyCtrlR: "<c-r>", tcell.KeyCtrlR: "<c-r>",
termbox.KeyCtrlS: "<c-s>", tcell.KeyCtrlS: "<c-s>",
termbox.KeyCtrlT: "<c-t>", tcell.KeyCtrlT: "<c-t>",
termbox.KeyCtrlU: "<c-u>", tcell.KeyCtrlU: "<c-u>",
termbox.KeyCtrlV: "<c-v>", tcell.KeyCtrlV: "<c-v>",
termbox.KeyCtrlW: "<c-w>", tcell.KeyCtrlW: "<c-w>",
termbox.KeyCtrlX: "<c-x>", tcell.KeyCtrlX: "<c-x>",
termbox.KeyCtrlY: "<c-y>", tcell.KeyCtrlY: "<c-y>",
termbox.KeyCtrlZ: "<c-z>", tcell.KeyCtrlZ: "<c-z>",
termbox.KeyEsc: "<esc>", tcell.KeyEsc: "<esc>",
termbox.KeyCtrlBackslash: "<c-\\>", tcell.KeyCtrlBackslash: "<c-\\>",
termbox.KeyCtrlRsqBracket: "<c-]>", tcell.KeyCtrlRightSq: "<c-]>",
termbox.KeyCtrl6: "<c-6>", // TODO: compatability only, they are discouraged
termbox.KeyCtrlSlash: "<c-/>", tcell.KeyCtrlCarat: "<c-6>",
termbox.KeySpace: "<space>", tcell.KeyCtrlUnderscore: "<c-/>",
termbox.KeyBackspace2: "<bs2>", tcell.KeyBackspace2: "<bs2>",
} }
var gValKey map[string]termbox.Key var gValKey map[string]tcell.Key
func init() { func init() {
gValKey = make(map[string]termbox.Key) gValKey = make(map[string]tcell.Key)
for k, v := range gKeyVal { for k, v := range gKeyVal {
gValKey[v] = k gValKey[v] = k
} }
@@ -129,7 +129,7 @@ func printLength(s string) int {
return ind 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 off := x
for i := 0; i < len(s); i++ { for i := 0; i < len(s); i++ {
r, w := utf8.DecodeRuneInString(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 continue
} }
fg, bg = applyAnsiCodes(s[i+2:i+j], fg, bg) st = applyAnsiCodes(s[i+2:i+j], st)
i += j i += j
continue continue
} }
if x < win.w { 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 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' { if r == '\t' {
s := gOpts.tabstop - (x-off)%gOpts.tabstop s := gOpts.tabstop - (x-off)%gOpts.tabstop
for i := 0; i < s && x+i < win.w; i++ { 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 x += s
} else { } 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{}) { func (win *win) printf(screen tcell.Screen, x, y int, st tcell.Style, format string, a ...interface{}) {
win.print(x, y, fg, bg, fmt.Sprintf(format, a...)) win.print(screen, x, y, st, fmt.Sprintf(format, a...))
} }
func (win *win) printLine(x, y int, fg, bg termbox.Attribute, s string) { func (win *win) printLine(screen tcell.Screen, x, y int, st tcell.Style, s string) {
win.printf(x, y, fg, bg, "%s%*s", s, win.w-len(s), "") 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) { func (win *win) printRight(screen tcell.Screen, y int, st tcell.Style, s string) {
win.print(win.w-len(s), y, fg, bg, s) 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 { if reg == nil {
return return
} }
fg, bg := termbox.ColorDefault, termbox.ColorDefault st := tcell.StyleDefault
if reg.loading { if reg.loading {
fg = termbox.AttrReverse st = st.Reverse(true)
win.print(2, 0, fg, bg, "loading...") win.print(screen, 2, 0, st, "loading...")
return return
} }
for i, l := range reg.lines { 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 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 { if win.w < 5 || dir == nil {
return return
} }
if dir.loading { if dir.loading {
win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "loading...") win.print(screen, 2, 0, tcell.StyleDefault.Reverse(true), "loading...")
return return
} }
if dir.noPerm { 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 return
} }
if len(dir.files) == 0 { 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 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] { for i, f := range dir.files[beg:end] {
fg, bg := colors.get(f) st := colors.get(f)
if lnwidth > 0 { if lnwidth > 0 {
var ln string 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()) path := filepath.Join(dir.path, f.Name())
if _, ok := selections[path]; ok { 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 { } else if cp, ok := saves[path]; ok {
if cp { if cp {
win.print(lnwidth, i, fg, termbox.ColorYellow, " ") win.print(screen, lnwidth, i, st.Background(tcell.ColorOlive), " ")
} else { } else {
win.print(lnwidth, i, fg, termbox.ColorRed, " ") win.print(screen, lnwidth, i, st.Background(tcell.ColorMaroon), " ")
} }
} }
if i == dir.pos { if i == dir.pos {
fg |= termbox.AttrReverse st = st.Reverse(true)
} }
var s []rune var s []rune
@@ -368,11 +372,12 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b
s = append(s, ' ') s = append(s, ' ')
win.print(lnwidth+1, i, fg, bg, string(s)) win.print(screen, lnwidth+1, i, st, string(s))
} }
} }
type ui struct { type ui struct {
screen tcell.Screen
wins []*win wins []*win
promptWin *win promptWin *win
msgWin *win msgWin *win
@@ -382,7 +387,7 @@ type ui struct {
dirPrev *dir dirPrev *dir
exprChan chan expr exprChan chan expr
keyChan chan string keyChan chan string
evChan chan termbox.Event evChan chan tcell.Event
menuBuf *bytes.Buffer menuBuf *bytes.Buffer
cmdPrefix string cmdPrefix string
cmdAccLeft []rune cmdAccLeft []rune
@@ -390,7 +395,7 @@ type ui struct {
cmdYankBuf []rune cmdYankBuf []rune
keyAcc []rune keyAcc []rune
keyCount []rune keyCount []rune
colors colorMap styles styleMap
icons iconMap icons iconMap
} }
@@ -417,8 +422,8 @@ func getWidths(wtot int) []int {
return widths return widths
} }
func getWins() []*win { func getWins(screen tcell.Screen) []*win {
wtot, htot := termbox.Size() wtot, htot := screen.Size()
var wins []*win var wins []*win
@@ -438,47 +443,76 @@ func getWins() []*win {
return wins return wins
} }
func newUI() *ui { func startEventListening(screen tcell.Screen) chan tcell.Event {
wtot, htot := termbox.Size() evQueue := make(chan tcell.Event)
evQueue := make(chan termbox.Event)
go func() { go func() {
var ev tcell.Event
for { 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() { go func() {
for { for {
ev := <-evQueue ev := <-evQueue
if ev.Type == termbox.EventKey && ev.Key == termbox.KeyEsc { // .(type) can't be used outside a switch
select { switch tev := ev.(type) {
case ev2 := <-evQueue: case *tcell.EventKey:
ev2.Mod = termbox.ModAlt // tcell.KeyESC is one of the few cases we don't need Rune() for
evChan <- ev2 if tev.Key() == tcell.KeyESC {
continue select {
case <-time.After(100 * time.Millisecond): 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 evChan <- ev
if ev == nil {
return
}
} }
}() }()
return evChan
}
func newUI(screen tcell.Screen) *ui {
wtot, htot := screen.Size()
return &ui{ return &ui{
wins: getWins(), screen: screen,
wins: getWins(screen),
promptWin: newWin(wtot, 1, 0, 0), promptWin: newWin(wtot, 1, 0, 0),
msgWin: newWin(wtot, 1, 0, htot-1), msgWin: newWin(wtot, 1, 0, htot-1),
menuWin: newWin(wtot, 1, 0, htot-2), menuWin: newWin(wtot, 1, 0, htot-2),
keyChan: make(chan string, 1000), keyChan: make(chan string, 1000),
evChan: evChan, evChan: startEventListening(screen),
colors: parseColors(), styles: parseStyles(),
icons: parseIcons(), icons: parseIcons(),
} }
} }
func (ui *ui) renew() { func (ui *ui) renew() {
wtot, htot := termbox.Size() wtot, htot := ui.screen.Size()
widths := getWidths(wtot) widths := getWidths(wtot)
@@ -571,7 +605,7 @@ func (ui *ui) loadFileInfo(nav *nav) {
} }
func (ui *ui) drawPromptLine(nav *nav) { func (ui *ui) drawPromptLine(nav *nav) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault st := tcell.StyleDefault
pwd := nav.currDir().path pwd := nav.currDir().path
@@ -614,15 +648,15 @@ func (ui *ui) drawPromptLine(nav *nav) {
prompt = strings.Replace(prompt, "%w", pwd, -1) 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) { func (ui *ui) drawStatLine(nav *nav) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault st := tcell.StyleDefault
dir := nav.currDir() 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) tot := len(dir.files)
ind := min(dir.ind+1, tot) 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) 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() { 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++ { for i := 1; i < w-1; i++ {
termbox.SetCell(i, 1, '─', fg, bg) ui.screen.SetContent(i, 1, '─', nil, st)
termbox.SetCell(i, h-2, '─', fg, bg) ui.screen.SetContent(i, h-2, '─', nil, st)
} }
for i := 2; i < h-2; i++ { for i := 2; i < h-2; i++ {
termbox.SetCell(0, i, '│', fg, bg) ui.screen.SetContent(0, i, '│', nil, st)
termbox.SetCell(w-1, i, '│', fg, bg) ui.screen.SetContent(w-1, i, '│', nil, st)
} }
termbox.SetCell(0, 1, '┌', fg, bg) ui.screen.SetContent(0, 1, '┌', nil, st)
termbox.SetCell(w-1, 1, '┐', fg, bg) ui.screen.SetContent(w-1, 1, '┐', nil, st)
termbox.SetCell(0, h-2, '└', fg, bg) ui.screen.SetContent(0, h-2, '└', nil, st)
termbox.SetCell(w-1, h-2, '┘', fg, bg) ui.screen.SetContent(w-1, h-2, '┘', nil, st)
wacc := 0 wacc := 0
for wind := 0; wind < len(ui.wins)-1; wind++ { for wind := 0; wind < len(ui.wins)-1; wind++ {
wacc += ui.wins[wind].w 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++ { 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) { 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) ui.drawPromptLine(nav)
@@ -696,24 +735,24 @@ func (ui *ui) draw(nav *nav) {
doff := len(nav.dirs) - length doff := len(nav.dirs) - length
for i := 0; i < length; i++ { 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 { switch ui.cmdPrefix {
case "": case "":
ui.drawStatLine(nav) ui.drawStatLine(nav)
termbox.HideCursor() ui.screen.HideCursor()
case ">": case ">":
ui.msgWin.printLine(0, 0, fg, bg, ui.cmdPrefix) ui.msgWin.printLine(ui.screen, 0, 0, st, ui.cmdPrefix)
ui.msgWin.print(len(ui.cmdPrefix), 0, fg, bg, ui.msg) ui.msgWin.print(ui.screen, len(ui.cmdPrefix), 0, st, ui.msg)
ui.msgWin.print(len(ui.cmdPrefix)+len(ui.msg), 0, fg, bg, string(ui.cmdAccLeft)) ui.msgWin.print(ui.screen, len(ui.cmdPrefix)+len(ui.msg), 0, st, string(ui.cmdAccLeft))
ui.msgWin.print(len(ui.cmdPrefix)+len(ui.msg)+runeSliceWidth(ui.cmdAccLeft), 0, fg, bg, string(ui.cmdAccRight)) ui.msgWin.print(ui.screen, len(ui.cmdPrefix)+len(ui.msg)+runeSliceWidth(ui.cmdAccLeft), 0, st, string(ui.cmdAccRight))
termbox.SetCursor(ui.msgWin.x+len(ui.cmdPrefix)+len(ui.msg)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y) ui.screen.ShowCursor(ui.msgWin.x+len(ui.cmdPrefix)+len(ui.msg)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y)
default: default:
ui.msgWin.printLine(0, 0, fg, bg, ui.cmdPrefix) ui.msgWin.printLine(ui.screen, 0, 0, st, ui.cmdPrefix)
ui.msgWin.print(len(ui.cmdPrefix), 0, fg, bg, string(ui.cmdAccLeft)) ui.msgWin.print(ui.screen, len(ui.cmdPrefix), 0, st, string(ui.cmdAccLeft))
ui.msgWin.print(len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), 0, fg, bg, string(ui.cmdAccRight)) ui.msgWin.print(ui.screen, len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), 0, st, string(ui.cmdAccRight))
termbox.SetCursor(ui.msgWin.x+len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y) ui.screen.ShowCursor(ui.msgWin.x+len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y)
} }
if gOpts.preview { if gOpts.preview {
@@ -722,9 +761,9 @@ func (ui *ui) draw(nav *nav) {
preview := ui.wins[len(ui.wins)-1] preview := ui.wins[len(ui.wins)-1]
if curr.IsDir() { 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() { } 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.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:] { for i, line := range lines[1:] {
ui.menuWin.printLine(0, i+1, fg, bg, "") ui.menuWin.printLine(ui.screen, 0, i+1, st, "")
ui.menuWin.print(0, i+1, fg, bg, line) 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) { 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 return b
} }
func (ui *ui) pollEvent() termbox.Event { func (ui *ui) pollEvent() tcell.Event {
select { select {
case key := <-ui.keyChan: 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 { if utf8.RuneCountInString(key) == 1 {
ev.Ch, _ = utf8.DecodeRuneInString(key) ch, _ = utf8.DecodeRuneInString(key)
} else { } else {
switch { switch {
case key == "<lt>": case key == "<lt>":
ev.Ch = '<' ch = '<'
case key == "<gt>": case key == "<gt>":
ev.Ch = '>' ch = '>'
case reAltKey.MatchString(key): case reAltKey.MatchString(key):
match := reAltKey.FindStringSubmatch(key)[1] match := reAltKey.FindStringSubmatch(key)[1]
ev.Ch, _ = utf8.DecodeRuneInString(match) ch, _ = utf8.DecodeRuneInString(match)
ev.Mod = termbox.ModAlt mod = tcell.ModMask(tcell.ModAlt)
default: default:
if val, ok := gValKey[key]; ok { if val, ok := gValKey[key]; ok {
ev.Key = val Key = val
} else { } else {
ev.Key = termbox.KeyEsc Key = tcell.KeyESC
ui.echoerrf("unknown key: %s", key) ui.echoerrf("unknown key: %s", key)
} }
} }
} }
return ev return tcell.NewEventKey(Key, ch, mod)
case ev := <-ui.evChan: case ev := <-ui.evChan:
return ev 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, // 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 // 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"). // 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} draw := &callExpr{"draw", nil, 1}
count := 1 count := 1
switch ev.Type { switch tev := ev.(type) {
case termbox.EventKey: case *tcell.EventKey:
if ev.Ch != 0 { // KeyRune is a regular character
if tev.Key() == tcell.KeyRune {
switch { switch {
case ev.Ch == '<': case tev.Rune() == '<':
ui.keyAcc = append(ui.keyAcc, []rune("<lt>")...) ui.keyAcc = append(ui.keyAcc, []rune("<lt>")...)
case ev.Ch == '>': case tev.Rune() == '>':
ui.keyAcc = append(ui.keyAcc, []rune("<gt>")...) ui.keyAcc = append(ui.keyAcc, []rune("<gt>")...)
case ev.Mod == termbox.ModAlt: case tev.Rune() == ' ':
ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', ev.Ch, '>') ui.keyAcc = append(ui.keyAcc, []rune("<space>")...)
case unicode.IsDigit(ev.Ch) && len(ui.keyAcc) == 0: case tev.Modifiers() == tcell.ModAlt:
ui.keyCount = append(ui.keyCount, ev.Ch) 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: default:
ui.keyAcc = append(ui.keyAcc, ev.Ch) ui.keyAcc = append(ui.keyAcc, tev.Rune())
} }
} else { } else {
val := gKeyVal[ev.Key] val := gKeyVal[tev.Key()]
if val == "<esc>" { if val == "<esc>" {
ch <- draw ch <- draw
ui.keyAcc = nil ui.keyAcc = nil
@@ -914,25 +962,34 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
ch <- draw ch <- draw
} }
} }
case termbox.EventResize: case *tcell.EventResize:
ch <- &callExpr{"redraw", nil, 1} 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) { func readCmdEvent(ch chan<- expr, ev tcell.Event) {
if ev.Ch != 0 { switch tev := ev.(type) {
if ev.Mod == termbox.ModAlt { case *tcell.EventKey:
val := string([]rune{'<', 'a', '-', ev.Ch, '>'}) 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 { if expr, ok := gOpts.cmdkeys[val]; ok {
ch <- expr 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 { for {
ev := ui.pollEvent() ev := ui.pollEvent()
if ui.cmdPrefix != "" && ev.Type == termbox.EventKey { switch ev.(type) {
readCmdEvent(ch, ev) case *tcell.EventKey:
continue if ui.cmdPrefix != "" {
readCmdEvent(ch, ev)
continue
}
} }
ui.readEvent(ch, ev) ui.readEvent(ch, ev)
@@ -960,34 +1020,29 @@ func (ui *ui) readExpr() <-chan expr {
return ch return ch
} }
func setColorMode() {
if gOpts.color256 {
termbox.SetOutputMode(termbox.Output256)
} else {
termbox.SetOutputMode(termbox.OutputNormal)
}
}
func (ui *ui) pause() { func (ui *ui) pause() {
termbox.Close() ui.screen.Fini()
} }
func (ui *ui) resume() { func (ui *ui) resume() {
if err := termbox.Init(); err != nil { var err error
log.Fatalf("initializing termbox: %s", err)
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() { func listMatches(screen tcell.Screen, matches []string) *bytes.Buffer {
if err := termbox.Sync(); err != nil {
log.Printf("syncing termbox: %s", err)
}
}
func listMatches(matches []string) *bytes.Buffer {
b := new(bytes.Buffer) b := new(bytes.Buffer)
wtot, _ := termbox.Size() wtot, _ := screen.Size()
wcol := 0 wcol := 0
for _, m := range matches { for _, m := range matches {