repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/util/util_test.go
src/util/util_test.go
package util import ( "math" "strings" "testing" ) func TestConstrain(t *testing.T) { if Constrain(-3, -1, 3) != -1 { t.Error("Expected", -1) } if Constrain(2, -1, 3) != 2 { t.Error("Expected", 2) } if Constrain(5, -1, 3) != 3 { t.Error("Expected", 3) } } func TestAsUint16(t *testing.T) { if AsUint16(5) != 5 { t.Error("Expected", 5) } if AsUint16(-10) != 0 { t.Error("Expected", 0) } if AsUint16(math.MaxUint16) != math.MaxUint16 { t.Error("Expected", math.MaxUint16) } if AsUint16(math.MinInt32) != 0 { t.Error("Expected", 0) } if AsUint16(math.MinInt16) != 0 { t.Error("Expected", 0) } if AsUint16(math.MaxUint16+1) != math.MaxUint16 { t.Error("Expected", math.MaxUint16) } } func TestOnce(t *testing.T) { o := Once(false) if o() { t.Error("Expected: false") } if !o() { t.Error("Expected: true") } if !o() { t.Error("Expected: true") } o = Once(true) if !o() { t.Error("Expected: true") } if o() { t.Error("Expected: false") } if o() { t.Error("Expected: false") } } func TestRunesWidth(t *testing.T) { for _, args := range [][]int{ {100, 5, -1}, {3, 4, 3}, {0, 1, 0}, } { width, overflowIdx := RunesWidth([]rune("hello"), 0, 0, args[0]) if width != args[1] { t.Errorf("Expected width: %d, actual: %d", args[1], width) } if overflowIdx != args[2] { t.Errorf("Expected overflow index: %d, actual: %d", args[2], overflowIdx) } } for _, input := range []struct { s string w int }{ {"▶", 1}, {"▶️", 2}, } { width, _ := RunesWidth([]rune(input.s), 0, 0, 100) if width != input.w { t.Errorf("Expected width of %s: %d, actual: %d", input.s, input.w, width) } } } func TestTruncate(t *testing.T) { truncated, width := Truncate("가나다라마", 7) if string(truncated) != "가나다" { t.Errorf("Expected: 가나다, actual: %s", string(truncated)) } if width != 6 { t.Errorf("Expected: 6, actual: %d", width) } } func TestRepeatToFill(t *testing.T) { if RepeatToFill("abcde", 10, 50) != strings.Repeat("abcde", 5) { t.Error("Expected:", strings.Repeat("abcde", 5)) } if RepeatToFill("abcde", 10, 42) != strings.Repeat("abcde", 4)+"abcde"[:2] { t.Error("Expected:", strings.Repeat("abcde", 4)+"abcde"[:2]) } } func TestStringWidth(t *testing.T) { w := StringWidth("─") if w != 1 { t.Errorf("Expected: %d, Actual: %d", 1, w) } } func TestCompareVersions(t *testing.T) { assert := func(a, b string, expected int) { if result := CompareVersions(a, b); result != expected { t.Errorf("Expected: %d, Actual: %d", expected, result) } } assert("2", "1", 1) assert("2", "2", 0) assert("2", "10", -1) assert("2.1", "2.2", -1) assert("2.1", "2.1.1", -1) assert("1.2.3", "1.2.2", 1) assert("1.2.3", "1.2.3", 0) assert("1.2.3", "1.2.3.0", 0) assert("1.2.3", "1.2.4", -1) // Different number of parts assert("1.0.0", "1", 0) assert("1.0.0", "1.0", 0) assert("1.0.0", "1.0.0", 0) assert("1.0", "1.0.0", 0) assert("1", "1.0.0", 0) assert("1.0.0", "1.0.0.1", -1) assert("1.0.0.1.0", "1.0.0.1", 0) assert("", "3.4.5", -1) }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/util/atomicbool.go
src/util/atomicbool.go
package util import ( "sync/atomic" ) func convertBoolToInt32(b bool) int32 { if b { return 1 } return 0 } // AtomicBool is a boxed-class that provides synchronized access to the // underlying boolean value type AtomicBool struct { state int32 // "1" is true, "0" is false } // NewAtomicBool returns a new AtomicBool func NewAtomicBool(initialState bool) *AtomicBool { return &AtomicBool{state: convertBoolToInt32(initialState)} } // Get returns the current boolean value synchronously func (a *AtomicBool) Get() bool { return atomic.LoadInt32(&a.state) == 1 } // Set updates the boolean value synchronously func (a *AtomicBool) Set(newState bool) bool { atomic.StoreInt32(&a.state, convertBoolToInt32(newState)) return newState }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/protector/protector.go
src/protector/protector.go
//go:build !openbsd package protector // Protect calls OS specific protections like pledge on OpenBSD func Protect() {}
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/protector/protector_openbsd.go
src/protector/protector_openbsd.go
//go:build openbsd package protector import "golang.org/x/sys/unix" // Protect calls OS specific protections like pledge on OpenBSD func Protect() { unix.PledgePromises("stdio dpath wpath rpath tty proc exec inet tmppath") }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/algo/algo_test.go
src/algo/algo_test.go
package algo import ( "math" "sort" "strings" "testing" "github.com/junegunn/fzf/src/util" ) func init() { Init("default") } func assertMatch(t *testing.T, fun Algo, caseSensitive, forward bool, input, pattern string, sidx int, eidx int, score int) { assertMatch2(t, fun, caseSensitive, false, forward, input, pattern, sidx, eidx, score) } func assertMatch2(t *testing.T, fun Algo, caseSensitive, normalize, forward bool, input, pattern string, sidx int, eidx int, score int) { if !caseSensitive { pattern = strings.ToLower(pattern) } chars := util.ToChars([]byte(input)) res, pos := fun(caseSensitive, normalize, forward, &chars, []rune(pattern), true, nil) var start, end int if pos == nil || len(*pos) == 0 { start = res.Start end = res.End } else { sort.Ints(*pos) start = (*pos)[0] end = (*pos)[len(*pos)-1] + 1 } if start != sidx { t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", start, sidx, input, pattern) } if end != eidx { t.Errorf("Invalid end index: %d (expected: %d, %s / %s)", end, eidx, input, pattern) } if res.Score != score { t.Errorf("Invalid score: %d (expected: %d, %s / %s)", res.Score, score, input, pattern) } } func TestFuzzyMatch(t *testing.T) { for _, fn := range []Algo{FuzzyMatchV1, FuzzyMatchV2} { for _, forward := range []bool{true, false} { assertMatch(t, fn, false, forward, "fooBarbaz1", "oBZ", 2, 9, scoreMatch*3+bonusCamel123+scoreGapStart+scoreGapExtension*3) assertMatch(t, fn, false, forward, "foo bar baz", "fbb", 0, 9, scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+ int(bonusBoundaryWhite)*2+2*scoreGapStart+4*scoreGapExtension) assertMatch(t, fn, false, forward, "/AutomatorDocument.icns", "rdoc", 9, 13, scoreMatch*4+bonusCamel123+bonusConsecutive*2) assertMatch(t, fn, false, forward, "/man1/zshcompctl.1", "zshc", 6, 10, scoreMatch*4+int(bonusBoundaryDelimiter)*bonusFirstCharMultiplier+int(bonusBoundaryDelimiter)*3) assertMatch(t, fn, false, forward, "/.oh-my-zsh/cache", "zshc", 8, 13, scoreMatch*4+bonusBoundary*bonusFirstCharMultiplier+bonusBoundary*2+scoreGapStart+int(bonusBoundaryDelimiter)) assertMatch(t, fn, false, forward, "ab0123 456", "12356", 3, 10, scoreMatch*5+bonusConsecutive*3+scoreGapStart+scoreGapExtension) assertMatch(t, fn, false, forward, "abc123 456", "12356", 3, 10, scoreMatch*5+bonusCamel123*bonusFirstCharMultiplier+bonusCamel123*2+bonusConsecutive+scoreGapStart+scoreGapExtension) assertMatch(t, fn, false, forward, "foo/bar/baz", "fbb", 0, 9, scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+ int(bonusBoundaryDelimiter)*2+2*scoreGapStart+4*scoreGapExtension) assertMatch(t, fn, false, forward, "fooBarBaz", "fbb", 0, 7, scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+ bonusCamel123*2+2*scoreGapStart+2*scoreGapExtension) assertMatch(t, fn, false, forward, "foo barbaz", "fbb", 0, 8, scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryWhite)+ scoreGapStart*2+scoreGapExtension*3) assertMatch(t, fn, false, forward, "fooBar Baz", "foob", 0, 4, scoreMatch*4+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryWhite)*3) assertMatch(t, fn, false, forward, "xFoo-Bar Baz", "foo-b", 1, 6, scoreMatch*5+bonusCamel123*bonusFirstCharMultiplier+bonusCamel123*2+ bonusNonWord+bonusBoundary) assertMatch(t, fn, true, forward, "fooBarbaz", "oBz", 2, 9, scoreMatch*3+bonusCamel123+scoreGapStart+scoreGapExtension*3) assertMatch(t, fn, true, forward, "Foo/Bar/Baz", "FBB", 0, 9, scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryDelimiter)*2+ scoreGapStart*2+scoreGapExtension*4) assertMatch(t, fn, true, forward, "FooBarBaz", "FBB", 0, 7, scoreMatch*3+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+bonusCamel123*2+ scoreGapStart*2+scoreGapExtension*2) assertMatch(t, fn, true, forward, "FooBar Baz", "FooB", 0, 4, scoreMatch*4+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryWhite)*2+ max(bonusCamel123, int(bonusBoundaryWhite))) // Consecutive bonus updated assertMatch(t, fn, true, forward, "foo-bar", "o-ba", 2, 6, scoreMatch*4+bonusBoundary*3) // Non-match assertMatch(t, fn, true, forward, "fooBarbaz", "oBZ", -1, -1, 0) assertMatch(t, fn, true, forward, "Foo Bar Baz", "fbb", -1, -1, 0) assertMatch(t, fn, true, forward, "fooBarbaz", "fooBarbazz", -1, -1, 0) } } } func TestFuzzyMatchBackward(t *testing.T) { assertMatch(t, FuzzyMatchV1, false, true, "foobar fb", "fb", 0, 4, scoreMatch*2+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+ scoreGapStart+scoreGapExtension) assertMatch(t, FuzzyMatchV1, false, false, "foobar fb", "fb", 7, 9, scoreMatch*2+int(bonusBoundaryWhite)*bonusFirstCharMultiplier+int(bonusBoundaryWhite)) } func TestExactMatchNaive(t *testing.T) { for _, dir := range []bool{true, false} { assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "oBA", -1, -1, 0) assertMatch(t, ExactMatchNaive, true, dir, "fooBarbaz", "fooBarbazz", -1, -1, 0) assertMatch(t, ExactMatchNaive, false, dir, "fooBarbaz", "oBA", 2, 5, scoreMatch*3+bonusCamel123+bonusConsecutive) assertMatch(t, ExactMatchNaive, false, dir, "/AutomatorDocument.icns", "rdoc", 9, 13, scoreMatch*4+bonusCamel123+bonusConsecutive*2) assertMatch(t, ExactMatchNaive, false, dir, "/man1/zshcompctl.1", "zshc", 6, 10, scoreMatch*4+int(bonusBoundaryDelimiter)*(bonusFirstCharMultiplier+3)) assertMatch(t, ExactMatchNaive, false, dir, "/.oh-my-zsh/cache", "zsh/c", 8, 13, scoreMatch*5+bonusBoundary*(bonusFirstCharMultiplier+3)+int(bonusBoundaryDelimiter)) } } func TestExactMatchNaiveBackward(t *testing.T) { assertMatch(t, ExactMatchNaive, false, true, "foobar foob", "oo", 1, 3, scoreMatch*2+bonusConsecutive) assertMatch(t, ExactMatchNaive, false, false, "foobar foob", "oo", 8, 10, scoreMatch*2+bonusConsecutive) } func TestPrefixMatch(t *testing.T) { score := scoreMatch*3 + int(bonusBoundaryWhite)*bonusFirstCharMultiplier + int(bonusBoundaryWhite)*2 for _, dir := range []bool{true, false} { assertMatch(t, PrefixMatch, true, dir, "fooBarbaz", "Foo", -1, -1, 0) assertMatch(t, PrefixMatch, false, dir, "fooBarBaz", "baz", -1, -1, 0) assertMatch(t, PrefixMatch, false, dir, "fooBarbaz", "Foo", 0, 3, score) assertMatch(t, PrefixMatch, false, dir, "foOBarBaZ", "foo", 0, 3, score) assertMatch(t, PrefixMatch, false, dir, "f-oBarbaz", "f-o", 0, 3, score) assertMatch(t, PrefixMatch, false, dir, " fooBar", "foo", 1, 4, score) assertMatch(t, PrefixMatch, false, dir, " fooBar", " fo", 0, 3, score) assertMatch(t, PrefixMatch, false, dir, " fo", "foo", -1, -1, 0) } } func TestSuffixMatch(t *testing.T) { for _, dir := range []bool{true, false} { assertMatch(t, SuffixMatch, true, dir, "fooBarbaz", "Baz", -1, -1, 0) assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "Foo", -1, -1, 0) assertMatch(t, SuffixMatch, false, dir, "fooBarbaz", "baz", 6, 9, scoreMatch*3+bonusConsecutive*2) assertMatch(t, SuffixMatch, false, dir, "fooBarBaZ", "baz", 6, 9, (scoreMatch+bonusCamel123)*3+bonusCamel123*(bonusFirstCharMultiplier-1)) // Strip trailing white space from the string assertMatch(t, SuffixMatch, false, dir, "fooBarbaz ", "baz", 6, 9, scoreMatch*3+bonusConsecutive*2) // Only when the pattern doesn't end with a space assertMatch(t, SuffixMatch, false, dir, "fooBarbaz ", "baz ", 6, 10, scoreMatch*4+bonusConsecutive*2+int(bonusBoundaryWhite)) } } func TestEmptyPattern(t *testing.T) { for _, dir := range []bool{true, false} { assertMatch(t, FuzzyMatchV1, true, dir, "foobar", "", 0, 0, 0) assertMatch(t, FuzzyMatchV2, true, dir, "foobar", "", 0, 0, 0) assertMatch(t, ExactMatchNaive, true, dir, "foobar", "", 0, 0, 0) assertMatch(t, PrefixMatch, true, dir, "foobar", "", 0, 0, 0) assertMatch(t, SuffixMatch, true, dir, "foobar", "", 6, 6, 0) } } func TestNormalize(t *testing.T) { caseSensitive := false normalize := true forward := true test := func(input, pattern string, sidx, eidx, score int, funs ...Algo) { for _, fun := range funs { assertMatch2(t, fun, caseSensitive, normalize, forward, input, pattern, sidx, eidx, score) } } test("Só Danço Samba", "So", 0, 2, 62, FuzzyMatchV1, FuzzyMatchV2, PrefixMatch, ExactMatchNaive) test("Só Danço Samba", "sodc", 0, 7, 97, FuzzyMatchV1, FuzzyMatchV2) test("Danço", "danco", 0, 5, 140, FuzzyMatchV1, FuzzyMatchV2, PrefixMatch, SuffixMatch, ExactMatchNaive, EqualMatch) } func TestLongString(t *testing.T) { bytes := make([]byte, math.MaxUint16*2) for i := range bytes { bytes[i] = 'x' } bytes[math.MaxUint16] = 'z' assertMatch(t, FuzzyMatchV2, true, true, string(bytes), "zx", math.MaxUint16, math.MaxUint16+2, scoreMatch*2+bonusConsecutive) } func TestLongStringWithNormalize(t *testing.T) { bytes := make([]byte, 30000) for i := range bytes { bytes[i] = 'x' } unicodeString := string(bytes) + " Minímal example" assertMatch2(t, FuzzyMatchV1, false, true, false, unicodeString, "minim", 30001, 30006, 140) }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/algo/algo.go
src/algo/algo.go
package algo /* Algorithm --------- FuzzyMatchV1 finds the first "fuzzy" occurrence of the pattern within the given text in O(n) time where n is the length of the text. Once the position of the last character is located, it traverses backwards to see if there's a shorter substring that matches the pattern. a_____b___abc__ To find "abc" *-----*-----*> 1. Forward scan <*** 2. Backward scan The algorithm is simple and fast, but as it only sees the first occurrence, it is not guaranteed to find the occurrence with the highest score. a_____b__c__abc *-----*--* *** FuzzyMatchV2 implements a modified version of Smith-Waterman algorithm to find the optimal solution (highest score) according to the scoring criteria. Unlike the original algorithm, omission or mismatch of a character in the pattern is not allowed. Performance ----------- The new V2 algorithm is slower than V1 as it examines all occurrences of the pattern instead of stopping immediately after finding the first one. The time complexity of the algorithm is O(nm) if a match is found and O(n) otherwise where n is the length of the item and m is the length of the pattern. Thus, the performance overhead may not be noticeable for a query with high selectivity. However, if the performance is more important than the quality of the result, you can still choose v1 algorithm with --algo=v1. Scoring criteria ---------------- - We prefer matches at special positions, such as the start of a word, or uppercase character in camelCase words. - That is, we prefer an occurrence of the pattern with more characters matching at special positions, even if the total match length is longer. e.g. "fuzzyfinder" vs. "fuzzy-finder" on "ff" ```````````` - Also, if the first character in the pattern appears at one of the special positions, the bonus point for the position is multiplied by a constant as it is extremely likely that the first character in the typed pattern has more significance than the rest. e.g. "fo-bar" vs. "foob-r" on "br" `````` - But since fzf is still a fuzzy finder, not an acronym finder, we should also consider the total length of the matched substring. This is why we have the gap penalty. The gap penalty increases as the length of the gap (distance between the matching characters) increases, so the effect of the bonus is eventually cancelled at some point. e.g. "fuzzyfinder" vs. "fuzzy-blurry-finder" on "ff" ``````````` - Consequently, it is crucial to find the right balance between the bonus and the gap penalty. The parameters were chosen that the bonus is cancelled when the gap size increases beyond 8 characters. - The bonus mechanism can have the undesirable side effect where consecutive matches are ranked lower than the ones with gaps. e.g. "foobar" vs. "foo-bar" on "foob" ``````` - To correct this anomaly, we also give extra bonus point to each character in a consecutive matching chunk. e.g. "foobar" vs. "foo-bar" on "foob" `````` - The amount of consecutive bonus is primarily determined by the bonus of the first character in the chunk. e.g. "foobar" vs. "out-of-bound" on "oob" ```````````` */ import ( "bytes" "fmt" "os" "strings" "unicode" "unicode/utf8" "github.com/junegunn/fzf/src/util" ) var DEBUG bool var delimiterChars = "/,:;|" const whiteChars = " \t\n\v\f\r\x85\xA0" func indexAt(index int, max int, forward bool) int { if forward { return index } return max - index - 1 } // Result contains the results of running a match function. type Result struct { // TODO int32 should suffice Start int End int Score int } const ( scoreMatch = 16 scoreGapStart = -3 scoreGapExtension = -1 // We prefer matches at the beginning of a word, but the bonus should not be // too great to prevent the longer acronym matches from always winning over // shorter fuzzy matches. The bonus point here was specifically chosen that // the bonus is cancelled when the gap between the acronyms grows over // 8 characters, which is approximately the average length of the words found // in web2 dictionary and my file system. bonusBoundary = scoreMatch / 2 // Although bonus point for non-word characters is non-contextual, we need it // for computing bonus points for consecutive chunks starting with a non-word // character. bonusNonWord = scoreMatch / 2 // Edge-triggered bonus for matches in camelCase words. // Compared to word-boundary case, they don't accompany single-character gaps // (e.g. FooBar vs. foo-bar), so we deduct bonus point accordingly. bonusCamel123 = bonusBoundary + scoreGapExtension // Minimum bonus point given to characters in consecutive chunks. // Note that bonus points for consecutive matches shouldn't have needed if we // used fixed match score as in the original algorithm. bonusConsecutive = -(scoreGapStart + scoreGapExtension) // The first character in the typed pattern usually has more significance // than the rest so it's important that it appears at special positions where // bonus points are given, e.g. "to-go" vs. "ongoing" on "og" or on "ogo". // The amount of the extra bonus should be limited so that the gap penalty is // still respected. bonusFirstCharMultiplier = 2 ) var ( // Extra bonus for word boundary after whitespace character or beginning of the string bonusBoundaryWhite int16 = bonusBoundary + 2 // Extra bonus for word boundary after slash, colon, semi-colon, and comma bonusBoundaryDelimiter int16 = bonusBoundary + 1 initialCharClass = charWhite // A minor optimization that can give 15%+ performance boost asciiCharClasses [unicode.MaxASCII + 1]charClass // A minor optimization that can give yet another 5% performance boost bonusMatrix [charNumber + 1][charNumber + 1]int16 ) type charClass int const ( charWhite charClass = iota charNonWord charDelimiter charLower charUpper charLetter charNumber ) func Init(scheme string) bool { switch scheme { case "default": bonusBoundaryWhite = bonusBoundary + 2 bonusBoundaryDelimiter = bonusBoundary + 1 case "path": bonusBoundaryWhite = bonusBoundary bonusBoundaryDelimiter = bonusBoundary + 1 if os.PathSeparator == '/' { delimiterChars = "/" } else { delimiterChars = string([]rune{os.PathSeparator, '/'}) } initialCharClass = charDelimiter case "history": bonusBoundaryWhite = bonusBoundary bonusBoundaryDelimiter = bonusBoundary default: return false } for i := 0; i <= unicode.MaxASCII; i++ { char := rune(i) c := charNonWord if char >= 'a' && char <= 'z' { c = charLower } else if char >= 'A' && char <= 'Z' { c = charUpper } else if char >= '0' && char <= '9' { c = charNumber } else if strings.ContainsRune(whiteChars, char) { c = charWhite } else if strings.ContainsRune(delimiterChars, char) { c = charDelimiter } asciiCharClasses[i] = c } for i := 0; i <= int(charNumber); i++ { for j := 0; j <= int(charNumber); j++ { bonusMatrix[i][j] = bonusFor(charClass(i), charClass(j)) } } return true } func posArray(withPos bool, len int) *[]int { if withPos { pos := make([]int, 0, len) return &pos } return nil } func alloc16(offset int, slab *util.Slab, size int) (int, []int16) { if slab != nil && cap(slab.I16) > offset+size { slice := slab.I16[offset : offset+size] return offset + size, slice } return offset, make([]int16, size) } func alloc32(offset int, slab *util.Slab, size int) (int, []int32) { if slab != nil && cap(slab.I32) > offset+size { slice := slab.I32[offset : offset+size] return offset + size, slice } return offset, make([]int32, size) } func charClassOfNonAscii(char rune) charClass { if unicode.IsLower(char) { return charLower } else if unicode.IsUpper(char) { return charUpper } else if unicode.IsNumber(char) { return charNumber } else if unicode.IsLetter(char) { return charLetter } else if unicode.IsSpace(char) { return charWhite } else if strings.ContainsRune(delimiterChars, char) { return charDelimiter } return charNonWord } func charClassOf(char rune) charClass { if char <= unicode.MaxASCII { return asciiCharClasses[char] } return charClassOfNonAscii(char) } func bonusFor(prevClass charClass, class charClass) int16 { if class > charNonWord { switch prevClass { case charWhite: // Word boundary after whitespace return bonusBoundaryWhite case charDelimiter: // Word boundary after a delimiter character return bonusBoundaryDelimiter case charNonWord: // Word boundary return bonusBoundary } } if prevClass == charLower && class == charUpper || prevClass != charNumber && class == charNumber { // camelCase letter123 return bonusCamel123 } switch class { case charNonWord, charDelimiter: return bonusNonWord case charWhite: return bonusBoundaryWhite } return 0 } func bonusAt(input *util.Chars, idx int) int16 { if idx == 0 { return bonusBoundaryWhite } return bonusMatrix[charClassOf(input.Get(idx-1))][charClassOf(input.Get(idx))] } func normalizeRune(r rune) rune { if r < 0x00C0 || r > 0xFF61 { return r } n := normalized[r] if n > 0 { return n } return r } // Algo functions make two assumptions // 1. "pattern" is given in lowercase if "caseSensitive" is false // 2. "pattern" is already normalized if "normalize" is true type Algo func(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) func trySkip(input *util.Chars, caseSensitive bool, b byte, from int) int { byteArray := input.Bytes()[from:] idx := bytes.IndexByte(byteArray, b) if idx == 0 { // Can't skip any further return from } // We may need to search for the uppercase letter again. We don't have to // consider normalization as we can be sure that this is an ASCII string. if !caseSensitive && b >= 'a' && b <= 'z' { if idx > 0 { byteArray = byteArray[:idx] } uidx := bytes.IndexByte(byteArray, b-32) if uidx >= 0 { idx = uidx } } if idx < 0 { return -1 } return from + idx } func isAscii(runes []rune) bool { for _, r := range runes { if r >= utf8.RuneSelf { return false } } return true } func asciiFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) (int, int) { // Can't determine if !input.IsBytes() { return 0, input.Length() } // Not possible if !isAscii(pattern) { return -1, -1 } firstIdx, idx, lastIdx := 0, 0, 0 var b byte for pidx := range pattern { b = byte(pattern[pidx]) idx = trySkip(input, caseSensitive, b, idx) if idx < 0 { return -1, -1 } if pidx == 0 && idx > 0 { // Step back to find the right bonus point firstIdx = idx - 1 } lastIdx = idx idx++ } // Find the last appearance of the last character of the pattern to limit the search scope bu := b if !caseSensitive && b >= 'a' && b <= 'z' { bu = b - 32 } scope := input.Bytes()[lastIdx:] for offset := len(scope) - 1; offset > 0; offset-- { if scope[offset] == b || scope[offset] == bu { return firstIdx, lastIdx + offset + 1 } } return firstIdx, lastIdx + 1 } func debugV2(T []rune, pattern []rune, F []int32, lastIdx int, H []int16, C []int16) { width := lastIdx - int(F[0]) + 1 for i, f := range F { I := i * width if i == 0 { fmt.Print(" ") for j := int(f); j <= lastIdx; j++ { fmt.Print(" " + string(T[j]) + " ") } fmt.Println() } fmt.Print(string(pattern[i]) + " ") for idx := int(F[0]); idx < int(f); idx++ { fmt.Print(" 0 ") } for idx := int(f); idx <= lastIdx; idx++ { fmt.Printf("%2d ", H[i*width+idx-int(F[0])]) } fmt.Println() fmt.Print(" ") for idx, p := range C[I : I+width] { if idx+int(F[0]) < int(F[i]) { p = 0 } if p > 0 { fmt.Printf("%2d ", p) } else { fmt.Print(" ") } } fmt.Println() } } func FuzzyMatchV2(caseSensitive bool, normalize bool, forward bool, input *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) { // Assume that pattern is given in lowercase if case-insensitive. // First check if there's a match and calculate bonus for each position. // If the input string is too long, consider finding the matching chars in // this phase as well (non-optimal alignment). M := len(pattern) if M == 0 { return Result{0, 0, 0}, posArray(withPos, M) } N := input.Length() if M > N { return Result{-1, -1, 0}, nil } // Since O(nm) algorithm can be prohibitively expensive for large input, // we fall back to the greedy algorithm. // Also, we should not allow a very long pattern to avoid 16-bit integer // overflow in the score matrix. 1000 is a safe limit. if slab != nil && N*M > cap(slab.I16) || M > 1000 { return FuzzyMatchV1(caseSensitive, normalize, forward, input, pattern, withPos, slab) } // Phase 1. Optimized search for ASCII string minIdx, maxIdx := asciiFuzzyIndex(input, pattern, caseSensitive) if minIdx < 0 { return Result{-1, -1, 0}, nil } // fmt.Println(N, maxIdx, idx, maxIdx-idx, input.ToString()) N = maxIdx - minIdx // Reuse pre-allocated integer slice to avoid unnecessary sweeping of garbages offset16 := 0 offset32 := 0 offset16, H0 := alloc16(offset16, slab, N) offset16, C0 := alloc16(offset16, slab, N) // Bonus point for each position offset16, B := alloc16(offset16, slab, N) // The first occurrence of each character in the pattern offset32, F := alloc32(offset32, slab, M) // Rune array _, T := alloc32(offset32, slab, N) input.CopyRunes(T, minIdx) // Phase 2. Calculate bonus for each point maxScore, maxScorePos := int16(0), 0 pidx, lastIdx := 0, 0 pchar0, pchar, prevH0, prevClass, inGap := pattern[0], pattern[0], int16(0), initialCharClass, false for off, char := range T { var class charClass if char <= unicode.MaxASCII { class = asciiCharClasses[char] if !caseSensitive && class == charUpper { char += 32 T[off] = char } } else { class = charClassOfNonAscii(char) if !caseSensitive && class == charUpper { char = unicode.To(unicode.LowerCase, char) } if normalize { char = normalizeRune(char) } T[off] = char } bonus := bonusMatrix[prevClass][class] B[off] = bonus prevClass = class if char == pchar { if pidx < M { F[pidx] = int32(off) pidx++ pchar = pattern[min(pidx, M-1)] } lastIdx = off } if char == pchar0 { score := scoreMatch + bonus*bonusFirstCharMultiplier H0[off] = score C0[off] = 1 if M == 1 && (forward && score > maxScore || !forward && score >= maxScore) { maxScore, maxScorePos = score, off if forward && bonus >= bonusBoundary { break } } inGap = false } else { if inGap { H0[off] = max(prevH0+scoreGapExtension, 0) } else { H0[off] = max(prevH0+scoreGapStart, 0) } C0[off] = 0 inGap = true } prevH0 = H0[off] } if pidx != M { return Result{-1, -1, 0}, nil } if M == 1 { result := Result{minIdx + maxScorePos, minIdx + maxScorePos + 1, int(maxScore)} if !withPos { return result, nil } pos := []int{minIdx + maxScorePos} return result, &pos } // Phase 3. Fill in score matrix (H) // Unlike the original algorithm, we do not allow omission. f0 := int(F[0]) width := lastIdx - f0 + 1 offset16, H := alloc16(offset16, slab, width*M) copy(H, H0[f0:lastIdx+1]) // Possible length of consecutive chunk at each position. _, C := alloc16(offset16, slab, width*M) copy(C, C0[f0:lastIdx+1]) Fsub := F[1:] Psub := pattern[1:][:len(Fsub)] for off, f := range Fsub { f := int(f) pchar := Psub[off] pidx := off + 1 row := pidx * width inGap := false Tsub := T[f : lastIdx+1] Bsub := B[f:][:len(Tsub)] Csub := C[row+f-f0:][:len(Tsub)] Cdiag := C[row+f-f0-1-width:][:len(Tsub)] Hsub := H[row+f-f0:][:len(Tsub)] Hdiag := H[row+f-f0-1-width:][:len(Tsub)] Hleft := H[row+f-f0-1:][:len(Tsub)] Hleft[0] = 0 for off, char := range Tsub { col := off + f var s1, s2, consecutive int16 if inGap { s2 = Hleft[off] + scoreGapExtension } else { s2 = Hleft[off] + scoreGapStart } if pchar == char { s1 = Hdiag[off] + scoreMatch b := Bsub[off] consecutive = Cdiag[off] + 1 if consecutive > 1 { fb := B[col-int(consecutive)+1] // Break consecutive chunk if b >= bonusBoundary && b > fb { consecutive = 1 } else { b = max(b, bonusConsecutive, fb) } } if s1+b < s2 { s1 += Bsub[off] consecutive = 0 } else { s1 += b } } Csub[off] = consecutive inGap = s1 < s2 score := max(s1, s2, 0) if pidx == M-1 && (forward && score > maxScore || !forward && score >= maxScore) { maxScore, maxScorePos = score, col } Hsub[off] = score } } if DEBUG { debugV2(T, pattern, F, lastIdx, H, C) } // Phase 4. (Optional) Backtrace to find character positions pos := posArray(withPos, M) j := f0 if withPos { i := M - 1 j = maxScorePos preferMatch := true for { I := i * width j0 := j - f0 s := H[I+j0] var s1, s2 int16 if i > 0 && j >= int(F[i]) { s1 = H[I-width+j0-1] } if j > int(F[i]) { s2 = H[I+j0-1] } if s > s1 && (s > s2 || s == s2 && preferMatch) { *pos = append(*pos, j+minIdx) if i == 0 { break } i-- } preferMatch = C[I+j0] > 1 || I+width+j0+1 < len(C) && C[I+width+j0+1] > 0 j-- } } // Start offset we return here is only relevant when begin tiebreak is used. // However finding the accurate offset requires backtracking, and we don't // want to pay extra cost for the option that has lost its importance. return Result{minIdx + j, minIdx + maxScorePos + 1, int(maxScore)}, pos } // Implement the same sorting criteria as V2 func calculateScore(caseSensitive bool, normalize bool, text *util.Chars, pattern []rune, sidx int, eidx int, withPos bool) (int, *[]int) { pidx, score, inGap, consecutive, firstBonus := 0, 0, false, 0, int16(0) pos := posArray(withPos, len(pattern)) prevClass := initialCharClass if sidx > 0 { prevClass = charClassOf(text.Get(sidx - 1)) } for idx := sidx; idx < eidx; idx++ { char := text.Get(idx) class := charClassOf(char) if !caseSensitive { if char >= 'A' && char <= 'Z' { char += 32 } else if char > unicode.MaxASCII { char = unicode.To(unicode.LowerCase, char) } } // pattern is already normalized if normalize { char = normalizeRune(char) } if char == pattern[pidx] { if withPos { *pos = append(*pos, idx) } score += scoreMatch bonus := bonusMatrix[prevClass][class] if consecutive == 0 { firstBonus = bonus } else { // Break consecutive chunk if bonus >= bonusBoundary && bonus > firstBonus { firstBonus = bonus } bonus = max(bonus, firstBonus, bonusConsecutive) } if pidx == 0 { score += int(bonus * bonusFirstCharMultiplier) } else { score += int(bonus) } inGap = false consecutive++ pidx++ } else { if inGap { score += scoreGapExtension } else { score += scoreGapStart } inGap = true consecutive = 0 firstBonus = 0 } prevClass = class } return score, pos } // FuzzyMatchV1 performs fuzzy-match func FuzzyMatchV1(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) { if len(pattern) == 0 { return Result{0, 0, 0}, nil } idx, _ := asciiFuzzyIndex(text, pattern, caseSensitive) if idx < 0 { return Result{-1, -1, 0}, nil } pidx := 0 sidx := -1 eidx := -1 lenRunes := text.Length() lenPattern := len(pattern) for index := range lenRunes { char := text.Get(indexAt(index, lenRunes, forward)) // This is considerably faster than blindly applying strings.ToLower to the // whole string if !caseSensitive { // Partially inlining `unicode.ToLower`. Ugly, but makes a noticeable // difference in CPU cost. (Measured on Go 1.4.1. Also note that the Go // compiler as of now does not inline non-leaf functions.) if char >= 'A' && char <= 'Z' { char += 32 } else if char > unicode.MaxASCII { char = unicode.To(unicode.LowerCase, char) } } if normalize { char = normalizeRune(char) } pchar := pattern[indexAt(pidx, lenPattern, forward)] if char == pchar { if sidx < 0 { sidx = index } if pidx++; pidx == lenPattern { eidx = index + 1 break } } } if sidx >= 0 && eidx >= 0 { pidx-- for index := eidx - 1; index >= sidx; index-- { tidx := indexAt(index, lenRunes, forward) char := text.Get(tidx) if !caseSensitive { if char >= 'A' && char <= 'Z' { char += 32 } else if char > unicode.MaxASCII { char = unicode.To(unicode.LowerCase, char) } } if normalize { char = normalizeRune(char) } pidx_ := indexAt(pidx, lenPattern, forward) pchar := pattern[pidx_] if char == pchar { if pidx--; pidx < 0 { sidx = index break } } } if !forward { sidx, eidx = lenRunes-eidx, lenRunes-sidx } score, pos := calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, withPos) return Result{sidx, eidx, score}, pos } return Result{-1, -1, 0}, nil } // ExactMatchNaive is a basic string searching algorithm that handles case // sensitivity. Although naive, it still performs better than the combination // of strings.ToLower + strings.Index for typical fzf use cases where input // strings and patterns are not very long. // // Since 0.15.0, this function searches for the match with the highest // bonus point, instead of stopping immediately after finding the first match. // The solution is much cheaper since there is only one possible alignment of // the pattern. func ExactMatchNaive(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) { return exactMatchNaive(caseSensitive, normalize, forward, false, text, pattern, withPos, slab) } func ExactMatchBoundary(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) { return exactMatchNaive(caseSensitive, normalize, forward, true, text, pattern, withPos, slab) } func exactMatchNaive(caseSensitive bool, normalize bool, forward bool, boundaryCheck bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) { if len(pattern) == 0 { return Result{0, 0, 0}, nil } lenRunes := text.Length() lenPattern := len(pattern) if lenRunes < lenPattern { return Result{-1, -1, 0}, nil } idx, _ := asciiFuzzyIndex(text, pattern, caseSensitive) if idx < 0 { return Result{-1, -1, 0}, nil } // For simplicity, only look at the bonus at the first character position pidx := 0 bestPos, bonus, bbonus, bestBonus := -1, int16(0), int16(0), int16(-1) for index := 0; index < lenRunes; index++ { index_ := indexAt(index, lenRunes, forward) char := text.Get(index_) if !caseSensitive { if char >= 'A' && char <= 'Z' { char += 32 } else if char > unicode.MaxASCII { char = unicode.To(unicode.LowerCase, char) } } if normalize { char = normalizeRune(char) } pidx_ := indexAt(pidx, lenPattern, forward) pchar := pattern[pidx_] ok := pchar == char if ok { if pidx_ == 0 { bonus = bonusAt(text, index_) } if boundaryCheck { if forward && pidx_ == 0 { bbonus = bonus } else if !forward && pidx_ == lenPattern-1 { if index_ < lenRunes-1 { bbonus = bonusAt(text, index_+1) } else { bbonus = bonusBoundaryWhite } } ok = bbonus >= bonusBoundary if ok && pidx_ == 0 { ok = index_ == 0 || charClassOf(text.Get(index_-1)) <= charDelimiter } if ok && pidx_ == len(pattern)-1 { ok = index_ == lenRunes-1 || charClassOf(text.Get(index_+1)) <= charDelimiter } } } if ok { pidx++ if pidx == lenPattern { if bonus > bestBonus { bestPos, bestBonus = index, bonus } if bonus >= bonusBoundary { break } index -= pidx - 1 pidx, bonus = 0, 0 } } else { index -= pidx pidx, bonus = 0, 0 } } if bestPos >= 0 { var sidx, eidx int if forward { sidx = bestPos - lenPattern + 1 eidx = bestPos + 1 } else { sidx = lenRunes - (bestPos + 1) eidx = lenRunes - (bestPos - lenPattern + 1) } var score int if boundaryCheck { // Underscore boundaries should be ranked lower than the other types of boundaries score = int(bonus) deduct := int(bonus-bonusBoundary) + 1 if sidx > 0 && text.Get(sidx-1) == '_' { score -= deduct + 1 deduct = 1 } if eidx < lenRunes && text.Get(eidx) == '_' { score -= deduct } // Add base score so that this can compete with other match types e.g. 'foo' | bar score += scoreMatch*lenPattern + int(bonusBoundaryWhite)*(lenPattern+1) } else { score, _ = calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false) } return Result{sidx, eidx, score}, nil } return Result{-1, -1, 0}, nil } // PrefixMatch performs prefix-match func PrefixMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) { if len(pattern) == 0 { return Result{0, 0, 0}, nil } trimmedLen := 0 if !unicode.IsSpace(pattern[0]) { trimmedLen = text.LeadingWhitespaces() } if text.Length()-trimmedLen < len(pattern) { return Result{-1, -1, 0}, nil } for index, r := range pattern { char := text.Get(trimmedLen + index) if !caseSensitive { char = unicode.ToLower(char) } if normalize { char = normalizeRune(char) } if char != r { return Result{-1, -1, 0}, nil } } lenPattern := len(pattern) score, _ := calculateScore(caseSensitive, normalize, text, pattern, trimmedLen, trimmedLen+lenPattern, false) return Result{trimmedLen, trimmedLen + lenPattern, score}, nil } // SuffixMatch performs suffix-match func SuffixMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) { lenRunes := text.Length() trimmedLen := lenRunes if len(pattern) == 0 || !unicode.IsSpace(pattern[len(pattern)-1]) { trimmedLen -= text.TrailingWhitespaces() } if len(pattern) == 0 { return Result{trimmedLen, trimmedLen, 0}, nil } diff := trimmedLen - len(pattern) if diff < 0 { return Result{-1, -1, 0}, nil } for index, r := range pattern { char := text.Get(index + diff) if !caseSensitive { char = unicode.ToLower(char) } if normalize { char = normalizeRune(char) } if char != r { return Result{-1, -1, 0}, nil } } lenPattern := len(pattern) sidx := trimmedLen - lenPattern eidx := trimmedLen score, _ := calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false) return Result{sidx, eidx, score}, nil } // EqualMatch performs equal-match func EqualMatch(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) { lenPattern := len(pattern) if lenPattern == 0 { return Result{-1, -1, 0}, nil } // Strip leading whitespaces trimmedLen := 0 if !unicode.IsSpace(pattern[0]) { trimmedLen = text.LeadingWhitespaces() } // Strip trailing whitespaces trimmedEndLen := 0 if !unicode.IsSpace(pattern[lenPattern-1]) { trimmedEndLen = text.TrailingWhitespaces() } if text.Length()-trimmedLen-trimmedEndLen != lenPattern { return Result{-1, -1, 0}, nil } match := true if normalize { runes := text.ToRunes() for idx, pchar := range pattern { char := runes[trimmedLen+idx] if !caseSensitive { char = unicode.To(unicode.LowerCase, char) } if normalizeRune(pchar) != normalizeRune(char) { match = false break } } } else { runes := text.ToRunes() runesStr := string(runes[trimmedLen : len(runes)-trimmedEndLen]) if !caseSensitive { runesStr = strings.ToLower(runesStr) } match = runesStr == string(pattern) } if match { return Result{trimmedLen, trimmedLen + lenPattern, (scoreMatch+int(bonusBoundaryWhite))*lenPattern + (bonusFirstCharMultiplier-1)*int(bonusBoundaryWhite)}, nil } return Result{-1, -1, 0}, nil }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/algo/normalize.go
src/algo/normalize.go
// Normalization of latin script letters // Reference: http://www.unicode.org/Public/UCD/latest/ucd/Index.txt package algo var normalized = map[rune]rune{ 0x00E1: 'a', // WITH ACUTE, LATIN SMALL LETTER 0x0103: 'a', // WITH BREVE, LATIN SMALL LETTER 0x01CE: 'a', // WITH CARON, LATIN SMALL LETTER 0x00E2: 'a', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x00E4: 'a', // WITH DIAERESIS, LATIN SMALL LETTER 0x0227: 'a', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1EA1: 'a', // WITH DOT BELOW, LATIN SMALL LETTER 0x0201: 'a', // WITH DOUBLE GRAVE, LATIN SMALL LETTER 0x00E0: 'a', // WITH GRAVE, LATIN SMALL LETTER 0x1EA3: 'a', // WITH HOOK ABOVE, LATIN SMALL LETTER 0x0203: 'a', // WITH INVERTED BREVE, LATIN SMALL LETTER 0x0101: 'a', // WITH MACRON, LATIN SMALL LETTER 0x0105: 'a', // WITH OGONEK, LATIN SMALL LETTER 0x1E9A: 'a', // WITH RIGHT HALF RING, LATIN SMALL LETTER 0x00E5: 'a', // WITH RING ABOVE, LATIN SMALL LETTER 0x1E01: 'a', // WITH RING BELOW, LATIN SMALL LETTER 0x00E3: 'a', // WITH TILDE, LATIN SMALL LETTER 0x0363: 'a', // , COMBINING LATIN SMALL LETTER 0x0250: 'a', // , LATIN SMALL LETTER TURNED 0x1E03: 'b', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E05: 'b', // WITH DOT BELOW, LATIN SMALL LETTER 0x0253: 'b', // WITH HOOK, LATIN SMALL LETTER 0x1E07: 'b', // WITH LINE BELOW, LATIN SMALL LETTER 0x0180: 'b', // WITH STROKE, LATIN SMALL LETTER 0x0183: 'b', // WITH TOPBAR, LATIN SMALL LETTER 0x0107: 'c', // WITH ACUTE, LATIN SMALL LETTER 0x010D: 'c', // WITH CARON, LATIN SMALL LETTER 0x00E7: 'c', // WITH CEDILLA, LATIN SMALL LETTER 0x0109: 'c', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x0255: 'c', // WITH CURL, LATIN SMALL LETTER 0x010B: 'c', // WITH DOT ABOVE, LATIN SMALL LETTER 0x0188: 'c', // WITH HOOK, LATIN SMALL LETTER 0x023C: 'c', // WITH STROKE, LATIN SMALL LETTER 0x0368: 'c', // , COMBINING LATIN SMALL LETTER 0x0297: 'c', // , LATIN LETTER STRETCHED 0x2184: 'c', // , LATIN SMALL LETTER REVERSED 0x010F: 'd', // WITH CARON, LATIN SMALL LETTER 0x1E11: 'd', // WITH CEDILLA, LATIN SMALL LETTER 0x1E13: 'd', // WITH CIRCUMFLEX BELOW, LATIN SMALL LETTER 0x0221: 'd', // WITH CURL, LATIN SMALL LETTER 0x1E0B: 'd', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E0D: 'd', // WITH DOT BELOW, LATIN SMALL LETTER 0x0257: 'd', // WITH HOOK, LATIN SMALL LETTER 0x1E0F: 'd', // WITH LINE BELOW, LATIN SMALL LETTER 0x0111: 'd', // WITH STROKE, LATIN SMALL LETTER 0x0256: 'd', // WITH TAIL, LATIN SMALL LETTER 0x018C: 'd', // WITH TOPBAR, LATIN SMALL LETTER 0x0369: 'd', // , COMBINING LATIN SMALL LETTER 0x00E9: 'e', // WITH ACUTE, LATIN SMALL LETTER 0x0115: 'e', // WITH BREVE, LATIN SMALL LETTER 0x011B: 'e', // WITH CARON, LATIN SMALL LETTER 0x0229: 'e', // WITH CEDILLA, LATIN SMALL LETTER 0x1E19: 'e', // WITH CIRCUMFLEX BELOW, LATIN SMALL LETTER 0x00EA: 'e', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x00EB: 'e', // WITH DIAERESIS, LATIN SMALL LETTER 0x0117: 'e', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1EB9: 'e', // WITH DOT BELOW, LATIN SMALL LETTER 0x0205: 'e', // WITH DOUBLE GRAVE, LATIN SMALL LETTER 0x00E8: 'e', // WITH GRAVE, LATIN SMALL LETTER 0x1EBB: 'e', // WITH HOOK ABOVE, LATIN SMALL LETTER 0x025D: 'e', // WITH HOOK, LATIN SMALL LETTER REVERSED OPEN 0x0207: 'e', // WITH INVERTED BREVE, LATIN SMALL LETTER 0x0113: 'e', // WITH MACRON, LATIN SMALL LETTER 0x0119: 'e', // WITH OGONEK, LATIN SMALL LETTER 0x0247: 'e', // WITH STROKE, LATIN SMALL LETTER 0x1E1B: 'e', // WITH TILDE BELOW, LATIN SMALL LETTER 0x1EBD: 'e', // WITH TILDE, LATIN SMALL LETTER 0x0364: 'e', // , COMBINING LATIN SMALL LETTER 0x029A: 'e', // , LATIN SMALL LETTER CLOSED OPEN 0x025E: 'e', // , LATIN SMALL LETTER CLOSED REVERSED OPEN 0x025B: 'e', // , LATIN SMALL LETTER OPEN 0x0258: 'e', // , LATIN SMALL LETTER REVERSED 0x025C: 'e', // , LATIN SMALL LETTER REVERSED OPEN 0x01DD: 'e', // , LATIN SMALL LETTER TURNED 0x1D08: 'e', // , LATIN SMALL LETTER TURNED OPEN 0x1E1F: 'f', // WITH DOT ABOVE, LATIN SMALL LETTER 0x0192: 'f', // WITH HOOK, LATIN SMALL LETTER 0x01F5: 'g', // WITH ACUTE, LATIN SMALL LETTER 0x011F: 'g', // WITH BREVE, LATIN SMALL LETTER 0x01E7: 'g', // WITH CARON, LATIN SMALL LETTER 0x0123: 'g', // WITH CEDILLA, LATIN SMALL LETTER 0x011D: 'g', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x0121: 'g', // WITH DOT ABOVE, LATIN SMALL LETTER 0x0260: 'g', // WITH HOOK, LATIN SMALL LETTER 0x1E21: 'g', // WITH MACRON, LATIN SMALL LETTER 0x01E5: 'g', // WITH STROKE, LATIN SMALL LETTER 0x0261: 'g', // , LATIN SMALL LETTER SCRIPT 0x1E2B: 'h', // WITH BREVE BELOW, LATIN SMALL LETTER 0x021F: 'h', // WITH CARON, LATIN SMALL LETTER 0x1E29: 'h', // WITH CEDILLA, LATIN SMALL LETTER 0x0125: 'h', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x1E27: 'h', // WITH DIAERESIS, LATIN SMALL LETTER 0x1E23: 'h', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E25: 'h', // WITH DOT BELOW, LATIN SMALL LETTER 0x02AE: 'h', // WITH FISHHOOK, LATIN SMALL LETTER TURNED 0x0266: 'h', // WITH HOOK, LATIN SMALL LETTER 0x1E96: 'h', // WITH LINE BELOW, LATIN SMALL LETTER 0x0127: 'h', // WITH STROKE, LATIN SMALL LETTER 0x036A: 'h', // , COMBINING LATIN SMALL LETTER 0x0265: 'h', // , LATIN SMALL LETTER TURNED 0x2095: 'h', // , LATIN SUBSCRIPT SMALL LETTER 0x00ED: 'i', // WITH ACUTE, LATIN SMALL LETTER 0x012D: 'i', // WITH BREVE, LATIN SMALL LETTER 0x01D0: 'i', // WITH CARON, LATIN SMALL LETTER 0x00EE: 'i', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x00EF: 'i', // WITH DIAERESIS, LATIN SMALL LETTER 0x1ECB: 'i', // WITH DOT BELOW, LATIN SMALL LETTER 0x0209: 'i', // WITH DOUBLE GRAVE, LATIN SMALL LETTER 0x00EC: 'i', // WITH GRAVE, LATIN SMALL LETTER 0x1EC9: 'i', // WITH HOOK ABOVE, LATIN SMALL LETTER 0x020B: 'i', // WITH INVERTED BREVE, LATIN SMALL LETTER 0x012B: 'i', // WITH MACRON, LATIN SMALL LETTER 0x012F: 'i', // WITH OGONEK, LATIN SMALL LETTER 0x0268: 'i', // WITH STROKE, LATIN SMALL LETTER 0x1E2D: 'i', // WITH TILDE BELOW, LATIN SMALL LETTER 0x0129: 'i', // WITH TILDE, LATIN SMALL LETTER 0x0365: 'i', // , COMBINING LATIN SMALL LETTER 0x0131: 'i', // , LATIN SMALL LETTER DOTLESS 0x1D09: 'i', // , LATIN SMALL LETTER TURNED 0x1D62: 'i', // , LATIN SUBSCRIPT SMALL LETTER 0x2071: 'i', // , SUPERSCRIPT LATIN SMALL LETTER 0x01F0: 'j', // WITH CARON, LATIN SMALL LETTER 0x0135: 'j', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x029D: 'j', // WITH CROSSED-TAIL, LATIN SMALL LETTER 0x0249: 'j', // WITH STROKE, LATIN SMALL LETTER 0x025F: 'j', // WITH STROKE, LATIN SMALL LETTER DOTLESS 0x0237: 'j', // , LATIN SMALL LETTER DOTLESS 0x1E31: 'k', // WITH ACUTE, LATIN SMALL LETTER 0x01E9: 'k', // WITH CARON, LATIN SMALL LETTER 0x0137: 'k', // WITH CEDILLA, LATIN SMALL LETTER 0x1E33: 'k', // WITH DOT BELOW, LATIN SMALL LETTER 0x0199: 'k', // WITH HOOK, LATIN SMALL LETTER 0x1E35: 'k', // WITH LINE BELOW, LATIN SMALL LETTER 0x029E: 'k', // , LATIN SMALL LETTER TURNED 0x2096: 'k', // , LATIN SUBSCRIPT SMALL LETTER 0x013A: 'l', // WITH ACUTE, LATIN SMALL LETTER 0x019A: 'l', // WITH BAR, LATIN SMALL LETTER 0x026C: 'l', // WITH BELT, LATIN SMALL LETTER 0x013E: 'l', // WITH CARON, LATIN SMALL LETTER 0x013C: 'l', // WITH CEDILLA, LATIN SMALL LETTER 0x1E3D: 'l', // WITH CIRCUMFLEX BELOW, LATIN SMALL LETTER 0x0234: 'l', // WITH CURL, LATIN SMALL LETTER 0x1E37: 'l', // WITH DOT BELOW, LATIN SMALL LETTER 0x1E3B: 'l', // WITH LINE BELOW, LATIN SMALL LETTER 0x0140: 'l', // WITH MIDDLE DOT, LATIN SMALL LETTER 0x026B: 'l', // WITH MIDDLE TILDE, LATIN SMALL LETTER 0x026D: 'l', // WITH RETROFLEX HOOK, LATIN SMALL LETTER 0x0142: 'l', // WITH STROKE, LATIN SMALL LETTER 0x2097: 'l', // , LATIN SUBSCRIPT SMALL LETTER 0x1E3F: 'm', // WITH ACUTE, LATIN SMALL LETTER 0x1E41: 'm', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E43: 'm', // WITH DOT BELOW, LATIN SMALL LETTER 0x0271: 'm', // WITH HOOK, LATIN SMALL LETTER 0x0270: 'm', // WITH LONG LEG, LATIN SMALL LETTER TURNED 0x036B: 'm', // , COMBINING LATIN SMALL LETTER 0x1D1F: 'm', // , LATIN SMALL LETTER SIDEWAYS TURNED 0x026F: 'm', // , LATIN SMALL LETTER TURNED 0x2098: 'm', // , LATIN SUBSCRIPT SMALL LETTER 0x0144: 'n', // WITH ACUTE, LATIN SMALL LETTER 0x0148: 'n', // WITH CARON, LATIN SMALL LETTER 0x0146: 'n', // WITH CEDILLA, LATIN SMALL LETTER 0x1E4B: 'n', // WITH CIRCUMFLEX BELOW, LATIN SMALL LETTER 0x0235: 'n', // WITH CURL, LATIN SMALL LETTER 0x1E45: 'n', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E47: 'n', // WITH DOT BELOW, LATIN SMALL LETTER 0x01F9: 'n', // WITH GRAVE, LATIN SMALL LETTER 0x0272: 'n', // WITH LEFT HOOK, LATIN SMALL LETTER 0x1E49: 'n', // WITH LINE BELOW, LATIN SMALL LETTER 0x019E: 'n', // WITH LONG RIGHT LEG, LATIN SMALL LETTER 0x0273: 'n', // WITH RETROFLEX HOOK, LATIN SMALL LETTER 0x00F1: 'n', // WITH TILDE, LATIN SMALL LETTER 0x2099: 'n', // , LATIN SUBSCRIPT SMALL LETTER 0x00F3: 'o', // WITH ACUTE, LATIN SMALL LETTER 0x014F: 'o', // WITH BREVE, LATIN SMALL LETTER 0x01D2: 'o', // WITH CARON, LATIN SMALL LETTER 0x00F4: 'o', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x00F6: 'o', // WITH DIAERESIS, LATIN SMALL LETTER 0x022F: 'o', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1ECD: 'o', // WITH DOT BELOW, LATIN SMALL LETTER 0x0151: 'o', // WITH DOUBLE ACUTE, LATIN SMALL LETTER 0x020D: 'o', // WITH DOUBLE GRAVE, LATIN SMALL LETTER 0x00F2: 'o', // WITH GRAVE, LATIN SMALL LETTER 0x1ECF: 'o', // WITH HOOK ABOVE, LATIN SMALL LETTER 0x01A1: 'o', // WITH HORN, LATIN SMALL LETTER 0x020F: 'o', // WITH INVERTED BREVE, LATIN SMALL LETTER 0x014D: 'o', // WITH MACRON, LATIN SMALL LETTER 0x01EB: 'o', // WITH OGONEK, LATIN SMALL LETTER 0x00F8: 'o', // WITH STROKE, LATIN SMALL LETTER 0x1D13: 'o', // WITH STROKE, LATIN SMALL LETTER SIDEWAYS 0x00F5: 'o', // WITH TILDE, LATIN SMALL LETTER 0x0366: 'o', // , COMBINING LATIN SMALL LETTER 0x0275: 'o', // , LATIN SMALL LETTER BARRED 0x1D17: 'o', // , LATIN SMALL LETTER BOTTOM HALF 0x0254: 'o', // , LATIN SMALL LETTER OPEN 0x1D11: 'o', // , LATIN SMALL LETTER SIDEWAYS 0x1D12: 'o', // , LATIN SMALL LETTER SIDEWAYS OPEN 0x1D16: 'o', // , LATIN SMALL LETTER TOP HALF 0x1E55: 'p', // WITH ACUTE, LATIN SMALL LETTER 0x1E57: 'p', // WITH DOT ABOVE, LATIN SMALL LETTER 0x01A5: 'p', // WITH HOOK, LATIN SMALL LETTER 0x209A: 'p', // , LATIN SUBSCRIPT SMALL LETTER 0x024B: 'q', // WITH HOOK TAIL, LATIN SMALL LETTER 0x02A0: 'q', // WITH HOOK, LATIN SMALL LETTER 0x0155: 'r', // WITH ACUTE, LATIN SMALL LETTER 0x0159: 'r', // WITH CARON, LATIN SMALL LETTER 0x0157: 'r', // WITH CEDILLA, LATIN SMALL LETTER 0x1E59: 'r', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E5B: 'r', // WITH DOT BELOW, LATIN SMALL LETTER 0x0211: 'r', // WITH DOUBLE GRAVE, LATIN SMALL LETTER 0x027E: 'r', // WITH FISHHOOK, LATIN SMALL LETTER 0x027F: 'r', // WITH FISHHOOK, LATIN SMALL LETTER REVERSED 0x027B: 'r', // WITH HOOK, LATIN SMALL LETTER TURNED 0x0213: 'r', // WITH INVERTED BREVE, LATIN SMALL LETTER 0x1E5F: 'r', // WITH LINE BELOW, LATIN SMALL LETTER 0x027C: 'r', // WITH LONG LEG, LATIN SMALL LETTER 0x027A: 'r', // WITH LONG LEG, LATIN SMALL LETTER TURNED 0x024D: 'r', // WITH STROKE, LATIN SMALL LETTER 0x027D: 'r', // WITH TAIL, LATIN SMALL LETTER 0x036C: 'r', // , COMBINING LATIN SMALL LETTER 0x0279: 'r', // , LATIN SMALL LETTER TURNED 0x1D63: 'r', // , LATIN SUBSCRIPT SMALL LETTER 0x015B: 's', // WITH ACUTE, LATIN SMALL LETTER 0x0161: 's', // WITH CARON, LATIN SMALL LETTER 0x015F: 's', // WITH CEDILLA, LATIN SMALL LETTER 0x015D: 's', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x0219: 's', // WITH COMMA BELOW, LATIN SMALL LETTER 0x1E61: 's', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E9B: 's', // WITH DOT ABOVE, LATIN SMALL LETTER LONG 0x1E63: 's', // WITH DOT BELOW, LATIN SMALL LETTER 0x0282: 's', // WITH HOOK, LATIN SMALL LETTER 0x023F: 's', // WITH SWASH TAIL, LATIN SMALL LETTER 0x017F: 's', // , LATIN SMALL LETTER LONG 0x00DF: 's', // , LATIN SMALL LETTER SHARP 0x209B: 's', // , LATIN SUBSCRIPT SMALL LETTER 0x0165: 't', // WITH CARON, LATIN SMALL LETTER 0x0163: 't', // WITH CEDILLA, LATIN SMALL LETTER 0x1E71: 't', // WITH CIRCUMFLEX BELOW, LATIN SMALL LETTER 0x021B: 't', // WITH COMMA BELOW, LATIN SMALL LETTER 0x0236: 't', // WITH CURL, LATIN SMALL LETTER 0x1E97: 't', // WITH DIAERESIS, LATIN SMALL LETTER 0x1E6B: 't', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E6D: 't', // WITH DOT BELOW, LATIN SMALL LETTER 0x01AD: 't', // WITH HOOK, LATIN SMALL LETTER 0x1E6F: 't', // WITH LINE BELOW, LATIN SMALL LETTER 0x01AB: 't', // WITH PALATAL HOOK, LATIN SMALL LETTER 0x0288: 't', // WITH RETROFLEX HOOK, LATIN SMALL LETTER 0x0167: 't', // WITH STROKE, LATIN SMALL LETTER 0x036D: 't', // , COMBINING LATIN SMALL LETTER 0x0287: 't', // , LATIN SMALL LETTER TURNED 0x209C: 't', // , LATIN SUBSCRIPT SMALL LETTER 0x0289: 'u', // BAR, LATIN SMALL LETTER 0x00FA: 'u', // WITH ACUTE, LATIN SMALL LETTER 0x016D: 'u', // WITH BREVE, LATIN SMALL LETTER 0x01D4: 'u', // WITH CARON, LATIN SMALL LETTER 0x1E77: 'u', // WITH CIRCUMFLEX BELOW, LATIN SMALL LETTER 0x00FB: 'u', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x1E73: 'u', // WITH DIAERESIS BELOW, LATIN SMALL LETTER 0x00FC: 'u', // WITH DIAERESIS, LATIN SMALL LETTER 0x1EE5: 'u', // WITH DOT BELOW, LATIN SMALL LETTER 0x0171: 'u', // WITH DOUBLE ACUTE, LATIN SMALL LETTER 0x0215: 'u', // WITH DOUBLE GRAVE, LATIN SMALL LETTER 0x00F9: 'u', // WITH GRAVE, LATIN SMALL LETTER 0x1EE7: 'u', // WITH HOOK ABOVE, LATIN SMALL LETTER 0x01B0: 'u', // WITH HORN, LATIN SMALL LETTER 0x0217: 'u', // WITH INVERTED BREVE, LATIN SMALL LETTER 0x016B: 'u', // WITH MACRON, LATIN SMALL LETTER 0x0173: 'u', // WITH OGONEK, LATIN SMALL LETTER 0x016F: 'u', // WITH RING ABOVE, LATIN SMALL LETTER 0x1E75: 'u', // WITH TILDE BELOW, LATIN SMALL LETTER 0x0169: 'u', // WITH TILDE, LATIN SMALL LETTER 0x0367: 'u', // , COMBINING LATIN SMALL LETTER 0x1D1D: 'u', // , LATIN SMALL LETTER SIDEWAYS 0x1D1E: 'u', // , LATIN SMALL LETTER SIDEWAYS DIAERESIZED 0x1D64: 'u', // , LATIN SUBSCRIPT SMALL LETTER 0x1E7F: 'v', // WITH DOT BELOW, LATIN SMALL LETTER 0x028B: 'v', // WITH HOOK, LATIN SMALL LETTER 0x1E7D: 'v', // WITH TILDE, LATIN SMALL LETTER 0x036E: 'v', // , COMBINING LATIN SMALL LETTER 0x028C: 'v', // , LATIN SMALL LETTER TURNED 0x1D65: 'v', // , LATIN SUBSCRIPT SMALL LETTER 0x1E83: 'w', // WITH ACUTE, LATIN SMALL LETTER 0x0175: 'w', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x1E85: 'w', // WITH DIAERESIS, LATIN SMALL LETTER 0x1E87: 'w', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E89: 'w', // WITH DOT BELOW, LATIN SMALL LETTER 0x1E81: 'w', // WITH GRAVE, LATIN SMALL LETTER 0x1E98: 'w', // WITH RING ABOVE, LATIN SMALL LETTER 0x028D: 'w', // , LATIN SMALL LETTER TURNED 0x1E8D: 'x', // WITH DIAERESIS, LATIN SMALL LETTER 0x1E8B: 'x', // WITH DOT ABOVE, LATIN SMALL LETTER 0x036F: 'x', // , COMBINING LATIN SMALL LETTER 0x00FD: 'y', // WITH ACUTE, LATIN SMALL LETTER 0x0177: 'y', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x00FF: 'y', // WITH DIAERESIS, LATIN SMALL LETTER 0x1E8F: 'y', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1EF5: 'y', // WITH DOT BELOW, LATIN SMALL LETTER 0x1EF3: 'y', // WITH GRAVE, LATIN SMALL LETTER 0x1EF7: 'y', // WITH HOOK ABOVE, LATIN SMALL LETTER 0x01B4: 'y', // WITH HOOK, LATIN SMALL LETTER 0x0233: 'y', // WITH MACRON, LATIN SMALL LETTER 0x1E99: 'y', // WITH RING ABOVE, LATIN SMALL LETTER 0x024F: 'y', // WITH STROKE, LATIN SMALL LETTER 0x1EF9: 'y', // WITH TILDE, LATIN SMALL LETTER 0x028E: 'y', // , LATIN SMALL LETTER TURNED 0x017A: 'z', // WITH ACUTE, LATIN SMALL LETTER 0x017E: 'z', // WITH CARON, LATIN SMALL LETTER 0x1E91: 'z', // WITH CIRCUMFLEX, LATIN SMALL LETTER 0x0291: 'z', // WITH CURL, LATIN SMALL LETTER 0x017C: 'z', // WITH DOT ABOVE, LATIN SMALL LETTER 0x1E93: 'z', // WITH DOT BELOW, LATIN SMALL LETTER 0x0225: 'z', // WITH HOOK, LATIN SMALL LETTER 0x1E95: 'z', // WITH LINE BELOW, LATIN SMALL LETTER 0x0290: 'z', // WITH RETROFLEX HOOK, LATIN SMALL LETTER 0x01B6: 'z', // WITH STROKE, LATIN SMALL LETTER 0x0240: 'z', // WITH SWASH TAIL, LATIN SMALL LETTER 0x0251: 'a', // , latin small letter script 0x00C1: 'A', // WITH ACUTE, LATIN CAPITAL LETTER 0x00C2: 'A', // WITH CIRCUMFLEX, LATIN CAPITAL LETTER 0x00C4: 'A', // WITH DIAERESIS, LATIN CAPITAL LETTER 0x00C0: 'A', // WITH GRAVE, LATIN CAPITAL LETTER 0x00C5: 'A', // WITH RING ABOVE, LATIN CAPITAL LETTER 0x023A: 'A', // WITH STROKE, LATIN CAPITAL LETTER 0x00C3: 'A', // WITH TILDE, LATIN CAPITAL LETTER 0x1D00: 'A', // , LATIN LETTER SMALL CAPITAL 0x0181: 'B', // WITH HOOK, LATIN CAPITAL LETTER 0x0243: 'B', // WITH STROKE, LATIN CAPITAL LETTER 0x0299: 'B', // , LATIN LETTER SMALL CAPITAL 0x1D03: 'B', // , LATIN LETTER SMALL CAPITAL BARRED 0x00C7: 'C', // WITH CEDILLA, LATIN CAPITAL LETTER 0x023B: 'C', // WITH STROKE, LATIN CAPITAL LETTER 0x1D04: 'C', // , LATIN LETTER SMALL CAPITAL 0x018A: 'D', // WITH HOOK, LATIN CAPITAL LETTER 0x0189: 'D', // , LATIN CAPITAL LETTER AFRICAN 0x1D05: 'D', // , LATIN LETTER SMALL CAPITAL 0x00C9: 'E', // WITH ACUTE, LATIN CAPITAL LETTER 0x00CA: 'E', // WITH CIRCUMFLEX, LATIN CAPITAL LETTER 0x00CB: 'E', // WITH DIAERESIS, LATIN CAPITAL LETTER 0x00C8: 'E', // WITH GRAVE, LATIN CAPITAL LETTER 0x0246: 'E', // WITH STROKE, LATIN CAPITAL LETTER 0x0190: 'E', // , LATIN CAPITAL LETTER OPEN 0x018E: 'E', // , LATIN CAPITAL LETTER REVERSED 0x1D07: 'E', // , LATIN LETTER SMALL CAPITAL 0x0193: 'G', // WITH HOOK, LATIN CAPITAL LETTER 0x029B: 'G', // WITH HOOK, LATIN LETTER SMALL CAPITAL 0x0262: 'G', // , LATIN LETTER SMALL CAPITAL 0x029C: 'H', // , LATIN LETTER SMALL CAPITAL 0x00CD: 'I', // WITH ACUTE, LATIN CAPITAL LETTER 0x00CE: 'I', // WITH CIRCUMFLEX, LATIN CAPITAL LETTER 0x00CF: 'I', // WITH DIAERESIS, LATIN CAPITAL LETTER 0x0130: 'I', // WITH DOT ABOVE, LATIN CAPITAL LETTER 0x00CC: 'I', // WITH GRAVE, LATIN CAPITAL LETTER 0x0197: 'I', // WITH STROKE, LATIN CAPITAL LETTER 0x026A: 'I', // , LATIN LETTER SMALL CAPITAL 0x0248: 'J', // WITH STROKE, LATIN CAPITAL LETTER 0x1D0A: 'J', // , LATIN LETTER SMALL CAPITAL 0x1D0B: 'K', // , LATIN LETTER SMALL CAPITAL 0x023D: 'L', // WITH BAR, LATIN CAPITAL LETTER 0x1D0C: 'L', // WITH STROKE, LATIN LETTER SMALL CAPITAL 0x029F: 'L', // , LATIN LETTER SMALL CAPITAL 0x019C: 'M', // , LATIN CAPITAL LETTER TURNED 0x1D0D: 'M', // , LATIN LETTER SMALL CAPITAL 0x019D: 'N', // WITH LEFT HOOK, LATIN CAPITAL LETTER 0x0220: 'N', // WITH LONG RIGHT LEG, LATIN CAPITAL LETTER 0x00D1: 'N', // WITH TILDE, LATIN CAPITAL LETTER 0x0274: 'N', // , LATIN LETTER SMALL CAPITAL 0x1D0E: 'N', // , LATIN LETTER SMALL CAPITAL REVERSED 0x00D3: 'O', // WITH ACUTE, LATIN CAPITAL LETTER 0x00D4: 'O', // WITH CIRCUMFLEX, LATIN CAPITAL LETTER 0x00D6: 'O', // WITH DIAERESIS, LATIN CAPITAL LETTER 0x00D2: 'O', // WITH GRAVE, LATIN CAPITAL LETTER 0x019F: 'O', // WITH MIDDLE TILDE, LATIN CAPITAL LETTER 0x00D8: 'O', // WITH STROKE, LATIN CAPITAL LETTER 0x00D5: 'O', // WITH TILDE, LATIN CAPITAL LETTER 0x0186: 'O', // , LATIN CAPITAL LETTER OPEN 0x1D0F: 'O', // , LATIN LETTER SMALL CAPITAL 0x1D10: 'O', // , LATIN LETTER SMALL CAPITAL OPEN 0x1D18: 'P', // , LATIN LETTER SMALL CAPITAL 0x024A: 'Q', // WITH HOOK TAIL, LATIN CAPITAL LETTER SMALL 0x024C: 'R', // WITH STROKE, LATIN CAPITAL LETTER 0x0280: 'R', // , LATIN LETTER SMALL CAPITAL 0x0281: 'R', // , LATIN LETTER SMALL CAPITAL INVERTED 0x1D19: 'R', // , LATIN LETTER SMALL CAPITAL REVERSED 0x1D1A: 'R', // , LATIN LETTER SMALL CAPITAL TURNED 0x023E: 'T', // WITH DIAGONAL STROKE, LATIN CAPITAL LETTER 0x01AE: 'T', // WITH RETROFLEX HOOK, LATIN CAPITAL LETTER 0x1D1B: 'T', // , LATIN LETTER SMALL CAPITAL 0x0244: 'U', // BAR, LATIN CAPITAL LETTER 0x00DA: 'U', // WITH ACUTE, LATIN CAPITAL LETTER 0x00DB: 'U', // WITH CIRCUMFLEX, LATIN CAPITAL LETTER 0x00DC: 'U', // WITH DIAERESIS, LATIN CAPITAL LETTER 0x00D9: 'U', // WITH GRAVE, LATIN CAPITAL LETTER 0x1D1C: 'U', // , LATIN LETTER SMALL CAPITAL 0x01B2: 'V', // WITH HOOK, LATIN CAPITAL LETTER 0x0245: 'V', // , LATIN CAPITAL LETTER TURNED 0x1D20: 'V', // , LATIN LETTER SMALL CAPITAL 0x1D21: 'W', // , LATIN LETTER SMALL CAPITAL 0x00DD: 'Y', // WITH ACUTE, LATIN CAPITAL LETTER 0x0178: 'Y', // WITH DIAERESIS, LATIN CAPITAL LETTER 0x024E: 'Y', // WITH STROKE, LATIN CAPITAL LETTER 0x028F: 'Y', // , LATIN LETTER SMALL CAPITAL 0x1D22: 'Z', // , LATIN LETTER SMALL CAPITAL 'Ắ': 'A', 'Ấ': 'A', 'Ằ': 'A', 'Ầ': 'A', 'Ẳ': 'A', 'Ẩ': 'A', 'Ẵ': 'A', 'Ẫ': 'A', 'Ặ': 'A', 'Ậ': 'A', 'ắ': 'a', 'ấ': 'a', 'ằ': 'a', 'ầ': 'a', 'ẳ': 'a', 'ẩ': 'a', 'ẵ': 'a', 'ẫ': 'a', 'ặ': 'a', 'ậ': 'a', 'Ế': 'E', 'Ề': 'E', 'Ể': 'E', 'Ễ': 'E', 'Ệ': 'E', 'ế': 'e', 'ề': 'e', 'ể': 'e', 'ễ': 'e', 'ệ': 'e', 'Ố': 'O', 'Ớ': 'O', 'Ồ': 'O', 'Ờ': 'O', 'Ổ': 'O', 'Ở': 'O', 'Ỗ': 'O', 'Ỡ': 'O', 'Ộ': 'O', 'Ợ': 'O', 'ố': 'o', 'ớ': 'o', 'ồ': 'o', 'ờ': 'o', 'ổ': 'o', 'ở': 'o', 'ỗ': 'o', 'ỡ': 'o', 'ộ': 'o', 'ợ': 'o', 'Ứ': 'U', 'Ừ': 'U', 'Ử': 'U', 'Ữ': 'U', 'Ự': 'U', 'ứ': 'u', 'ừ': 'u', 'ử': 'u', 'ữ': 'u', 'ự': 'u', // https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block) 0xFF01: '!', // Fullwidth exclamation 0xFF02: '"', // Fullwidth quotation mark 0xFF03: '#', // Fullwidth number sign 0xFF04: '$', // Fullwidth dollar sign 0xFF05: '%', // Fullwidth percent 0xFF06: '&', // Fullwidth ampersand 0xFF07: '\'', // Fullwidth apostrophe 0xFF08: '(', // Fullwidth left parenthesis 0xFF09: ')', // Fullwidth right parenthesis 0xFF0A: '*', // Fullwidth asterisk 0xFF0B: '+', // Fullwidth plus 0xFF0C: ',', // Fullwidth comma 0xFF0D: '-', // Fullwidth hyphen-minus 0xFF0E: '.', // Fullwidth period 0xFF0F: '/', // Fullwidth slash 0xFF10: '0', 0xFF11: '1', 0xFF12: '2', 0xFF13: '3', 0xFF14: '4', 0xFF15: '5', 0xFF16: '6', 0xFF17: '7', 0xFF18: '8', 0xFF19: '9', 0xFF1A: ':', // Fullwidth colon 0xFF1B: ';', // Fullwidth semicolon 0xFF1C: '<', // Fullwidth less-than 0xFF1D: '=', // Fullwidth equal 0xFF1E: '>', // Fullwidth greater-than 0xFF1F: '?', // Fullwidth question mark 0xFF20: '@', // Fullwidth at sign 0xFF21: 'A', 0xFF22: 'B', 0xFF23: 'C', 0xFF24: 'D', 0xFF25: 'E', 0xFF26: 'F', 0xFF27: 'G', 0xFF28: 'H', 0xFF29: 'I', 0xFF2A: 'J', 0xFF2B: 'K', 0xFF2C: 'L', 0xFF2D: 'M', 0xFF2E: 'N', 0xFF2F: 'O', 0xFF30: 'P', 0xFF31: 'Q', 0xFF32: 'R', 0xFF33: 'S', 0xFF34: 'T', 0xFF35: 'U', 0xFF36: 'V', 0xFF37: 'W', 0xFF38: 'X', 0xFF39: 'Y', 0xFF3A: 'Z', 0xFF3B: '[', // Fullwidth left bracket 0xFF3C: '\\', // Fullwidth backslash 0xFF3D: ']', // Fullwidth right bracket 0xFF3E: '^', // Fullwidth circumflex 0xFF3F: '_', // Fullwidth underscore 0xFF40: '`', // Fullwidth grave accent 0xFF41: 'a', 0xFF42: 'b', 0xFF43: 'c', 0xFF44: 'd', 0xFF45: 'e', 0xFF46: 'f', 0xFF47: 'g', 0xFF48: 'h', 0xFF49: 'i', 0xFF4A: 'j', 0xFF4B: 'k', 0xFF4C: 'l', 0xFF4D: 'm', 0xFF4E: 'n', 0xFF4F: 'o', 0xFF50: 'p', 0xFF51: 'q', 0xFF52: 'r', 0xFF53: 's', 0xFF54: 't', 0xFF55: 'u', 0xFF56: 'v', 0xFF57: 'w', 0xFF58: 'x', 0xFF59: 'y', 0xFF5A: 'z', 0xFF5B: '{', // Fullwidth left brace 0xFF5C: '|', // Fullwidth vertical bar 0xFF5D: '}', // Fullwidth right brace 0xFF5E: '~', // Fullwidth tilde 0xFF61: '.', // Halfwidth ideographic full stop } // NormalizeRunes normalizes latin script letters func NormalizeRunes(runes []rune) []rune { ret := make([]rune, len(runes)) copy(ret, runes) for idx, r := range runes { if r < 0x00C0 || r > 0xFF61 { continue } n := normalized[r] if n > 0 { ret[idx] = normalized[r] } } return ret }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/tui_test.go
src/tui/tui_test.go
package tui import "testing" func TestHexToColor(t *testing.T) { assert := func(expr string, r, g, b int) { color := HexToColor(expr) if !color.is24() || int((color>>16)&0xff) != r || int((color>>8)&0xff) != g || int((color)&0xff) != b { t.Fail() } } assert("#ff0000", 255, 0, 0) assert("#010203", 1, 2, 3) assert("#102030", 16, 32, 48) assert("#ffffff", 255, 255, 255) }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/tcell.go
src/tui/tcell.go
//go:build tcell || windows package tui import ( "os" "regexp" "time" "github.com/gdamore/tcell/v2" "github.com/junegunn/fzf/src/util" "github.com/rivo/uniseg" ) func HasFullscreenRenderer() bool { return true } var DefaultBorderShape BorderShape = BorderSharp func asTcellColor(color Color) tcell.Color { if color == colDefault { return tcell.ColorDefault } value := uint64(tcell.ColorValid) + uint64(color) if color.is24() { value = value | uint64(tcell.ColorIsRGB) } return tcell.Color(value) } func (p ColorPair) style() tcell.Style { style := tcell.StyleDefault return style.Foreground(asTcellColor(p.Fg())).Background(asTcellColor(p.Bg())) } type TcellWindow struct { color bool windowType WindowType top int left int width int height int normal ColorPair lastX int lastY int moveCursor bool borderStyle BorderStyle uri *string params *string showCursor bool wrapSign string wrapSignWidth int } func (w *TcellWindow) Top() int { return w.top } func (w *TcellWindow) Left() int { return w.left } func (w *TcellWindow) Width() int { return w.width } func (w *TcellWindow) Height() int { return w.height } func (w *TcellWindow) Refresh() { if w.moveCursor { if w.showCursor { _screen.ShowCursor(w.left+w.lastX, w.top+w.lastY) } w.moveCursor = false } w.lastX = 0 w.lastY = 0 } func (w *TcellWindow) FinishFill() { // NO-OP } const ( Bold Attr = Attr(tcell.AttrBold) Dim = Attr(tcell.AttrDim) Blink = Attr(tcell.AttrBlink) Reverse = Attr(tcell.AttrReverse) Underline = Attr(tcell.AttrUnderline) StrikeThrough = Attr(tcell.AttrStrikeThrough) Italic = Attr(tcell.AttrItalic) ) func (r *FullscreenRenderer) Bell() { _screen.Beep() } func (r *FullscreenRenderer) HideCursor() { r.showCursor = false } func (r *FullscreenRenderer) ShowCursor() { r.showCursor = true } func (r *FullscreenRenderer) PassThrough(str string) { // No-op // https://github.com/gdamore/tcell/pull/650#issuecomment-1806442846 } func (r *FullscreenRenderer) Resize(maxHeightFunc func(int) int) {} func (r *FullscreenRenderer) DefaultTheme() *ColorTheme { s, e := r.getScreen() if e != nil { return Default16 } if s.Colors() >= 256 { return Dark256 } return Default16 } var ( _colorToAttribute = []tcell.Color{ tcell.ColorBlack, tcell.ColorRed, tcell.ColorGreen, tcell.ColorYellow, tcell.ColorBlue, tcell.ColorDarkMagenta, tcell.ColorLightCyan, tcell.ColorWhite, } ) func (c Color) Style() tcell.Color { if c <= colDefault { return tcell.ColorDefault } else if c >= colBlack && c <= colWhite { return _colorToAttribute[int(c)] } else { return tcell.Color(c) } } // handle the following as private members of FullscreenRenderer instance // they are declared here to prevent introducing tcell library in non-windows builds var ( _screen tcell.Screen _prevMouseButton tcell.ButtonMask _initialResize bool = true ) func (r *FullscreenRenderer) getScreen() (tcell.Screen, error) { if _screen == nil { s, e := tcell.NewScreen() if e != nil { return nil, e } if !r.showCursor { s.HideCursor() } _screen = s } return _screen, nil } func (r *FullscreenRenderer) initScreen() error { s, e := r.getScreen() if e != nil { return e } if e = s.Init(); e != nil { return e } s.EnablePaste() if r.mouse { s.EnableMouse() } else { s.DisableMouse() } return nil } func (r *FullscreenRenderer) Init() error { if os.Getenv("TERM") == "cygwin" { os.Setenv("TERM", "") } if err := r.initScreen(); err != nil { return err } return nil } func (r *FullscreenRenderer) Top() int { return 0 } func (r *FullscreenRenderer) MaxX() int { ncols, _ := _screen.Size() return int(ncols) } func (r *FullscreenRenderer) MaxY() int { _, nlines := _screen.Size() return int(nlines) } func (w *TcellWindow) X() int { return w.lastX } func (w *TcellWindow) Y() int { return w.lastY } func (r *FullscreenRenderer) Clear() { _screen.Sync() _screen.Clear() } func (r *FullscreenRenderer) NeedScrollbarRedraw() bool { return true } func (r *FullscreenRenderer) ShouldEmitResizeEvent() bool { return true } func (r *FullscreenRenderer) Refresh() { // noop } // TODO: Pixel width and height not implemented func (r *FullscreenRenderer) Size() TermSize { cols, lines := _screen.Size() return TermSize{lines, cols, 0, 0} } func (r *FullscreenRenderer) GetChar() Event { ev := _screen.PollEvent() switch ev := ev.(type) { case *tcell.EventPaste: if ev.Start() { return Event{BracketedPasteBegin, 0, nil} } return Event{BracketedPasteEnd, 0, nil} case *tcell.EventResize: // Ignore the first resize event // https://github.com/gdamore/tcell/blob/v2.7.0/TUTORIAL.md?plain=1#L18 if _initialResize { _initialResize = false return Event{Invalid, 0, nil} } return Event{Resize, 0, nil} // process mouse events: case *tcell.EventMouse: // mouse down events have zeroed buttons, so we can't use them // mouse up event consists of two events, 1. (main) event with modifier and other metadata, 2. event with zeroed buttons // so mouse click is three consecutive events, but the first and last are indistinguishable from movement events (with released buttons) // dragging has same structure, it only repeats the middle (main) event appropriately x, y := ev.Position() mod := ev.Modifiers() ctrl := (mod & tcell.ModCtrl) > 0 alt := (mod & tcell.ModAlt) > 0 shift := (mod & tcell.ModShift) > 0 // since we dont have mouse down events (unlike LightRenderer), we need to track state in prevButton prevButton, button := _prevMouseButton, ev.Buttons() _prevMouseButton = button drag := prevButton == button switch { case button&tcell.WheelDown != 0: return Event{Mouse, 0, &MouseEvent{y, x, -1, false, false, false, ctrl, alt, shift}} case button&tcell.WheelUp != 0: return Event{Mouse, 0, &MouseEvent{y, x, +1, false, false, false, ctrl, alt, shift}} case button&tcell.Button1 != 0: double := false if !drag { // all potential double click events put their coordinates in the clicks array // double click event has two conditions, temporal and spatial, the first is checked here now := time.Now() if now.Sub(r.prevDownTime) < doubleClickDuration { r.clicks = append(r.clicks, [2]int{x, y}) } else { r.clicks = [][2]int{{x, y}} } r.prevDownTime = now // detect double clicks (also check for spatial condition) n := len(r.clicks) double = n > 1 && r.clicks[n-2][0] == r.clicks[n-1][0] && r.clicks[n-2][1] == r.clicks[n-1][1] if double { // make sure two consecutive double clicks require four clicks r.clicks = [][2]int{} } } // fire single or double click event return Event{Mouse, 0, &MouseEvent{y, x, 0, true, !double, double, ctrl, alt, shift}} case button&tcell.Button2 != 0: return Event{Mouse, 0, &MouseEvent{y, x, 0, false, true, false, ctrl, alt, shift}} default: // double and single taps on Windows don't quite work due to // the console acting on the events and not allowing us // to consume them. left := button&tcell.Button1 != 0 down := left || button&tcell.Button3 != 0 double := false // No need to report mouse movement events when no button is pressed if drag { return Event{Invalid, 0, nil} } return Event{Mouse, 0, &MouseEvent{y, x, 0, left, down, double, ctrl, alt, shift}} } // process keyboard: case *tcell.EventKey: mods := ev.Modifiers() none := mods == tcell.ModNone alt := (mods & tcell.ModAlt) > 0 ctrl := (mods & tcell.ModCtrl) > 0 shift := (mods & tcell.ModShift) > 0 ctrlAlt := ctrl && alt altShift := alt && shift ctrlShift := ctrl && shift ctrlAltShift := ctrl && alt && shift keyfn := func(r rune) Event { if alt { return CtrlAltKey(r) } return EventType(CtrlA.Int() - 'a' + int(r)).AsEvent() } switch ev.Key() { // section 1: Ctrl+(Alt)+[a-z] case tcell.KeyCtrlA: return keyfn('a') case tcell.KeyCtrlB: return keyfn('b') case tcell.KeyCtrlC: return keyfn('c') case tcell.KeyCtrlD: return keyfn('d') case tcell.KeyCtrlE: return keyfn('e') case tcell.KeyCtrlF: return keyfn('f') case tcell.KeyCtrlG: return keyfn('g') case tcell.KeyCtrlH: switch ev.Rune() { case 0: if ctrlAlt { return Event{CtrlAltBackspace, 0, nil} } if ctrl { return Event{CtrlBackspace, 0, nil} } case rune(tcell.KeyCtrlH): switch { case ctrl: return keyfn('h') case alt: return Event{AltBackspace, 0, nil} case none, shift: return Event{Backspace, 0, nil} } } case tcell.KeyCtrlI: return keyfn('i') case tcell.KeyCtrlJ: return keyfn('j') case tcell.KeyCtrlK: return keyfn('k') case tcell.KeyCtrlL: return keyfn('l') case tcell.KeyCtrlM: return keyfn('m') case tcell.KeyCtrlN: return keyfn('n') case tcell.KeyCtrlO: return keyfn('o') case tcell.KeyCtrlP: return keyfn('p') case tcell.KeyCtrlQ: return keyfn('q') case tcell.KeyCtrlR: return keyfn('r') case tcell.KeyCtrlS: return keyfn('s') case tcell.KeyCtrlT: return keyfn('t') case tcell.KeyCtrlU: return keyfn('u') case tcell.KeyCtrlV: return keyfn('v') case tcell.KeyCtrlW: return keyfn('w') case tcell.KeyCtrlX: return keyfn('x') case tcell.KeyCtrlY: return keyfn('y') case tcell.KeyCtrlZ: return keyfn('z') // section 2: Ctrl+[ \]_] case tcell.KeyCtrlSpace: return Event{CtrlSpace, 0, nil} case tcell.KeyCtrlBackslash: return Event{CtrlBackSlash, 0, nil} case tcell.KeyCtrlRightSq: return Event{CtrlRightBracket, 0, nil} case tcell.KeyCtrlCarat: return Event{CtrlCaret, 0, nil} case tcell.KeyCtrlUnderscore: return Event{CtrlSlash, 0, nil} // section 3: (Alt)+Backspace2 case tcell.KeyBackspace2: if ctrl { return Event{CtrlBackspace, 0, nil} } if alt { return Event{AltBackspace, 0, nil} } return Event{Backspace, 0, nil} // section 4: (Alt+Shift)+Key(Up|Down|Left|Right) case tcell.KeyUp: if ctrlAltShift { return Event{CtrlAltShiftUp, 0, nil} } if ctrlAlt { return Event{CtrlAltUp, 0, nil} } if ctrlShift { return Event{CtrlShiftUp, 0, nil} } if altShift { return Event{AltShiftUp, 0, nil} } if ctrl { return Event{CtrlUp, 0, nil} } if shift { return Event{ShiftUp, 0, nil} } if alt { return Event{AltUp, 0, nil} } return Event{Up, 0, nil} case tcell.KeyDown: if ctrlAltShift { return Event{CtrlAltShiftDown, 0, nil} } if ctrlAlt { return Event{CtrlAltDown, 0, nil} } if ctrlShift { return Event{CtrlShiftDown, 0, nil} } if altShift { return Event{AltShiftDown, 0, nil} } if ctrl { return Event{CtrlDown, 0, nil} } if shift { return Event{ShiftDown, 0, nil} } if alt { return Event{AltDown, 0, nil} } return Event{Down, 0, nil} case tcell.KeyLeft: if ctrlAltShift { return Event{CtrlAltShiftLeft, 0, nil} } if ctrlAlt { return Event{CtrlAltLeft, 0, nil} } if ctrlShift { return Event{CtrlShiftLeft, 0, nil} } if altShift { return Event{AltShiftLeft, 0, nil} } if ctrl { return Event{CtrlLeft, 0, nil} } if shift { return Event{ShiftLeft, 0, nil} } if alt { return Event{AltLeft, 0, nil} } return Event{Left, 0, nil} case tcell.KeyRight: if ctrlAltShift { return Event{CtrlAltShiftRight, 0, nil} } if ctrlAlt { return Event{CtrlAltRight, 0, nil} } if ctrlShift { return Event{CtrlShiftRight, 0, nil} } if altShift { return Event{AltShiftRight, 0, nil} } if ctrl { return Event{CtrlRight, 0, nil} } if shift { return Event{ShiftRight, 0, nil} } if alt { return Event{AltRight, 0, nil} } return Event{Right, 0, nil} // section 5: (Insert|Home|Delete|End|PgUp|PgDn|BackTab|F1-F12) case tcell.KeyInsert: return Event{Insert, 0, nil} case tcell.KeyHome: if ctrlAltShift { return Event{CtrlAltShiftHome, 0, nil} } if ctrlAlt { return Event{CtrlAltHome, 0, nil} } if ctrlShift { return Event{CtrlShiftHome, 0, nil} } if altShift { return Event{AltShiftHome, 0, nil} } if ctrl { return Event{CtrlHome, 0, nil} } if shift { return Event{ShiftHome, 0, nil} } if alt { return Event{AltHome, 0, nil} } return Event{Home, 0, nil} case tcell.KeyDelete: if ctrlAltShift { return Event{CtrlAltShiftDelete, 0, nil} } if ctrlAlt { return Event{CtrlAltDelete, 0, nil} } if ctrlShift { return Event{CtrlShiftDelete, 0, nil} } if altShift { return Event{AltShiftDelete, 0, nil} } if ctrl { return Event{CtrlDelete, 0, nil} } if alt { return Event{AltDelete, 0, nil} } if shift { return Event{ShiftDelete, 0, nil} } return Event{Delete, 0, nil} case tcell.KeyEnd: if ctrlAltShift { return Event{CtrlAltShiftEnd, 0, nil} } if ctrlAlt { return Event{CtrlAltEnd, 0, nil} } if ctrlShift { return Event{CtrlShiftEnd, 0, nil} } if altShift { return Event{AltShiftEnd, 0, nil} } if ctrl { return Event{CtrlEnd, 0, nil} } if shift { return Event{ShiftEnd, 0, nil} } if alt { return Event{AltEnd, 0, nil} } return Event{End, 0, nil} case tcell.KeyPgUp: if ctrlAltShift { return Event{CtrlAltShiftPageUp, 0, nil} } if ctrlAlt { return Event{CtrlAltPageUp, 0, nil} } if ctrlShift { return Event{CtrlShiftPageUp, 0, nil} } if altShift { return Event{AltShiftPageUp, 0, nil} } if ctrl { return Event{CtrlPageUp, 0, nil} } if shift { return Event{ShiftPageUp, 0, nil} } if alt { return Event{AltPageUp, 0, nil} } return Event{PageUp, 0, nil} case tcell.KeyPgDn: if ctrlAltShift { return Event{CtrlAltShiftPageDown, 0, nil} } if ctrlAlt { return Event{CtrlAltPageDown, 0, nil} } if ctrlShift { return Event{CtrlShiftPageDown, 0, nil} } if altShift { return Event{AltShiftPageDown, 0, nil} } if ctrl { return Event{CtrlPageDown, 0, nil} } if shift { return Event{ShiftPageDown, 0, nil} } if alt { return Event{AltPageDown, 0, nil} } return Event{PageDown, 0, nil} case tcell.KeyBacktab: return Event{ShiftTab, 0, nil} case tcell.KeyF1: return Event{F1, 0, nil} case tcell.KeyF2: return Event{F2, 0, nil} case tcell.KeyF3: return Event{F3, 0, nil} case tcell.KeyF4: return Event{F4, 0, nil} case tcell.KeyF5: return Event{F5, 0, nil} case tcell.KeyF6: return Event{F6, 0, nil} case tcell.KeyF7: return Event{F7, 0, nil} case tcell.KeyF8: return Event{F8, 0, nil} case tcell.KeyF9: return Event{F9, 0, nil} case tcell.KeyF10: return Event{F10, 0, nil} case tcell.KeyF11: return Event{F11, 0, nil} case tcell.KeyF12: return Event{F12, 0, nil} // section 6: (Ctrl+Alt)+'rune' case tcell.KeyRune: r := ev.Rune() switch { // translate native key events to ascii control characters case r == ' ' && ctrl: return Event{CtrlSpace, 0, nil} // handle AltGr characters case ctrlAlt: return Event{Rune, r, nil} // dropping modifiers // simple characters (possibly with modifier) case alt: return AltKey(r) default: return Event{Rune, r, nil} } // section 7: Esc case tcell.KeyEsc: return Event{Esc, 0, nil} } } // section 8: Invalid return Event{Invalid, 0, nil} } func (r *FullscreenRenderer) Pause(clear bool) { if clear { _screen.Suspend() } } func (r *FullscreenRenderer) Resume(clear bool, sigcont bool) { if clear { _screen.Resume() } } func (r *FullscreenRenderer) Close() { _screen.Fini() _screen = nil } func (r *FullscreenRenderer) RefreshWindows(windows []Window) { // TODO for _, w := range windows { w.Refresh() } _screen.Show() } func (r *FullscreenRenderer) NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window { width = max(0, width) height = max(0, height) normal := ColBorder switch windowType { case WindowList: normal = ColNormal case WindowHeader: normal = ColHeader case WindowFooter: normal = ColFooter case WindowInput: normal = ColInput case WindowPreview: normal = ColPreview } w := &TcellWindow{ color: r.theme.Colored, windowType: windowType, top: top, left: left, width: width, height: height, normal: normal, borderStyle: borderStyle, showCursor: r.showCursor} w.Erase() return w } func fill(x, y, w, h int, n ColorPair, r rune) { for ly := 0; ly <= h; ly++ { for lx := 0; lx <= w; lx++ { _screen.SetContent(x+lx, y+ly, r, nil, n.style()) } } } func (w *TcellWindow) Erase() { fill(w.left, w.top, w.width-1, w.height-1, w.normal, ' ') w.drawBorder(false) } func (w *TcellWindow) EraseMaybe() bool { w.Erase() return true } func (w *TcellWindow) SetWrapSign(sign string, width int) { w.wrapSign = sign w.wrapSignWidth = width } func (w *TcellWindow) EncloseX(x int) bool { return x >= w.left && x < (w.left+w.width) } func (w *TcellWindow) EncloseY(y int) bool { return y >= w.top && y < (w.top+w.height) } func (w *TcellWindow) Enclose(y int, x int) bool { return w.EncloseX(x) && w.EncloseY(y) } func (w *TcellWindow) Move(y int, x int) { w.lastX = x w.lastY = y w.moveCursor = true } func (w *TcellWindow) MoveAndClear(y int, x int) { w.Move(y, x) for i := w.lastX; i < w.width; i++ { _screen.SetContent(i+w.left, w.lastY+w.top, rune(' '), nil, w.normal.style()) } w.lastX = x } func (w *TcellWindow) Print(text string) { w.printString(text, w.normal) } func (w *TcellWindow) withUrl(style tcell.Style) tcell.Style { if w.uri != nil { style = style.Url(*w.uri) if md := regexp.MustCompile(`id=([^:]+)`).FindStringSubmatch(*w.params); len(md) > 1 { style = style.UrlId(md[1]) } } return style } func (w *TcellWindow) printString(text string, pair ColorPair) { lx := 0 a := pair.Attr() style := pair.style() if a&AttrClear == 0 { style = style. Reverse(a&Attr(tcell.AttrReverse) != 0). Underline(a&Attr(tcell.AttrUnderline) != 0). StrikeThrough(a&Attr(tcell.AttrStrikeThrough) != 0). Italic(a&Attr(tcell.AttrItalic) != 0). Blink(a&Attr(tcell.AttrBlink) != 0). Dim(a&Attr(tcell.AttrDim) != 0) } style = w.withUrl(style) gr := uniseg.NewGraphemes(text) for gr.Next() { st := style rs := gr.Runes() if len(rs) == 1 { r := rs[0] if r == '\r' { st = style.Dim(true) rs[0] = '␍' } else if r == '\n' { st = style.Dim(true) rs[0] = '␊' } else if r < rune(' ') { // ignore control characters continue } } var xPos = w.left + w.lastX + lx var yPos = w.top + w.lastY if xPos < (w.left+w.width) && yPos < (w.top+w.height) { _screen.SetContent(xPos, yPos, rs[0], rs[1:], st) } lx += util.StringWidth(string(rs)) } w.lastX += lx } func (w *TcellWindow) CPrint(pair ColorPair, text string) { w.printString(text, pair) } func (w *TcellWindow) fillString(text string, pair ColorPair) FillReturn { lx := 0 a := pair.Attr() var style tcell.Style if w.color { style = pair.style() } else { style = w.normal.style() } style = style. Blink(a&Attr(tcell.AttrBlink) != 0). Bold(a&Attr(tcell.AttrBold) != 0 || a&BoldForce != 0). Dim(a&Attr(tcell.AttrDim) != 0). Reverse(a&Attr(tcell.AttrReverse) != 0). Underline(a&Attr(tcell.AttrUnderline) != 0). StrikeThrough(a&Attr(tcell.AttrStrikeThrough) != 0). Italic(a&Attr(tcell.AttrItalic) != 0) style = w.withUrl(style) gr := uniseg.NewGraphemes(text) Loop: for gr.Next() { st := style rs := gr.Runes() if len(rs) == 1 { r := rs[0] switch r { case '\r': st = style.Dim(true) rs[0] = '␍' case '\n': w.lastY++ w.lastX = 0 lx = 0 continue Loop } } // word wrap: xPos := w.left + w.lastX + lx if xPos >= w.left+w.width { w.lastY++ if w.lastY >= w.height { return FillSuspend } w.lastX = 0 lx = 0 xPos = w.left sign := w.wrapSign if w.wrapSignWidth > w.width { runes, _ := util.Truncate(sign, w.width) sign = string(runes) } wgr := uniseg.NewGraphemes(sign) for wgr.Next() { rs := wgr.Runes() _screen.SetContent(w.left+lx, w.top+w.lastY, rs[0], rs[1:], style.Dim(true)) lx += uniseg.StringWidth(string(rs)) } xPos = w.left + lx } yPos := w.top + w.lastY if yPos >= (w.top + w.height) { return FillSuspend } _screen.SetContent(xPos, yPos, rs[0], rs[1:], st) lx += util.StringWidth(string(rs)) } w.lastX += lx if w.lastX == w.width { w.lastY++ w.lastX = 0 return FillNextLine } return FillContinue } func (w *TcellWindow) Fill(str string) FillReturn { return w.fillString(str, w.normal) } func (w *TcellWindow) LinkBegin(uri string, params string) { w.uri = &uri w.params = &params } func (w *TcellWindow) LinkEnd() { w.uri = nil w.params = nil } func (w *TcellWindow) CFill(fg Color, bg Color, a Attr, str string) FillReturn { if fg == colDefault { fg = w.normal.Fg() } if bg == colDefault { bg = w.normal.Bg() } return w.fillString(str, NewColorPair(fg, bg, a)) } func (w *TcellWindow) DrawBorder() { w.drawBorder(false) } func (w *TcellWindow) DrawHBorder() { w.drawBorder(true) } func (w *TcellWindow) drawBorder(onlyHorizontal bool) { if w.height == 0 { return } shape := w.borderStyle.shape if shape == BorderNone { return } left := w.left right := left + w.width top := w.top bot := top + w.height var style tcell.Style if w.color { switch w.windowType { case WindowBase: style = ColBorder.style() case WindowList: style = ColListBorder.style() case WindowHeader: style = ColHeaderBorder.style() case WindowFooter: style = ColFooterBorder.style() case WindowInput: style = ColInputBorder.style() case WindowPreview: style = ColPreviewBorder.style() } } else { style = w.normal.style() } hw := runeWidth(w.borderStyle.top) switch shape { case BorderRounded, BorderSharp, BorderBold, BorderBlock, BorderThinBlock, BorderDouble, BorderHorizontal, BorderTop: max := right - 2*hw if shape == BorderHorizontal || shape == BorderTop { max = right - hw } // tcell has an issue displaying two overlapping wide runes // e.g. SetContent( HH ) // SetContent( TR ) // ================== // ( HH ) => TR is ignored for x := left; x <= max; x += hw { _screen.SetContent(x, top, w.borderStyle.top, nil, style) } } switch shape { case BorderRounded, BorderSharp, BorderBold, BorderBlock, BorderThinBlock, BorderDouble, BorderHorizontal, BorderBottom: max := right - 2*hw if shape == BorderHorizontal || shape == BorderBottom { max = right - hw } for x := left; x <= max; x += hw { _screen.SetContent(x, bot-1, w.borderStyle.bottom, nil, style) } } if !onlyHorizontal { switch shape { case BorderRounded, BorderSharp, BorderBold, BorderBlock, BorderThinBlock, BorderDouble, BorderVertical, BorderLeft: for y := top; y < bot; y++ { _screen.SetContent(left, y, w.borderStyle.left, nil, style) } } switch shape { case BorderRounded, BorderSharp, BorderBold, BorderBlock, BorderThinBlock, BorderDouble, BorderVertical, BorderRight: vw := runeWidth(w.borderStyle.right) for y := top; y < bot; y++ { _screen.SetContent(right-vw, y, w.borderStyle.right, nil, style) } } } switch shape { case BorderRounded, BorderSharp, BorderBold, BorderBlock, BorderThinBlock, BorderDouble: _screen.SetContent(left, top, w.borderStyle.topLeft, nil, style) _screen.SetContent(right-runeWidth(w.borderStyle.topRight), top, w.borderStyle.topRight, nil, style) _screen.SetContent(left, bot-1, w.borderStyle.bottomLeft, nil, style) _screen.SetContent(right-runeWidth(w.borderStyle.bottomRight), bot-1, w.borderStyle.bottomRight, nil, style) } }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/light_unix.go
src/tui/light_unix.go
//go:build !windows package tui import ( "errors" "os" "os/exec" "strings" "syscall" "github.com/junegunn/fzf/src/util" "golang.org/x/sys/unix" "golang.org/x/term" ) func IsLightRendererSupported() bool { return true } func (r *LightRenderer) DefaultTheme() *ColorTheme { if strings.Contains(os.Getenv("TERM"), "256") { return Dark256 } colors, err := exec.Command("tput", "colors").Output() if err == nil && atoi(strings.TrimSpace(string(colors)), 16) > 16 { return Dark256 } return Default16 } func (r *LightRenderer) fd() int { return int(r.ttyin.Fd()) } func (r *LightRenderer) initPlatform() (err error) { r.origState, err = term.MakeRaw(r.fd()) return err } func (r *LightRenderer) closePlatform() { r.ttyout.Close() } func openTty(ttyDefault string, mode int) (*os.File, error) { var in *os.File var err error if len(ttyDefault) > 0 { in, err = os.OpenFile(ttyDefault, mode, 0) } if in == nil || err != nil || ttyDefault != DefaultTtyDevice && !util.IsTty(in) { tty := ttyname() if len(tty) > 0 { if in, err := os.OpenFile(tty, mode, 0); err == nil { return in, nil } } if ttyDefault != DefaultTtyDevice { if in, err = os.OpenFile(DefaultTtyDevice, mode, 0); err == nil { return in, nil } } return nil, errors.New("failed to open " + DefaultTtyDevice) } return in, nil } func openTtyIn(ttyDefault string) (*os.File, error) { return openTty(ttyDefault, syscall.O_RDONLY) } func openTtyOut(ttyDefault string) (*os.File, error) { return openTty(ttyDefault, syscall.O_WRONLY) } func (r *LightRenderer) setupTerminal() { term.MakeRaw(r.fd()) } func (r *LightRenderer) restoreTerminal() { term.Restore(r.fd(), r.origState) } func (r *LightRenderer) updateTerminalSize() { width, height, err := term.GetSize(r.fd()) if err == nil { r.width = width r.height = r.maxHeightFunc(height) } else { r.width = getEnv("COLUMNS", defaultWidth) r.height = r.maxHeightFunc(getEnv("LINES", defaultHeight)) } } func (r *LightRenderer) findOffset() (row int, col int) { r.csi("6n") r.flush() var err error bytes := []byte{} for tries := range offsetPollTries { bytes, err = r.getBytesInternal(bytes, tries > 0) if err != nil { return -1, -1 } offsets := offsetRegexp.FindSubmatch(bytes) if len(offsets) > 3 { // Add anything we skipped over to the input buffer r.buffer = append(r.buffer, offsets[1]...) return atoi(string(offsets[2]), 0) - 1, atoi(string(offsets[3]), 0) - 1 } } return -1, -1 } func (r *LightRenderer) getch(nonblock bool) (int, bool) { b := make([]byte, 1) fd := r.fd() util.SetNonblock(r.ttyin, nonblock) _, err := util.Read(fd, b) if err != nil { return 0, false } return int(b[0]), true } func (r *LightRenderer) Size() TermSize { ws, err := unix.IoctlGetWinsize(int(r.ttyin.Fd()), unix.TIOCGWINSZ) if err != nil { return TermSize{} } return TermSize{int(ws.Row), int(ws.Col), int(ws.Xpixel), int(ws.Ypixel)} }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/tui.go
src/tui/tui.go
package tui import ( "strconv" "time" "github.com/junegunn/fzf/src/util" "github.com/rivo/uniseg" ) type Attr int32 const ( AttrUndefined = Attr(0) AttrRegular = Attr(1 << 8) AttrClear = Attr(1 << 9) BoldForce = Attr(1 << 10) FullBg = Attr(1 << 11) Strip = Attr(1 << 12) ) func (a Attr) Merge(b Attr) Attr { if b&AttrRegular > 0 { // Only keep bold attribute set by the system return (b &^ AttrRegular) | (a & BoldForce) } return (a &^ AttrRegular) | b } // Types of user action // //go:generate stringer -type=EventType type EventType int const ( Rune EventType = iota CtrlA CtrlB CtrlC CtrlD CtrlE CtrlF CtrlG CtrlH Tab CtrlJ CtrlK CtrlL Enter CtrlN CtrlO CtrlP CtrlQ CtrlR CtrlS CtrlT CtrlU CtrlV CtrlW CtrlX CtrlY CtrlZ Esc CtrlSpace // https://apple.stackexchange.com/questions/24261/how-do-i-send-c-that-is-control-slash-to-the-terminal CtrlBackSlash CtrlRightBracket CtrlCaret CtrlSlash ShiftTab Backspace Delete PageUp PageDown Up Down Left Right Home End Insert ShiftUp ShiftDown ShiftLeft ShiftRight ShiftDelete ShiftHome ShiftEnd ShiftPageUp ShiftPageDown F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 AltBackspace AltUp AltDown AltLeft AltRight AltDelete AltHome AltEnd AltPageUp AltPageDown AltShiftUp AltShiftDown AltShiftLeft AltShiftRight AltShiftDelete AltShiftHome AltShiftEnd AltShiftPageUp AltShiftPageDown CtrlUp CtrlDown CtrlLeft CtrlRight CtrlHome CtrlEnd CtrlBackspace CtrlDelete CtrlPageUp CtrlPageDown Alt CtrlAlt CtrlAltUp CtrlAltDown CtrlAltLeft CtrlAltRight CtrlAltHome CtrlAltEnd CtrlAltBackspace CtrlAltDelete CtrlAltPageUp CtrlAltPageDown CtrlShiftUp CtrlShiftDown CtrlShiftLeft CtrlShiftRight CtrlShiftHome CtrlShiftEnd CtrlShiftDelete CtrlShiftPageUp CtrlShiftPageDown CtrlAltShiftUp CtrlAltShiftDown CtrlAltShiftLeft CtrlAltShiftRight CtrlAltShiftHome CtrlAltShiftEnd CtrlAltShiftDelete CtrlAltShiftPageUp CtrlAltShiftPageDown Invalid Fatal BracketedPasteBegin BracketedPasteEnd Mouse DoubleClick LeftClick RightClick SLeftClick SRightClick ScrollUp ScrollDown SScrollUp SScrollDown PreviewScrollUp PreviewScrollDown // Events Resize Change BackwardEOF Start Load Focus One Zero Result Jump JumpCancel ClickHeader ClickFooter Multi ) func (t EventType) AsEvent() Event { return Event{t, 0, nil} } func (t EventType) Int() int { return int(t) } func (t EventType) Byte() byte { return byte(t) } func (e Event) Comparable() Event { // Ignore MouseEvent pointer return Event{e.Type, e.Char, nil} } func (e Event) KeyName() string { if me := e.MouseEvent; me != nil { return me.Name() } if e.Type >= Invalid { return "" } switch e.Type { case Rune: if e.Char == ' ' { return "space" } return string(e.Char) case Alt: return "alt-" + string(e.Char) case CtrlAlt: return "ctrl-alt-" + string(e.Char) case CtrlBackSlash: return "ctrl-\\" case CtrlRightBracket: return "ctrl-]" case CtrlCaret: return "ctrl-^" case CtrlSlash: return "ctrl-/" } return util.ToKebabCase(e.Type.String()) } func Key(r rune) Event { return Event{Rune, r, nil} } func AltKey(r rune) Event { return Event{Alt, r, nil} } func CtrlAltKey(r rune) Event { return Event{CtrlAlt, r, nil} } const ( doubleClickDuration = 500 * time.Millisecond ) type Color int32 func (c Color) IsDefault() bool { return c == colDefault } func (c Color) is24() bool { return c > 0 && (c&(1<<24)) > 0 } type ColorAttr struct { Color Color Attr Attr } func (a ColorAttr) IsColorDefined() bool { return a.Color != colUndefined } func (a ColorAttr) IsAttrDefined() bool { return a.Attr&^BoldForce != AttrUndefined } func (a ColorAttr) IsUndefined() bool { return !a.IsColorDefined() && !a.IsAttrDefined() } func NewColorAttr() ColorAttr { return ColorAttr{Color: colUndefined, Attr: AttrUndefined} } func (a ColorAttr) Merge(other ColorAttr) ColorAttr { if other.Color != colUndefined { a.Color = other.Color } if other.Attr != AttrUndefined { a.Attr = a.Attr.Merge(other.Attr) } return a } const ( colUndefined Color = -2 colDefault Color = -1 ) const ( colBlack Color = iota colRed colGreen colYellow colBlue colMagenta colCyan colWhite colGrey colBrightRed colBrightGreen colBrightYellow colBrightBlue colBrightMagenta colBrightCyan colBrightWhite ) type FillReturn int const ( FillContinue FillReturn = iota FillNextLine FillSuspend ) type ColorPair struct { fg Color bg Color attr Attr } func HexToColor(rrggbb string) Color { r, _ := strconv.ParseInt(rrggbb[1:3], 16, 0) g, _ := strconv.ParseInt(rrggbb[3:5], 16, 0) b, _ := strconv.ParseInt(rrggbb[5:7], 16, 0) return Color((1 << 24) + (r << 16) + (g << 8) + b) } func NewColorPair(fg Color, bg Color, attr Attr) ColorPair { return ColorPair{fg, bg, attr} } func NoColorPair() ColorPair { return ColorPair{-1, -1, 0} } func (p ColorPair) Fg() Color { return p.fg } func (p ColorPair) Bg() Color { return p.bg } func (p ColorPair) Attr() Attr { return p.attr } func (p ColorPair) IsFullBgMarker() bool { return p.attr&FullBg > 0 } func (p ColorPair) ShouldStripColors() bool { return p.attr&Strip > 0 } func (p ColorPair) HasBg() bool { return p.attr&Reverse == 0 && p.bg != colDefault || p.attr&Reverse > 0 && p.fg != colDefault } func (p ColorPair) merge(other ColorPair, except Color) ColorPair { dup := p dup.attr = dup.attr.Merge(other.attr) if other.fg != except { dup.fg = other.fg } if other.bg != except { dup.bg = other.bg } return dup } func (p ColorPair) WithAttr(attr Attr) ColorPair { dup := p dup.attr = dup.attr.Merge(attr) return dup } func (p ColorPair) WithFg(fg ColorAttr) ColorPair { dup := p fgPair := ColorPair{fg.Color, colUndefined, fg.Attr} return dup.Merge(fgPair) } func (p ColorPair) WithBg(bg ColorAttr) ColorPair { dup := p bgPair := ColorPair{colUndefined, bg.Color, bg.Attr} return dup.Merge(bgPair) } func (p ColorPair) MergeAttr(other ColorPair) ColorPair { return p.WithAttr(other.attr) } func (p ColorPair) Merge(other ColorPair) ColorPair { return p.merge(other, colUndefined) } func (p ColorPair) MergeNonDefault(other ColorPair) ColorPair { return p.merge(other, colDefault) } type ColorTheme struct { Colored bool Input ColorAttr Ghost ColorAttr Disabled ColorAttr Fg ColorAttr Bg ColorAttr ListFg ColorAttr ListBg ColorAttr AltBg ColorAttr Nth ColorAttr Nomatch ColorAttr SelectedFg ColorAttr SelectedBg ColorAttr SelectedMatch ColorAttr PreviewFg ColorAttr PreviewBg ColorAttr DarkBg ColorAttr Gutter ColorAttr AltGutter ColorAttr Prompt ColorAttr InputBg ColorAttr InputBorder ColorAttr InputLabel ColorAttr Match ColorAttr Current ColorAttr CurrentMatch ColorAttr Spinner ColorAttr Info ColorAttr Cursor ColorAttr Marker ColorAttr Header ColorAttr HeaderBg ColorAttr HeaderBorder ColorAttr HeaderLabel ColorAttr Footer ColorAttr FooterBg ColorAttr FooterBorder ColorAttr FooterLabel ColorAttr Separator ColorAttr Scrollbar ColorAttr Border ColorAttr PreviewBorder ColorAttr PreviewLabel ColorAttr PreviewScrollbar ColorAttr BorderLabel ColorAttr ListLabel ColorAttr ListBorder ColorAttr GapLine ColorAttr } type Event struct { Type EventType Char rune MouseEvent *MouseEvent } type MouseEvent struct { Y int X int S int Left bool Down bool Double bool Ctrl bool Alt bool Shift bool } func (e MouseEvent) Mod() bool { return e.Ctrl || e.Alt || e.Shift } func (e MouseEvent) Name() string { name := "" if e.Down { return name } if e.Ctrl { name += "ctrl-" } if e.Alt { name += "alt-" } if e.Shift { name += "shift-" } if e.Double { name += "double-" } if !e.Left { name += "right-" } return name + "click" } type BorderShape int const ( BorderUndefined BorderShape = iota BorderLine BorderNone BorderPhantom BorderRounded BorderSharp BorderBold BorderBlock BorderThinBlock BorderDouble BorderHorizontal BorderVertical BorderTop BorderBottom BorderLeft BorderRight ) func (s BorderShape) HasLeft() bool { switch s { case BorderNone, BorderPhantom, BorderLine, BorderRight, BorderTop, BorderBottom, BorderHorizontal: // No Left return false } return true } func (s BorderShape) HasRight() bool { switch s { case BorderNone, BorderPhantom, BorderLine, BorderLeft, BorderTop, BorderBottom, BorderHorizontal: // No right return false } return true } func (s BorderShape) HasTop() bool { switch s { case BorderNone, BorderPhantom, BorderLine, BorderLeft, BorderRight, BorderBottom, BorderVertical: // No top return false } return true } func (s BorderShape) HasBottom() bool { switch s { case BorderNone, BorderPhantom, BorderLine, BorderLeft, BorderRight, BorderTop, BorderVertical: // No bottom return false } return true } func (s BorderShape) Visible() bool { return s != BorderNone } type BorderStyle struct { shape BorderShape top rune bottom rune left rune right rune topLeft rune topRight rune bottomLeft rune bottomRight rune } type BorderCharacter int func MakeBorderStyle(shape BorderShape, unicode bool) BorderStyle { if shape == BorderNone || shape == BorderPhantom { return BorderStyle{ shape: BorderNone, top: ' ', bottom: ' ', left: ' ', right: ' ', topLeft: ' ', topRight: ' ', bottomLeft: ' ', bottomRight: ' '} } if !unicode { return BorderStyle{ shape: shape, top: '-', bottom: '-', left: '|', right: '|', topLeft: '+', topRight: '+', bottomLeft: '+', bottomRight: '+', } } switch shape { case BorderSharp: return BorderStyle{ shape: shape, top: '─', bottom: '─', left: '│', right: '│', topLeft: '┌', topRight: '┐', bottomLeft: '└', bottomRight: '┘', } case BorderBold: return BorderStyle{ shape: shape, top: '━', bottom: '━', left: '┃', right: '┃', topLeft: '┏', topRight: '┓', bottomLeft: '┗', bottomRight: '┛', } case BorderBlock: // ▛▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▜ // ▌ ▐ // ▙▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▟ return BorderStyle{ shape: shape, top: '▀', bottom: '▄', left: '▌', right: '▐', topLeft: '▛', topRight: '▜', bottomLeft: '▙', bottomRight: '▟', } case BorderThinBlock: // 🭽▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔🭾 // ▏ ▕ // 🭼▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁🭿 return BorderStyle{ shape: shape, top: '▔', bottom: '▁', left: '▏', right: '▕', topLeft: '🭽', topRight: '🭾', bottomLeft: '🭼', bottomRight: '🭿', } case BorderDouble: return BorderStyle{ shape: shape, top: '═', bottom: '═', left: '║', right: '║', topLeft: '╔', topRight: '╗', bottomLeft: '╚', bottomRight: '╝', } } return BorderStyle{ shape: shape, top: '─', bottom: '─', left: '│', right: '│', topLeft: '╭', topRight: '╮', bottomLeft: '╰', bottomRight: '╯', } } type TermSize struct { Lines int Columns int PxWidth int PxHeight int } type WindowType int const ( WindowBase WindowType = iota WindowList WindowPreview WindowInput WindowHeader WindowFooter ) type Renderer interface { DefaultTheme() *ColorTheme Init() error Resize(maxHeightFunc func(int) int) Pause(clear bool) Resume(clear bool, sigcont bool) Clear() RefreshWindows(windows []Window) Refresh() Close() PassThrough(string) NeedScrollbarRedraw() bool ShouldEmitResizeEvent() bool Bell() HideCursor() ShowCursor() GetChar() Event Top() int MaxX() int MaxY() int Size() TermSize NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window } type Window interface { Top() int Left() int Width() int Height() int DrawBorder() DrawHBorder() Refresh() FinishFill() X() int Y() int EncloseX(x int) bool EncloseY(y int) bool Enclose(y int, x int) bool Move(y int, x int) MoveAndClear(y int, x int) Print(text string) CPrint(color ColorPair, text string) Fill(text string) FillReturn CFill(fg Color, bg Color, attr Attr, text string) FillReturn LinkBegin(uri string, params string) LinkEnd() Erase() EraseMaybe() bool SetWrapSign(string, int) } type FullscreenRenderer struct { theme *ColorTheme mouse bool forceBlack bool prevDownTime time.Time clicks [][2]int showCursor bool } func NewFullscreenRenderer(theme *ColorTheme, forceBlack bool, mouse bool) Renderer { r := &FullscreenRenderer{ theme: theme, mouse: mouse, forceBlack: forceBlack, prevDownTime: time.Unix(0, 0), clicks: [][2]int{}, showCursor: true} return r } var ( NoColorTheme *ColorTheme EmptyTheme *ColorTheme Default16 *ColorTheme Dark256 *ColorTheme Light256 *ColorTheme ColPrompt ColorPair ColNormal ColorPair ColInput ColorPair ColDisabled ColorPair ColGhost ColorPair ColMatch ColorPair ColCursor ColorPair ColCursorEmpty ColorPair ColCursorEmptyChar ColorPair ColAltCursorEmpty ColorPair ColAltCursorEmptyChar ColorPair ColMarker ColorPair ColSelected ColorPair ColSelectedMatch ColorPair ColCurrent ColorPair ColCurrentMatch ColorPair ColCurrentCursor ColorPair ColCurrentCursorEmpty ColorPair ColCurrentMarker ColorPair ColCurrentSelectedEmpty ColorPair ColSpinner ColorPair ColInfo ColorPair ColHeader ColorPair ColHeaderBorder ColorPair ColHeaderLabel ColorPair ColFooter ColorPair ColFooterBorder ColorPair ColFooterLabel ColorPair ColSeparator ColorPair ColScrollbar ColorPair ColGapLine ColorPair ColBorder ColorPair ColPreview ColorPair ColPreviewBorder ColorPair ColBorderLabel ColorPair ColPreviewLabel ColorPair ColPreviewScrollbar ColorPair ColPreviewSpinner ColorPair ColListBorder ColorPair ColListLabel ColorPair ColInputBorder ColorPair ColInputLabel ColorPair ) func init() { defaultColor := ColorAttr{colDefault, AttrUndefined} undefined := ColorAttr{colUndefined, AttrUndefined} NoColorTheme = &ColorTheme{ Colored: false, Input: defaultColor, Fg: defaultColor, Bg: defaultColor, ListFg: defaultColor, ListBg: defaultColor, AltBg: undefined, SelectedFg: defaultColor, SelectedBg: defaultColor, SelectedMatch: defaultColor, DarkBg: defaultColor, Prompt: defaultColor, Match: defaultColor, Current: undefined, CurrentMatch: undefined, Spinner: defaultColor, Info: defaultColor, Cursor: defaultColor, Marker: defaultColor, Header: defaultColor, Border: undefined, BorderLabel: defaultColor, Ghost: undefined, Disabled: defaultColor, PreviewFg: defaultColor, PreviewBg: defaultColor, Gutter: undefined, AltGutter: undefined, PreviewBorder: defaultColor, PreviewScrollbar: defaultColor, PreviewLabel: defaultColor, ListLabel: defaultColor, ListBorder: defaultColor, Separator: defaultColor, Scrollbar: defaultColor, InputBg: defaultColor, InputBorder: defaultColor, InputLabel: defaultColor, HeaderBg: defaultColor, HeaderBorder: defaultColor, HeaderLabel: defaultColor, FooterBg: defaultColor, FooterBorder: defaultColor, FooterLabel: defaultColor, GapLine: defaultColor, Nth: undefined, Nomatch: undefined, } EmptyTheme = &ColorTheme{ Colored: true, Input: undefined, Fg: undefined, Bg: undefined, ListFg: undefined, ListBg: undefined, AltBg: undefined, SelectedFg: undefined, SelectedBg: undefined, SelectedMatch: undefined, DarkBg: undefined, Prompt: undefined, Match: undefined, Current: undefined, CurrentMatch: undefined, Spinner: undefined, Info: undefined, Cursor: undefined, Marker: undefined, Header: undefined, Footer: undefined, Border: undefined, BorderLabel: undefined, ListLabel: undefined, ListBorder: undefined, Ghost: undefined, Disabled: undefined, PreviewFg: undefined, PreviewBg: undefined, Gutter: undefined, AltGutter: undefined, PreviewBorder: undefined, PreviewScrollbar: undefined, PreviewLabel: undefined, Separator: undefined, Scrollbar: undefined, InputBg: undefined, InputBorder: undefined, InputLabel: undefined, HeaderBg: undefined, HeaderBorder: undefined, HeaderLabel: undefined, FooterBg: undefined, FooterBorder: undefined, FooterLabel: undefined, GapLine: undefined, Nth: undefined, Nomatch: undefined, } Default16 = &ColorTheme{ Colored: true, Input: defaultColor, Fg: defaultColor, Bg: defaultColor, ListFg: undefined, ListBg: undefined, AltBg: undefined, SelectedFg: undefined, SelectedBg: undefined, SelectedMatch: undefined, DarkBg: ColorAttr{colGrey, AttrUndefined}, Prompt: ColorAttr{colBlue, AttrUndefined}, Match: ColorAttr{colGreen, AttrUndefined}, Current: ColorAttr{colBrightWhite, AttrUndefined}, CurrentMatch: ColorAttr{colBrightGreen, AttrUndefined}, Spinner: ColorAttr{colGreen, AttrUndefined}, Info: ColorAttr{colYellow, AttrUndefined}, Cursor: ColorAttr{colRed, AttrUndefined}, Marker: ColorAttr{colMagenta, AttrUndefined}, Header: ColorAttr{colCyan, AttrUndefined}, Footer: ColorAttr{colCyan, AttrUndefined}, Border: undefined, BorderLabel: defaultColor, Ghost: undefined, Disabled: undefined, PreviewFg: undefined, PreviewBg: undefined, Gutter: undefined, AltGutter: undefined, PreviewBorder: undefined, PreviewScrollbar: undefined, PreviewLabel: undefined, ListLabel: undefined, ListBorder: undefined, Separator: undefined, Scrollbar: undefined, InputBg: undefined, InputBorder: undefined, InputLabel: undefined, HeaderBg: undefined, HeaderBorder: undefined, HeaderLabel: undefined, FooterBg: undefined, FooterBorder: undefined, FooterLabel: undefined, GapLine: undefined, Nth: undefined, Nomatch: undefined, } Dark256 = &ColorTheme{ Colored: true, Input: defaultColor, Fg: defaultColor, Bg: defaultColor, ListFg: undefined, ListBg: undefined, AltBg: undefined, SelectedFg: undefined, SelectedBg: undefined, SelectedMatch: undefined, DarkBg: ColorAttr{236, AttrUndefined}, Prompt: ColorAttr{110, AttrUndefined}, Match: ColorAttr{108, AttrUndefined}, Current: ColorAttr{254, AttrUndefined}, CurrentMatch: ColorAttr{151, AttrUndefined}, Spinner: ColorAttr{148, AttrUndefined}, Info: ColorAttr{144, AttrUndefined}, Cursor: ColorAttr{161, AttrUndefined}, Marker: ColorAttr{168, AttrUndefined}, Header: ColorAttr{109, AttrUndefined}, Footer: ColorAttr{109, AttrUndefined}, Border: ColorAttr{59, AttrUndefined}, BorderLabel: ColorAttr{145, AttrUndefined}, Ghost: undefined, Disabled: undefined, PreviewFg: undefined, PreviewBg: undefined, Gutter: undefined, AltGutter: undefined, PreviewBorder: undefined, PreviewScrollbar: undefined, PreviewLabel: undefined, ListLabel: undefined, ListBorder: undefined, Separator: undefined, Scrollbar: undefined, InputBg: undefined, InputBorder: undefined, InputLabel: undefined, HeaderBg: undefined, HeaderBorder: undefined, HeaderLabel: undefined, FooterBg: undefined, FooterBorder: undefined, FooterLabel: undefined, GapLine: undefined, Nth: undefined, Nomatch: undefined, } Light256 = &ColorTheme{ Colored: true, Input: defaultColor, Fg: defaultColor, Bg: defaultColor, ListFg: undefined, ListBg: undefined, AltBg: undefined, SelectedFg: undefined, SelectedBg: undefined, SelectedMatch: undefined, DarkBg: ColorAttr{251, AttrUndefined}, Prompt: ColorAttr{25, AttrUndefined}, Match: ColorAttr{66, AttrUndefined}, Current: ColorAttr{237, AttrUndefined}, CurrentMatch: ColorAttr{23, AttrUndefined}, Spinner: ColorAttr{65, AttrUndefined}, Info: ColorAttr{101, AttrUndefined}, Cursor: ColorAttr{161, AttrUndefined}, Marker: ColorAttr{168, AttrUndefined}, Header: ColorAttr{31, AttrUndefined}, Footer: ColorAttr{31, AttrUndefined}, Border: ColorAttr{145, AttrUndefined}, BorderLabel: ColorAttr{59, AttrUndefined}, Ghost: undefined, Disabled: undefined, PreviewFg: undefined, PreviewBg: undefined, Gutter: undefined, AltGutter: undefined, PreviewBorder: undefined, PreviewScrollbar: undefined, PreviewLabel: undefined, ListLabel: undefined, ListBorder: undefined, Separator: undefined, Scrollbar: undefined, InputBg: undefined, InputBorder: undefined, InputLabel: undefined, HeaderBg: undefined, HeaderBorder: undefined, HeaderLabel: undefined, FooterBg: undefined, FooterBorder: undefined, FooterLabel: undefined, GapLine: undefined, Nth: undefined, Nomatch: undefined, } } func InitTheme(theme *ColorTheme, baseTheme *ColorTheme, boldify bool, forceBlack bool, hasInputWindow bool, hasHeaderWindow bool) { if forceBlack { theme.Bg = ColorAttr{colBlack, AttrUndefined} } if boldify { boldify := func(c ColorAttr) ColorAttr { dup := c if (c.Attr & AttrRegular) == 0 { dup.Attr |= BoldForce } return dup } theme.Current = boldify(theme.Current) theme.CurrentMatch = boldify(theme.CurrentMatch) theme.Prompt = boldify(theme.Prompt) theme.Input = boldify(theme.Input) theme.Cursor = boldify(theme.Cursor) theme.Spinner = boldify(theme.Spinner) } o := func(a ColorAttr, b ColorAttr) ColorAttr { c := a if b.Color != colUndefined { c.Color = b.Color } if b.Attr != AttrUndefined { c.Attr = b.Attr } return c } theme.Input = o(baseTheme.Input, theme.Input) theme.Fg = o(baseTheme.Fg, theme.Fg) theme.Bg = o(baseTheme.Bg, theme.Bg) theme.DarkBg = o(baseTheme.DarkBg, theme.DarkBg) theme.Prompt = o(baseTheme.Prompt, theme.Prompt) match := theme.Match if !baseTheme.Colored && match.IsUndefined() { match.Attr = Underline } theme.Match = o(baseTheme.Match, match) // Inherit from 'fg', so that we don't have to write 'current-fg:dim' // e.g. fzf --delimiter / --nth -1 --color fg:dim,nth:regular current := theme.Current if !baseTheme.Colored && current.IsUndefined() { current.Attr |= Reverse } theme.Current = theme.Fg.Merge(o(baseTheme.Current, current)) currentMatch := theme.CurrentMatch if !baseTheme.Colored && currentMatch.IsUndefined() { currentMatch.Attr |= Reverse | Underline } theme.CurrentMatch = o(baseTheme.CurrentMatch, currentMatch) theme.Spinner = o(baseTheme.Spinner, theme.Spinner) theme.Info = o(baseTheme.Info, theme.Info) theme.Cursor = o(baseTheme.Cursor, theme.Cursor) theme.Marker = o(baseTheme.Marker, theme.Marker) theme.Header = o(baseTheme.Header, theme.Header) theme.Footer = o(baseTheme.Footer, theme.Footer) // If border color is undefined, set it to default color with dim attribute. border := theme.Border if baseTheme.Border.IsUndefined() && border.IsUndefined() { border.Attr = Dim } theme.Border = o(baseTheme.Border, border) theme.BorderLabel = o(baseTheme.BorderLabel, theme.BorderLabel) undefined := NewColorAttr() scrollbarDefined := theme.Scrollbar != undefined previewBorderDefined := theme.PreviewBorder != undefined // These colors are not defined in the base themes theme.ListFg = o(theme.Fg, theme.ListFg) theme.ListBg = o(theme.Bg, theme.ListBg) theme.SelectedFg = o(theme.ListFg, theme.SelectedFg) theme.SelectedBg = o(theme.ListBg, theme.SelectedBg) theme.SelectedMatch = o(theme.Match, theme.SelectedMatch) ghost := theme.Ghost if ghost.IsUndefined() { ghost.Attr = Dim } else if ghost.IsColorDefined() && !ghost.IsAttrDefined() { // Don't want to inherit 'bold' from 'input' ghost.Attr = AttrRegular } theme.Ghost = o(theme.Input, ghost) theme.Disabled = o(theme.Input, theme.Disabled) // Use dim gutter on non-colored themes if undefined gutter := theme.Gutter if !baseTheme.Colored && gutter.IsUndefined() { gutter.Attr = Dim } theme.Gutter = o(theme.DarkBg, gutter) theme.AltGutter = o(theme.Gutter, theme.AltGutter) theme.PreviewFg = o(theme.Fg, theme.PreviewFg) theme.PreviewBg = o(theme.Bg, theme.PreviewBg) theme.PreviewLabel = o(theme.BorderLabel, theme.PreviewLabel) theme.PreviewBorder = o(theme.Border, theme.PreviewBorder) theme.ListLabel = o(theme.BorderLabel, theme.ListLabel) theme.ListBorder = o(theme.Border, theme.ListBorder) theme.Separator = o(theme.ListBorder, theme.Separator) theme.Scrollbar = o(theme.ListBorder, theme.Scrollbar) theme.GapLine = o(theme.ListBorder, theme.GapLine) /* --color list-border:green --color scrollbar:red --color scrollbar:red,list-border:green --color scrollbar:red,preview-border:green */ if scrollbarDefined && !previewBorderDefined { theme.PreviewScrollbar = o(theme.Scrollbar, theme.PreviewScrollbar) } else { theme.PreviewScrollbar = o(theme.PreviewBorder, theme.PreviewScrollbar) } if hasInputWindow { theme.InputBg = o(theme.Bg, theme.InputBg) } else { // We shouldn't use input-bg if there's no separate input window // e.g. fzf --color 'list-bg:green,input-bg:red' --no-input-border theme.InputBg = o(theme.Bg, theme.ListBg) } theme.InputBorder = o(theme.Border, theme.InputBorder) theme.InputLabel = o(theme.BorderLabel, theme.InputLabel) if hasHeaderWindow { theme.HeaderBg = o(theme.Bg, theme.HeaderBg) } else { theme.HeaderBg = o(theme.Bg, theme.ListBg) } theme.HeaderBorder = o(theme.Border, theme.HeaderBorder) theme.HeaderLabel = o(theme.BorderLabel, theme.HeaderLabel) theme.FooterBg = o(theme.Bg, theme.FooterBg) theme.FooterBorder = o(theme.Border, theme.FooterBorder) theme.FooterLabel = o(theme.BorderLabel, theme.FooterLabel) if theme.Nomatch.IsUndefined() { theme.Nomatch.Attr = Dim } initPalette(theme) } func initPalette(theme *ColorTheme) { pair := func(fg, bg ColorAttr) ColorPair { if fg.Color == colDefault && (fg.Attr&Reverse) > 0 { bg.Color = colDefault } return ColorPair{fg.Color, bg.Color, fg.Attr} } blank := theme.ListFg blank.Attr = AttrRegular ColPrompt = pair(theme.Prompt, theme.InputBg) ColNormal = pair(theme.ListFg, theme.ListBg) ColSelected = pair(theme.SelectedFg, theme.SelectedBg) ColInput = pair(theme.Input, theme.InputBg) ColGhost = pair(theme.Ghost, theme.InputBg) ColDisabled = pair(theme.Disabled, theme.InputBg) ColMatch = pair(theme.Match, theme.ListBg) ColSelectedMatch = pair(theme.SelectedMatch, theme.SelectedBg) ColCursor = pair(theme.Cursor, theme.Gutter) ColCursorEmpty = pair(blank, theme.Gutter) ColCursorEmptyChar = pair(theme.Gutter, theme.ListBg) ColAltCursorEmpty = pair(blank, theme.AltGutter) ColAltCursorEmptyChar = pair(theme.AltGutter, theme.ListBg) if theme.SelectedBg.Color != theme.ListBg.Color { ColMarker = pair(theme.Marker, theme.SelectedBg) } else { ColMarker = pair(theme.Marker, theme.ListBg) } ColCurrent = pair(theme.Current, theme.DarkBg) ColCurrentMatch = pair(theme.CurrentMatch, theme.DarkBg) ColCurrentCursor = pair(theme.Cursor, theme.DarkBg) ColCurrentCursorEmpty = pair(blank, theme.DarkBg) ColCurrentMarker = pair(theme.Marker, theme.DarkBg) ColCurrentSelectedEmpty = pair(blank, theme.DarkBg) ColSpinner = pair(theme.Spinner, theme.InputBg) ColInfo = pair(theme.Info, theme.InputBg) ColSeparator = pair(theme.Separator, theme.InputBg) ColScrollbar = pair(theme.Scrollbar, theme.ListBg) ColGapLine = pair(theme.GapLine, theme.ListBg) ColBorder = pair(theme.Border, theme.Bg) ColBorderLabel = pair(theme.BorderLabel, theme.Bg) ColPreviewLabel = pair(theme.PreviewLabel, theme.PreviewBg) ColPreview = pair(theme.PreviewFg, theme.PreviewBg) ColPreviewBorder = pair(theme.PreviewBorder, theme.PreviewBg) ColPreviewScrollbar = pair(theme.PreviewScrollbar, theme.PreviewBg) ColPreviewSpinner = pair(theme.Spinner, theme.PreviewBg) ColListLabel = pair(theme.ListLabel, theme.ListBg) ColListBorder = pair(theme.ListBorder, theme.ListBg) ColInputBorder = pair(theme.InputBorder, theme.InputBg) ColInputLabel = pair(theme.InputLabel, theme.InputBg) ColHeader = pair(theme.Header, theme.HeaderBg) ColHeaderBorder = pair(theme.HeaderBorder, theme.HeaderBg) ColHeaderLabel = pair(theme.HeaderLabel, theme.HeaderBg) ColFooter = pair(theme.Footer, theme.FooterBg) ColFooterBorder = pair(theme.FooterBorder, theme.FooterBg) ColFooterLabel = pair(theme.FooterLabel, theme.FooterBg) } func runeWidth(r rune) int { return uniseg.StringWidth(string(r)) }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/eventtype_string.go
src/tui/eventtype_string.go
// Code generated by "stringer -type=EventType"; DO NOT EDIT. package tui import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[Rune-0] _ = x[CtrlA-1] _ = x[CtrlB-2] _ = x[CtrlC-3] _ = x[CtrlD-4] _ = x[CtrlE-5] _ = x[CtrlF-6] _ = x[CtrlG-7] _ = x[CtrlH-8] _ = x[Tab-9] _ = x[CtrlJ-10] _ = x[CtrlK-11] _ = x[CtrlL-12] _ = x[Enter-13] _ = x[CtrlN-14] _ = x[CtrlO-15] _ = x[CtrlP-16] _ = x[CtrlQ-17] _ = x[CtrlR-18] _ = x[CtrlS-19] _ = x[CtrlT-20] _ = x[CtrlU-21] _ = x[CtrlV-22] _ = x[CtrlW-23] _ = x[CtrlX-24] _ = x[CtrlY-25] _ = x[CtrlZ-26] _ = x[Esc-27] _ = x[CtrlSpace-28] _ = x[CtrlBackSlash-29] _ = x[CtrlRightBracket-30] _ = x[CtrlCaret-31] _ = x[CtrlSlash-32] _ = x[ShiftTab-33] _ = x[Backspace-34] _ = x[Delete-35] _ = x[PageUp-36] _ = x[PageDown-37] _ = x[Up-38] _ = x[Down-39] _ = x[Left-40] _ = x[Right-41] _ = x[Home-42] _ = x[End-43] _ = x[Insert-44] _ = x[ShiftUp-45] _ = x[ShiftDown-46] _ = x[ShiftLeft-47] _ = x[ShiftRight-48] _ = x[ShiftDelete-49] _ = x[ShiftHome-50] _ = x[ShiftEnd-51] _ = x[ShiftPageUp-52] _ = x[ShiftPageDown-53] _ = x[F1-54] _ = x[F2-55] _ = x[F3-56] _ = x[F4-57] _ = x[F5-58] _ = x[F6-59] _ = x[F7-60] _ = x[F8-61] _ = x[F9-62] _ = x[F10-63] _ = x[F11-64] _ = x[F12-65] _ = x[AltBackspace-66] _ = x[AltUp-67] _ = x[AltDown-68] _ = x[AltLeft-69] _ = x[AltRight-70] _ = x[AltDelete-71] _ = x[AltHome-72] _ = x[AltEnd-73] _ = x[AltPageUp-74] _ = x[AltPageDown-75] _ = x[AltShiftUp-76] _ = x[AltShiftDown-77] _ = x[AltShiftLeft-78] _ = x[AltShiftRight-79] _ = x[AltShiftDelete-80] _ = x[AltShiftHome-81] _ = x[AltShiftEnd-82] _ = x[AltShiftPageUp-83] _ = x[AltShiftPageDown-84] _ = x[CtrlUp-85] _ = x[CtrlDown-86] _ = x[CtrlLeft-87] _ = x[CtrlRight-88] _ = x[CtrlHome-89] _ = x[CtrlEnd-90] _ = x[CtrlBackspace-91] _ = x[CtrlDelete-92] _ = x[CtrlPageUp-93] _ = x[CtrlPageDown-94] _ = x[Alt-95] _ = x[CtrlAlt-96] _ = x[CtrlAltUp-97] _ = x[CtrlAltDown-98] _ = x[CtrlAltLeft-99] _ = x[CtrlAltRight-100] _ = x[CtrlAltHome-101] _ = x[CtrlAltEnd-102] _ = x[CtrlAltBackspace-103] _ = x[CtrlAltDelete-104] _ = x[CtrlAltPageUp-105] _ = x[CtrlAltPageDown-106] _ = x[CtrlShiftUp-107] _ = x[CtrlShiftDown-108] _ = x[CtrlShiftLeft-109] _ = x[CtrlShiftRight-110] _ = x[CtrlShiftHome-111] _ = x[CtrlShiftEnd-112] _ = x[CtrlShiftDelete-113] _ = x[CtrlShiftPageUp-114] _ = x[CtrlShiftPageDown-115] _ = x[CtrlAltShiftUp-116] _ = x[CtrlAltShiftDown-117] _ = x[CtrlAltShiftLeft-118] _ = x[CtrlAltShiftRight-119] _ = x[CtrlAltShiftHome-120] _ = x[CtrlAltShiftEnd-121] _ = x[CtrlAltShiftDelete-122] _ = x[CtrlAltShiftPageUp-123] _ = x[CtrlAltShiftPageDown-124] _ = x[Invalid-125] _ = x[Fatal-126] _ = x[BracketedPasteBegin-127] _ = x[BracketedPasteEnd-128] _ = x[Mouse-129] _ = x[DoubleClick-130] _ = x[LeftClick-131] _ = x[RightClick-132] _ = x[SLeftClick-133] _ = x[SRightClick-134] _ = x[ScrollUp-135] _ = x[ScrollDown-136] _ = x[SScrollUp-137] _ = x[SScrollDown-138] _ = x[PreviewScrollUp-139] _ = x[PreviewScrollDown-140] _ = x[Resize-141] _ = x[Change-142] _ = x[BackwardEOF-143] _ = x[Start-144] _ = x[Load-145] _ = x[Focus-146] _ = x[One-147] _ = x[Zero-148] _ = x[Result-149] _ = x[Jump-150] _ = x[JumpCancel-151] _ = x[ClickHeader-152] _ = x[ClickFooter-153] _ = x[Multi-154] } const _EventType_name = "RuneCtrlACtrlBCtrlCCtrlDCtrlECtrlFCtrlGCtrlHTabCtrlJCtrlKCtrlLEnterCtrlNCtrlOCtrlPCtrlQCtrlRCtrlSCtrlTCtrlUCtrlVCtrlWCtrlXCtrlYCtrlZEscCtrlSpaceCtrlBackSlashCtrlRightBracketCtrlCaretCtrlSlashShiftTabBackspaceDeletePageUpPageDownUpDownLeftRightHomeEndInsertShiftUpShiftDownShiftLeftShiftRightShiftDeleteShiftHomeShiftEndShiftPageUpShiftPageDownF1F2F3F4F5F6F7F8F9F10F11F12AltBackspaceAltUpAltDownAltLeftAltRightAltDeleteAltHomeAltEndAltPageUpAltPageDownAltShiftUpAltShiftDownAltShiftLeftAltShiftRightAltShiftDeleteAltShiftHomeAltShiftEndAltShiftPageUpAltShiftPageDownCtrlUpCtrlDownCtrlLeftCtrlRightCtrlHomeCtrlEndCtrlBackspaceCtrlDeleteCtrlPageUpCtrlPageDownAltCtrlAltCtrlAltUpCtrlAltDownCtrlAltLeftCtrlAltRightCtrlAltHomeCtrlAltEndCtrlAltBackspaceCtrlAltDeleteCtrlAltPageUpCtrlAltPageDownCtrlShiftUpCtrlShiftDownCtrlShiftLeftCtrlShiftRightCtrlShiftHomeCtrlShiftEndCtrlShiftDeleteCtrlShiftPageUpCtrlShiftPageDownCtrlAltShiftUpCtrlAltShiftDownCtrlAltShiftLeftCtrlAltShiftRightCtrlAltShiftHomeCtrlAltShiftEndCtrlAltShiftDeleteCtrlAltShiftPageUpCtrlAltShiftPageDownInvalidFatalBracketedPasteBeginBracketedPasteEndMouseDoubleClickLeftClickRightClickSLeftClickSRightClickScrollUpScrollDownSScrollUpSScrollDownPreviewScrollUpPreviewScrollDownResizeChangeBackwardEOFStartLoadFocusOneZeroResultJumpJumpCancelClickHeaderClickFooterMulti" var _EventType_index = [...]uint16{0, 4, 9, 14, 19, 24, 29, 34, 39, 44, 47, 52, 57, 62, 67, 72, 77, 82, 87, 92, 97, 102, 107, 112, 117, 122, 127, 132, 135, 144, 157, 173, 182, 191, 199, 208, 214, 220, 228, 230, 234, 238, 243, 247, 250, 256, 263, 272, 281, 291, 302, 311, 319, 330, 343, 345, 347, 349, 351, 353, 355, 357, 359, 361, 364, 367, 370, 382, 387, 394, 401, 409, 418, 425, 431, 440, 451, 461, 473, 485, 498, 512, 524, 535, 549, 565, 571, 579, 587, 596, 604, 611, 624, 634, 644, 656, 659, 666, 675, 686, 697, 709, 720, 730, 746, 759, 772, 787, 798, 811, 824, 838, 851, 863, 878, 893, 910, 924, 940, 956, 973, 989, 1004, 1022, 1040, 1060, 1067, 1072, 1091, 1108, 1113, 1124, 1133, 1143, 1153, 1164, 1172, 1182, 1191, 1202, 1217, 1234, 1240, 1246, 1257, 1262, 1266, 1271, 1274, 1278, 1284, 1288, 1298, 1309, 1320, 1325} func (i EventType) String() string { if i < 0 || i >= EventType(len(_EventType_index)-1) { return "EventType(" + strconv.FormatInt(int64(i), 10) + ")" } return _EventType_name[_EventType_index[i]:_EventType_index[i+1]] }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/light_test.go
src/tui/light_test.go
package tui import ( "fmt" "os" "testing" "unicode" ) func TestLightRenderer(t *testing.T) { tty_file, _ := os.Open("") renderer, _ := NewLightRenderer( "", tty_file, &ColorTheme{}, true, false, 0, false, true, func(h int) int { return h }) light_renderer := renderer.(*LightRenderer) assertCharSequence := func(sequence string, name string) { bytes := []byte(sequence) light_renderer.buffer = bytes event := light_renderer.GetChar() if event.KeyName() != name { t.Errorf( "sequence: %q | %v | '%s' (%s) != %s", string(bytes), bytes, event.KeyName(), event.Type.String(), name) } } assertEscSequence := func(sequence string, name string) { bytes := []byte(sequence) light_renderer.buffer = bytes sz := 1 event := light_renderer.escSequence(&sz) if fmt.Sprintf("!%s", event.Type.String()) == name { // this is fine } else if event.KeyName() != name { t.Errorf( "sequence: %q | %v | '%s' (%s) != %s", string(bytes), bytes, event.KeyName(), event.Type.String(), name) } } // invalid assertEscSequence("\x1b[<", "!Invalid") assertEscSequence("\x1b[1;1R", "!Invalid") assertEscSequence("\x1b[", "!Invalid") assertEscSequence("\x1b[1", "!Invalid") assertEscSequence("\x1b[3;3~1", "!Invalid") assertEscSequence("\x1b[13", "!Invalid") assertEscSequence("\x1b[1;3", "!Invalid") assertEscSequence("\x1b[1;10", "!Invalid") assertEscSequence("\x1b[220~", "!Invalid") assertEscSequence("\x1b[5;30~", "!Invalid") assertEscSequence("\x1b[6;30~", "!Invalid") // general for r := 'a'; r < 'z'; r++ { lower_r := fmt.Sprintf("%c", r) upper_r := fmt.Sprintf("%c", unicode.ToUpper(r)) assertCharSequence(lower_r, lower_r) assertCharSequence(upper_r, upper_r) } assertCharSequence("\x01", "ctrl-a") assertCharSequence("\x02", "ctrl-b") assertCharSequence("\x03", "ctrl-c") assertCharSequence("\x04", "ctrl-d") assertCharSequence("\x05", "ctrl-e") assertCharSequence("\x06", "ctrl-f") assertCharSequence("\x07", "ctrl-g") // ctrl-h is the same as ctrl-backspace // ctrl-i is the same as tab assertCharSequence("\n", "ctrl-j") assertCharSequence("\x0b", "ctrl-k") assertCharSequence("\x0c", "ctrl-l") assertCharSequence("\r", "enter") // enter assertCharSequence("\x0e", "ctrl-n") assertCharSequence("\x0f", "ctrl-o") assertCharSequence("\x10", "ctrl-p") assertCharSequence("\x11", "ctrl-q") assertCharSequence("\x12", "ctrl-r") assertCharSequence("\x13", "ctrl-s") assertCharSequence("\x14", "ctrl-t") assertCharSequence("\x15", "ctrl-u") assertCharSequence("\x16", "ctrl-v") assertCharSequence("\x17", "ctrl-w") assertCharSequence("\x18", "ctrl-x") assertCharSequence("\x19", "ctrl-y") assertCharSequence("\x1a", "ctrl-z") assertCharSequence("\x00", "ctrl-space") assertCharSequence("\x1c", "ctrl-\\") assertCharSequence("\x1d", "ctrl-]") assertCharSequence("\x1e", "ctrl-^") assertCharSequence("\x1f", "ctrl-/") assertEscSequence("\x1ba", "alt-a") assertEscSequence("\x1bb", "alt-b") assertEscSequence("\x1bc", "alt-c") assertEscSequence("\x1bd", "alt-d") assertEscSequence("\x1be", "alt-e") assertEscSequence("\x1bf", "alt-f") assertEscSequence("\x1bg", "alt-g") assertEscSequence("\x1bh", "alt-h") assertEscSequence("\x1bi", "alt-i") assertEscSequence("\x1bj", "alt-j") assertEscSequence("\x1bk", "alt-k") assertEscSequence("\x1bl", "alt-l") assertEscSequence("\x1bm", "alt-m") assertEscSequence("\x1bn", "alt-n") assertEscSequence("\x1bo", "alt-o") assertEscSequence("\x1bp", "alt-p") assertEscSequence("\x1bq", "alt-q") assertEscSequence("\x1br", "alt-r") assertEscSequence("\x1bs", "alt-s") assertEscSequence("\x1bt", "alt-t") assertEscSequence("\x1bu", "alt-u") assertEscSequence("\x1bv", "alt-v") assertEscSequence("\x1bw", "alt-w") assertEscSequence("\x1bx", "alt-x") assertEscSequence("\x1by", "alt-y") assertEscSequence("\x1bz", "alt-z") assertEscSequence("\x1bOP", "f1") assertEscSequence("\x1bOQ", "f2") assertEscSequence("\x1bOR", "f3") assertEscSequence("\x1bOS", "f4") assertEscSequence("\x1b[15~", "f5") assertEscSequence("\x1b[17~", "f6") assertEscSequence("\x1b[18~", "f7") assertEscSequence("\x1b[19~", "f8") assertEscSequence("\x1b[20~", "f9") assertEscSequence("\x1b[21~", "f10") assertEscSequence("\x1b[23~", "f11") assertEscSequence("\x1b[24~", "f12") assertEscSequence("\x1b", "esc") assertCharSequence("\t", "tab") assertEscSequence("\x1b[Z", "shift-tab") assertCharSequence("\x7f", "backspace") assertEscSequence("\x1b\x7f", "alt-backspace") assertCharSequence("\b", "ctrl-backspace") assertEscSequence("\x1b\b", "ctrl-alt-backspace") assertEscSequence("\x1b[A", "up") assertEscSequence("\x1b[B", "down") assertEscSequence("\x1b[C", "right") assertEscSequence("\x1b[D", "left") assertEscSequence("\x1b[H", "home") assertEscSequence("\x1b[F", "end") assertEscSequence("\x1b[2~", "insert") assertEscSequence("\x1b[3~", "delete") assertEscSequence("\x1b[5~", "page-up") assertEscSequence("\x1b[6~", "page-down") assertEscSequence("\x1b[7~", "home") assertEscSequence("\x1b[8~", "end") assertEscSequence("\x1b[1;2A", "shift-up") assertEscSequence("\x1b[1;2B", "shift-down") assertEscSequence("\x1b[1;2C", "shift-right") assertEscSequence("\x1b[1;2D", "shift-left") assertEscSequence("\x1b[1;2H", "shift-home") assertEscSequence("\x1b[1;2F", "shift-end") assertEscSequence("\x1b[3;2~", "shift-delete") assertEscSequence("\x1b[5;2~", "shift-page-up") assertEscSequence("\x1b[6;2~", "shift-page-down") assertEscSequence("\x1b\x1b", "esc") assertEscSequence("\x1b\x1b[A", "alt-up") assertEscSequence("\x1b\x1b[B", "alt-down") assertEscSequence("\x1b\x1b[C", "alt-right") assertEscSequence("\x1b\x1b[D", "alt-left") assertEscSequence("\x1b[1;3A", "alt-up") assertEscSequence("\x1b[1;3B", "alt-down") assertEscSequence("\x1b[1;3C", "alt-right") assertEscSequence("\x1b[1;3D", "alt-left") assertEscSequence("\x1b[1;3H", "alt-home") assertEscSequence("\x1b[1;3F", "alt-end") assertEscSequence("\x1b[3;3~", "alt-delete") assertEscSequence("\x1b[5;3~", "alt-page-up") assertEscSequence("\x1b[6;3~", "alt-page-down") assertEscSequence("\x1b[1;4A", "alt-shift-up") assertEscSequence("\x1b[1;4B", "alt-shift-down") assertEscSequence("\x1b[1;4C", "alt-shift-right") assertEscSequence("\x1b[1;4D", "alt-shift-left") assertEscSequence("\x1b[1;4H", "alt-shift-home") assertEscSequence("\x1b[1;4F", "alt-shift-end") assertEscSequence("\x1b[3;4~", "alt-shift-delete") assertEscSequence("\x1b[5;4~", "alt-shift-page-up") assertEscSequence("\x1b[6;4~", "alt-shift-page-down") assertEscSequence("\x1b[1;5A", "ctrl-up") assertEscSequence("\x1b[1;5B", "ctrl-down") assertEscSequence("\x1b[1;5C", "ctrl-right") assertEscSequence("\x1b[1;5D", "ctrl-left") assertEscSequence("\x1b[1;5H", "ctrl-home") assertEscSequence("\x1b[1;5F", "ctrl-end") assertEscSequence("\x1b[3;5~", "ctrl-delete") assertEscSequence("\x1b[5;5~", "ctrl-page-up") assertEscSequence("\x1b[6;5~", "ctrl-page-down") assertEscSequence("\x1b[1;7A", "ctrl-alt-up") assertEscSequence("\x1b[1;7B", "ctrl-alt-down") assertEscSequence("\x1b[1;7C", "ctrl-alt-right") assertEscSequence("\x1b[1;7D", "ctrl-alt-left") assertEscSequence("\x1b[1;7H", "ctrl-alt-home") assertEscSequence("\x1b[1;7F", "ctrl-alt-end") assertEscSequence("\x1b[3;7~", "ctrl-alt-delete") assertEscSequence("\x1b[5;7~", "ctrl-alt-page-up") assertEscSequence("\x1b[6;7~", "ctrl-alt-page-down") assertEscSequence("\x1b[1;6A", "ctrl-shift-up") assertEscSequence("\x1b[1;6B", "ctrl-shift-down") assertEscSequence("\x1b[1;6C", "ctrl-shift-right") assertEscSequence("\x1b[1;6D", "ctrl-shift-left") assertEscSequence("\x1b[1;6H", "ctrl-shift-home") assertEscSequence("\x1b[1;6F", "ctrl-shift-end") assertEscSequence("\x1b[3;6~", "ctrl-shift-delete") assertEscSequence("\x1b[5;6~", "ctrl-shift-page-up") assertEscSequence("\x1b[6;6~", "ctrl-shift-page-down") assertEscSequence("\x1b[1;8A", "ctrl-alt-shift-up") assertEscSequence("\x1b[1;8B", "ctrl-alt-shift-down") assertEscSequence("\x1b[1;8C", "ctrl-alt-shift-right") assertEscSequence("\x1b[1;8D", "ctrl-alt-shift-left") assertEscSequence("\x1b[1;8H", "ctrl-alt-shift-home") assertEscSequence("\x1b[1;8F", "ctrl-alt-shift-end") assertEscSequence("\x1b[3;8~", "ctrl-alt-shift-delete") assertEscSequence("\x1b[5;8~", "ctrl-alt-shift-page-up") assertEscSequence("\x1b[6;8~", "ctrl-alt-shift-page-down") // xterm meta & mac assertEscSequence("\x1b[1;9A", "alt-up") assertEscSequence("\x1b[1;9B", "alt-down") assertEscSequence("\x1b[1;9C", "alt-right") assertEscSequence("\x1b[1;9D", "alt-left") assertEscSequence("\x1b[1;9H", "alt-home") assertEscSequence("\x1b[1;9F", "alt-end") assertEscSequence("\x1b[3;9~", "alt-delete") assertEscSequence("\x1b[5;9~", "alt-page-up") assertEscSequence("\x1b[6;9~", "alt-page-down") assertEscSequence("\x1b[1;10A", "alt-shift-up") assertEscSequence("\x1b[1;10B", "alt-shift-down") assertEscSequence("\x1b[1;10C", "alt-shift-right") assertEscSequence("\x1b[1;10D", "alt-shift-left") assertEscSequence("\x1b[1;10H", "alt-shift-home") assertEscSequence("\x1b[1;10F", "alt-shift-end") assertEscSequence("\x1b[3;10~", "alt-shift-delete") assertEscSequence("\x1b[5;10~", "alt-shift-page-up") assertEscSequence("\x1b[6;10~", "alt-shift-page-down") assertEscSequence("\x1b[1;11A", "alt-up") assertEscSequence("\x1b[1;11B", "alt-down") assertEscSequence("\x1b[1;11C", "alt-right") assertEscSequence("\x1b[1;11D", "alt-left") assertEscSequence("\x1b[1;11H", "alt-home") assertEscSequence("\x1b[1;11F", "alt-end") assertEscSequence("\x1b[3;11~", "alt-delete") assertEscSequence("\x1b[5;11~", "alt-page-up") assertEscSequence("\x1b[6;11~", "alt-page-down") assertEscSequence("\x1b[1;12A", "alt-shift-up") assertEscSequence("\x1b[1;12B", "alt-shift-down") assertEscSequence("\x1b[1;12C", "alt-shift-right") assertEscSequence("\x1b[1;12D", "alt-shift-left") assertEscSequence("\x1b[1;12H", "alt-shift-home") assertEscSequence("\x1b[1;12F", "alt-shift-end") assertEscSequence("\x1b[3;12~", "alt-shift-delete") assertEscSequence("\x1b[5;12~", "alt-shift-page-up") assertEscSequence("\x1b[6;12~", "alt-shift-page-down") assertEscSequence("\x1b[1;13A", "ctrl-alt-up") assertEscSequence("\x1b[1;13B", "ctrl-alt-down") assertEscSequence("\x1b[1;13C", "ctrl-alt-right") assertEscSequence("\x1b[1;13D", "ctrl-alt-left") assertEscSequence("\x1b[1;13H", "ctrl-alt-home") assertEscSequence("\x1b[1;13F", "ctrl-alt-end") assertEscSequence("\x1b[3;13~", "ctrl-alt-delete") assertEscSequence("\x1b[5;13~", "ctrl-alt-page-up") assertEscSequence("\x1b[6;13~", "ctrl-alt-page-down") assertEscSequence("\x1b[1;14A", "ctrl-alt-shift-up") assertEscSequence("\x1b[1;14B", "ctrl-alt-shift-down") assertEscSequence("\x1b[1;14C", "ctrl-alt-shift-right") assertEscSequence("\x1b[1;14D", "ctrl-alt-shift-left") assertEscSequence("\x1b[1;14H", "ctrl-alt-shift-home") assertEscSequence("\x1b[1;14F", "ctrl-alt-shift-end") assertEscSequence("\x1b[3;14~", "ctrl-alt-shift-delete") assertEscSequence("\x1b[5;14~", "ctrl-alt-shift-page-up") assertEscSequence("\x1b[6;14~", "ctrl-alt-shift-page-down") assertEscSequence("\x1b[1;15A", "ctrl-alt-up") assertEscSequence("\x1b[1;15B", "ctrl-alt-down") assertEscSequence("\x1b[1;15C", "ctrl-alt-right") assertEscSequence("\x1b[1;15D", "ctrl-alt-left") assertEscSequence("\x1b[1;15H", "ctrl-alt-home") assertEscSequence("\x1b[1;15F", "ctrl-alt-end") assertEscSequence("\x1b[3;15~", "ctrl-alt-delete") assertEscSequence("\x1b[5;15~", "ctrl-alt-page-up") assertEscSequence("\x1b[6;15~", "ctrl-alt-page-down") assertEscSequence("\x1b[1;16A", "ctrl-alt-shift-up") assertEscSequence("\x1b[1;16B", "ctrl-alt-shift-down") assertEscSequence("\x1b[1;16C", "ctrl-alt-shift-right") assertEscSequence("\x1b[1;16D", "ctrl-alt-shift-left") assertEscSequence("\x1b[1;16H", "ctrl-alt-shift-home") assertEscSequence("\x1b[1;16F", "ctrl-alt-shift-end") assertEscSequence("\x1b[3;16~", "ctrl-alt-shift-delete") assertEscSequence("\x1b[5;16~", "ctrl-alt-shift-page-up") assertEscSequence("\x1b[6;16~", "ctrl-alt-shift-page-down") // tmux & emacs assertEscSequence("\x1bOA", "up") assertEscSequence("\x1bOB", "down") assertEscSequence("\x1bOC", "right") assertEscSequence("\x1bOD", "left") assertEscSequence("\x1bOH", "home") assertEscSequence("\x1bOF", "end") // rrvt assertEscSequence("\x1b[1~", "home") assertEscSequence("\x1b[4~", "end") assertEscSequence("\x1b[11~", "f1") assertEscSequence("\x1b[12~", "f2") assertEscSequence("\x1b[13~", "f3") assertEscSequence("\x1b[14~", "f4") }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/light_windows.go
src/tui/light_windows.go
//go:build windows package tui import ( "os" "syscall" "time" "github.com/junegunn/fzf/src/util" "golang.org/x/sys/windows" ) const ( timeoutInterval = 10 ) var ( consoleFlagsInput = uint32(windows.ENABLE_VIRTUAL_TERMINAL_INPUT | windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_EXTENDED_FLAGS) consoleFlagsOutput = uint32(windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING | windows.ENABLE_PROCESSED_OUTPUT | windows.DISABLE_NEWLINE_AUTO_RETURN) counter = uint64(0) ) // IsLightRendererSupported checks to see if the Light renderer is supported func IsLightRendererSupported() bool { var oldState uint32 // enable vt100 emulation (https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) if windows.GetConsoleMode(windows.Stderr, &oldState) != nil { return false } // attempt to set mode to determine if we support VT 100 codes. This will work on newer Windows 10 // version: canSetVt100 := windows.SetConsoleMode(windows.Stderr, oldState|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING) == nil var checkState uint32 if windows.GetConsoleMode(windows.Stderr, &checkState) != nil || (checkState&windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING) != windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING { return false } windows.SetConsoleMode(windows.Stderr, oldState) return canSetVt100 } func (r *LightRenderer) DefaultTheme() *ColorTheme { // the getenv check is borrowed from here: https://github.com/gdamore/tcell/commit/0c473b86d82f68226a142e96cc5a34c5a29b3690#diff-b008fcd5e6934bf31bc3d33bf49f47d8R178: if !IsLightRendererSupported() || os.Getenv("ConEmuPID") != "" || os.Getenv("TCELL_TRUECOLOR") == "disable" { return Default16 } return Dark256 } func (r *LightRenderer) initPlatform() error { //outHandle := windows.Stdout outHandle, _ := syscall.Open("CONOUT$", syscall.O_RDWR, 0) // enable vt100 emulation (https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) if err := windows.GetConsoleMode(windows.Handle(outHandle), &r.origStateOutput); err != nil { return err } r.outHandle = uintptr(outHandle) inHandle, _ := syscall.Open("CONIN$", syscall.O_RDWR, 0) if err := windows.GetConsoleMode(windows.Handle(inHandle), &r.origStateInput); err != nil { return err } r.inHandle = uintptr(inHandle) // channel for non-blocking reads. Buffer to make sure // we get the ESC sets: r.ttyinChannel = make(chan byte, 1024) r.setupTerminal() return nil } func (r *LightRenderer) closePlatform() { windows.SetConsoleMode(windows.Handle(r.outHandle), r.origStateOutput) windows.SetConsoleMode(windows.Handle(r.inHandle), r.origStateInput) } func openTtyIn(ttyDefault string) (*os.File, error) { // not used return nil, nil } func openTtyOut(ttyDefault string) (*os.File, error) { return os.Stderr, nil } func (r *LightRenderer) setupTerminal() { windows.SetConsoleMode(windows.Handle(r.outHandle), consoleFlagsOutput) windows.SetConsoleMode(windows.Handle(r.inHandle), consoleFlagsInput) // The following allows for non-blocking IO. // syscall.SetNonblock() is a NOOP under Windows. current := counter go func() { fd := int(r.inHandle) b := make([]byte, 1) for { if _, err := util.Read(fd, b); err == nil { r.mutex.Lock() // This condition prevents the goroutine from running after the renderer // has been closed or paused. if current != counter { r.mutex.Unlock() break } r.ttyinChannel <- b[0] // HACK: if run from PSReadline, something resets ConsoleMode to remove ENABLE_VIRTUAL_TERMINAL_INPUT. windows.SetConsoleMode(windows.Handle(r.inHandle), consoleFlagsInput) r.mutex.Unlock() } } }() } func (r *LightRenderer) restoreTerminal() { r.mutex.Lock() counter++ // We're setting ENABLE_VIRTUAL_TERMINAL_INPUT to allow escape sequences to be read during 'execute'. // e.g. fzf --bind 'enter:execute:less {}' windows.SetConsoleMode(windows.Handle(r.inHandle), r.origStateInput|windows.ENABLE_VIRTUAL_TERMINAL_INPUT) windows.SetConsoleMode(windows.Handle(r.outHandle), r.origStateOutput) r.mutex.Unlock() } func (r *LightRenderer) Size() TermSize { var w, h int var bufferInfo windows.ConsoleScreenBufferInfo if err := windows.GetConsoleScreenBufferInfo(windows.Handle(r.outHandle), &bufferInfo); err != nil { w = getEnv("COLUMNS", defaultWidth) h = r.maxHeightFunc(getEnv("LINES", defaultHeight)) } else { w = int(bufferInfo.Window.Right - bufferInfo.Window.Left) h = r.maxHeightFunc(int(bufferInfo.Window.Bottom - bufferInfo.Window.Top)) } return TermSize{h, w, 0, 0} } func (r *LightRenderer) updateTerminalSize() { size := r.Size() r.width = size.Columns r.height = size.Lines } func (r *LightRenderer) findOffset() (row int, col int) { var bufferInfo windows.ConsoleScreenBufferInfo if err := windows.GetConsoleScreenBufferInfo(windows.Handle(r.outHandle), &bufferInfo); err != nil { return -1, -1 } return int(bufferInfo.CursorPosition.Y), int(bufferInfo.CursorPosition.X) } func (r *LightRenderer) getch(nonblock bool) (int, bool) { if nonblock { select { case bc := <-r.ttyinChannel: return int(bc), true case <-time.After(timeoutInterval * time.Millisecond): return 0, false } } else { bc := <-r.ttyinChannel return int(bc), true } }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/ttyname_windows.go
src/tui/ttyname_windows.go
//go:build windows package tui import ( "os" ) func ttyname() string { return "" } // TtyIn on Windows returns os.Stdin func TtyIn(ttyDefault string) (*os.File, error) { return os.Stdin, nil } // TtyOut on Windows returns nil func TtyOut(ttyDefault string) (*os.File, error) { return nil, nil }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/tcell_test.go
src/tui/tcell_test.go
//go:build tcell || windows package tui import ( "os" "testing" "github.com/gdamore/tcell/v2" "github.com/junegunn/fzf/src/util" ) func assert(t *testing.T, context string, got any, want any) bool { if got == want { return true } else { t.Errorf("%s = (%T)%v, want (%T)%v", context, got, got, want, want) return false } } // Test the handling of the tcell keyboard events. func TestGetCharEventKey(t *testing.T) { if util.IsTty(os.Stdout) { // This test is skipped when output goes to terminal, because it causes // some glitches: // - output lines may not start at the beginning of a row which makes // the output unreadable // - terminal may get cleared which prevents you from seeing results of // previous tests // Good ways to prevent the glitches are piping the output to a pager // or redirecting to a file. I've found `less +G` to be trouble-free. t.Skip("Skipped because this test misbehaves in terminal, pipe to a pager or redirect output to a file to run it safely.") } else if testing.Verbose() { // I have observed a behaviour when this test outputted more than 8192 // bytes (32*256) into the 'less' pager, both the go's test executable // and the pager hanged. The go's executable was blocking on printing. // I was able to create minimal working example of that behaviour, but // that example hanged after 12256 bytes (32*(256+127)). t.Log("If you are piping this test to a pager and it hangs, make the pager greedy for input, e.g. 'less +G'.") } if !HasFullscreenRenderer() { t.Skip("Can't test FullscreenRenderer.") } // construct test cases type giveKey struct { Type tcell.Key Char rune Mods tcell.ModMask } type wantKey = Event type testCase struct { giveKey wantKey } /* Some test cases are marked "fabricated". It means that giveKey value is valid, but it is not what you get when you press the keys. For example Ctrl+C will NOT give you tcell.KeyCtrlC, but tcell.KeyETX (End-Of-Text character, causing SIGINT). I was trying to accompany the fabricated test cases with real ones. Some test cases are marked "unhandled". It means that giveKey.Type is not present in tcell.go source code. It can still be handled via implicit or explicit alias. If not said otherwise, test cases are for US keyboard. (tabstop=44) */ tests := []testCase{ // section 1: Ctrl+(Alt)+[a-z] {giveKey{tcell.KeyCtrlA, rune(tcell.KeyCtrlA), tcell.ModCtrl}, wantKey{CtrlA, 0, nil}}, {giveKey{tcell.KeyCtrlC, rune(tcell.KeyCtrlC), tcell.ModCtrl}, wantKey{CtrlC, 0, nil}}, // fabricated {giveKey{tcell.KeyETX, rune(tcell.KeyETX), tcell.ModCtrl}, wantKey{CtrlC, 0, nil}}, // this is SIGINT (Ctrl+C) {giveKey{tcell.KeyCtrlZ, rune(tcell.KeyCtrlZ), tcell.ModCtrl}, wantKey{CtrlZ, 0, nil}}, // fabricated // KeyTab is alias for KeyTAB {giveKey{tcell.KeyCtrlI, rune(tcell.KeyCtrlI), tcell.ModCtrl}, wantKey{Tab, 0, nil}}, // fabricated {giveKey{tcell.KeyTab, rune(tcell.KeyTab), tcell.ModNone}, wantKey{Tab, 0, nil}}, // unhandled, actual "Tab" keystroke {giveKey{tcell.KeyTAB, rune(tcell.KeyTAB), tcell.ModNone}, wantKey{Tab, 0, nil}}, // fabricated, unhandled // KeyEnter is alias for KeyCR {giveKey{tcell.KeyCtrlM, rune(tcell.KeyCtrlM), tcell.ModNone}, wantKey{Enter, 0, nil}}, // actual "Enter" keystroke {giveKey{tcell.KeyCR, rune(tcell.KeyCR), tcell.ModNone}, wantKey{Enter, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyEnter, rune(tcell.KeyEnter), tcell.ModNone}, wantKey{Enter, 0, nil}}, // fabricated, unhandled // Ctrl+Alt keys {giveKey{tcell.KeyCtrlA, rune(tcell.KeyCtrlA), tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAlt, 'a', nil}}, // fabricated {giveKey{tcell.KeyCtrlA, rune(tcell.KeyCtrlA), tcell.ModCtrl | tcell.ModAlt | tcell.ModShift}, wantKey{CtrlAlt, 'a', nil}}, // fabricated // section 2: Ctrl+[ \]_] {giveKey{tcell.KeyCtrlSpace, rune(tcell.KeyCtrlSpace), tcell.ModCtrl}, wantKey{CtrlSpace, 0, nil}}, // fabricated {giveKey{tcell.KeyNUL, rune(tcell.KeyNUL), tcell.ModNone}, wantKey{CtrlSpace, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyRune, ' ', tcell.ModCtrl}, wantKey{CtrlSpace, 0, nil}}, // actual Ctrl+' ' {giveKey{tcell.KeyCtrlBackslash, rune(tcell.KeyCtrlBackslash), tcell.ModCtrl}, wantKey{CtrlBackSlash, 0, nil}}, {giveKey{tcell.KeyCtrlRightSq, rune(tcell.KeyCtrlRightSq), tcell.ModCtrl}, wantKey{CtrlRightBracket, 0, nil}}, {giveKey{tcell.KeyCtrlCarat, rune(tcell.KeyCtrlCarat), tcell.ModShift | tcell.ModCtrl}, wantKey{CtrlCaret, 0, nil}}, // fabricated {giveKey{tcell.KeyRS, rune(tcell.KeyRS), tcell.ModShift | tcell.ModCtrl}, wantKey{CtrlCaret, 0, nil}}, // actual Ctrl+Shift+6 (i.e. Ctrl+^) keystroke {giveKey{tcell.KeyCtrlUnderscore, rune(tcell.KeyCtrlUnderscore), tcell.ModShift | tcell.ModCtrl}, wantKey{CtrlSlash, 0, nil}}, // section 3: (Alt)+Backspace2 // KeyBackspace2 is alias for KeyDEL = 0x7F (ASCII) (allegedly unused by Windows) // KeyDelete = 0x2E (VK_DELETE constant in Windows) // KeyBackspace is alias for KeyBS = 0x08 (ASCII) (implicit alias with KeyCtrlH) {giveKey{tcell.KeyBackspace2, 0, tcell.ModNone}, wantKey{Backspace, 0, nil}}, // fabricated {giveKey{tcell.KeyBackspace2, 0, tcell.ModAlt}, wantKey{AltBackspace, 0, nil}}, // fabricated {giveKey{tcell.KeyDEL, 0, tcell.ModNone}, wantKey{Backspace, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyDelete, 0, tcell.ModNone}, wantKey{Delete, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModAlt}, wantKey{AltDelete, 0, nil}}, {giveKey{tcell.KeyBackspace, 0, tcell.ModCtrl}, wantKey{CtrlBackspace, 0, nil}}, {giveKey{tcell.KeyBackspace, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltBackspace, 0, nil}}, {giveKey{tcell.KeyBackspace, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyBS, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyCtrlH, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyCtrlH, rune(tcell.KeyCtrlH), tcell.ModNone}, wantKey{Backspace, 0, nil}}, // actual "Backspace" keystroke {giveKey{tcell.KeyCtrlH, rune(tcell.KeyCtrlH), tcell.ModAlt}, wantKey{AltBackspace, 0, nil}}, // actual "Alt+Backspace" keystroke {giveKey{tcell.KeyDEL, rune(tcell.KeyDEL), tcell.ModCtrl}, wantKey{CtrlBackspace, 0, nil}}, // actual "Ctrl+Backspace" keystroke {giveKey{tcell.KeyCtrlH, rune(tcell.KeyCtrlH), tcell.ModShift}, wantKey{Backspace, 0, nil}}, // actual "Shift+Backspace" keystroke {giveKey{tcell.KeyCtrlH, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltBackspace, 0, nil}}, // actual "Ctrl+Alt+Backspace" keystroke {giveKey{tcell.KeyCtrlH, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlBackspace, 0, nil}}, // actual "Ctrl+Shift+Backspace" keystroke {giveKey{tcell.KeyCtrlH, rune(tcell.KeyCtrlH), tcell.ModShift | tcell.ModAlt}, wantKey{AltBackspace, 0, nil}}, // actual "Shift+Alt+Backspace" keystroke {giveKey{tcell.KeyCtrlH, 0, tcell.ModCtrl | tcell.ModAlt | tcell.ModShift}, wantKey{CtrlAltBackspace, 0, nil}}, // actual "Ctrl+Shift+Alt+Backspace" keystroke {giveKey{tcell.KeyCtrlH, rune(tcell.KeyCtrlH), tcell.ModCtrl}, wantKey{CtrlH, 0, nil}}, // actual "Ctrl+H" keystroke {giveKey{tcell.KeyCtrlH, rune(tcell.KeyCtrlH), tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAlt, 'h', nil}}, // fabricated "Ctrl+Alt+H" keystroke {giveKey{tcell.KeyCtrlH, rune(tcell.KeyCtrlH), tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlH, 0, nil}}, // actual "Ctrl+Shift+H" keystroke {giveKey{tcell.KeyCtrlH, rune(tcell.KeyCtrlH), tcell.ModCtrl | tcell.ModAlt | tcell.ModShift}, wantKey{CtrlAlt, 'h', nil}}, // fabricated "Ctrl+Shift+Alt+H" keystroke // section 4: (Alt+Shift)+Key(Up|Down|Left|Right) {giveKey{tcell.KeyUp, 0, tcell.ModNone}, wantKey{Up, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModNone}, wantKey{Down, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModNone}, wantKey{Left, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModNone}, wantKey{Right, 0, nil}}, {giveKey{tcell.KeyUp, 0, tcell.ModNone}, wantKey{Up, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModNone}, wantKey{Down, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModNone}, wantKey{Right, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModNone}, wantKey{Left, 0, nil}}, {giveKey{tcell.KeyUp, 0, tcell.ModCtrl}, wantKey{CtrlUp, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModCtrl}, wantKey{CtrlDown, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModCtrl}, wantKey{CtrlRight, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModCtrl}, wantKey{CtrlLeft, 0, nil}}, {giveKey{tcell.KeyUp, 0, tcell.ModShift}, wantKey{ShiftUp, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModShift}, wantKey{ShiftDown, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModShift}, wantKey{ShiftRight, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModShift}, wantKey{ShiftLeft, 0, nil}}, {giveKey{tcell.KeyUp, 0, tcell.ModAlt}, wantKey{AltUp, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModAlt}, wantKey{AltDown, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModAlt}, wantKey{AltRight, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModAlt}, wantKey{AltLeft, 0, nil}}, {giveKey{tcell.KeyUp, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftUp, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftDown, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftRight, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftLeft, 0, nil}}, {giveKey{tcell.KeyUp, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltUp, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltDown, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltRight, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltLeft, 0, nil}}, {giveKey{tcell.KeyUp, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftUp, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftDown, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftRight, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftLeft, 0, nil}}, {giveKey{tcell.KeyUp, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftUp, 0, nil}}, {giveKey{tcell.KeyDown, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftDown, 0, nil}}, {giveKey{tcell.KeyRight, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftRight, 0, nil}}, {giveKey{tcell.KeyLeft, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftLeft, 0, nil}}, {giveKey{tcell.KeyUpLeft, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyUpRight, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyDownLeft, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyDownRight, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyCenter, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled // section 5: (Insert|Home|Delete|End|PgUp|PgDn|BackTab|F1-F12) {giveKey{tcell.KeyInsert, 0, tcell.ModNone}, wantKey{Insert, 0, nil}}, {giveKey{tcell.KeyF1, 0, tcell.ModNone}, wantKey{F1, 0, nil}}, {giveKey{tcell.KeyHome, 0, tcell.ModNone}, wantKey{Home, 0, nil}}, {giveKey{tcell.KeyEnd, 0, tcell.ModNone}, wantKey{End, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModNone}, wantKey{Delete, 0, nil}}, {giveKey{tcell.KeyPgUp, 0, tcell.ModNone}, wantKey{PageUp, 0, nil}}, {giveKey{tcell.KeyPgDn, 0, tcell.ModNone}, wantKey{PageDown, 0, nil}}, {giveKey{tcell.KeyHome, 0, tcell.ModCtrl}, wantKey{CtrlHome, 0, nil}}, {giveKey{tcell.KeyEnd, 0, tcell.ModCtrl}, wantKey{CtrlEnd, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModCtrl}, wantKey{CtrlDelete, 0, nil}}, {giveKey{tcell.KeyPgUp, 0, tcell.ModCtrl}, wantKey{CtrlPageUp, 0, nil}}, {giveKey{tcell.KeyPgDn, 0, tcell.ModCtrl}, wantKey{CtrlPageDown, 0, nil}}, {giveKey{tcell.KeyHome, 0, tcell.ModShift}, wantKey{ShiftHome, 0, nil}}, {giveKey{tcell.KeyEnd, 0, tcell.ModShift}, wantKey{ShiftEnd, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModShift}, wantKey{ShiftDelete, 0, nil}}, {giveKey{tcell.KeyPgUp, 0, tcell.ModShift}, wantKey{ShiftPageUp, 0, nil}}, {giveKey{tcell.KeyPgDn, 0, tcell.ModShift}, wantKey{ShiftPageDown, 0, nil}}, {giveKey{tcell.KeyHome, 0, tcell.ModAlt}, wantKey{AltHome, 0, nil}}, {giveKey{tcell.KeyEnd, 0, tcell.ModAlt}, wantKey{AltEnd, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModAlt}, wantKey{AltDelete, 0, nil}}, {giveKey{tcell.KeyPgUp, 0, tcell.ModAlt}, wantKey{AltPageUp, 0, nil}}, {giveKey{tcell.KeyPgDn, 0, tcell.ModAlt}, wantKey{AltPageDown, 0, nil}}, {giveKey{tcell.KeyHome, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftHome, 0, nil}}, {giveKey{tcell.KeyEnd, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftEnd, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftDelete, 0, nil}}, {giveKey{tcell.KeyPgUp, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftPageUp, 0, nil}}, {giveKey{tcell.KeyPgDn, 0, tcell.ModCtrl | tcell.ModShift}, wantKey{CtrlShiftPageDown, 0, nil}}, {giveKey{tcell.KeyHome, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltHome, 0, nil}}, {giveKey{tcell.KeyEnd, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltEnd, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltDelete, 0, nil}}, {giveKey{tcell.KeyPgUp, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltPageUp, 0, nil}}, {giveKey{tcell.KeyPgDn, 0, tcell.ModCtrl | tcell.ModAlt}, wantKey{CtrlAltPageDown, 0, nil}}, {giveKey{tcell.KeyHome, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftHome, 0, nil}}, {giveKey{tcell.KeyEnd, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftEnd, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftDelete, 0, nil}}, {giveKey{tcell.KeyPgUp, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftPageUp, 0, nil}}, {giveKey{tcell.KeyPgDn, 0, tcell.ModShift | tcell.ModAlt}, wantKey{AltShiftPageDown, 0, nil}}, {giveKey{tcell.KeyHome, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftHome, 0, nil}}, {giveKey{tcell.KeyEnd, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftEnd, 0, nil}}, {giveKey{tcell.KeyDelete, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftDelete, 0, nil}}, {giveKey{tcell.KeyPgUp, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftPageUp, 0, nil}}, {giveKey{tcell.KeyPgDn, 0, tcell.ModCtrl | tcell.ModShift | tcell.ModAlt}, wantKey{CtrlAltShiftPageDown, 0, nil}}, // section 6: (Ctrl+Alt)+'rune' {giveKey{tcell.KeyRune, 'a', tcell.ModNone}, wantKey{Rune, 'a', nil}}, {giveKey{tcell.KeyRune, 'a', tcell.ModCtrl}, wantKey{Rune, 'a', nil}}, // fabricated {giveKey{tcell.KeyRune, 'a', tcell.ModAlt}, wantKey{Alt, 'a', nil}}, {giveKey{tcell.KeyRune, 'A', tcell.ModAlt}, wantKey{Alt, 'A', nil}}, {giveKey{tcell.KeyRune, '`', tcell.ModAlt}, wantKey{Alt, '`', nil}}, /* "Input method" in Windows Language options: US: "US Keyboard" does not generate any characters (and thus any events) in Ctrl+Alt+[a-z] range CS: "Czech keyboard" DE: "German keyboard" Note that right Alt is not just `tcell.ModAlt` on foreign language keyboards, but it is the AltGr `tcell.ModCtrl|tcell.ModAlt`. */ {giveKey{tcell.KeyRune, '{', tcell.ModCtrl | tcell.ModAlt}, wantKey{Rune, '{', nil}}, // CS: Ctrl+Alt+b = "{" // Note that this does not interfere with CtrlB, since the "b" is replaced with "{" on OS level {giveKey{tcell.KeyRune, '$', tcell.ModCtrl | tcell.ModAlt}, wantKey{Rune, '$', nil}}, // CS: Ctrl+Alt+ů = "$" {giveKey{tcell.KeyRune, '~', tcell.ModCtrl | tcell.ModAlt}, wantKey{Rune, '~', nil}}, // CS: Ctrl+Alt++ = "~" {giveKey{tcell.KeyRune, '`', tcell.ModCtrl | tcell.ModAlt}, wantKey{Rune, '`', nil}}, // CS: Ctrl+Alt+ý,Space = "`" // this is dead key, space is required to emit the char {giveKey{tcell.KeyRune, '{', tcell.ModCtrl | tcell.ModAlt}, wantKey{Rune, '{', nil}}, // DE: Ctrl+Alt+7 = "{" {giveKey{tcell.KeyRune, '@', tcell.ModCtrl | tcell.ModAlt}, wantKey{Rune, '@', nil}}, // DE: Ctrl+Alt+q = "@" {giveKey{tcell.KeyRune, 'µ', tcell.ModCtrl | tcell.ModAlt}, wantKey{Rune, 'µ', nil}}, // DE: Ctrl+Alt+m = "µ" // section 7: Esc // KeyEsc and KeyEscape are aliases for KeyESC {giveKey{tcell.KeyEsc, rune(tcell.KeyEsc), tcell.ModNone}, wantKey{Esc, 0, nil}}, // fabricated {giveKey{tcell.KeyESC, rune(tcell.KeyESC), tcell.ModNone}, wantKey{Esc, 0, nil}}, // unhandled {giveKey{tcell.KeyEscape, rune(tcell.KeyEscape), tcell.ModNone}, wantKey{Esc, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyESC, rune(tcell.KeyESC), tcell.ModCtrl}, wantKey{Esc, 0, nil}}, // actual Ctrl+[ keystroke {giveKey{tcell.KeyCtrlLeftSq, rune(tcell.KeyCtrlLeftSq), tcell.ModCtrl}, wantKey{Esc, 0, nil}}, // fabricated, unhandled // section 8: Invalid {giveKey{tcell.KeyRune, 'a', tcell.ModMeta}, wantKey{Rune, 'a', nil}}, // fabricated {giveKey{tcell.KeyF24, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, {giveKey{tcell.KeyHelp, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyExit, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyClear, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // unhandled, actual keystroke Numpad_5 with Numlock OFF {giveKey{tcell.KeyCancel, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyPrint, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // fabricated, unhandled {giveKey{tcell.KeyPause, 0, tcell.ModNone}, wantKey{Invalid, 0, nil}}, // unhandled } r := NewFullscreenRenderer(&ColorTheme{}, false, false) r.Init() // run and evaluate the tests initialResizeAsInvalid := true for _, test := range tests { // generate key event giveEvent := tcell.NewEventKey(test.giveKey.Type, test.giveKey.Char, test.giveKey.Mods) _screen.PostEventWait(giveEvent) t.Logf("giveEvent = %T{key: %v, ch: %q (%[3]v), mod: %#04b}\n", giveEvent, giveEvent.Key(), giveEvent.Rune(), giveEvent.Modifiers()) // process the event in fzf and evaluate the test gotEvent := r.GetChar() // skip Resize events, those are sometimes put in the buffer outside of this test if initialResizeAsInvalid && gotEvent.Type == Invalid { t.Logf("Resize as Invalid swallowed") initialResizeAsInvalid = false gotEvent = r.GetChar() } if gotEvent.Type == Resize { t.Logf("Resize swallowed") gotEvent = r.GetChar() } t.Logf("wantEvent = %T{Type: %v, Char: %q (%[3]v)}\n", test.wantKey, test.wantKey.Type, test.wantKey.Char) t.Logf("gotEvent = %T{Type: %v, Char: %q (%[3]v)}\n", gotEvent, gotEvent.Type, gotEvent.Char) assert(t, "r.GetChar().Type", gotEvent.Type, test.wantKey.Type) assert(t, "r.GetChar().Char", gotEvent.Char, test.wantKey.Char) } r.Close() } /* Quick reference --------------- (tabstop=18) (this is not mapping table, it merely puts multiple constants ranges in one table) ¹) the two columns are each other implicit alias ²) explicit aliases here %v section # tcell ctrl key¹ tcell ctrl char¹ tcell alias² tui constants tcell named keys tcell mods -- --------- -------------- --------------- ----------- ------------- ---------------- ---------- 0 2 KeyCtrlSpace KeyNUL = ^@ Rune ModNone 1 1 KeyCtrlA KeySOH = ^A CtrlA ModShift 2 1 KeyCtrlB KeySTX = ^B CtrlB ModCtrl 3 1 KeyCtrlC KeyETX = ^C CtrlC 4 1 KeyCtrlD KeyEOT = ^D CtrlD ModAlt 5 1 KeyCtrlE KeyENQ = ^E CtrlE 6 1 KeyCtrlF KeyACK = ^F CtrlF 7 1 KeyCtrlG KeyBEL = ^G CtrlG 8 1 KeyCtrlH KeyBS = ^H KeyBackspace CtrlH ModMeta 9 1 KeyCtrlI KeyTAB = ^I KeyTab Tab 10 1 KeyCtrlJ KeyLF = ^J CtrlJ 11 1 KeyCtrlK KeyVT = ^K CtrlK 12 1 KeyCtrlL KeyFF = ^L CtrlL 13 1 KeyCtrlM KeyCR = ^M KeyEnter Enter 14 1 KeyCtrlN KeySO = ^N CtrlN 15 1 KeyCtrlO KeySI = ^O CtrlO 16 1 KeyCtrlP KeyDLE = ^P CtrlP 17 1 KeyCtrlQ KeyDC1 = ^Q CtrlQ 18 1 KeyCtrlR KeyDC2 = ^R CtrlR 19 1 KeyCtrlS KeyDC3 = ^S CtrlS 20 1 KeyCtrlT KeyDC4 = ^T CtrlT 21 1 KeyCtrlU KeyNAK = ^U CtrlU 22 1 KeyCtrlV KeySYN = ^V CtrlV 23 1 KeyCtrlW KeyETB = ^W CtrlW 24 1 KeyCtrlX KeyCAN = ^X CtrlX 25 1 KeyCtrlY KeyEM = ^Y CtrlY 26 1 KeyCtrlZ KeySUB = ^Z CtrlZ 27 7 KeyCtrlLeftSq KeyESC = ^[ KeyEsc, KeyEscape ESC 28 2 KeyCtrlBackslash KeyFS = ^\ CtrlSpace 29 2 KeyCtrlRightSq KeyGS = ^] CtrlBackSlash 30 2 KeyCtrlCarat KeyRS = ^^ CtrlRightBracket 31 2 KeyCtrlUnderscore KeyUS = ^_ CtrlCaret 32 CtrlSlash 33 Invalid 34 Resize 35 Mouse 36 DoubleClick 37 LeftClick 38 RightClick 39 BTab 40 Backspace 41 Del 42 PgUp 43 PgDn 44 Up 45 Down 46 Left 47 Right 48 Home 49 End 50 Insert 51 SUp 52 SDown 53 ShiftLeft 54 SRight 55 F1 56 F2 57 F3 58 F4 59 F5 60 F6 61 F7 62 F8 63 F9 64 F10 65 F11 66 F12 67 Change 68 BackwardEOF 69 AltBackspace 70 AltUp 71 AltDown 72 AltLeft 73 AltRight 74 AltSUp 75 AltSDown 76 AltShiftLeft 77 AltShiftRight 78 Alt 79 CtrlAlt .. 127 3 KeyDEL KeyBackspace2 .. 256 6 KeyRune 257 4 KeyUp 258 4 KeyDown 259 4 KeyRight 260 4 KeyLeft 261 8 KeyUpLeft 262 8 KeyUpRight 263 8 KeyDownLeft 264 8 KeyDownRight 265 8 KeyCenter 266 5 KeyPgUp 267 5 KeyPgDn 268 5 KeyHome 269 5 KeyEnd 270 5 KeyInsert 271 5 KeyDelete 272 8 KeyHelp 273 8 KeyExit 274 8 KeyClear 275 8 KeyCancel 276 8 KeyPrint 277 8 KeyPause 278 5 KeyBacktab 279 5 KeyF1 280 5 KeyF2 281 5 KeyF3 282 5 KeyF4 283 5 KeyF5 284 5 KeyF6 285 5 KeyF7 286 5 KeyF8 287 5 KeyF9 288 5 KeyF10 289 5 KeyF11 290 5 KeyF12 291 8 KeyF13 292 8 KeyF14 293 8 KeyF15 294 8 KeyF16 295 8 KeyF17 296 8 KeyF18 297 8 KeyF19 298 8 KeyF20 299 8 KeyF21 300 8 KeyF22 301 8 KeyF23 302 8 KeyF24 303 8 KeyF25 304 8 KeyF26 305 8 KeyF27 306 8 KeyF28 307 8 KeyF29 308 8 KeyF30 309 8 KeyF31 310 8 KeyF32 311 8 KeyF33 312 8 KeyF34 313 8 KeyF35 314 8 KeyF36 315 8 KeyF37 316 8 KeyF38 317 8 KeyF39 318 8 KeyF40 319 8 KeyF41 320 8 KeyF42 321 8 KeyF43 322 8 KeyF44 323 8 KeyF45 324 8 KeyF46 325 8 KeyF47 326 8 KeyF48 327 8 KeyF49 328 8 KeyF50 329 8 KeyF51 330 8 KeyF52 331 8 KeyF53 332 8 KeyF54 333 8 KeyF55 334 8 KeyF56 335 8 KeyF57 336 8 KeyF58 337 8 KeyF59 338 8 KeyF60 339 8 KeyF61 340 8 KeyF62 341 8 KeyF63 342 8 KeyF64 -- --------- -------------- --------------- ----------- ------------- ---------------- ---------- %v section # tcell ctrl key tcell ctrl char tcell alias tui constants tcell named keys tcell mods */
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/dummy.go
src/tui/dummy.go
//go:build !tcell && !windows package tui const ( Bold = Attr(1) Dim = Attr(1 << 1) Italic = Attr(1 << 2) Underline = Attr(1 << 3) Blink = Attr(1 << 4) Blink2 = Attr(1 << 5) Reverse = Attr(1 << 6) StrikeThrough = Attr(1 << 7) ) func HasFullscreenRenderer() bool { return false } var DefaultBorderShape = BorderRounded func (r *FullscreenRenderer) Init() error { return nil } func (r *FullscreenRenderer) DefaultTheme() *ColorTheme { return nil } func (r *FullscreenRenderer) Resize(maxHeightFunc func(int) int) {} func (r *FullscreenRenderer) Pause(bool) {} func (r *FullscreenRenderer) Resume(bool, bool) {} func (r *FullscreenRenderer) PassThrough(string) {} func (r *FullscreenRenderer) Clear() {} func (r *FullscreenRenderer) NeedScrollbarRedraw() bool { return false } func (r *FullscreenRenderer) ShouldEmitResizeEvent() bool { return false } func (r *FullscreenRenderer) Bell() {} func (r *FullscreenRenderer) HideCursor() {} func (r *FullscreenRenderer) ShowCursor() {} func (r *FullscreenRenderer) Refresh() {} func (r *FullscreenRenderer) Close() {} func (r *FullscreenRenderer) Size() TermSize { return TermSize{} } func (r *FullscreenRenderer) GetChar() Event { return Event{} } func (r *FullscreenRenderer) Top() int { return 0 } func (r *FullscreenRenderer) MaxX() int { return 0 } func (r *FullscreenRenderer) MaxY() int { return 0 } func (r *FullscreenRenderer) RefreshWindows(windows []Window) {} func (r *FullscreenRenderer) NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window { return nil }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/light.go
src/tui/light.go
package tui import ( "bytes" "errors" "fmt" "os" "regexp" "strconv" "strings" "sync" "time" "unicode/utf8" "github.com/junegunn/fzf/src/util" "github.com/rivo/uniseg" "golang.org/x/term" ) const ( defaultWidth = 80 defaultHeight = 24 defaultEscDelay = 100 escPollInterval = 5 offsetPollTries = 10 maxInputBuffer = 1024 * 1024 ) const DefaultTtyDevice string = "/dev/tty" var offsetRegexp = regexp.MustCompile("(.*?)\x00?\x1b\\[([0-9]+);([0-9]+)R") var offsetRegexpBegin = regexp.MustCompile("^\x1b\\[[0-9]+;[0-9]+R") func (r *LightRenderer) Bell() { r.flushRaw("\a") } func (r *LightRenderer) PassThrough(str string) { r.queued.WriteString("\x1b7" + str + "\x1b8") } func (r *LightRenderer) stderr(str string) { r.stderrInternal(str, true, "") } const DIM string = "\x1b[2m" const CR string = DIM + "␍" const LF string = DIM + "␊" func (r *LightRenderer) stderrInternal(str string, allowNLCR bool, resetCode string) { bytes := []byte(str) runes := []rune{} for len(bytes) > 0 { r, sz := utf8.DecodeRune(bytes) nlcr := r == '\n' || r == '\r' if r >= 32 || r == '\x1b' || nlcr { if nlcr && !allowNLCR { if r == '\r' { runes = append(runes, []rune(CR+resetCode)...) } else { runes = append(runes, []rune(LF+resetCode)...) } } else if r != utf8.RuneError { runes = append(runes, r) } } bytes = bytes[sz:] } r.queued.WriteString(string(runes)) } func (r *LightRenderer) csi(code string) string { fullcode := "\x1b[" + code r.stderr(fullcode) return fullcode } func (r *LightRenderer) flush() { if r.queued.Len() > 0 { raw := "\x1b[?7l\x1b[?25l" + r.queued.String() if r.showCursor { raw += "\x1b[?25h\x1b[?7h" } else { raw += "\x1b[?7h" } r.flushRaw(raw) r.queued.Reset() } } func (r *LightRenderer) flushRaw(sequence string) { fmt.Fprint(r.ttyout, sequence) } // Light renderer type LightRenderer struct { theme *ColorTheme mouse bool forceBlack bool clearOnExit bool prevDownTime time.Time clicks [][2]int ttyin *os.File ttyout *os.File buffer []byte origState *term.State width int height int yoffset int tabstop int escDelay int fullscreen bool upOneLine bool queued strings.Builder y int x int maxHeightFunc func(int) int showCursor bool // Windows only mutex sync.Mutex ttyinChannel chan byte inHandle uintptr outHandle uintptr origStateInput uint32 origStateOutput uint32 } type LightWindow struct { renderer *LightRenderer colored bool windowType WindowType border BorderStyle top int left int width int height int posx int posy int tabstop int fg Color bg Color wrapSign string wrapSignWidth int } func NewLightRenderer(ttyDefault string, ttyin *os.File, theme *ColorTheme, forceBlack bool, mouse bool, tabstop int, clearOnExit bool, fullscreen bool, maxHeightFunc func(int) int) (Renderer, error) { out, err := openTtyOut(ttyDefault) if err != nil { out = os.Stderr } r := LightRenderer{ theme: theme, forceBlack: forceBlack, mouse: mouse, clearOnExit: clearOnExit, ttyin: ttyin, ttyout: out, yoffset: 0, tabstop: tabstop, fullscreen: fullscreen, upOneLine: false, maxHeightFunc: maxHeightFunc, showCursor: true} return &r, nil } func repeat(r rune, times int) string { if times > 0 { return strings.Repeat(string(r), times) } return "" } func atoi(s string, defaultValue int) int { value, err := strconv.Atoi(s) if err != nil { return defaultValue } return value } func (r *LightRenderer) Init() error { r.escDelay = atoi(os.Getenv("ESCDELAY"), defaultEscDelay) if err := r.initPlatform(); err != nil { return err } r.updateTerminalSize() if r.fullscreen { r.smcup() } else { // We assume that --no-clear is used for repetitive relaunching of fzf. // So we do not clear the lower bottom of the screen. if r.clearOnExit { r.csi("J") } y, x := r.findOffset() r.mouse = r.mouse && y >= 0 // When --no-clear is used for repetitive relaunching, there is a small // time frame between fzf processes where the user keystrokes are not // captured by either of fzf process which can cause x offset to be // increased and we're left with unwanted extra new line. if x > 0 && r.clearOnExit { r.upOneLine = true r.makeSpace() } for i := 1; i < r.MaxY(); i++ { r.makeSpace() } } r.enableModes() r.csi(fmt.Sprintf("%dA", r.MaxY()-1)) r.csi("G") r.csi("K") if !r.clearOnExit && !r.fullscreen { r.csi("s") } if !r.fullscreen && r.mouse { r.yoffset, _ = r.findOffset() } return nil } func (r *LightRenderer) Resize(maxHeightFunc func(int) int) { r.maxHeightFunc = maxHeightFunc } func (r *LightRenderer) makeSpace() { r.stderr("\n") r.csi("G") } func (r *LightRenderer) move(y int, x int) { // w.csi("u") if r.y < y { r.csi(fmt.Sprintf("%dB", y-r.y)) } else if r.y > y { r.csi(fmt.Sprintf("%dA", r.y-y)) } r.stderr("\r") if x > 0 { r.csi(fmt.Sprintf("%dC", x)) } r.y = y r.x = x } func (r *LightRenderer) origin() { r.move(0, 0) } func getEnv(name string, defaultValue int) int { env := os.Getenv(name) if len(env) == 0 { return defaultValue } return atoi(env, defaultValue) } func (r *LightRenderer) getBytes() ([]byte, error) { bytes, err := r.getBytesInternal(r.buffer, false) return bytes, err } func (r *LightRenderer) getBytesInternal(buffer []byte, nonblock bool) ([]byte, error) { c, ok := r.getch(nonblock) if !nonblock && !ok { r.Close() return nil, errors.New("failed to read " + DefaultTtyDevice) } retries := 0 if c == Esc.Int() || nonblock { retries = r.escDelay / escPollInterval } buffer = append(buffer, byte(c)) pc := c for { c, ok = r.getch(true) if !ok { if retries > 0 { retries-- time.Sleep(escPollInterval * time.Millisecond) continue } break } else if c == Esc.Int() && pc != c { retries = r.escDelay / escPollInterval } else { retries = 0 } buffer = append(buffer, byte(c)) pc = c // This should never happen under normal conditions, // so terminate fzf immediately. if len(buffer) > maxInputBuffer { r.Close() return nil, fmt.Errorf("input buffer overflow (%d): %v", len(buffer), buffer) } } return buffer, nil } func (r *LightRenderer) GetChar() Event { var err error if len(r.buffer) == 0 { r.buffer, err = r.getBytes() if err != nil { return Event{Fatal, 0, nil} } } if len(r.buffer) == 0 { return Event{Fatal, 0, nil} } sz := 1 defer func() { r.buffer = r.buffer[sz:] }() switch r.buffer[0] { case CtrlC.Byte(): return Event{CtrlC, 0, nil} case CtrlG.Byte(): return Event{CtrlG, 0, nil} case CtrlQ.Byte(): return Event{CtrlQ, 0, nil} case 127: return Event{Backspace, 0, nil} case 8: return Event{CtrlBackspace, 0, nil} case 0: return Event{CtrlSpace, 0, nil} case 28: return Event{CtrlBackSlash, 0, nil} case 29: return Event{CtrlRightBracket, 0, nil} case 30: return Event{CtrlCaret, 0, nil} case 31: return Event{CtrlSlash, 0, nil} case Esc.Byte(): ev := r.escSequence(&sz) // Second chance if ev.Type == Invalid { if r.buffer, err = r.getBytes(); err != nil { return Event{Fatal, 0, nil} } ev = r.escSequence(&sz) } return ev } // CTRL-A ~ CTRL-Z if r.buffer[0] <= CtrlZ.Byte() { return Event{EventType(r.buffer[0]), 0, nil} } char, rsz := utf8.DecodeRune(r.buffer) if char == utf8.RuneError { return Event{Esc, 0, nil} } sz = rsz return Event{Rune, char, nil} } func (r *LightRenderer) escSequence(sz *int) Event { if len(r.buffer) < 2 { return Event{Esc, 0, nil} } loc := offsetRegexpBegin.FindIndex(r.buffer) if loc != nil && loc[0] == 0 { *sz = loc[1] return Event{Invalid, 0, nil} } *sz = 2 if r.buffer[1] == 8 { return Event{CtrlAltBackspace, 0, nil} } if r.buffer[1] >= 1 && r.buffer[1] <= 'z'-'a'+1 { return CtrlAltKey(rune(r.buffer[1] + 'a' - 1)) } alt := false if len(r.buffer) > 2 && r.buffer[1] == Esc.Byte() { r.buffer = r.buffer[1:] alt = true } switch r.buffer[1] { case Esc.Byte(): return Event{Esc, 0, nil} case 127: return Event{AltBackspace, 0, nil} case '[', 'O': if len(r.buffer) < 3 { return Event{Invalid, 0, nil} } *sz = 3 switch r.buffer[2] { case 'D': if alt { return Event{AltLeft, 0, nil} } return Event{Left, 0, nil} case 'C': if alt { // Ugh.. return Event{AltRight, 0, nil} } return Event{Right, 0, nil} case 'B': if alt { return Event{AltDown, 0, nil} } return Event{Down, 0, nil} case 'A': if alt { return Event{AltUp, 0, nil} } return Event{Up, 0, nil} case 'Z': return Event{ShiftTab, 0, nil} case 'H': return Event{Home, 0, nil} case 'F': return Event{End, 0, nil} case '<': return r.mouseSequence(sz) case 'P': return Event{F1, 0, nil} case 'Q': return Event{F2, 0, nil} case 'R': return Event{F3, 0, nil} case 'S': return Event{F4, 0, nil} case '1', '2', '3', '4', '5', '6', '7', '8': if len(r.buffer) < 4 { return Event{Invalid, 0, nil} } *sz = 4 switch r.buffer[2] { case '2': if r.buffer[3] == '~' { return Event{Insert, 0, nil} } if len(r.buffer) > 4 && r.buffer[4] == '~' { *sz = 5 switch r.buffer[3] { case '0': return Event{F9, 0, nil} case '1': return Event{F10, 0, nil} case '3': return Event{F11, 0, nil} case '4': return Event{F12, 0, nil} } } // Bracketed paste mode: \e[200~ ... \e[201~ if len(r.buffer) > 5 && r.buffer[3] == '0' && (r.buffer[4] == '0' || r.buffer[4] == '1') && r.buffer[5] == '~' { *sz = 6 if r.buffer[4] == '0' { return Event{BracketedPasteBegin, 0, nil} } return Event{BracketedPasteEnd, 0, nil} } return Event{Invalid, 0, nil} // INS case '3': if r.buffer[3] == '~' { return Event{Delete, 0, nil} } if len(r.buffer) == 7 && r.buffer[6] == '~' && r.buffer[4] == '1' { *sz = 7 switch r.buffer[5] { case '0': return Event{AltShiftDelete, 0, nil} case '1': return Event{AltDelete, 0, nil} case '2': return Event{AltShiftDelete, 0, nil} case '3': return Event{CtrlAltDelete, 0, nil} case '4': return Event{CtrlAltShiftDelete, 0, nil} case '5': return Event{CtrlAltDelete, 0, nil} case '6': return Event{CtrlAltShiftDelete, 0, nil} } } if len(r.buffer) == 6 && r.buffer[5] == '~' { *sz = 6 switch r.buffer[4] { case '2': return Event{ShiftDelete, 0, nil} case '3': return Event{AltDelete, 0, nil} case '4': return Event{AltShiftDelete, 0, nil} case '5': return Event{CtrlDelete, 0, nil} case '6': return Event{CtrlShiftDelete, 0, nil} case '7': return Event{CtrlAltDelete, 0, nil} case '8': return Event{CtrlAltShiftDelete, 0, nil} case '9': return Event{AltDelete, 0, nil} } } return Event{Invalid, 0, nil} case '4': return Event{End, 0, nil} case '5': if r.buffer[3] == '~' { return Event{PageUp, 0, nil} } if len(r.buffer) == 7 && r.buffer[6] == '~' && r.buffer[4] == '1' { *sz = 7 switch r.buffer[5] { case '0': return Event{AltShiftPageUp, 0, nil} case '1': return Event{AltPageUp, 0, nil} case '2': return Event{AltShiftPageUp, 0, nil} case '3': return Event{CtrlAltPageUp, 0, nil} case '4': return Event{CtrlAltShiftPageUp, 0, nil} case '5': return Event{CtrlAltPageUp, 0, nil} case '6': return Event{CtrlAltShiftPageUp, 0, nil} } } if len(r.buffer) == 6 && r.buffer[5] == '~' { *sz = 6 switch r.buffer[4] { case '2': return Event{ShiftPageUp, 0, nil} case '3': return Event{AltPageUp, 0, nil} case '4': return Event{AltShiftPageUp, 0, nil} case '5': return Event{CtrlPageUp, 0, nil} case '6': return Event{CtrlShiftPageUp, 0, nil} case '7': return Event{CtrlAltPageUp, 0, nil} case '8': return Event{CtrlAltShiftPageUp, 0, nil} case '9': return Event{AltPageUp, 0, nil} } } return Event{Invalid, 0, nil} case '6': if r.buffer[3] == '~' { return Event{PageDown, 0, nil} } if len(r.buffer) == 7 && r.buffer[6] == '~' && r.buffer[4] == '1' { *sz = 7 switch r.buffer[5] { case '0': return Event{AltShiftPageDown, 0, nil} case '1': return Event{AltPageDown, 0, nil} case '2': return Event{AltShiftPageDown, 0, nil} case '3': return Event{CtrlAltPageDown, 0, nil} case '4': return Event{CtrlAltShiftPageDown, 0, nil} case '5': return Event{CtrlAltPageDown, 0, nil} case '6': return Event{CtrlAltShiftPageDown, 0, nil} } } if len(r.buffer) == 6 && r.buffer[5] == '~' { *sz = 6 switch r.buffer[4] { case '2': return Event{ShiftPageDown, 0, nil} case '3': return Event{AltPageDown, 0, nil} case '4': return Event{AltShiftPageDown, 0, nil} case '5': return Event{CtrlPageDown, 0, nil} case '6': return Event{CtrlShiftPageDown, 0, nil} case '7': return Event{CtrlAltPageDown, 0, nil} case '8': return Event{CtrlAltShiftPageDown, 0, nil} case '9': return Event{AltPageDown, 0, nil} } } return Event{Invalid, 0, nil} case '7': return Event{Home, 0, nil} case '8': return Event{End, 0, nil} case '1': switch r.buffer[3] { case '~': return Event{Home, 0, nil} case '1', '2', '3', '4', '5', '7', '8', '9': if len(r.buffer) == 5 && r.buffer[4] == '~' { *sz = 5 switch r.buffer[3] { case '1': return Event{F1, 0, nil} case '2': return Event{F2, 0, nil} case '3': return Event{F3, 0, nil} case '4': return Event{F4, 0, nil} case '5': return Event{F5, 0, nil} case '7': return Event{F6, 0, nil} case '8': return Event{F7, 0, nil} case '9': return Event{F8, 0, nil} } } return Event{Invalid, 0, nil} case ';': if len(r.buffer) < 6 { return Event{Invalid, 0, nil} } *sz = 6 switch r.buffer[4] { case '1', '2', '3', '4', '5', '6', '7', '8', '9': // Kitty iTerm2 WezTerm // SHIFT-ARROW "\e[1;2D" // ALT-SHIFT-ARROW "\e[1;4D" "\e[1;10D" "\e[1;4D" // CTRL-SHIFT-ARROW "\e[1;6D" N/A // CMD-SHIFT-ARROW "\e[1;10D" N/A N/A ("\e[1;2D") ctrl := bytes.IndexByte([]byte{'5', '6', '7', '8'}, r.buffer[4]) >= 0 alt := bytes.IndexByte([]byte{'3', '4', '7', '8'}, r.buffer[4]) >= 0 shift := bytes.IndexByte([]byte{'2', '4', '6', '8'}, r.buffer[4]) >= 0 char := r.buffer[5] if r.buffer[4] == '9' { ctrl = false alt = true shift = false if len(r.buffer) < 6 { return Event{Invalid, 0, nil} } *sz = 6 char = r.buffer[5] } else if r.buffer[4] == '1' && bytes.IndexByte([]byte{'0', '1', '2', '3', '4', '5', '6'}, r.buffer[5]) >= 0 { ctrl = bytes.IndexByte([]byte{'3', '4', '5', '6'}, r.buffer[5]) >= 0 alt = true shift = bytes.IndexByte([]byte{'0', '2', '4', '6'}, r.buffer[5]) >= 0 if len(r.buffer) < 7 { return Event{Invalid, 0, nil} } *sz = 7 char = r.buffer[6] } ctrlShift := ctrl && shift ctrlAlt := ctrl && alt altShift := alt && shift ctrlAltShift := ctrl && alt && shift switch char { case 'A': if ctrlAltShift { return Event{CtrlAltShiftUp, 0, nil} } if ctrlAlt { return Event{CtrlAltUp, 0, nil} } if ctrlShift { return Event{CtrlShiftUp, 0, nil} } if altShift { return Event{AltShiftUp, 0, nil} } if ctrl { return Event{CtrlUp, 0, nil} } if alt { return Event{AltUp, 0, nil} } if shift { return Event{ShiftUp, 0, nil} } case 'B': if ctrlAltShift { return Event{CtrlAltShiftDown, 0, nil} } if ctrlAlt { return Event{CtrlAltDown, 0, nil} } if ctrlShift { return Event{CtrlShiftDown, 0, nil} } if altShift { return Event{AltShiftDown, 0, nil} } if ctrl { return Event{CtrlDown, 0, nil} } if alt { return Event{AltDown, 0, nil} } if shift { return Event{ShiftDown, 0, nil} } case 'C': if ctrlAltShift { return Event{CtrlAltShiftRight, 0, nil} } if ctrlAlt { return Event{CtrlAltRight, 0, nil} } if ctrlShift { return Event{CtrlShiftRight, 0, nil} } if altShift { return Event{AltShiftRight, 0, nil} } if ctrl { return Event{CtrlRight, 0, nil} } if shift { return Event{ShiftRight, 0, nil} } if alt { return Event{AltRight, 0, nil} } case 'D': if ctrlAltShift { return Event{CtrlAltShiftLeft, 0, nil} } if ctrlAlt { return Event{CtrlAltLeft, 0, nil} } if ctrlShift { return Event{CtrlShiftLeft, 0, nil} } if altShift { return Event{AltShiftLeft, 0, nil} } if ctrl { return Event{CtrlLeft, 0, nil} } if alt { return Event{AltLeft, 0, nil} } if shift { return Event{ShiftLeft, 0, nil} } case 'H': if ctrlAltShift { return Event{CtrlAltShiftHome, 0, nil} } if ctrlAlt { return Event{CtrlAltHome, 0, nil} } if ctrlShift { return Event{CtrlShiftHome, 0, nil} } if altShift { return Event{AltShiftHome, 0, nil} } if ctrl { return Event{CtrlHome, 0, nil} } if alt { return Event{AltHome, 0, nil} } if shift { return Event{ShiftHome, 0, nil} } case 'F': if ctrlAltShift { return Event{CtrlAltShiftEnd, 0, nil} } if ctrlAlt { return Event{CtrlAltEnd, 0, nil} } if ctrlShift { return Event{CtrlShiftEnd, 0, nil} } if altShift { return Event{AltShiftEnd, 0, nil} } if ctrl { return Event{CtrlEnd, 0, nil} } if alt { return Event{AltEnd, 0, nil} } if shift { return Event{ShiftEnd, 0, nil} } } } // r.buffer[4] } // r.buffer[3] } // r.buffer[2] } // r.buffer[2] } // r.buffer[1] rest := bytes.NewBuffer(r.buffer[1:]) c, size, err := rest.ReadRune() if err == nil { *sz = 1 + size return AltKey(c) } return Event{Invalid, 0, nil} } // https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking func (r *LightRenderer) mouseSequence(sz *int) Event { // "\e[<0;0;0M" if len(r.buffer) < 9 || !r.mouse { return Event{Invalid, 0, nil} } rest := r.buffer[*sz:] end := bytes.IndexAny(rest, "mM") if end == -1 { return Event{Invalid, 0, nil} } elems := strings.SplitN(string(rest[:end]), ";", 3) if len(elems) != 3 { return Event{Invalid, 0, nil} } t := atoi(elems[0], -1) x := atoi(elems[1], -1) - 1 y := atoi(elems[2], -1) - 1 - r.yoffset if t < 0 || x < 0 { return Event{Invalid, 0, nil} } *sz += end + 1 down := rest[end] == 'M' scroll := 0 if t >= 64 { t -= 64 if t&0b1 == 1 { scroll = -1 } else { scroll = 1 } } // middle := t & 0b1 left := t&0b11 == 0 ctrl := t&0b10000 > 0 alt := t&0b01000 > 0 shift := t&0b00100 > 0 drag := t&0b100000 > 0 // 32 if scroll != 0 { return Event{Mouse, 0, &MouseEvent{y, x, scroll, false, false, false, ctrl, alt, shift}} } double := false if down && !drag { now := time.Now() if !left { // Right double click is not allowed r.clicks = [][2]int{} } else if now.Sub(r.prevDownTime) < doubleClickDuration { r.clicks = append(r.clicks, [2]int{x, y}) } else { r.clicks = [][2]int{{x, y}} } r.prevDownTime = now } else { n := len(r.clicks) if len(r.clicks) > 1 && r.clicks[n-2][0] == r.clicks[n-1][0] && r.clicks[n-2][1] == r.clicks[n-1][1] && time.Since(r.prevDownTime) < doubleClickDuration { double = true if double { r.clicks = [][2]int{} } } } return Event{Mouse, 0, &MouseEvent{y, x, 0, left, down, double, ctrl, alt, shift}} } func (r *LightRenderer) smcup() { r.flush() r.flushRaw("\x1b[?1049h") } func (r *LightRenderer) rmcup() { r.flush() r.flushRaw("\x1b[?1049l") } func (r *LightRenderer) Pause(clear bool) { r.disableModes() r.restoreTerminal() if clear { if r.fullscreen { r.rmcup() } else { r.smcup() r.csi("H") } r.flush() } } func (r *LightRenderer) enableModes() { if r.mouse { r.csi("?1000h") r.csi("?1002h") r.csi("?1006h") } r.csi("?2004h") // Enable bracketed paste mode } func (r *LightRenderer) disableMouse() { if r.mouse { r.csi("?1000l") r.csi("?1002l") r.csi("?1006l") } } func (r *LightRenderer) disableModes() { r.disableMouse() r.csi("?2004l") } func (r *LightRenderer) Resume(clear bool, sigcont bool) { r.setupTerminal() if clear { if r.fullscreen { r.smcup() } else { r.rmcup() } r.enableModes() r.flush() } else if sigcont && !r.fullscreen && r.mouse { // NOTE: SIGCONT (Coming back from CTRL-Z): // It's highly likely that the offset we obtained at the beginning is // no longer correct, so we simply disable mouse input. r.disableMouse() r.mouse = false } } func (r *LightRenderer) Clear() { if r.fullscreen { r.csi("H") } // r.csi("u") r.origin() r.csi("J") r.flush() } func (r *LightRenderer) NeedScrollbarRedraw() bool { return false } func (r *LightRenderer) ShouldEmitResizeEvent() bool { return false } func (r *LightRenderer) RefreshWindows(windows []Window) { r.flush() } func (r *LightRenderer) Refresh() { r.updateTerminalSize() } func (r *LightRenderer) Close() { // r.csi("u") if r.clearOnExit { if r.fullscreen { r.rmcup() } else { r.origin() if r.upOneLine { r.csi("A") } r.csi("J") } } else if !r.fullscreen { r.csi("u") } if !r.showCursor { r.csi("?25h") } r.disableModes() r.flush() r.restoreTerminal() r.closePlatform() } func (r *LightRenderer) Top() int { return r.yoffset } func (r *LightRenderer) MaxX() int { return r.width } func (r *LightRenderer) MaxY() int { if r.height == 0 { r.updateTerminalSize() } return r.height } func (r *LightRenderer) NewWindow(top int, left int, width int, height int, windowType WindowType, borderStyle BorderStyle, erase bool) Window { width = max(0, width) height = max(0, height) w := &LightWindow{ renderer: r, colored: r.theme.Colored, windowType: windowType, border: borderStyle, top: top, left: left, width: width, height: height, tabstop: r.tabstop, fg: colDefault, bg: colDefault} switch windowType { case WindowBase: w.fg = r.theme.Fg.Color w.bg = r.theme.Bg.Color case WindowList: w.fg = r.theme.ListFg.Color w.bg = r.theme.ListBg.Color case WindowInput: w.fg = r.theme.Input.Color w.bg = r.theme.InputBg.Color case WindowHeader: w.fg = r.theme.Header.Color w.bg = r.theme.HeaderBg.Color case WindowFooter: w.fg = r.theme.Footer.Color w.bg = r.theme.FooterBg.Color case WindowPreview: w.fg = r.theme.PreviewFg.Color w.bg = r.theme.PreviewBg.Color } if erase && !w.bg.IsDefault() && w.border.shape != BorderNone && w.height > 0 { // fzf --color bg:blue --border --padding 1,2 w.Erase() } w.drawBorder(false) return w } func (w *LightWindow) DrawBorder() { w.drawBorder(false) } func (w *LightWindow) DrawHBorder() { w.drawBorder(true) } func (w *LightWindow) drawBorder(onlyHorizontal bool) { if w.height == 0 { return } switch w.border.shape { case BorderRounded, BorderSharp, BorderBold, BorderBlock, BorderThinBlock, BorderDouble: w.drawBorderAround(onlyHorizontal) case BorderHorizontal: w.drawBorderHorizontal(true, true) case BorderVertical: if onlyHorizontal { return } w.drawBorderVertical(true, true) case BorderTop: w.drawBorderHorizontal(true, false) case BorderBottom: w.drawBorderHorizontal(false, true) case BorderLeft: if onlyHorizontal { return } w.drawBorderVertical(true, false) case BorderRight: if onlyHorizontal { return } w.drawBorderVertical(false, true) } } func (w *LightWindow) drawBorderHorizontal(top, bottom bool) { color := ColBorder switch w.windowType { case WindowList: color = ColListBorder case WindowInput: color = ColInputBorder case WindowHeader: color = ColHeaderBorder case WindowFooter: color = ColFooterBorder case WindowPreview: color = ColPreviewBorder } hw := runeWidth(w.border.top) if top { w.Move(0, 0) w.CPrint(color, repeat(w.border.top, w.width/hw)) } if bottom { w.Move(w.height-1, 0) w.CPrint(color, repeat(w.border.bottom, w.width/hw)) } } func (w *LightWindow) drawBorderVertical(left, right bool) { vw := runeWidth(w.border.left) color := ColBorder switch w.windowType { case WindowList: color = ColListBorder case WindowInput: color = ColInputBorder case WindowHeader: color = ColHeaderBorder case WindowFooter: color = ColFooterBorder case WindowPreview: color = ColPreviewBorder } for y := 0; y < w.height; y++ { if left { w.Move(y, 0) w.CPrint(color, string(w.border.left)) w.CPrint(color, " ") // Margin } if right { w.Move(y, w.width-vw-1) w.CPrint(color, " ") // Margin w.CPrint(color, string(w.border.right)) } } } func (w *LightWindow) drawBorderAround(onlyHorizontal bool) { w.Move(0, 0) color := ColBorder switch w.windowType { case WindowList: color = ColListBorder case WindowInput: color = ColInputBorder case WindowHeader: color = ColHeaderBorder case WindowFooter: color = ColFooterBorder case WindowPreview: color = ColPreviewBorder } hw := runeWidth(w.border.top) tcw := runeWidth(w.border.topLeft) + runeWidth(w.border.topRight) bcw := runeWidth(w.border.bottomLeft) + runeWidth(w.border.bottomRight) rem := (w.width - tcw) % hw w.CPrint(color, string(w.border.topLeft)+repeat(w.border.top, (w.width-tcw)/hw)+repeat(' ', rem)+string(w.border.topRight)) if !onlyHorizontal { vw := runeWidth(w.border.left) for y := 1; y < w.height-1; y++ { w.Move(y, 0) w.CPrint(color, string(w.border.left)) w.CPrint(color, " ") // Margin w.Move(y, w.width-vw-1) w.CPrint(color, " ") // Margin w.CPrint(color, string(w.border.right)) } } w.Move(w.height-1, 0) rem = (w.width - bcw) % hw w.CPrint(color, string(w.border.bottomLeft)+repeat(w.border.bottom, (w.width-bcw)/hw)+repeat(' ', rem)+string(w.border.bottomRight)) } func (w *LightWindow) csi(code string) string { return w.renderer.csi(code) } func (w *LightWindow) stderrInternal(str string, allowNLCR bool, resetCode string) { w.renderer.stderrInternal(str, allowNLCR, resetCode) } func (w *LightWindow) Top() int { return w.top } func (w *LightWindow) Left() int { return w.left } func (w *LightWindow) Width() int { return w.width } func (w *LightWindow) Height() int { return w.height } func (w *LightWindow) Refresh() { } func (w *LightWindow) X() int { return w.posx } func (w *LightWindow) Y() int { return w.posy } func (w *LightWindow) EncloseX(x int) bool { return x >= w.left && x < (w.left+w.width) } func (w *LightWindow) EncloseY(y int) bool { return y >= w.top && y < (w.top+w.height) } func (w *LightWindow) Enclose(y int, x int) bool { return w.EncloseX(x) && w.EncloseY(y) } func (w *LightWindow) Move(y int, x int) { w.posx = x w.posy = y w.renderer.move(w.Top()+y, w.Left()+x) } func (w *LightWindow) MoveAndClear(y int, x int) { w.Move(y, x) // We should not delete preview window on the right // csi("K") w.Print(repeat(' ', w.width-x)) w.Move(y, x) } func attrCodes(attr Attr) []string { codes := []string{} if (attr & AttrClear) > 0 { return codes } if (attr&Bold) > 0 || (attr&BoldForce) > 0 { codes = append(codes, "1") } if (attr & Dim) > 0 { codes = append(codes, "2") } if (attr & Italic) > 0 { codes = append(codes, "3") } if (attr & Underline) > 0 { codes = append(codes, "4") } if (attr & Blink) > 0 { codes = append(codes, "5") } if (attr & Reverse) > 0 { codes = append(codes, "7") } if (attr & StrikeThrough) > 0 { codes = append(codes, "9") } return codes } func colorCodes(fg Color, bg Color) []string { codes := []string{} appendCode := func(c Color, offset int) { if c == colDefault { return } if c.is24() { r := (c >> 16) & 0xff g := (c >> 8) & 0xff b := (c) & 0xff codes = append(codes, fmt.Sprintf("%d;2;%d;%d;%d", 38+offset, r, g, b)) } else if c >= colBlack && c <= colWhite { codes = append(codes, fmt.Sprintf("%d", int(c)+30+offset)) } else if c > colWhite && c < 16 { codes = append(codes, fmt.Sprintf("%d", int(c)+90+offset-8)) } else if c >= 16 && c < 256 { codes = append(codes, fmt.Sprintf("%d;5;%d", 38+offset, c)) } } appendCode(fg, 0) appendCode(bg, 10) return codes } func (w *LightWindow) csiColor(fg Color, bg Color, attr Attr) (bool, string) { codes := append(attrCodes(attr), colorCodes(fg, bg)...) code := w.csi(";" + strings.Join(codes, ";") + "m") return len(codes) > 0, code } func (w *LightWindow) Print(text string) { w.cprint2(colDefault, w.bg, AttrRegular, text) } func cleanse(str string) string { return strings.ReplaceAll(str, "\x1b", "") } func (w *LightWindow) CPrint(pair ColorPair, text string) { _, code := w.csiColor(pair.Fg(), pair.Bg(), pair.Attr()) w.stderrInternal(cleanse(text), false, code) w.csi("0m") } func (w *LightWindow) cprint2(fg Color, bg Color, attr Attr, text string) { hasColors, code := w.csiColor(fg, bg, attr) if hasColors { defer w.csi("0m") } w.stderrInternal(cleanse(text), false, code) } type wrappedLine struct { text string displayWidth int } func wrapLine(input string, prefixLength int, initialMax int, tabstop int, wrapSignWidth int) []wrappedLine { lines := []wrappedLine{} width := 0 line := "" gr := uniseg.NewGraphemes(input) max := initialMax for gr.Next() { rs := gr.Runes() str := string(rs) var w int if len(rs) == 1 && rs[0] == '\t' { w = tabstop - (prefixLength+width)%tabstop str = repeat(' ', w) } else if rs[0] == '\r' { w++ } else { w = uniseg.StringWidth(str) } width += w if prefixLength+width <= max { line += str } else { lines = append(lines, wrappedLine{string(line), width - w}) line = str prefixLength = 0 width = w max = initialMax - wrapSignWidth } } lines = append(lines, wrappedLine{string(line), width}) return lines } func (w *LightWindow) fill(str string, resetCode string) FillReturn { allLines := strings.Split(str, "\n") for i, line := range allLines { lines := wrapLine(line, w.posx, w.width, w.tabstop, w.wrapSignWidth) for j, wl := range lines { w.stderrInternal(wl.text, false, resetCode) w.posx += wl.displayWidth // Wrap line if j < len(lines)-1 || i < len(allLines)-1 { if w.posy+1 >= w.height { return FillSuspend } w.MoveAndClear(w.posy, w.posx) w.Move(w.posy+1, 0) w.renderer.stderr(resetCode) if len(lines) > 1 { sign := w.wrapSign width := w.wrapSignWidth if width > w.width { runes, truncatedWidth := util.Truncate(w.wrapSign, w.width) sign = string(runes) width = truncatedWidth } w.stderrInternal(DIM+sign, false, resetCode) w.renderer.stderr(resetCode) w.Move(w.posy, width) } } } } if w.posx >= w.Width() { if w.posy+1 >= w.height { return FillSuspend } w.Move(w.posy+1, 0) w.renderer.stderr(resetCode) return FillNextLine } return FillContinue } func (w *LightWindow) setBg() string { if w.bg != colDefault { _, code := w.csiColor(colDefault, w.bg, AttrRegular) return code } // Should clear dim attribute after ␍ in the preview window // e.g. printf "foo\rbar" | fzf --ansi --preview 'printf "foo\rbar"' return "\x1b[m" }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
true
junegunn/fzf
https://github.com/junegunn/fzf/blob/3c7cbc9d476025e0cf90e2303bce38935898df1f/src/tui/ttyname_unix.go
src/tui/ttyname_unix.go
//go:build !windows package tui import ( "os" "sync/atomic" "syscall" ) var devPrefixes = [...]string{"/dev/pts/", "/dev/"} var tty atomic.Value func ttyname() string { if cached := tty.Load(); cached != nil { return cached.(string) } var stderr syscall.Stat_t if syscall.Fstat(2, &stderr) != nil { return "" } for _, prefix := range devPrefixes { files, err := os.ReadDir(prefix) if err != nil { continue } for _, file := range files { info, err := file.Info() if err != nil { continue } if stat, ok := info.Sys().(*syscall.Stat_t); ok && stat.Rdev == stderr.Rdev { value := prefix + file.Name() tty.Store(value) return value } } } return "" } // TtyIn returns terminal device to read user input func TtyIn(ttyDefault string) (*os.File, error) { return openTtyIn(ttyDefault) } // TtyOut returns terminal device to write to func TtyOut(ttyDefault string) (*os.File, error) { return openTtyOut(ttyDefault) }
go
MIT
3c7cbc9d476025e0cf90e2303bce38935898df1f
2026-01-07T08:35:43.431645Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/main.go
cmd/dive/main.go
package main // Copyright © 2018 Alex Goodman // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import ( "github.com/anchore/clio" "github.com/wagoodman/dive/cmd/dive/cli" ) // applicationName is the non-capitalized name of the application (do not change this) const ( applicationName = "dive" notProvided = "[not provided]" ) // TODO: these need to be wired up to the build flags // all variables here are provided as build-time arguments, with clear default values var ( version = notProvided buildDate = notProvided gitCommit = notProvided gitDescription = notProvided ) func main() { app := cli.Application( clio.Identification{ Name: applicationName, Version: version, BuildDate: buildDate, GitCommit: gitCommit, GitDescription: gitDescription, }, ) app.Run() }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/cli_test.go
cmd/dive/cli/cli_test.go
package cli import ( "bytes" "flag" "github.com/anchore/clio" "github.com/charmbracelet/lipgloss" snapsPkg "github.com/gkampitakis/go-snaps/snaps" "github.com/google/shlex" "github.com/muesli/termenv" "github.com/spf13/cobra" "github.com/stretchr/testify/require" "go.uber.org/atomic" "io" "os" "os/exec" "path/filepath" "strings" "testing" ) var ( updateSnapshot = flag.Bool("update", false, "update any test snapshots") snaps *snapsPkg.Config repoRootCache atomic.String ) func TestMain(m *testing.M) { // flags are not parsed until after test.Main is called... flag.Parse() os.Unsetenv("DIVE_CONFIG") // disable colors lipgloss.SetColorProfile(termenv.Ascii) snaps = snapsPkg.WithConfig( snapsPkg.Update(*updateSnapshot), snapsPkg.Dir("testdata/snapshots"), ) v := m.Run() snapsPkg.Clean(m) os.Exit(v) } func TestUpdateSnapshotDisabled(t *testing.T) { require.False(t, *updateSnapshot, "update snapshot flag should be disabled") } func repoPath(t testing.TB, path string) string { t.Helper() root := repoRoot(t) return filepath.Join(root, path) } func repoRoot(t testing.TB) string { val := repoRootCache.Load() if val != "" { return val } t.Helper() // use git to find the root of the repo out, err := exec.Command("git", "rev-parse", "--show-toplevel").Output() if err != nil { t.Fatalf("failed to get repo root: %v", err) } val = strings.TrimSpace(string(out)) repoRootCache.Store(val) return val } func getTestCommand(t testing.TB, cmd string) *cobra.Command { switch os.Getenv("DIVE_CONFIG") { case "": t.Setenv("DIVE_CONFIG", "./testdata/dive-enable-ci.yaml") case "-": t.Setenv("DIVE_CONFIG", "") } // need basic output to logger for testing... //l, err := logrus.New(logrus.DefaultConfig()) //require.NoError(t, err) //log.Set(l) // get the root command c := Command(clio.Identification{ Name: "dive", Version: "testing", }) args, err := shlex.Split(cmd) require.NoError(t, err, "failed to parse command line %q", cmd) c.SetArgs(args) return c } type capturer struct { stdout bool stderr bool suppress bool } func Capture() *capturer { return &capturer{} } func (c *capturer) WithSuppress() *capturer { c.suppress = true return c } func (c *capturer) All() *capturer { c.stdout = true c.stderr = true return c } func (c *capturer) WithStdout() *capturer { c.stdout = true return c } func (c *capturer) WithStderr() *capturer { c.stderr = true return c } func (c *capturer) Run(t testing.TB, f func()) string { t.Helper() r, w, err := os.Pipe() if err != nil { panic(err) } devNull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) if err != nil { panic(err) } defer devNull.Close() oldStdout := os.Stdout oldStderr := os.Stderr if c.stdout { os.Stdout = w } else if c.suppress { os.Stdout = devNull } if c.stderr { os.Stderr = w } else if c.suppress { os.Stderr = devNull } defer func() { os.Stdout = oldStdout os.Stderr = oldStderr }() f() require.NoError(t, w.Close()) var buf bytes.Buffer _, err = io.Copy(&buf, r) require.NoError(t, err) return buf.String() }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/cli_build_test.go
cmd/dive/cli/cli_build_test.go
package cli import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "regexp" "testing" ) func Test_Build_Dockerfile(t *testing.T) { t.Setenv("DIVE_CONFIG", "./testdata/image-multi-layer-dockerfile/dive-pass.yaml") t.Run("implicit dockerfile", func(t *testing.T) { rootCmd := getTestCommand(t, "build testdata/image-multi-layer-dockerfile") stdout := Capture().WithStdout().WithSuppress().Run(t, func() { require.NoError(t, rootCmd.Execute()) }) snaps.MatchSnapshot(t, stdout) }) t.Run("explicit file flag", func(t *testing.T) { rootCmd := getTestCommand(t, "build testdata/image-multi-layer-dockerfile -f testdata/image-multi-layer-dockerfile/Dockerfile") stdout := Capture().WithStdout().WithSuppress().Run(t, func() { require.NoError(t, rootCmd.Execute()) }) snaps.MatchSnapshot(t, stdout) }) } func Test_Build_Containerfile(t *testing.T) { t.Setenv("DIVE_CONFIG", "./testdata/image-multi-layer-containerfile/dive-pass.yaml") t.Run("implicit containerfile", func(t *testing.T) { rootCmd := getTestCommand(t, "build testdata/image-multi-layer-containerfile") stdout := Capture().WithStdout().WithSuppress().Run(t, func() { require.NoError(t, rootCmd.Execute()) }) snaps.MatchSnapshot(t, stdout) }) t.Run("explicit file flag", func(t *testing.T) { rootCmd := getTestCommand(t, "build testdata/image-multi-layer-containerfile -f testdata/image-multi-layer-containerfile/Containerfile") stdout := Capture().WithStdout().WithSuppress().Run(t, func() { require.NoError(t, rootCmd.Execute()) }) snaps.MatchSnapshot(t, stdout) }) } func Test_Build_CI_gate_fail(t *testing.T) { t.Setenv("DIVE_CONFIG", "./testdata/image-multi-layer-dockerfile/dive-fail.yaml") rootCmd := getTestCommand(t, "build testdata/image-multi-layer-dockerfile") stdout := Capture().WithStdout().WithSuppress().Run(t, func() { // failing gate should result in a non-zero exit code require.Error(t, rootCmd.Execute()) }) snaps.MatchSnapshot(t, stdout) } func Test_BuildFailure(t *testing.T) { t.Run("nonexistent directory", func(t *testing.T) { rootCmd := getTestCommand(t, "build ./path/does/not/exist") combined := Capture().WithStdout().WithStderr().Run(t, func() { require.ErrorContains(t, rootCmd.Execute(), "could not find Containerfile or Dockerfile") }) assert.Contains(t, combined, "Building image") snaps.MatchSnapshot(t, combined) }) t.Run("invalid dockerfile", func(t *testing.T) { rootCmd := getTestCommand(t, "build ./testdata/invalid") combined := Capture().WithStdout().WithStderr().WithSuppress().Run(t, func() { require.ErrorContains(t, rootCmd.Execute(), "cannot build image: exit status 1") }) assert.Contains(t, combined, "Building image") // ensure we're passing through docker feedback assert.Contains(t, combined, "unknown instruction: INVALID") // replace anything starting with "docker-desktop://", like "docker-desktop://dashboard/build/desktop-linux/desktop-linux/ujdmhgkwo0sqqpopsnum3xakd" combined = regexp.MustCompile("docker-desktop://[^ ]+").ReplaceAllString(combined, "docker-desktop://<redacted>") snaps.MatchSnapshot(t, combined) }) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/cli_config_test.go
cmd/dive/cli/cli_config_test.go
package cli import ( "github.com/stretchr/testify/require" "testing" ) func Test_Config(t *testing.T) { t.Setenv("DIVE_CONFIG", "./testdata/image-multi-layer-dockerfile/dive-pass.yaml") rootCmd := getTestCommand(t, "config --load") all := Capture().All().Run(t, func() { require.NoError(t, rootCmd.Execute()) }) snaps.MatchSnapshot(t, all) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/cli_json_test.go
cmd/dive/cli/cli_json_test.go
package cli import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "os" "path/filepath" "testing" ) func Test_JsonOutput(t *testing.T) { t.Run("json output", func(t *testing.T) { dest := t.TempDir() file := filepath.Join(dest, "output.json") rootCmd := getTestCommand(t, "busybox:1.37.0@sha256:ad9fa4d07136a83e69a54ef00102f579d04eba431932de3b0f098cc5d5948f9f --json "+file) combined := Capture().WithStdout().WithStderr().Run(t, func() { require.NoError(t, rootCmd.Execute()) }) assert.Contains(t, combined, "Exporting details") assert.Contains(t, combined, "file") contents, err := os.ReadFile(file) require.NoError(t, err) snaps.MatchJSON(t, contents) }) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/cli_load_test.go
cmd/dive/cli/cli_load_test.go
package cli import ( "fmt" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "os" "os/exec" "testing" ) func Test_LoadImage(t *testing.T) { image := "busybox:1.37.0@sha256:ad9fa4d07136a83e69a54ef00102f579d04eba431932de3b0f098cc5d5948f9f" archive := repoPath(t, ".data/test-docker-image.tar") t.Run("from docker engine", func(t *testing.T) { runWithCombinedOutput(t, fmt.Sprintf("docker://%s", image)) }) t.Run("from docker engine (flag)", func(t *testing.T) { runWithCombinedOutput(t, fmt.Sprintf("--source docker %s", image)) }) t.Run("from podman engine", func(t *testing.T) { if _, err := exec.LookPath("podman"); err != nil { t.Skip("podman not installed, skipping test") } // pull the image from podman first require.NoError(t, exec.Command("podman", "pull", image).Run()) runWithCombinedOutput(t, fmt.Sprintf("podman://%s", image)) }) t.Run("from podman engine (flag)", func(t *testing.T) { if _, err := exec.LookPath("podman"); err != nil { t.Skip("podman not installed, skipping test") } // pull the image from podman first require.NoError(t, exec.Command("podman", "pull", image).Run()) runWithCombinedOutput(t, fmt.Sprintf("--source podman %s", image)) }) t.Run("from archive", func(t *testing.T) { runWithCombinedOutput(t, fmt.Sprintf("docker-archive://%s", archive)) }) t.Run("from archive (flag)", func(t *testing.T) { runWithCombinedOutput(t, fmt.Sprintf("--source docker-archive %s", archive)) }) } func runWithCombinedOutput(t testing.TB, cmd string) { t.Helper() rootCmd := getTestCommand(t, cmd) combined := Capture().WithStdout().WithStderr().Run(t, func() { require.NoError(t, rootCmd.Execute()) }) assertLoadOutput(t, combined) } func assertLoadOutput(t testing.TB, combined string) { t.Helper() assert.Contains(t, combined, "Loading image") assert.Contains(t, combined, "Analyzing image") assert.Contains(t, combined, "Evaluating image") snaps.MatchSnapshot(t, combined) } func Test_FetchFailure(t *testing.T) { t.Run("nonexistent image", func(t *testing.T) { rootCmd := getTestCommand(t, "docker:wagoodman/nonexistent/image:tag") combined := Capture().WithStdout().WithStderr().Run(t, func() { require.ErrorContains(t, rootCmd.Execute(), "cannot load image: Error response from daemon: invalid reference format") }) assert.Contains(t, combined, "Loading image") snaps.MatchSnapshot(t, combined) }) t.Run("invalid image name", func(t *testing.T) { rootCmd := getTestCommand(t, "docker:///wagoodman/invalid:image:format") combined := Capture().WithStdout().WithStderr().Run(t, func() { require.ErrorContains(t, rootCmd.Execute(), "cannot load image: Error response from daemon: invalid reference format") }) assert.Contains(t, combined, "Loading image") snaps.MatchSnapshot(t, combined) }) } func cd(t testing.TB, to string) { t.Helper() from, err := os.Getwd() require.NoError(t, err) require.NoError(t, os.Chdir(to)) t.Cleanup(func() { require.NoError(t, os.Chdir(from)) }) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/cli.go
cmd/dive/cli/cli.go
package cli import ( "github.com/anchore/clio" "github.com/spf13/cobra" "github.com/wagoodman/dive/cmd/dive/cli/internal/command" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui" "github.com/wagoodman/dive/internal/bus" "github.com/wagoodman/dive/internal/log" ) func Application(id clio.Identification) clio.Application { app, _ := create(id) return app } func Command(id clio.Identification) *cobra.Command { _, cmd := create(id) return cmd } func create(id clio.Identification) (clio.Application, *cobra.Command) { clioCfg := clio.NewSetupConfig(id). WithGlobalConfigFlag(). // add persistent -c <path> for reading an application config from WithGlobalLoggingFlags(). // add persistent -v and -q flags tied to the logging config WithConfigInRootHelp(). // --help on the root command renders the full application config in the help text WithUI(ui.None()). WithInitializers( func(state *clio.State) error { bus.Set(state.Bus) log.Set(state.Logger) //stereoscope.SetBus(state.Bus) //stereoscope.SetLogger(state.Logger) return nil }, ) //WithPostRuns(func(_ *clio.State, _ error) { // stereoscope.Cleanup() //}) app := clio.New(*clioCfg) rootCmd := command.Root(app) rootCmd.AddCommand( clio.VersionCommand(id), clio.ConfigCommand(app, nil), command.Build(app), ) return app, rootCmd }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/cli_ci_test.go
cmd/dive/cli/cli_ci_test.go
package cli import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "testing" ) func Test_CI_DefaultCIConfig(t *testing.T) { // this lets the test harness to unset any DIVE_CONFIG env var t.Setenv("DIVE_CONFIG", "-") rootCmd := getTestCommand(t, repoPath(t, ".data/test-docker-image.tar")+" -vv") cd(t, "testdata/default-ci-config") combined := Capture().WithStdout().WithStderr().Run(t, func() { // failing gate should result in a non-zero exit code require.Error(t, rootCmd.Execute()) }) assert.Contains(t, combined, "lowest-efficiency: \"0.96\"", "missing lowest-efficiency rule") assert.Contains(t, combined, "highest-wasted-bytes: 19Mb", "missing highest-wasted-bytes rule") assert.Contains(t, combined, "highest-user-wasted-percent: \"0.6\"", "missing highest-user-wasted-percent rule") snaps.MatchSnapshot(t, combined) } func Test_CI_Fail(t *testing.T) { t.Setenv("DIVE_CONFIG", "./testdata/image-multi-layer-dockerfile/dive-fail.yaml") rootCmd := getTestCommand(t, "build testdata/image-multi-layer-dockerfile") stdout := Capture().WithStdout().WithSuppress().Run(t, func() { // failing gate should result in a non-zero exit code require.Error(t, rootCmd.Execute()) }) snaps.MatchSnapshot(t, stdout) } func Test_CI_LegacyRules(t *testing.T) { t.Setenv("DIVE_CONFIG", "./testdata/config/dive-ci-legacy.yaml") rootCmd := getTestCommand(t, "config --load") all := Capture().All().Run(t, func() { require.NoError(t, rootCmd.Execute()) }) // this proves that we can load the legacy rules and map them to the standard rules assert.Contains(t, all, "lowest-efficiency: '0.95'", "missing lowest-efficiency legacy rule") assert.Contains(t, all, "highest-wasted-bytes: '20MB'", "missing highest-wasted-bytes legacy rule") assert.Contains(t, all, "highest-user-wasted-percent: '0.2'", "missing highest-user-wasted-percent legacy rule") }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/ci_rules.go
cmd/dive/cli/internal/options/ci_rules.go
package options import ( "github.com/anchore/clio" "github.com/wagoodman/dive/cmd/dive/cli/internal/command/ci" "github.com/wagoodman/dive/internal/log" ) type CIRules struct { LowestEfficiencyThresholdString string `yaml:"lowest-efficiency" mapstructure:"lowest-efficiency"` LegacyLowestEfficiencyThresholdString string `yaml:"-" mapstructure:"lowestEfficiency"` HighestWastedBytesString string `yaml:"highest-wasted-bytes" mapstructure:"highest-wasted-bytes"` LegacyHighestWastedBytesString string `yaml:"-" mapstructure:"highestWastedBytes"` HighestUserWastedPercentString string `yaml:"highest-user-wasted-percent" mapstructure:"highest-user-wasted-percent"` LegacyHighestUserWastedPercentString string `yaml:"-" mapstructure:"highestUserWastedPercent"` List []ci.Rule `yaml:"-" mapstructure:"-"` } func DefaultCIRules() CIRules { return CIRules{ LowestEfficiencyThresholdString: "0.9", HighestWastedBytesString: "disabled", HighestUserWastedPercentString: "0.1", } } func (c *CIRules) DescribeFields(descriptions clio.FieldDescriptionSet) { descriptions.Add(&c.LowestEfficiencyThresholdString, "lowest allowable image efficiency (as a ratio between 0-1), otherwise CI validation will fail.") descriptions.Add(&c.HighestWastedBytesString, "highest allowable bytes wasted, otherwise CI validation will fail.") descriptions.Add(&c.HighestUserWastedPercentString, "highest allowable percentage of bytes wasted (as a ratio between 0-1), otherwise CI validation will fail.") } func (c *CIRules) AddFlags(flags clio.FlagSet) { flags.StringVarP(&c.LowestEfficiencyThresholdString, "lowestEfficiency", "", "(only valid with --ci given) lowest allowable image efficiency (as a ratio between 0-1), otherwise CI validation will fail.") flags.StringVarP(&c.HighestWastedBytesString, "highestWastedBytes", "", "(only valid with --ci given) highest allowable bytes wasted, otherwise CI validation will fail.") flags.StringVarP(&c.HighestUserWastedPercentString, "highestUserWastedPercent", "", "(only valid with --ci given) highest allowable percentage of bytes wasted (as a ratio between 0-1), otherwise CI validation will fail.") } func (c CIRules) hasLegacyOptionsInUse() bool { return c.LegacyLowestEfficiencyThresholdString != "" || c.LegacyHighestWastedBytesString != "" || c.LegacyHighestUserWastedPercentString != "" } func (c *CIRules) PostLoad() error { // protect against repeated calls c.List = nil if c.hasLegacyOptionsInUse() { log.Warnf("please specify ci rules in snake-case (the legacy camelCase format is deprecated)") } if c.LegacyLowestEfficiencyThresholdString != "" { c.LowestEfficiencyThresholdString = c.LegacyLowestEfficiencyThresholdString } if c.LegacyHighestWastedBytesString != "" { c.HighestWastedBytesString = c.LegacyHighestWastedBytesString } if c.LegacyHighestUserWastedPercentString != "" { c.HighestUserWastedPercentString = c.LegacyHighestUserWastedPercentString } rules, err := ci.Rules(c.LowestEfficiencyThresholdString, c.HighestWastedBytesString, c.HighestUserWastedPercentString) if err != nil { return err } c.List = append(c.List, rules...) return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/ci.go
cmd/dive/cli/internal/options/ci.go
package options import ( "fmt" "github.com/anchore/clio" "gopkg.in/yaml.v3" "os" ) var _ interface { clio.PostLoader clio.FieldDescriber clio.FlagAdder } = (*CI)(nil) const defaultCIConfigPath = ".dive-ci" type CI struct { Enabled bool `yaml:"ci" mapstructure:"ci"` ConfigPath string `yaml:"ci-config" mapstructure:"ci-config"` Rules CIRules `yaml:"rules" mapstructure:"rules"` } func DefaultCI() CI { return CI{ Enabled: false, ConfigPath: defaultCIConfigPath, Rules: DefaultCIRules(), } } func (c *CI) DescribeFields(descriptions clio.FieldDescriptionSet) { descriptions.Add(&c.Enabled, "enable CI mode") descriptions.Add(&c.ConfigPath, "path to the CI config file") } func (c *CI) AddFlags(flags clio.FlagSet) { flags.BoolVarP(&c.Enabled, "ci", "", "skip the interactive TUI and validate against CI rules (same as env var CI=true)") flags.StringVarP(&c.ConfigPath, "ci-config", "", "if CI=true in the environment, use the given yaml to drive validation rules.") } func (c *CI) PostLoad() error { enabledFromEnv := truthy(os.Getenv("CI")) if !c.Enabled && enabledFromEnv { c.Enabled = true } if c.ConfigPath != "" { if fileExists(c.ConfigPath) { // if a config file is provided, load it and override any values provided in the application config. // If we're hitting this case we should pretend that only the config file was provided and applied // on top of the default config values. yamlFile, err := os.ReadFile(c.ConfigPath) if err != nil { return fmt.Errorf("failed to read CI config file %s: %w", c.ConfigPath, err) } def := DefaultCIRules() r := legacyRuleFile{ LowestEfficiencyThresholdString: def.LowestEfficiencyThresholdString, HighestWastedBytesString: def.HighestWastedBytesString, HighestUserWastedPercentString: def.HighestUserWastedPercentString, } wrapper := struct { Rules *legacyRuleFile `yaml:"rules"` }{ Rules: &r, } if err := yaml.Unmarshal(yamlFile, &wrapper); err != nil { return fmt.Errorf("failed to unmarshal CI config file %s: %w", c.ConfigPath, err) } // TODO: should this be a deprecated use warning in the future? c.Rules = CIRules{ LowestEfficiencyThresholdString: r.LowestEfficiencyThresholdString, HighestWastedBytesString: r.HighestWastedBytesString, HighestUserWastedPercentString: r.HighestUserWastedPercentString, } } } return nil } type legacyRuleFile struct { LowestEfficiencyThresholdString string `yaml:"lowestEfficiency"` HighestWastedBytesString string `yaml:"highestWastedBytes"` HighestUserWastedPercentString string `yaml:"highestUserWastedPercent"` } func fileExists(path string) bool { if _, err := os.Stat(path); os.IsNotExist(err) { return false } return true } func truthy(value string) bool { switch value { case "true", "1", "yes": return true case "false", "0", "no": return false default: return false } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/ui_diff.go
cmd/dive/cli/internal/options/ui_diff.go
package options import ( "github.com/anchore/clio" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "github.com/wagoodman/dive/internal/log" ) var _ interface { clio.PostLoader clio.FieldDescriber } = (*UIDiff)(nil) // UIDiff provides configuration for how differences are displayed type UIDiff struct { Hide []string `yaml:"hide" mapstructure:"hide"` } func DefaultUIDiff() UIDiff { prefs := v1.DefaultPreferences() return UIDiff{ Hide: prefs.FiletreeDiffHide, } } func (c *UIDiff) DescribeFields(descriptions clio.FieldDescriptionSet) { descriptions.Add(&c.Hide, "types of file differences to hide (added, removed, modified, unmodified)") } func (c *UIDiff) PostLoad() error { validHideValues := map[string]bool{"added": true, "removed": true, "modified": true, "unmodified": true} for _, value := range c.Hide { if _, ok := validHideValues[value]; !ok { log.Warnf("invalid diff hide value: %s (valid values: added, removed, modified, unmodified)", value) } } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/ui_keybindings.go
cmd/dive/cli/internal/options/ui_keybindings.go
package options import ( "github.com/anchore/clio" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/key" "reflect" ) var _ interface { clio.FieldDescriber } = (*UIKeybindings)(nil) // UIKeybindings provides configuration for all keyboard shortcuts type UIKeybindings struct { Global GlobalBindings `yaml:",inline" mapstructure:",squash"` Navigation NavigationBindings `yaml:",inline" mapstructure:",squash"` Layer LayerBindings `yaml:",inline" mapstructure:",squash"` Filetree FiletreeBindings `yaml:",inline" mapstructure:",squash"` Config key.Bindings `yaml:"-" mapstructure:"-"` } type GlobalBindings struct { Quit string `yaml:"quit" mapstructure:"quit"` ToggleView string `yaml:"toggle-view" mapstructure:"toggle-view"` FilterFiles string `yaml:"filter-files" mapstructure:"filter-files"` CloseFilterFiles string `yaml:"close-filter-files" mapstructure:"close-filter-files"` } type NavigationBindings struct { Up string `yaml:"up" mapstructure:"up"` Down string `yaml:"down" mapstructure:"down"` Left string `yaml:"left" mapstructure:"left"` Right string `yaml:"right" mapstructure:"right"` PageUp string `yaml:"page-up" mapstructure:"page-up"` PageDown string `yaml:"page-down" mapstructure:"page-down"` } type LayerBindings struct { CompareAll string `yaml:"compare-all" mapstructure:"compare-all"` CompareLayer string `yaml:"compare-layer" mapstructure:"compare-layer"` } type FiletreeBindings struct { ToggleCollapseDir string `yaml:"toggle-collapse-dir" mapstructure:"toggle-collapse-dir"` ToggleCollapseAllDir string `yaml:"toggle-collapse-all-dir" mapstructure:"toggle-collapse-all-dir"` ToggleAddedFiles string `yaml:"toggle-added-files" mapstructure:"toggle-added-files"` ToggleRemovedFiles string `yaml:"toggle-removed-files" mapstructure:"toggle-removed-files"` ToggleModifiedFiles string `yaml:"toggle-modified-files" mapstructure:"toggle-modified-files"` ToggleUnmodifiedFiles string `yaml:"toggle-unmodified-files" mapstructure:"toggle-unmodified-files"` ToggleTreeAttributes string `yaml:"toggle-filetree-attributes" mapstructure:"toggle-filetree-attributes"` ToggleSortOrder string `yaml:"toggle-sort-order" mapstructure:"toggle-sort-order"` ToggleWrapTree string `yaml:"toggle-wrap-tree" mapstructure:"toggle-wrap-tree"` ExtractFile string `yaml:"extract-file" mapstructure:"extract-file"` } func DefaultUIKeybinding() UIKeybindings { var result UIKeybindings defaults := key.DefaultBindings() // converts from key.Bindings to UIKeybindings getUIBindingValues(reflect.ValueOf(defaults), reflect.ValueOf(&result).Elem()) return result } func getUIBindingValues(src, dst reflect.Value) { switch src.Kind() { case reflect.Struct: for i := 0; i < src.NumField(); i++ { srcField := src.Field(i) srcType := src.Type().Field(i) if !srcField.CanInterface() { continue } dstField := dst.FieldByName(srcType.Name) if !dstField.IsValid() || !dstField.CanSet() { continue } if srcType.Type.Name() == "Config" { inputField := srcField.FieldByName("Input") if inputField.IsValid() && dstField.Kind() == reflect.String { dstField.SetString(inputField.String()) } continue } getUIBindingValues(srcField, dstField) } } } func (c *UIKeybindings) PostLoad() error { cfg := key.Bindings{} // convert UIKeybindings to key.Bindings err := createKeyBindings(reflect.ValueOf(c).Elem(), reflect.ValueOf(&cfg).Elem()) if err != nil { return err } c.Config = cfg return nil } func createKeyBindings(src, dst reflect.Value) error { switch dst.Kind() { case reflect.Struct: for i := 0; i < dst.NumField(); i++ { dstField := dst.Field(i) dstType := dst.Type().Field(i) if !dstField.CanSet() { continue } srcField := src.FieldByName(dstType.Name) if !srcField.IsValid() { continue } if dstType.Type.Name() == "Config" { inputField := dstField.FieldByName("Input") if inputField.IsValid() && inputField.CanSet() && srcField.Kind() == reflect.String { inputField.SetString(srcField.String()) // call the Setup method if it exists setupMethod := dstField.Addr().MethodByName("Setup") if setupMethod.IsValid() { result := setupMethod.Call([]reflect.Value{}) if !result[0].IsNil() { return result[0].Interface().(error) } } } continue } err := createKeyBindings(srcField, dstField) if err != nil { return err } } } return nil } func (c *UIKeybindings) DescribeFields(descriptions clio.FieldDescriptionSet) { // global keybindings descriptions.Add(&c.Global.Quit, "quit the application (global)") descriptions.Add(&c.Global.ToggleView, "toggle between different views (global)") descriptions.Add(&c.Global.FilterFiles, "filter files by name (global)") descriptions.Add(&c.Global.CloseFilterFiles, "close file filtering (global)") // navigation keybindings descriptions.Add(&c.Navigation.Up, "move cursor up (global)") descriptions.Add(&c.Navigation.Down, "move cursor down (global)") descriptions.Add(&c.Navigation.Left, "move cursor left (global)") descriptions.Add(&c.Navigation.Right, "move cursor right (global)") descriptions.Add(&c.Navigation.PageUp, "scroll page up (file view)") descriptions.Add(&c.Navigation.PageDown, "scroll page down (file view)") // layer view keybindings descriptions.Add(&c.Layer.CompareAll, "compare all layers (layer view)") descriptions.Add(&c.Layer.CompareLayer, "compare specific layer (layer view)") // file view keybindings descriptions.Add(&c.Filetree.ToggleCollapseDir, "toggle directory collapse (file view)") descriptions.Add(&c.Filetree.ToggleCollapseAllDir, "toggle collapse all directories (file view)") descriptions.Add(&c.Filetree.ToggleAddedFiles, "toggle visibility of added files (file view)") descriptions.Add(&c.Filetree.ToggleRemovedFiles, "toggle visibility of removed files (file view)") descriptions.Add(&c.Filetree.ToggleModifiedFiles, "toggle visibility of modified files (file view)") descriptions.Add(&c.Filetree.ToggleUnmodifiedFiles, "toggle visibility of unmodified files (file view)") descriptions.Add(&c.Filetree.ToggleTreeAttributes, "toggle display of file attributes (file view)") descriptions.Add(&c.Filetree.ToggleSortOrder, "toggle sort order (file view)") descriptions.Add(&c.Filetree.ExtractFile, "extract file contents (file view)") }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/ui_layers.go
cmd/dive/cli/internal/options/ui_layers.go
package options import "github.com/anchore/clio" var _ clio.FieldDescriber = (*UILayers)(nil) // UILayers provides configuration for layer display behavior type UILayers struct { ShowAggregatedChanges bool `yaml:"show-aggregated-changes" mapstructure:"show-aggregated-changes"` } func DefaultUILayers() UILayers { return UILayers{ ShowAggregatedChanges: false, } } func (c *UILayers) DescribeFields(descriptions clio.FieldDescriptionSet) { descriptions.Add(&c.ShowAggregatedChanges, "show aggregated changes across all previous layers") }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/export.go
cmd/dive/cli/internal/options/export.go
package options import ( "fmt" "os" "path" "github.com/anchore/clio" ) var _ interface { clio.FlagAdder clio.PostLoader } = (*Export)(nil) // Export provides configuration for data export functionality type Export struct { // Path to export analysis results as JSON (empty string = disabled) JsonPath string `yaml:"json-path" json:"json-path" mapstructure:"json-path"` } func DefaultExport() Export { return Export{} } func (o *Export) AddFlags(flags clio.FlagSet) { flags.StringVarP(&o.JsonPath, "json", "j", "Skip the interactive TUI and write the layer analysis statistics to a given file.") } func (o *Export) PostLoad() error { if o.JsonPath != "" { dir := path.Dir(o.JsonPath) if _, err := os.Stat(dir); os.IsNotExist(err) { return fmt.Errorf("directory for JSON export does not exist: %s", dir) } } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/ui.go
cmd/dive/cli/internal/options/ui.go
package options // UI combines all UI configuration elements type UI struct { Keybinding UIKeybindings `yaml:"keybinding" mapstructure:"keybinding"` Diff UIDiff `yaml:"diff" mapstructure:"diff"` Filetree UIFiletree `yaml:"filetree" mapstructure:"filetree"` Layer UILayers `yaml:"layer" mapstructure:"layer"` } func DefaultUI() UI { return UI{ Keybinding: DefaultUIKeybinding(), Diff: DefaultUIDiff(), Filetree: DefaultUIFiletree(), Layer: DefaultUILayers(), } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/application.go
cmd/dive/cli/internal/options/application.go
package options import ( "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" ) type Application struct { Analysis Analysis `yaml:",inline" mapstructure:",squash"` CI CI `yaml:",inline" mapstructure:",squash"` Export Export `yaml:",inline" mapstructure:",squash"` UI UI `yaml:",inline" mapstructure:",squash"` } func DefaultApplication() Application { return Application{ Analysis: DefaultAnalysis(), CI: DefaultCI(), Export: DefaultExport(), UI: DefaultUI(), } } func (c Application) V1Preferences() v1.Preferences { return v1.Preferences{ KeyBindings: c.UI.Keybinding.Config, ShowFiletreeAttributes: c.UI.Filetree.ShowAttributes, ShowAggregatedLayerChanges: c.UI.Layer.ShowAggregatedChanges, CollapseFiletreeDirectory: c.UI.Filetree.CollapseDir, FiletreePaneWidth: c.UI.Filetree.PaneWidth, FiletreeDiffHide: nil, } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/ui_filetree.go
cmd/dive/cli/internal/options/ui_filetree.go
package options import ( "github.com/anchore/clio" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "github.com/wagoodman/dive/internal/log" ) var _ interface { clio.PostLoader clio.FieldDescriber } = (*UIFiletree)(nil) // UIFiletree provides configuration for the file tree display type UIFiletree struct { CollapseDir bool `yaml:"collapse-dir" mapstructure:"collapse-dir"` PaneWidth float64 `yaml:"pane-width" mapstructure:"pane-width"` ShowAttributes bool `yaml:"show-attributes" mapstructure:"show-attributes"` } func DefaultUIFiletree() UIFiletree { prefs := v1.DefaultPreferences() return UIFiletree{ CollapseDir: prefs.CollapseFiletreeDirectory, PaneWidth: prefs.FiletreePaneWidth, ShowAttributes: prefs.ShowFiletreeAttributes, } } func (c *UIFiletree) DescribeFields(descriptions clio.FieldDescriptionSet) { descriptions.Add(&c.CollapseDir, "collapse directories by default in the filetree") descriptions.Add(&c.PaneWidth, "percentage of screen width for the filetree pane (must be >0 and <1)") descriptions.Add(&c.ShowAttributes, "show file attributes in the filetree view") } func (c *UIFiletree) PostLoad() error { // Validate pane width is between 0 and 1 if c.PaneWidth <= 0 || c.PaneWidth >= 1 { log.Warnf("filetree pane-width must be >0 and <1, got %v, resetting to default 0.5", c.PaneWidth) c.PaneWidth = 0.5 } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/options/analysis.go
cmd/dive/cli/internal/options/analysis.go
package options import ( "fmt" "github.com/anchore/clio" "github.com/scylladb/go-set/strset" "github.com/wagoodman/dive/dive" "github.com/wagoodman/dive/internal/log" "strings" ) const defaultContainerEngine = "docker" var _ interface { clio.PostLoader clio.FieldDescriber } = (*Analysis)(nil) // Analysis provides configuration for the image analysis behavior type Analysis struct { Image string `yaml:"image" mapstructure:"-"` ContainerEngine string `yaml:"container-engine" mapstructure:"container-engine"` Source dive.ImageSource `yaml:"-" mapstructure:"-"` IgnoreErrors bool `yaml:"ignore-errors" mapstructure:"ignore-errors"` AvailableContainerEngines []string `yaml:"-" mapstructure:"-"` } func DefaultAnalysis() Analysis { return Analysis{ ContainerEngine: defaultContainerEngine, IgnoreErrors: false, AvailableContainerEngines: dive.ImageSources, } } func (c *Analysis) DescribeFields(descriptions clio.FieldDescriptionSet) { descriptions.Add(&c.ContainerEngine, "container engine to use for image analysis (supported options: 'docker' and 'podman')") descriptions.Add(&c.IgnoreErrors, "continue with analysis even if there are errors parsing the image archive") } func (c *Analysis) AddFlags(flags clio.FlagSet) { flags.StringVarP(&c.ContainerEngine, "source", "", fmt.Sprintf("The container engine to fetch the image from. Allowed values: %s", strings.Join(c.AvailableContainerEngines, ", "))) flags.BoolVarP(&c.IgnoreErrors, "ignore-errors", "i", "ignore image parsing errors and run the analysis anyway") } func (c *Analysis) PostLoad() error { validEngines := strset.New(c.AvailableContainerEngines...) if !validEngines.Has(c.ContainerEngine) { log.Warnf("invalid container engine: %s (valid options: %s), using default %q", c.ContainerEngine, strings.Join(c.AvailableContainerEngines, ", "), defaultContainerEngine) c.ContainerEngine = "docker" } if c.Image != "" { sourceType, imageStr := dive.DeriveImageSource(c.Image) if sourceType == dive.SourceUnknown { sourceType = dive.ParseImageSource(c.ContainerEngine) if sourceType == dive.SourceUnknown { return fmt.Errorf("unable to determine image source from %q: %v\n", c.Image, c.ContainerEngine) } // use exactly what the user provided imageStr = c.Image } c.Image = imageStr c.Source = sourceType } else { c.Source = dive.ParseImageSource(c.ContainerEngine) } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/root.go
cmd/dive/cli/internal/command/root.go
package command import ( "context" "errors" "fmt" "github.com/anchore/clio" "github.com/spf13/afero" "github.com/spf13/cobra" "github.com/wagoodman/dive/cmd/dive/cli/internal/command/adapter" "github.com/wagoodman/dive/cmd/dive/cli/internal/options" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui" "github.com/wagoodman/dive/dive" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/bus" "os" ) type rootOptions struct { options.Application `yaml:",inline" mapstructure:",squash"` // reserved for future use of root-only flags } func Root(app clio.Application) *cobra.Command { opts := &rootOptions{ Application: options.DefaultApplication(), } return app.SetupRootCommand(&cobra.Command{ Use: "dive [IMAGE]", Short: "Docker Image Visualizer & Explorer", Long: `This tool provides a way to discover and explore the contents of a docker image. Additionally the tool estimates the amount of wasted space and identifies the offending files from the image.`, Args: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { return fmt.Errorf("exactly one argument is required") } opts.Analysis.Image = args[0] return nil }, RunE: func(cmd *cobra.Command, _ []string) error { if err := setUI(app, opts.Application); err != nil { return fmt.Errorf("failed to set UI: %w", err) } resolver, err := dive.GetImageResolver(opts.Analysis.Source) if err != nil { return fmt.Errorf("cannot determine image provider to fetch from: %w", err) } ctx := cmd.Context() img, err := adapter.ImageResolver(resolver).Fetch(ctx, opts.Analysis.Image) if err != nil { return fmt.Errorf("cannot load image: %w", err) } return run(ctx, opts.Application, img, resolver) }, }, opts) } func setUI(app clio.Application, opts options.Application) error { type Stater interface { State() *clio.State } state := app.(Stater).State() ux := ui.NewV1UI(opts.V1Preferences(), os.Stdout, state.Config.Log.Quiet, state.Config.Log.Verbosity) return state.UI.Replace(ux) } func run(ctx context.Context, opts options.Application, img *image.Image, content image.ContentReader) error { analysis, err := adapter.NewAnalyzer().Analyze(ctx, img) if err != nil { return fmt.Errorf("cannot analyze image: %w", err) } if opts.Export.JsonPath != "" { if err := adapter.NewExporter(afero.NewOsFs()).ExportTo(ctx, analysis, opts.Export.JsonPath); err != nil { return fmt.Errorf("cannot export analysis: %w", err) } return nil } if opts.CI.Enabled { eval := adapter.NewEvaluator(opts.CI.Rules.List).Evaluate(ctx, analysis) if !eval.Pass { return errors.New("evaluation failed") } return nil } bus.ExploreAnalysis(*analysis, content) return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/build.go
cmd/dive/cli/internal/command/build.go
package command import ( "fmt" "github.com/anchore/clio" "github.com/spf13/cobra" "github.com/wagoodman/dive/cmd/dive/cli/internal/command/adapter" "github.com/wagoodman/dive/cmd/dive/cli/internal/options" "github.com/wagoodman/dive/dive" ) type buildOptions struct { options.Application `yaml:",inline" mapstructure:",squash"` // reserved for future use of build-only flags } func Build(app clio.Application) *cobra.Command { opts := &buildOptions{ Application: options.DefaultApplication(), } return app.SetupCommand(&cobra.Command{ Use: "build [any valid `docker build` arguments]", Short: "Builds and analyzes a docker image from a Dockerfile (this is a thin wrapper for the `docker build` command).", DisableFlagParsing: true, RunE: func(cmd *cobra.Command, args []string) error { if err := setUI(app, opts.Application); err != nil { return fmt.Errorf("failed to set UI: %w", err) } resolver, err := dive.GetImageResolver(opts.Analysis.Source) if err != nil { return fmt.Errorf("cannot determine image provider for build: %w", err) } ctx := cmd.Context() img, err := adapter.ImageResolver(resolver).Build(ctx, args) if err != nil { return fmt.Errorf("cannot build image: %w", err) } return run(cmd.Context(), opts.Application, img, resolver) }, }, opts) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/ci/rules.go
cmd/dive/cli/internal/command/ci/rules.go
package ci import ( "errors" "fmt" "github.com/dustin/go-humanize" "github.com/wagoodman/dive/dive/image" "strconv" "strings" ) const ( ciKeyLowestEfficiencyThreshold = "lowestEfficiency" ciKeyHighestWastedBytes = "highestWastedBytes" ciKeyHighestUserWastedPercent = "highestUserWastedPercent" ) func Rules(lowerEfficiency, highestWastedBytes, highestUserWastedPercent string) ([]Rule, error) { var rules []Rule var errs []error lowestEfficiencyRule, err := NewLowestEfficiencyRule(lowerEfficiency) if err != nil { errs = append(errs, err) } rules = append(rules, lowestEfficiencyRule) highestWastedBytesRule, err := NewHighestWastedBytesRule(highestWastedBytes) if err != nil { errs = append(errs, err) } rules = append(rules, highestWastedBytesRule) highestUserWastedPercentRule, err := NewHighestUserWastedPercentRule(highestUserWastedPercent) if err != nil { errs = append(errs, err) } rules = append(rules, highestUserWastedPercentRule) return rules, errors.Join(errs...) } func DisabledRule(key string) Rule { return &BaseRule{ key: key, configValue: "disabled", evaluator: func(_ *image.Analysis) (RuleStatus, string) { return RuleDisabled, "rule disabled" }, } } type BaseRule struct { key string configValue string status RuleStatus evaluator func(*image.Analysis) (RuleStatus, string) } func (rule *BaseRule) Key() string { return rule.key } func (rule *BaseRule) Configuration() string { return rule.configValue } func (rule *BaseRule) Evaluate(result *image.Analysis) (RuleStatus, string) { if rule.status != RuleUnknown { return rule.status, "" } return rule.evaluator(result) } // LowestEfficiencyRule checks if image efficiency is above threshold type LowestEfficiencyRule struct { BaseRule threshold float64 } // HighestWastedBytesRule checks if wasted bytes are below threshold type HighestWastedBytesRule struct { BaseRule threshold uint64 } // HighestUserWastedPercentRule checks if percentage of wasted bytes is below threshold type HighestUserWastedPercentRule struct { BaseRule threshold float64 } func NewLowestEfficiencyRule(configValue string) (Rule, error) { if isRuleDisabled(configValue) { return DisabledRule(ciKeyLowestEfficiencyThreshold), nil } threshold, err := strconv.ParseFloat(configValue, 64) if err != nil { return nil, fmt.Errorf("invalid %s config value, given %q: %v", ciKeyLowestEfficiencyThreshold, configValue, err) } if threshold < 0 || threshold > 1 { return nil, fmt.Errorf("%s config value is outside allowed range (0-1), given '%f'", ciKeyLowestEfficiencyThreshold, threshold) } return &LowestEfficiencyRule{ BaseRule: BaseRule{ key: ciKeyLowestEfficiencyThreshold, configValue: configValue, }, threshold: threshold, }, nil } func (r *LowestEfficiencyRule) Evaluate(analysis *image.Analysis) (RuleStatus, string) { if r.threshold > analysis.Efficiency { return RuleFailed, fmt.Sprintf( "image efficiency is too low (efficiency=%2.2f < threshold=%v)", analysis.Efficiency, r.threshold) } return RulePassed, "" } // NewHighestWastedBytesRule creates a new rule to check wasted bytes func NewHighestWastedBytesRule(configValue string) (Rule, error) { if isRuleDisabled(configValue) { return DisabledRule(ciKeyHighestWastedBytes), nil } threshold, err := humanize.ParseBytes(configValue) if err != nil { return nil, fmt.Errorf("invalid highestWastedBytes config value, given %q: %v", configValue, err) } return &HighestWastedBytesRule{ BaseRule: BaseRule{ key: ciKeyHighestWastedBytes, configValue: configValue, }, threshold: threshold, }, nil } func (r *HighestWastedBytesRule) Evaluate(analysis *image.Analysis) (RuleStatus, string) { if analysis.WastedBytes > r.threshold { return RuleFailed, fmt.Sprintf( "too many bytes wasted (wasted-bytes=%d > threshold=%v)", analysis.WastedBytes, r.threshold) } return RulePassed, "" } // NewHighestUserWastedPercentRule creates a new rule to check percentage of wasted bytes func NewHighestUserWastedPercentRule(configValue string) (Rule, error) { if isRuleDisabled(configValue) { return DisabledRule(ciKeyHighestUserWastedPercent), nil } threshold, err := strconv.ParseFloat(configValue, 64) if err != nil { return nil, fmt.Errorf("invalid highestUserWastedPercent config value, given %q: %v", configValue, err) } if threshold < 0 || threshold > 1 { return nil, fmt.Errorf("highestUserWastedPercent config value is outside allowed range (0-1), given '%f'", threshold) } return &HighestUserWastedPercentRule{ BaseRule: BaseRule{ key: ciKeyHighestUserWastedPercent, configValue: configValue, }, threshold: threshold, }, nil } func (r *HighestUserWastedPercentRule) Evaluate(analysis *image.Analysis) (RuleStatus, string) { if analysis.WastedUserPercent > r.threshold { return RuleFailed, fmt.Sprintf( "too many bytes wasted, relative to the user bytes added (%%-user-wasted-bytes=%2.2f > threshold=%v)", analysis.WastedUserPercent, r.threshold) } return RulePassed, "" } func isRuleDisabled(value string) bool { value = strings.TrimSpace(strings.ToLower(value)) return value == "" || value == "disabled" || value == "off" || value == "false" }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/ci/evaluator_test.go
cmd/dive/cli/internal/command/ci/evaluator_test.go
package ci import ( "context" "github.com/stretchr/testify/require" "go.uber.org/atomic" "os/exec" "path/filepath" "strings" "testing" "github.com/wagoodman/dive/dive/image/docker" ) var repoRootCache atomic.String func Test_Evaluator(t *testing.T) { result := docker.TestAnalysisFromArchive(t, repoPath(t, ".data/test-docker-image.tar")) validTests := []struct { name string efficiency string wastedBytes string wastedPercent string expectedPass bool expectedResult map[string]RuleStatus }{ { name: "allFail", efficiency: "0.99", wastedBytes: "1B", wastedPercent: "0.01", expectedPass: false, expectedResult: map[string]RuleStatus{ "lowestEfficiency": RuleFailed, "highestWastedBytes": RuleFailed, "highestUserWastedPercent": RuleFailed, }, }, { name: "allPass", efficiency: "0.9", wastedBytes: "50kB", wastedPercent: "0.5", expectedPass: true, expectedResult: map[string]RuleStatus{ "lowestEfficiency": RulePassed, "highestWastedBytes": RulePassed, "highestUserWastedPercent": RulePassed, }, }, { name: "allDisabled", efficiency: "disabled", wastedBytes: "disabled", wastedPercent: "disabled", expectedPass: true, expectedResult: map[string]RuleStatus{ "lowestEfficiency": RuleDisabled, "highestWastedBytes": RuleDisabled, "highestUserWastedPercent": RuleDisabled, }, }, { name: "mixedResults", efficiency: "0.9", wastedBytes: "1B", wastedPercent: "0.5", expectedPass: false, expectedResult: map[string]RuleStatus{ "lowestEfficiency": RulePassed, "highestWastedBytes": RuleFailed, "highestUserWastedPercent": RulePassed, }, }, } for _, test := range validTests { t.Run(test.name, func(t *testing.T) { // Create rules - these should not error rules, err := Rules(test.efficiency, test.wastedBytes, test.wastedPercent) require.NoError(t, err) evaluator := NewEvaluator(rules) eval := evaluator.Evaluate(context.TODO(), result) if test.expectedPass != eval.Pass { t.Errorf("expected pass=%v, got %v", test.expectedPass, eval.Pass) } if len(test.expectedResult) != len(evaluator.Results) { t.Errorf("expected %v results, got %v", len(test.expectedResult), len(evaluator.Results)) } for rule, actualResult := range evaluator.Results { expectedStatus := test.expectedResult[rule] if expectedStatus != actualResult.status { t.Errorf("%v: expected %v rule status, got %v: %v", rule, expectedStatus, actualResult.status, actualResult) } } }) } } func Test_Evaluator_Misconfigurations(t *testing.T) { invalidTests := []struct { name string efficiency string wastedBytes string wastedPercent string expectError bool }{ { name: "invalid_efficiency_too_high", efficiency: "1.1", // fail! wastedBytes: "50kB", wastedPercent: "0.5", expectError: true, }, { name: "invalid_efficiency_too_low", efficiency: "-0.1", // fail! wastedBytes: "50kB", wastedPercent: "0.5", expectError: true, }, { name: "invalid_efficiency_format", efficiency: "not_a_number", // fail! wastedBytes: "50kB", wastedPercent: "0.5", expectError: true, }, { name: "invalid_wasted_bytes_format", efficiency: "0.9", wastedBytes: "not_a_size", // fail! wastedPercent: "0.5", expectError: true, }, { name: "invalid_wasted_percent_high", efficiency: "0.9", wastedBytes: "50kB", wastedPercent: "1.1", // fail! expectError: true, }, { name: "invalid_wasted_percent_low", efficiency: "0.9", wastedBytes: "50kB", wastedPercent: "-0.1", // fail! expectError: true, }, { name: "invalid_wasted_percent_format", efficiency: "0.9", wastedBytes: "50kB", wastedPercent: "not_a_number", // fail! expectError: true, }, } for _, test := range invalidTests { t.Run(test.name, func(t *testing.T) { _, err := Rules(test.efficiency, test.wastedBytes, test.wastedPercent) if test.expectError { require.Error(t, err, "Expected an error for invalid configuration") } else { require.NoError(t, err, "Expected no error for valid configuration") } }) } } func repoPath(t testing.TB, path string) string { t.Helper() root := repoRoot(t) return filepath.Join(root, path) } func repoRoot(t testing.TB) string { val := repoRootCache.Load() if val != "" { return val } t.Helper() // use git to find the root of the repo out, err := exec.Command("git", "rev-parse", "--show-toplevel").Output() if err != nil { t.Fatalf("failed to get repo root: %v", err) } val = strings.TrimSpace(string(out)) repoRootCache.Store(val) return val }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/ci/rule.go
cmd/dive/cli/internal/command/ci/rule.go
package ci import ( "github.com/wagoodman/dive/dive/image" ) const ( RuleUnknown = iota RulePassed RuleFailed RuleWarning RuleDisabled RuleMisconfigured RuleConfigured ) type Rule interface { Key() string Configuration() string Evaluate(result *image.Analysis) (RuleStatus, string) } type RuleStatus int type RuleResult struct { status RuleStatus message string } func (status RuleStatus) String(f format) string { switch status { case RulePassed: return f.Success.Render("PASS") case RuleFailed: return f.Failure.Render("FAIL") case RuleWarning: return f.Warning.Render("WARN") case RuleDisabled: return f.Disabled.Render("SKIP") case RuleMisconfigured: return f.Warning.Render("MISCONFIGURED") case RuleConfigured: return "CONFIGURED " default: return f.Warning.Render("Unknown") } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/ci/evaluator.go
cmd/dive/cli/internal/command/ci/evaluator.go
package ci import ( "fmt" "github.com/charmbracelet/lipgloss" "golang.org/x/net/context" "sort" "strconv" "strings" "github.com/dustin/go-humanize" "github.com/wagoodman/dive/dive/image" ) type Evaluation struct { Report string Pass bool } type Evaluator struct { Rules []Rule Results map[string]RuleResult Tally ResultTally Pass bool Misconfigured bool InefficientFiles []ReferenceFile format format } type format struct { Title lipgloss.Style Success lipgloss.Style Warning lipgloss.Style Disabled lipgloss.Style Failure lipgloss.Style TableHeader lipgloss.Style Label lipgloss.Style Aux lipgloss.Style Value lipgloss.Style } type ResultTally struct { Pass int Fail int Skip int Warn int Total int } type ReferenceFile struct { References int `json:"count"` SizeBytes uint64 `json:"sizeBytes"` Path string `json:"file"` } func NewEvaluator(rules []Rule) Evaluator { return Evaluator{ Rules: rules, Results: make(map[string]RuleResult), Pass: true, format: format{ Title: lipgloss.NewStyle().Bold(true), Success: lipgloss.NewStyle().Foreground(lipgloss.Color("2")), Warning: lipgloss.NewStyle().Foreground(lipgloss.Color("3")), Disabled: lipgloss.NewStyle().Faint(true), Failure: lipgloss.NewStyle().Foreground(lipgloss.Color("1")).Bold(true), TableHeader: lipgloss.NewStyle().Bold(true), Label: lipgloss.NewStyle().Width(18), Aux: lipgloss.NewStyle().Faint(true), Value: lipgloss.NewStyle(), }, } } func (e Evaluator) isRuleEnabled(rule Rule) bool { return rule.Configuration() != "disabled" } func (e Evaluator) Evaluate(ctx context.Context, analysis *image.Analysis) Evaluation { for _, rule := range e.Rules { if !e.isRuleEnabled(rule) { e.Results[rule.Key()] = RuleResult{ status: RuleConfigured, message: "rule disabled", } continue } e.Results[rule.Key()] = RuleResult{ status: RuleConfigured, message: "test", } } // capture inefficient files for idx := 0; idx < len(analysis.Inefficiencies); idx++ { fileData := analysis.Inefficiencies[len(analysis.Inefficiencies)-1-idx] e.InefficientFiles = append(e.InefficientFiles, ReferenceFile{ References: len(fileData.Nodes), SizeBytes: uint64(fileData.CumulativeSize), Path: fileData.Path, }) } // evaluate results against the configured CI rules for _, rule := range e.Rules { if !e.isRuleEnabled(rule) { e.Results[rule.Key()] = RuleResult{ status: RuleDisabled, message: "disabled", } continue } status, message := rule.Evaluate(analysis) if value, exists := e.Results[rule.Key()]; exists && value.status != RuleConfigured && value.status != RuleMisconfigured { panic(fmt.Errorf("CI rule result recorded twice: %s", rule.Key())) } if status == RuleFailed { e.Pass = false } if message == "" { message = rule.Configuration() } e.Results[rule.Key()] = RuleResult{ status: status, message: message, } } e.Tally.Total = len(e.Results) for rule, result := range e.Results { switch result.status { case RulePassed: e.Tally.Pass++ case RuleFailed: e.Tally.Fail++ case RuleWarning: e.Tally.Warn++ case RuleDisabled: e.Tally.Skip++ default: panic(fmt.Errorf("unknown test status (rule='%v'): %v", rule, result.status)) } } return Evaluation{ Report: e.report(analysis), Pass: e.Pass, } } func (e Evaluator) report(analysis *image.Analysis) string { sections := []string{ e.renderAnalysisSection(analysis), e.renderInefficientFilesSection(analysis), e.renderEvaluationSection(), } return strings.Join(sections, "\n\n") } func (e Evaluator) renderAnalysisSection(analysis *image.Analysis) string { wastedByteStr := "" userWastedPercent := "0 %" if analysis.WastedBytes > 0 { wastedByteStr = fmt.Sprintf("(%s)", humanize.Bytes(analysis.WastedBytes)) userWastedPercent = fmt.Sprintf("%.2f %%", analysis.WastedUserPercent*100) } title := e.format.Title.Render("Analysis:") rows := []string{ formatKeyValue(e.format, "efficiency", fmt.Sprintf("%.2f %%", analysis.Efficiency*100)), formatKeyValue(e.format, "wastedBytes", fmt.Sprintf("%d bytes %s", analysis.WastedBytes, wastedByteStr)), formatKeyValue(e.format, "userWastedPercent", userWastedPercent), } return title + "\n" + strings.Join(rows, "\n") } func (e Evaluator) renderInefficientFilesSection(analysis *image.Analysis) string { title := e.format.Title.Render("Inefficient Files:") if len(analysis.Inefficiencies) == 0 { return title + " (None)" } header := e.format.TableHeader.Render( fmt.Sprintf(" %-5s %-12s %-s", "Count", "Wasted Space", "File Path"), ) rows := []string{header} for _, file := range e.InefficientFiles { row := fmt.Sprintf(" %-5s %-12s %-s", strconv.Itoa(file.References), humanize.Bytes(file.SizeBytes), file.Path, ) rows = append(rows, row) } return title + "\n" + strings.Join(rows, "\n") } func (e Evaluator) renderEvaluationSection() string { title := e.format.Title.Render("Evaluation:") // sort rules by name for consistent output rules := make([]string, 0, len(e.Results)) for name := range e.Results { rules = append(rules, name) } sort.Strings(rules) ruleResults := []string{} for _, rule := range rules { result := e.Results[rule] ruleResult := e.formatRuleResult(rule, result) ruleResults = append(ruleResults, ruleResult) } status := e.renderStatusSummary() return title + "\n" + strings.Join(ruleResults, "\n") + "\n\n" + status } func (e Evaluator) formatRuleResult(ruleName string, result RuleResult) string { var style lipgloss.Style textStyle := lipgloss.NewStyle() switch result.status { case RulePassed: style = e.format.Success case RuleFailed: style = e.format.Failure case RuleWarning, RuleMisconfigured: style = e.format.Warning case RuleDisabled: style = e.format.Disabled textStyle = e.format.Disabled default: style = lipgloss.NewStyle() } statusStr := style.Render(result.status.String(e.format)) if result.message != "" { return fmt.Sprintf(" %s %s", statusStr, textStyle.Render(ruleName+" ("+result.message+")")) } return fmt.Sprintf(" %s %s", statusStr, textStyle.Render(ruleName)) } func (e Evaluator) renderStatusSummary() string { if e.Misconfigured { return e.format.Failure.Render("CI Misconfigured") } status := "PASS" if e.Tally.Fail > 0 { status = "FAIL" } parts := []string{} type tallyItem struct { name string value int } items := []tallyItem{ //{"total", e.Tally.Total}, {"pass", e.Tally.Pass}, {"fail", e.Tally.Fail}, {"warn", e.Tally.Warn}, {"skip", e.Tally.Skip}, } for _, item := range items { if item.value > 0 { parts = append(parts, fmt.Sprintf("%s:%d", item.name, item.value)) } } auxSummary := e.format.Aux.Render(" [" + strings.Join(parts, " ") + "]") var style lipgloss.Style switch { case e.Pass && e.Tally.Warn == 0: style = e.format.Success case e.Pass && e.Tally.Warn > 0: style = e.format.Warning default: style = e.format.Failure } return style.Render(status) + auxSummary } func formatKeyValue(f format, key, value string) string { formattedKey := f.Label.Render(key + ":") return fmt.Sprintf(" %s %s", formattedKey, value) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/export/main_test.go
cmd/dive/cli/internal/command/export/main_test.go
package export import ( "flag" "github.com/charmbracelet/lipgloss" snapsPkg "github.com/gkampitakis/go-snaps/snaps" "github.com/muesli/termenv" "github.com/stretchr/testify/require" "go.uber.org/atomic" "os" "os/exec" "path/filepath" "strings" "testing" ) var ( updateSnapshot = flag.Bool("update", false, "update any test snapshots") snaps *snapsPkg.Config repoRootCache atomic.String ) func TestMain(m *testing.M) { // flags are not parsed until after test.Main is called... flag.Parse() os.Unsetenv("DIVE_CONFIG") // disable colors lipgloss.SetColorProfile(termenv.Ascii) snaps = snapsPkg.WithConfig( snapsPkg.Update(*updateSnapshot), snapsPkg.Dir("testdata/snapshots"), ) v := m.Run() snapsPkg.Clean(m) os.Exit(v) } func TestUpdateSnapshotDisabled(t *testing.T) { require.False(t, *updateSnapshot, "update snapshot flag should be disabled") } func repoPath(t testing.TB, path string) string { t.Helper() root := repoRoot(t) return filepath.Join(root, path) } func repoRoot(t testing.TB) string { val := repoRootCache.Load() if val != "" { return val } t.Helper() // use git to find the root of the repo out, err := exec.Command("git", "rev-parse", "--show-toplevel").Output() if err != nil { t.Fatalf("failed to get repo root: %v", err) } val = strings.TrimSpace(string(out)) repoRootCache.Store(val) return val }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/export/export.go
cmd/dive/cli/internal/command/export/export.go
package export import ( "encoding/json" "github.com/wagoodman/dive/dive/filetree" diveImage "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/log" ) type Export struct { Layer []Layer `json:"layer"` Image Image `json:"image"` } type Layer struct { Index int `json:"index"` ID string `json:"id"` DigestID string `json:"digestId"` SizeBytes uint64 `json:"sizeBytes"` Command string `json:"command"` FileList []filetree.FileInfo `json:"fileList"` } type Image struct { SizeBytes uint64 `json:"sizeBytes"` InefficientBytes uint64 `json:"inefficientBytes"` EfficiencyScore float64 `json:"efficiencyScore"` InefficientFiles []FileReference `json:"fileReference"` } type FileReference struct { References int `json:"count"` SizeBytes uint64 `json:"sizeBytes"` Path string `json:"file"` } // NewExport exports the analysis to a JSON func NewExport(analysis *diveImage.Analysis) *Export { data := Export{ Layer: make([]Layer, len(analysis.Layers)), Image: Image{ InefficientFiles: make([]FileReference, len(analysis.Inefficiencies)), SizeBytes: analysis.SizeBytes, EfficiencyScore: analysis.Efficiency, InefficientBytes: analysis.WastedBytes, }, } // export layers in order for idx, curLayer := range analysis.Layers { layerFileList := make([]filetree.FileInfo, 0) visitor := func(node *filetree.FileNode) error { layerFileList = append(layerFileList, node.Data.FileInfo) return nil } err := curLayer.Tree.VisitDepthChildFirst(visitor, nil) if err != nil { log.WithFields("layer", curLayer.Id, "error", err).Debug("unable to propagate layer tree") } data.Layer[idx] = Layer{ Index: curLayer.Index, ID: curLayer.Id, DigestID: curLayer.Digest, SizeBytes: curLayer.Size, Command: curLayer.Command, FileList: layerFileList, } } // add file references for idx := 0; idx < len(analysis.Inefficiencies); idx++ { fileData := analysis.Inefficiencies[len(analysis.Inefficiencies)-1-idx] data.Image.InefficientFiles[idx] = FileReference{ References: len(fileData.Nodes), SizeBytes: uint64(fileData.CumulativeSize), Path: fileData.Path, } } return &data } func (exp *Export) Marshal() ([]byte, error) { return json.MarshalIndent(&exp, "", " ") }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/export/export_test.go
cmd/dive/cli/internal/command/export/export_test.go
package export import ( "testing" "github.com/wagoodman/dive/dive/image/docker" ) func Test_Export(t *testing.T) { result := docker.TestAnalysisFromArchive(t, repoPath(t, ".data/test-docker-image.tar")) export := NewExport(result) payload, err := export.Marshal() if err != nil { t.Errorf("Test_Export: unable to export analysis: %v", err) } snaps.MatchJSON(t, payload) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/adapter/resolver.go
cmd/dive/cli/internal/command/adapter/resolver.go
package adapter import ( "context" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/bus" "github.com/wagoodman/dive/internal/bus/event/payload" "github.com/wagoodman/dive/internal/log" "strings" "time" ) type imageActionObserver struct { image.Resolver } func ImageResolver(resolver image.Resolver) image.Resolver { return imageActionObserver{ Resolver: resolver, } } func (i imageActionObserver) Build(ctx context.Context, options []string) (*image.Image, error) { log.Info("building image") log.Debugf("└── %s", strings.Join(options, " ")) mon := bus.StartTask(payload.GenericTask{ Title: payload.Title{ Default: "Building image", WhileRunning: "Building image", OnSuccess: "Built image", }, HideOnSuccess: false, HideStageOnSuccess: false, Context: "... " + strings.Join(options, " "), }) ctx = payload.SetGenericProgressToContext(ctx, mon) img, err := i.Resolver.Build(ctx, options) if err != nil { mon.SetError(err) } else { mon.SetCompleted() } return img, err } func (i imageActionObserver) Fetch(ctx context.Context, id string) (*image.Image, error) { log.WithFields("image", id).Info("fetching") log.Debugf("└── resolver: %s", i.Resolver.Name()) ctx, cancel := context.WithCancel(ctx) defer cancel() mon := bus.StartTask(payload.GenericTask{ Title: payload.Title{ Default: "Loading image", WhileRunning: "Loading image", OnSuccess: "Fetched image", }, HideOnSuccess: false, HideStageOnSuccess: false, ID: id, Context: id, }) ctx = payload.SetGenericProgressToContext(ctx, mon) go func() { // in 5 seconds if the context is not cancelled, log the message select { // nolint:gosimple case <-time.After(3 * time.Second): if ctx.Err() == nil { bus.Notify(" • this can take a while for large images...") mon.AtomicStage.Set("(this can take a while for large images)") // TODO: default level should be error for this to work when using the UI //log.Warn("this can take a while for large images") } } }() img, err := i.Resolver.Fetch(ctx, id) if err != nil { mon.SetError(err) } else { mon.SetCompleted() } return img, err }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/adapter/exporter.go
cmd/dive/cli/internal/command/adapter/exporter.go
package adapter import ( "context" "fmt" "github.com/spf13/afero" "github.com/wagoodman/dive/cmd/dive/cli/internal/command/export" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/bus" "github.com/wagoodman/dive/internal/bus/event/payload" "github.com/wagoodman/dive/internal/log" "os" ) type Exporter interface { ExportTo(ctx context.Context, img *image.Analysis, path string) error } type jsonExporter struct { filesystem afero.Fs } func NewExporter(fs afero.Fs) Exporter { return &jsonExporter{ filesystem: fs, } } func (e *jsonExporter) ExportTo(ctx context.Context, analysis *image.Analysis, path string) error { log.WithFields("path", path).Infof("exporting analysis") mon := bus.StartTask(payload.GenericTask{ Title: payload.Title{ Default: "Exporting details", WhileRunning: "Exporting details", OnSuccess: "Exported details", }, HideOnSuccess: false, HideStageOnSuccess: false, ID: analysis.Image, Context: fmt.Sprintf("[file: %s]", path), }) bytes, err := export.NewExport(analysis).Marshal() if err != nil { mon.SetError(err) return fmt.Errorf("cannot marshal export payload: %w", err) } else { mon.SetCompleted() } file, err := e.filesystem.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644) if err != nil { return fmt.Errorf("cannot open export file: %w", err) } defer file.Close() _, err = file.Write(bytes) if err != nil { return fmt.Errorf("cannot write to export file: %w", err) } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/adapter/analyzer.go
cmd/dive/cli/internal/command/adapter/analyzer.go
package adapter import ( "context" "fmt" "github.com/dustin/go-humanize" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/bus" "github.com/wagoodman/dive/internal/bus/event/payload" "github.com/wagoodman/dive/internal/log" ) type Analyzer interface { Analyze(ctx context.Context, img *image.Image) (*image.Analysis, error) } type analysisActionObserver struct { Analyzer func(context.Context, *image.Image) (*image.Analysis, error) } func NewAnalyzer() Analyzer { return analysisActionObserver{ Analyzer: image.Analyze, } } func (a analysisActionObserver) Analyze(ctx context.Context, img *image.Image) (*image.Analysis, error) { log.WithFields("image", img.Request).Infof("analyzing") layers := len(img.Layers) var files int var fileSize uint64 for _, layer := range img.Layers { files += layer.Tree.Size fileSize += layer.Tree.FileSize } fileSizeStr := humanize.Bytes(fileSize) filesStr := humanize.Comma(int64(files)) log.Debugf("├── layers: %d", layers) log.Debugf("├── files: %s", filesStr) log.Debugf("└── file size: %s", fileSizeStr) mon := bus.StartTask(payload.GenericTask{ Title: payload.Title{ Default: "Analyzing image", WhileRunning: "Analyzing image", OnSuccess: "Analyzed image", }, HideOnSuccess: false, HideStageOnSuccess: false, ID: img.Request, Context: fmt.Sprintf("[layers:%d files:%s size:%s]", layers, filesStr, fileSizeStr), }) analysis, err := a.Analyzer(ctx, img) if err != nil { mon.SetError(err) } else { mon.SetCompleted() } if err == nil && analysis == nil { err = fmt.Errorf("no results returned") } return analysis, err }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/command/adapter/evaluator.go
cmd/dive/cli/internal/command/adapter/evaluator.go
package adapter import ( "context" "fmt" "github.com/wagoodman/dive/cmd/dive/cli/internal/command/ci" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/bus" "github.com/wagoodman/dive/internal/bus/event/payload" "github.com/wagoodman/dive/internal/log" ) type Evaluator interface { Evaluate(ctx context.Context, analysis *image.Analysis) ci.Evaluation } type evaluationActionObserver struct { ci.Evaluator } func NewEvaluator(rules []ci.Rule) Evaluator { return evaluationActionObserver{ Evaluator: ci.NewEvaluator(rules), } } func (c evaluationActionObserver) Evaluate(ctx context.Context, analysis *image.Analysis) ci.Evaluation { log.WithFields("image", analysis.Image).Infof("evaluating image") mon := bus.StartTask(payload.GenericTask{ Title: payload.Title{ Default: "Evaluating image", WhileRunning: "Evaluating image", OnSuccess: "Evaluated image", }, HideOnSuccess: false, HideStageOnSuccess: false, ID: analysis.Image, Context: fmt.Sprintf("[rules: %d]", len(c.Rules)), }) eval := c.Evaluator.Evaluate(ctx, analysis) if eval.Pass { mon.SetCompleted() } else { mon.SetError(fmt.Errorf("failed evaluation")) } bus.Report(eval.Report) return eval }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/no_ui.go
cmd/dive/cli/internal/ui/no_ui.go
package ui import ( "github.com/wagoodman/go-partybus" "github.com/anchore/clio" ) var _ clio.UI = (*NoUI)(nil) type NoUI struct { subscription partybus.Unsubscribable } func None() *NoUI { return &NoUI{} } func (n *NoUI) Setup(subscription partybus.Unsubscribable) error { n.subscription = subscription return nil } func (n *NoUI) Handle(_ partybus.Event) error { return nil } func (n NoUI) Teardown(_ bool) error { return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1.go
cmd/dive/cli/internal/ui/v1.go
package ui import ( "context" "fmt" "github.com/anchore/clio" "github.com/anchore/go-logger/adapter/discard" "github.com/charmbracelet/lipgloss" "github.com/muesli/termenv" v1 "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/app" "github.com/wagoodman/dive/internal/bus/event" "github.com/wagoodman/dive/internal/bus/event/parser" "github.com/wagoodman/dive/internal/log" "github.com/wagoodman/go-partybus" "io" "os" "strings" ) var _ clio.UI = (*V1UI)(nil) type V1UI struct { cfg v1.Preferences out io.Writer err io.Writer subscription partybus.Unsubscribable quiet bool verbosity int format format } type format struct { Title lipgloss.Style Aux lipgloss.Style Line lipgloss.Style Notification lipgloss.Style } func NewV1UI(cfg v1.Preferences, out io.Writer, quiet bool, verbosity int) *V1UI { return &V1UI{ cfg: cfg, out: out, err: os.Stderr, quiet: quiet, verbosity: verbosity, format: format{ Title: lipgloss.NewStyle().Bold(true).Width(30), Aux: lipgloss.NewStyle().Faint(true), Notification: lipgloss.NewStyle().Foreground(lipgloss.Color("#A77BCA")), }, } } func (n *V1UI) Setup(subscription partybus.Unsubscribable) error { if n.verbosity == 0 || n.quiet { // we still use the UI, but we want to suppress responding to events that would print out what is already // being logged. log.Set(discard.New()) } // remove CI var from consideration when determining if we should use the UI lipgloss.SetDefaultRenderer(lipgloss.NewRenderer(n.out, termenv.WithEnvironment(environWithoutCI{}))) n.subscription = subscription return nil } var _ termenv.Environ = (*environWithoutCI)(nil) type environWithoutCI struct { } func (e environWithoutCI) Environ() []string { var out []string for _, s := range os.Environ() { if strings.HasPrefix(s, "CI=") { continue } out = append(out, s) } return out } func (e environWithoutCI) Getenv(s string) string { if s == "CI" { return "" } return os.Getenv(s) } func (n *V1UI) Handle(e partybus.Event) error { switch e.Type { case event.TaskStarted: if n.quiet { return nil } prog, task, err := parser.ParseTaskStarted(e) if err != nil { log.WithFields("error", err, "event", fmt.Sprintf("%#v", e)).Warn("failed to parse event") } var aux string stage := prog.Stage() switch { case task.Context != "": aux = task.Context case stage != "": aux = stage } if aux != "" { aux = n.format.Aux.Render(aux) } n.writeToStderr(n.format.Title.Render(task.Title.Default) + aux) case event.Notification: if n.quiet { return nil } _, text, err := parser.ParseNotification(e) if err != nil { log.WithFields("error", err, "event", fmt.Sprintf("%#v", e)).Warn("failed to parse event") } n.writeToStderr(n.format.Notification.Render(text)) case event.Report: if n.quiet { return nil } _, text, err := parser.ParseReport(e) if err != nil { log.WithFields("error", err, "event", fmt.Sprintf("%#v", e)).Warn("failed to parse event") } n.writeToStderr("") n.writeToStdout(text) case event.ExploreAnalysis: analysis, content, err := parser.ParseExploreAnalysis(e) if err != nil { log.WithFields("error", err, "event", fmt.Sprintf("%#v", e)).Warn("failed to parse event") } // ensure the logger will not interfere with the UI log.Set(discard.New()) return app.Run( // TODO: this is not plumbed through from the command object... context.Background(), v1.Config{ Content: content, Analysis: analysis, Preferences: n.cfg, }, ) } return nil } func (n *V1UI) writeToStdout(s string) { fmt.Fprintln(n.out, s) } func (n *V1UI) writeToStderr(s string) { if n.quiet || n.verbosity > 0 { // we've been told to not report anything or that we're in verbose mode thus the logger should report all info. // This only applies to status like info on stderr, not to primary reports on stdout. return } fmt.Fprintln(n.err, s) } func (n V1UI) Teardown(_ bool) error { return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/config.go
cmd/dive/cli/internal/ui/v1/config.go
package v1 import ( "errors" "fmt" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/key" "github.com/wagoodman/dive/dive/filetree" "github.com/wagoodman/dive/dive/image" "golang.org/x/net/context" "sync" ) type Config struct { // required input Analysis image.Analysis Content ContentReader Preferences Preferences stack filetree.Comparer stackErrs error do *sync.Once } type Preferences struct { KeyBindings key.Bindings IgnoreErrors bool ShowFiletreeAttributes bool ShowAggregatedLayerChanges bool CollapseFiletreeDirectory bool FiletreePaneWidth float64 FiletreeDiffHide []string } func DefaultPreferences() Preferences { return Preferences{ KeyBindings: key.DefaultBindings(), ShowFiletreeAttributes: true, ShowAggregatedLayerChanges: true, CollapseFiletreeDirectory: false, // don't start with collapsed directories FiletreePaneWidth: 0.5, FiletreeDiffHide: []string{}, // empty slice means show all } } func (c *Config) TreeComparer() (filetree.Comparer, error) { if c.do == nil { c.do = &sync.Once{} } c.do.Do(func() { treeStack := filetree.NewComparer(c.Analysis.RefTrees) errs := treeStack.BuildCache() if errs != nil { if !c.Preferences.IgnoreErrors { errs = append(errs, fmt.Errorf("file tree has path errors (use '--ignore-errors' to attempt to continue)")) c.stackErrs = errors.Join(errs...) return } } c.stack = treeStack }) return c.stack, c.stackErrs } type ContentReader interface { Extract(ctx context.Context, id string, layer string, path string) error }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/app/job_control_unix.go
cmd/dive/cli/internal/ui/v1/app/job_control_unix.go
//go:build !windows // +build !windows package app import ( "syscall" "github.com/awesome-gocui/gocui" ) // handle ctrl+z func handle_ctrl_z(g *gocui.Gui, v *gocui.View) error { gocui.Suspend() if err := syscall.Kill(syscall.Getpid(), syscall.SIGSTOP); err != nil { return err } return gocui.Resume() }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/app/controller.go
cmd/dive/cli/internal/ui/v1/app/controller.go
package app import ( "fmt" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/view" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/viewmodel" "golang.org/x/net/context" "regexp" "github.com/awesome-gocui/gocui" ) type controller struct { gui *gocui.Gui views *view.Views config v1.Config ctx context.Context // TODO: storing context in the controller is not ideal } func newController(ctx context.Context, g *gocui.Gui, cfg v1.Config) (*controller, error) { views, err := view.NewViews(g, cfg) if err != nil { return nil, err } c := &controller{ gui: g, views: views, config: cfg, ctx: ctx, } // layer view cursor down event should trigger an update in the file tree c.views.Layer.AddLayerChangeListener(c.onLayerChange) // update the status pane when a filetree option is changed by the user c.views.Tree.AddViewOptionChangeListener(c.onFileTreeViewOptionChange) // update the status pane when a filetree option is changed by the user c.views.Tree.AddViewExtractListener(c.onFileTreeViewExtract) // update the tree view while the user types into the filter view c.views.Filter.AddFilterEditListener(c.onFilterEdit) // propagate initial conditions to necessary views err = c.onLayerChange(viewmodel.LayerSelection{ Layer: c.views.Layer.CurrentLayer(), BottomTreeStart: 0, BottomTreeStop: 0, TopTreeStart: 0, TopTreeStop: 0, }) if err != nil { return nil, err } return c, nil } func (c *controller) onFileTreeViewExtract(p string) error { return c.config.Content.Extract(c.ctx, c.config.Analysis.Image, c.views.LayerDetails.CurrentLayer.Id, p) } func (c *controller) onFileTreeViewOptionChange() error { err := c.views.Status.Update() if err != nil { return err } return c.views.Status.Render() } func (c *controller) onFilterEdit(filter string) error { var filterRegex *regexp.Regexp var err error if len(filter) > 0 { filterRegex, err = regexp.Compile(filter) if err != nil { return err } } c.views.Tree.SetFilterRegex(filterRegex) err = c.views.Tree.Update() if err != nil { return err } return c.views.Tree.Render() } func (c *controller) onLayerChange(selection viewmodel.LayerSelection) error { // update the details c.views.LayerDetails.CurrentLayer = selection.Layer // update the filetree err := c.views.Tree.SetTree(selection.BottomTreeStart, selection.BottomTreeStop, selection.TopTreeStart, selection.TopTreeStop) if err != nil { return err } if c.views.Layer.CompareMode() == viewmodel.CompareAllLayers { c.views.Tree.SetTitle("Aggregated Layer Contents") } else { c.views.Tree.SetTitle("Current Layer Contents") } // update details and filetree panes return c.UpdateAndRender() } func (c *controller) UpdateAndRender() error { err := c.Update() if err != nil { return fmt.Errorf("controller failed update: %w", err) } err = c.Render() if err != nil { return fmt.Errorf("controller failed render: %w", err) } return nil } // Update refreshes the state objects for future rendering. func (c *controller) Update() error { for _, v := range c.views.Renderers() { err := v.Update() if err != nil { return fmt.Errorf("controller unable to update view: %w", err) } } return nil } // Render flushes the state objects to the screen. func (c *controller) Render() error { for _, v := range c.views.Renderers() { if v.IsVisible() { err := v.Render() if err != nil { return err } } } return nil } //nolint:dupl func (c *controller) NextPane() (err error) { v := c.gui.CurrentView() if v == nil { panic("CurrentView is nil") } if v.Name() == c.views.Layer.Name() { _, err = c.gui.SetCurrentView(c.views.LayerDetails.Name()) c.views.Status.SetCurrentView(c.views.LayerDetails) } else if v.Name() == c.views.LayerDetails.Name() { _, err = c.gui.SetCurrentView(c.views.ImageDetails.Name()) c.views.Status.SetCurrentView(c.views.ImageDetails) } else if v.Name() == c.views.ImageDetails.Name() { _, err = c.gui.SetCurrentView(c.views.Layer.Name()) c.views.Status.SetCurrentView(c.views.Layer) } if err != nil { return fmt.Errorf("controller unable to switch to next pane: %w", err) } return c.UpdateAndRender() } //nolint:dupl func (c *controller) PrevPane() (err error) { v := c.gui.CurrentView() if v == nil { panic("Current view is nil") } if v.Name() == c.views.Layer.Name() { _, err = c.gui.SetCurrentView(c.views.ImageDetails.Name()) c.views.Status.SetCurrentView(c.views.ImageDetails) } else if v.Name() == c.views.LayerDetails.Name() { _, err = c.gui.SetCurrentView(c.views.Layer.Name()) c.views.Status.SetCurrentView(c.views.Layer) } else if v.Name() == c.views.ImageDetails.Name() { _, err = c.gui.SetCurrentView(c.views.LayerDetails.Name()) c.views.Status.SetCurrentView(c.views.LayerDetails) } if err != nil { return fmt.Errorf("controller unable to switch to previous pane: %w", err) } return c.UpdateAndRender() } // ToggleView switches between the file view and the layer view and re-renders the screen. func (c *controller) ToggleView() (err error) { v := c.gui.CurrentView() if v == nil || v.Name() == c.views.Layer.Name() { _, err = c.gui.SetCurrentView(c.views.Tree.Name()) c.views.Status.SetCurrentView(c.views.Tree) } else { _, err = c.gui.SetCurrentView(c.views.Layer.Name()) c.views.Status.SetCurrentView(c.views.Layer) } if err != nil { return fmt.Errorf("controller unable to toggle view: %w", err) } return c.UpdateAndRender() } func (c *controller) CloseFilterView() error { // filter view needs to be visible if c.views.Filter.IsVisible() { // toggle filter view return c.ToggleFilterView() } return nil } func (c *controller) ToggleFilterView() error { // delete all user input from the tree view err := c.views.Filter.ToggleVisible() if err != nil { return fmt.Errorf("unable to toggle filter visibility: %w", err) } // we have just hidden the filter view... if !c.views.Filter.IsVisible() { // ...remove any filter from the tree c.views.Tree.SetFilterRegex(nil) // ...adjust focus to a valid (visible) view err = c.ToggleView() if err != nil { return fmt.Errorf("unable to toggle filter view (back): %w", err) } } return c.UpdateAndRender() }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/app/job_control_other.go
cmd/dive/cli/internal/ui/v1/app/job_control_other.go
//go:build windows // +build windows package app import ( "github.com/awesome-gocui/gocui" ) // handle ctrl+z not supported on windows func handle_ctrl_z(_ *gocui.Gui, _ *gocui.View) error { return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/app/app.go
cmd/dive/cli/internal/ui/v1/app/app.go
package app import ( "errors" "github.com/awesome-gocui/gocui" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/key" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/layout" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/layout/compound" "golang.org/x/net/context" "time" ) const debug = false type app struct { gui *gocui.Gui controller *controller layout *layout.Manager } // Run is the UI entrypoint. func Run(ctx context.Context, c v1.Config) error { var err error // it appears there is a race condition where termbox.Init() will // block nearly indefinitely when running as the first process in // a Docker container when started within ~25ms of container startup. // I can't seem to determine the exact root cause, however, a large // enough sleep will prevent this behavior (todo: remove this hack) time.Sleep(100 * time.Millisecond) g, err := gocui.NewGui(gocui.OutputNormal, true) if err != nil { return err } defer g.Close() _, err = newApp(ctx, g, c) if err != nil { return err } k, mod := gocui.MustParse("Ctrl+Z") if err := g.SetKeybinding("", k, mod, handle_ctrl_z); err != nil { return err } if err := g.MainLoop(); err != nil && !errors.Is(err, gocui.ErrQuit) { return err } return nil } func newApp(ctx context.Context, gui *gocui.Gui, cfg v1.Config) (*app, error) { var err error var c *controller var globalHelpKeys []*key.Binding c, err = newController(ctx, gui, cfg) if err != nil { return nil, err } // note: order matters when adding elements to the layout lm := layout.NewManager() lm.Add(c.views.Status, layout.LocationFooter) lm.Add(c.views.Filter, layout.LocationFooter) lm.Add(compound.NewLayerDetailsCompoundLayout(c.views.Layer, c.views.LayerDetails, c.views.ImageDetails), layout.LocationColumn) lm.Add(c.views.Tree, layout.LocationColumn) // todo: access this more programmatically if debug { lm.Add(c.views.Debug, layout.LocationColumn) } gui.Cursor = false // g.Mouse = true gui.SetManagerFunc(lm.Layout) a := &app{ gui: gui, controller: c, layout: lm, } var infos = []key.BindingInfo{ { Config: cfg.Preferences.KeyBindings.Global.Quit, OnAction: a.quit, Display: "Quit", }, { Config: cfg.Preferences.KeyBindings.Global.ToggleView, OnAction: c.ToggleView, Display: "Switch view", }, { Config: cfg.Preferences.KeyBindings.Navigation.Right, OnAction: c.NextPane, }, { Config: cfg.Preferences.KeyBindings.Navigation.Left, OnAction: c.PrevPane, }, { Config: cfg.Preferences.KeyBindings.Global.FilterFiles, OnAction: c.ToggleFilterView, IsSelected: c.views.Filter.IsVisible, Display: "Filter", }, { Config: cfg.Preferences.KeyBindings.Global.CloseFilterFiles, OnAction: c.CloseFilterView, }, } globalHelpKeys, err = key.GenerateBindings(gui, "", infos) if err != nil { return nil, err } c.views.Status.AddHelpKeys(globalHelpKeys...) // perform the first update and render now that all resources have been loaded err = c.UpdateAndRender() if err != nil { return nil, err } return a, err } // quit is the gocui callback invoked when the user hits Ctrl+C func (a *app) quit() error { return gocui.ErrQuit }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/key/binding.go
cmd/dive/cli/internal/ui/v1/key/binding.go
package key import ( "fmt" "github.com/awesome-gocui/gocui" "github.com/awesome-gocui/keybinding" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" ) type BindingInfo struct { Key gocui.Key Modifier gocui.Modifier Config Config OnAction func() error IsSelected func() bool Display string } type Binding struct { key []keybinding.Key displayName string selectedFn func() bool actionFn func() error } func GenerateBindings(gui *gocui.Gui, influence string, infos []BindingInfo) ([]*Binding, error) { var result = make([]*Binding, 0) for _, info := range infos { if len(info.Config.Keys) == 0 { return nil, fmt.Errorf("no keybinding configured for '%s'", info.Display) } binding, err := newBinding(gui, influence, info.Config.Keys, info.Display, info.OnAction) if err != nil { return nil, err } if info.IsSelected != nil { binding.RegisterSelectionFn(info.IsSelected) } if len(info.Display) > 0 { result = append(result, binding) } } return result, nil } func newBinding(gui *gocui.Gui, influence string, keys []keybinding.Key, displayName string, actionFn func() error) (*Binding, error) { binding := &Binding{ key: keys, displayName: displayName, actionFn: actionFn, } for _, key := range keys { if err := gui.SetKeybinding(influence, key.Value, key.Modifier, binding.onAction); err != nil { return nil, err } } return binding, nil } func (binding *Binding) RegisterSelectionFn(selectedFn func() bool) { binding.selectedFn = selectedFn } func (binding *Binding) onAction(*gocui.Gui, *gocui.View) error { if binding.actionFn == nil { return fmt.Errorf("no action configured for '%+v'", binding) } return binding.actionFn() } func (binding *Binding) isSelected() bool { if binding.selectedFn == nil { return false } return binding.selectedFn() } func (binding *Binding) RenderKeyHelp() string { return format.RenderHelpKey(binding.key[0].String(), binding.displayName, binding.isSelected()) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/key/config.go
cmd/dive/cli/internal/ui/v1/key/config.go
package key import ( "fmt" "github.com/awesome-gocui/keybinding" ) type Config struct { Input string Keys []keybinding.Key `yaml:"-" mapstructure:"-"` } func (c *Config) Setup() error { if len(c.Input) == 0 { return nil } parsed, err := keybinding.ParseAll(c.Input) if err != nil { return fmt.Errorf("failed to parse key %q: %w", c.Input, err) } c.Keys = parsed return nil } type Bindings struct { Global GlobalBindings `yaml:",inline" mapstructure:",squash"` Navigation NavigationBindings `yaml:",inline" mapstructure:",squash"` Layer LayerBindings `yaml:",inline" mapstructure:",squash"` Filetree FiletreeBindings `yaml:",inline" mapstructure:",squash"` } type GlobalBindings struct { Quit Config `yaml:"quit" mapstructure:"quit"` ToggleView Config `yaml:"toggle-view" mapstructure:"toggle-view"` FilterFiles Config `yaml:"filter-files" mapstructure:"filter-files"` CloseFilterFiles Config `yaml:"close-filter-files" mapstructure:"close-filter-files"` } type NavigationBindings struct { Up Config `yaml:"up" mapstructure:"up"` Down Config `yaml:"down" mapstructure:"down"` Left Config `yaml:"left" mapstructure:"left"` Right Config `yaml:"right" mapstructure:"right"` PageUp Config `yaml:"page-up" mapstructure:"page-up"` PageDown Config `yaml:"page-down" mapstructure:"page-down"` } type LayerBindings struct { CompareAll Config `yaml:"compare-all" mapstructure:"compare-all"` CompareLayer Config `yaml:"compare-layer" mapstructure:"compare-layer"` } type FiletreeBindings struct { ToggleCollapseDir Config `yaml:"toggle-collapse-dir" mapstructure:"toggle-collapse-dir"` ToggleCollapseAllDir Config `yaml:"toggle-collapse-all-dir" mapstructure:"toggle-collapse-all-dir"` ToggleAddedFiles Config `yaml:"toggle-added-files" mapstructure:"toggle-added-files"` ToggleRemovedFiles Config `yaml:"toggle-removed-files" mapstructure:"toggle-removed-files"` ToggleModifiedFiles Config `yaml:"toggle-modified-files" mapstructure:"toggle-modified-files"` ToggleUnmodifiedFiles Config `yaml:"toggle-unmodified-files" mapstructure:"toggle-unmodified-files"` ToggleTreeAttributes Config `yaml:"toggle-filetree-attributes" mapstructure:"toggle-filetree-attributes"` ToggleSortOrder Config `yaml:"toggle-sort-order" mapstructure:"toggle-sort-order"` ToggleWrapTree Config `yaml:"toggle-wrap-tree" mapstructure:"toggle-wrap-tree"` ExtractFile Config `yaml:"extract-file" mapstructure:"extract-file"` } func DefaultBindings() Bindings { return Bindings{ Global: GlobalBindings{ Quit: Config{Input: "ctrl+c"}, ToggleView: Config{Input: "tab"}, FilterFiles: Config{Input: "ctrl+f, ctrl+slash"}, CloseFilterFiles: Config{Input: "esc"}, }, Navigation: NavigationBindings{ Up: Config{Input: "up,k"}, Down: Config{Input: "down,j"}, Left: Config{Input: "left,h"}, Right: Config{Input: "right,l"}, PageUp: Config{Input: "pgup,u"}, PageDown: Config{Input: "pgdn,d"}, }, Layer: LayerBindings{ CompareAll: Config{Input: "ctrl+a"}, CompareLayer: Config{Input: "ctrl+l"}, }, Filetree: FiletreeBindings{ ToggleCollapseDir: Config{Input: "space"}, ToggleCollapseAllDir: Config{Input: "ctrl+space"}, ToggleAddedFiles: Config{Input: "ctrl+a"}, ToggleRemovedFiles: Config{Input: "ctrl+r"}, ToggleModifiedFiles: Config{Input: "ctrl+m"}, ToggleUnmodifiedFiles: Config{Input: "ctrl+u"}, ToggleTreeAttributes: Config{Input: "ctrl+b"}, ToggleWrapTree: Config{Input: "ctrl+p"}, ToggleSortOrder: Config{Input: "ctrl+o"}, ExtractFile: Config{Input: "ctrl+e"}, }, } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/viewmodel/filetree_test.go
cmd/dive/cli/internal/ui/v1/viewmodel/filetree_test.go
package viewmodel import ( "flag" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "go.uber.org/atomic" "os" "os/exec" "path/filepath" "regexp" "strings" "testing" "github.com/wagoodman/dive/dive/filetree" "github.com/wagoodman/dive/dive/image/docker" ) var repoRootCache atomic.String var updateSnapshot = flag.Bool("update", false, "update any test snapshots") func TestUpdateSnapshotDisabled(t *testing.T) { require.False(t, *updateSnapshot, "update snapshot flag should be disabled") } func fileExists(filename string) bool { info, err := os.Stat(filename) if os.IsNotExist(err) { return false } return !info.IsDir() } func testCaseDataFilePath(name string) string { return filepath.Join("testdata", name+".txt") } func helperLoadBytes(t *testing.T) []byte { t.Helper() path := testCaseDataFilePath(t.Name()) theBytes, err := os.ReadFile(path) if err != nil { t.Fatalf("unable to load test data ('%s'): %+v", t.Name(), err) } return theBytes } func helperCaptureBytes(t *testing.T, data []byte) { // TODO: switch to https://github.com/gkampitakis/go-snaps t.Helper() if *updateSnapshot { t.Fatalf("cannot capture data in test mode: %s", t.Name()) } path := testCaseDataFilePath(t.Name()) err := os.WriteFile(path, data, 0644) if err != nil { t.Fatalf("unable to save test data ('%s'): %+v", t.Name(), err) } } func initializeTestViewModel(t *testing.T) *FileTreeViewModel { t.Helper() result := docker.TestAnalysisFromArchive(t, repoPath(t, ".data/test-docker-image.tar")) require.NotNil(t, result, "unable to load test data") vm, err := NewFileTreeViewModel(v1.Config{ Analysis: *result, Preferences: v1.DefaultPreferences(), }, 0) require.NoError(t, err, "unable to create viewmodel") return vm } func runTestCase(t *testing.T, vm *FileTreeViewModel, width, height int, filterRegex *regexp.Regexp) { t.Helper() err := vm.Update(filterRegex, width, height) if err != nil { t.Errorf("failed to update viewmodel: %v", err) } err = vm.Render() if err != nil { t.Errorf("failed to render viewmodel: %v", err) } actualBytes := vm.Buffer.Bytes() path := testCaseDataFilePath(t.Name()) if !fileExists(path) { if *updateSnapshot { helperCaptureBytes(t, actualBytes) } else { t.Fatalf("missing test data: %s", path) } } expectedBytes := helperLoadBytes(t) if d := cmp.Diff(string(expectedBytes), string(actualBytes)); d != "" { t.Errorf("bytes mismatch (-want +got):\n%s", d) } } func checkError(t *testing.T, err error, message string) { if err != nil { t.Errorf(message+": %+v", err) } } func TestFileTreeGoCase(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 1000 vm.Setup(0, height) vm.ShowAttributes = true runTestCase(t, vm, width, height, nil) } func TestFileTreeNoAttributes(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 1000 vm.Setup(0, height) vm.ShowAttributes = false runTestCase(t, vm, width, height, nil) } func TestFileTreeRestrictedHeight(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 20 vm.Setup(0, height) vm.ShowAttributes = false runTestCase(t, vm, width, height, nil) } func TestFileTreeDirCollapse(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 100 vm.Setup(0, height) vm.ShowAttributes = true assertPath(t, vm, "/bin", "before toggle of bin") // collapse /bin err := vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /bin") assertPath(t, vm, "/bin", "after toggle of bin") moved := vm.CursorDown() // select /dev require.True(t, moved, "unable to cursor down") assertPath(t, vm, "/dev", "down to dev") moved = vm.CursorDown() // select /etc require.True(t, moved, "unable to cursor down") assertPath(t, vm, "/etc", "down to etc") // collapse /etc err = vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /etc") assertPath(t, vm, "/etc", "after toggle of etc") runTestCase(t, vm, width, height, nil) } func assertPath(t *testing.T, vm *FileTreeViewModel, expected string, msg string) { t.Helper() n := vm.CurrentNode(nil) require.NotNil(t, n, "unable to get current node") assert.Equal(t, expected, n.Path(), msg) } func TestFileTreeDirCollapseAll(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 100 vm.Setup(0, height) vm.ShowAttributes = true err := vm.ToggleCollapseAll() checkError(t, err, "unable to collapse all dir") runTestCase(t, vm, width, height, nil) } func TestFileTreeSelectLayer(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 100 vm.Setup(0, height) vm.ShowAttributes = true // collapse /bin err := vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /bin") // select the next layer, compareMode = layer err = vm.SetTreeByLayer(0, 0, 1, 1) if err != nil { t.Errorf("unable to SetTreeByLayer: %v", err) } runTestCase(t, vm, width, height, nil) } func TestFileShowAggregateChanges(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 100 vm.Setup(0, height) vm.ShowAttributes = true // collapse /bin err := vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /bin") // select the next layer, compareMode = layer err = vm.SetTreeByLayer(0, 0, 1, 13) checkError(t, err, "unable to SetTreeByLayer") runTestCase(t, vm, width, height, nil) } func TestFileTreePageDown(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 10 vm.Setup(0, height) vm.ShowAttributes = true err := vm.Update(nil, width, height) checkError(t, err, "unable to update") err = vm.PageDown() checkError(t, err, "unable to page down") err = vm.PageDown() checkError(t, err, "unable to page down") err = vm.PageDown() checkError(t, err, "unable to page down") runTestCase(t, vm, width, height, nil) } func TestFileTreePageUp(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 10 vm.Setup(0, height) vm.ShowAttributes = true // these operations have a render step for intermediate results, which require at least one update to be done first err := vm.Update(nil, width, height) checkError(t, err, "unable to update") err = vm.PageDown() checkError(t, err, "unable to page down") err = vm.PageDown() checkError(t, err, "unable to page down") err = vm.PageUp() checkError(t, err, "unable to page up") runTestCase(t, vm, width, height, nil) } func TestFileTreeDirCursorRight(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 100 vm.Setup(0, height) vm.ShowAttributes = true // collapse /bin err := vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /bin") moved := vm.CursorDown() if !moved { t.Error("unable to cursor down") } moved = vm.CursorDown() if !moved { t.Error("unable to cursor down") } // collapse /etc err = vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /etc") // expand /etc err = vm.CursorRight(nil) checkError(t, err, "unable to cursor right") runTestCase(t, vm, width, height, nil) } func TestFileTreeFilterTree(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 1000 vm.Setup(0, height) vm.ShowAttributes = true regex, err := regexp.Compile("network") if err != nil { t.Errorf("could not create filter regex: %+v", err) } runTestCase(t, vm, width, height, regex) } func TestFileTreeHideAddedRemovedModified(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 100 vm.Setup(0, height) vm.ShowAttributes = true // collapse /bin err := vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /bin") // select the 7th layer, compareMode = layer err = vm.SetTreeByLayer(0, 0, 1, 7) if err != nil { t.Errorf("unable to SetTreeByLayer: %v", err) } // hide added files vm.ToggleShowDiffType(filetree.Added) // hide modified files vm.ToggleShowDiffType(filetree.Modified) // hide removed files vm.ToggleShowDiffType(filetree.Removed) runTestCase(t, vm, width, height, nil) } func TestFileTreeHideUnmodified(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 100 vm.Setup(0, height) vm.ShowAttributes = true // collapse /bin err := vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /bin") // select the 7th layer, compareMode = layer err = vm.SetTreeByLayer(0, 0, 1, 7) if err != nil { t.Errorf("unable to SetTreeByLayer: %v", err) } // hide unmodified files vm.ToggleShowDiffType(filetree.Unmodified) runTestCase(t, vm, width, height, nil) } func TestFileTreeHideTypeWithFilter(t *testing.T) { vm := initializeTestViewModel(t) width, height := 100, 100 vm.Setup(0, height) vm.ShowAttributes = true // collapse /bin err := vm.ToggleCollapse(nil) checkError(t, err, "unable to collapse /bin") // select the 7th layer, compareMode = layer err = vm.SetTreeByLayer(0, 0, 1, 7) if err != nil { t.Errorf("unable to SetTreeByLayer: %v", err) } // hide added files vm.ToggleShowDiffType(filetree.Added) regex, err := regexp.Compile("saved") if err != nil { t.Errorf("could not create filter regex: %+v", err) } runTestCase(t, vm, width, height, regex) } func repoPath(t testing.TB, path string) string { t.Helper() root := repoRoot(t) return filepath.Join(root, path) } func repoRoot(t testing.TB) string { val := repoRootCache.Load() if val != "" { return val } t.Helper() // use git to find the root of the repo out, err := exec.Command("git", "rev-parse", "--show-toplevel").Output() if err != nil { t.Fatalf("failed to get repo root: %v", err) } val = strings.TrimSpace(string(out)) repoRootCache.Store(val) return val }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/viewmodel/config.go
cmd/dive/cli/internal/ui/v1/viewmodel/config.go
package viewmodel
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/viewmodel/layer_compare.go
cmd/dive/cli/internal/ui/v1/viewmodel/layer_compare.go
package viewmodel const ( CompareSingleLayer LayerCompareMode = iota CompareAllLayers ) type LayerCompareMode int
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/viewmodel/layer_selection.go
cmd/dive/cli/internal/ui/v1/viewmodel/layer_selection.go
package viewmodel import ( "github.com/wagoodman/dive/dive/image" ) type LayerSelection struct { Layer *image.Layer BottomTreeStart, BottomTreeStop, TopTreeStart, TopTreeStop int }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/viewmodel/layer_set_state_test.go
cmd/dive/cli/internal/ui/v1/viewmodel/layer_set_state_test.go
package viewmodel import ( "testing" ) func TestGetCompareIndexes(t *testing.T) { tests := []struct { name string layerIndex int compareMode LayerCompareMode compareStartIndex int expected [4]int }{ { name: "LayerIndex equals CompareStartIndex", layerIndex: 2, compareMode: CompareSingleLayer, compareStartIndex: 2, expected: [4]int{2, 2, 2, 2}, }, { name: "CompareMode is CompareSingleLayer", layerIndex: 3, compareMode: CompareSingleLayer, compareStartIndex: 1, expected: [4]int{1, 2, 3, 3}, }, { name: "Default CompareMode", layerIndex: 4, compareMode: CompareAllLayers, compareStartIndex: 1, expected: [4]int{1, 1, 2, 4}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { state := &LayerSetState{ LayerIndex: tt.layerIndex, CompareMode: tt.compareMode, CompareStartIndex: tt.compareStartIndex, } bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop := state.GetCompareIndexes() actual := [4]int{bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop} if actual != tt.expected { t.Errorf("expected %v, got %v", tt.expected, actual) } }) } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/viewmodel/filetree.go
cmd/dive/cli/internal/ui/v1/viewmodel/filetree.go
package viewmodel import ( "bytes" "fmt" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" "github.com/wagoodman/dive/internal/log" "regexp" "strings" "github.com/lunixbochs/vtclean" "github.com/wagoodman/dive/dive/filetree" ) // FileTreeViewModel holds the UI objects and data models for populating the right pane. Specifically, the pane that // shows selected layer or aggregate file ASCII tree. type FileTreeViewModel struct { ModelTree *filetree.FileTree ViewTree *filetree.FileTree RefTrees []*filetree.FileTree comparer filetree.Comparer constrainedRealEstate bool CollapseAll bool ShowAttributes bool unconstrainedShowAttributes bool HiddenDiffTypes []bool TreeIndex int bufferIndex int bufferIndexLowerBound int refHeight int refWidth int Buffer bytes.Buffer } // NewFileTreeViewModel creates a new view object attached the global [gocui] screen object. func NewFileTreeViewModel(cfg v1.Config, initialLayer int) (treeViewModel *FileTreeViewModel, err error) { treeViewModel = new(FileTreeViewModel) comparer, err := cfg.TreeComparer() if err != nil { return nil, err } // populate main fields treeViewModel.ShowAttributes = cfg.Preferences.ShowFiletreeAttributes treeViewModel.unconstrainedShowAttributes = treeViewModel.ShowAttributes treeViewModel.CollapseAll = cfg.Preferences.CollapseFiletreeDirectory treeViewModel.ModelTree = cfg.Analysis.RefTrees[initialLayer] treeViewModel.RefTrees = cfg.Analysis.RefTrees treeViewModel.comparer = comparer treeViewModel.HiddenDiffTypes = make([]bool, 4) hiddenTypes := cfg.Preferences.FiletreeDiffHide for _, hType := range hiddenTypes { switch t := strings.ToLower(hType); t { case "added": treeViewModel.HiddenDiffTypes[filetree.Added] = true case "removed": treeViewModel.HiddenDiffTypes[filetree.Removed] = true case "modified": treeViewModel.HiddenDiffTypes[filetree.Modified] = true case "unmodified": treeViewModel.HiddenDiffTypes[filetree.Unmodified] = true default: return nil, fmt.Errorf("unknown diff.hide value: %s", t) } } return treeViewModel, treeViewModel.SetTreeByLayer(0, 0, initialLayer, initialLayer) } // Setup initializes the UI concerns within the context of a global [gocui] view object. func (vm *FileTreeViewModel) Setup(lowerBound, height int) { vm.bufferIndexLowerBound = lowerBound vm.refHeight = height } // height returns the current height and considers the header func (vm *FileTreeViewModel) height() int { if vm.ShowAttributes { return vm.refHeight - 1 } return vm.refHeight } // bufferIndexUpperBound returns the current upper bounds for the view func (vm *FileTreeViewModel) bufferIndexUpperBound() int { return vm.bufferIndexLowerBound + vm.height() } // IsVisible indicates if the file tree view pane is currently initialized func (vm *FileTreeViewModel) IsVisible() bool { return vm != nil } // ResetCursor moves the cursor back to the top of the buffer and translates to the top of the buffer. func (vm *FileTreeViewModel) ResetCursor() { vm.TreeIndex = 0 vm.bufferIndex = 0 vm.bufferIndexLowerBound = 0 } // SetTreeByLayer populates the view model by stacking the indicated image layer file trees. func (vm *FileTreeViewModel) SetTreeByLayer(bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop int) error { if topTreeStop > len(vm.RefTrees)-1 { return fmt.Errorf("invalid layer index given: %d of %d", topTreeStop, len(vm.RefTrees)-1) } newTree, err := vm.comparer.GetTree(filetree.NewTreeIndexKey(bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop)) if err != nil { return fmt.Errorf("unable to fetch layer tree from cache: %w", err) } // preserve vm state on copy visitor := func(node *filetree.FileNode) error { newNode, err := newTree.GetNode(node.Path()) if err == nil { newNode.Data.ViewInfo = node.Data.ViewInfo } return nil } err = vm.ModelTree.VisitDepthChildFirst(visitor, nil) if err != nil { return fmt.Errorf("unable to propagate layer tree: %w", err) } vm.ModelTree = newTree return nil } // CursorUp performs the internal view's buffer adjustments on cursor up. Note: this is independent of the gocui buffer. func (vm *FileTreeViewModel) CursorUp() bool { if vm.TreeIndex <= 0 { return false } vm.TreeIndex-- if vm.TreeIndex < vm.bufferIndexLowerBound { vm.bufferIndexLowerBound-- } if vm.bufferIndex > 0 { vm.bufferIndex-- } return true } // CursorDown performs the internal view's buffer adjustments on cursor down. Note: this is independent of the gocui buffer. func (vm *FileTreeViewModel) CursorDown() bool { if vm.TreeIndex >= vm.ModelTree.VisibleSize() { return false } vm.TreeIndex++ if vm.TreeIndex > vm.bufferIndexUpperBound() { vm.bufferIndexLowerBound++ } vm.bufferIndex++ if vm.bufferIndex > vm.height() { vm.bufferIndex = vm.height() } return true } func (vm *FileTreeViewModel) CurrentNode(filterRegex *regexp.Regexp) *filetree.FileNode { return vm.getAbsPositionNode(filterRegex) } // CursorLeft moves the cursor up until we reach the Parent Node or top of the tree func (vm *FileTreeViewModel) CursorLeft(filterRegex *regexp.Regexp) error { var visitor func(*filetree.FileNode) error var evaluator func(*filetree.FileNode) bool var dfsCounter, newIndex int oldIndex := vm.TreeIndex currentNode := vm.getAbsPositionNode(filterRegex) if currentNode == nil { return nil } parentPath := currentNode.Parent.Path() visitor = func(curNode *filetree.FileNode) error { if strings.Compare(parentPath, curNode.Path()) == 0 { newIndex = dfsCounter } dfsCounter++ return nil } evaluator = func(curNode *filetree.FileNode) bool { regexMatch := true if filterRegex != nil { match := filterRegex.Find([]byte(curNode.Path())) regexMatch = match != nil } return !curNode.Parent.Data.ViewInfo.Collapsed && !curNode.Data.ViewInfo.Hidden && regexMatch } err := vm.ModelTree.VisitDepthParentFirst(visitor, evaluator) if err != nil { return fmt.Errorf("unable to propagate tree on cursorLeft: %w", err) } vm.TreeIndex = newIndex moveIndex := oldIndex - newIndex if newIndex < vm.bufferIndexLowerBound { vm.bufferIndexLowerBound = vm.TreeIndex } if vm.bufferIndex > moveIndex { vm.bufferIndex -= moveIndex } else { vm.bufferIndex = 0 } return nil } // CursorRight descends into directory expanding it if needed func (vm *FileTreeViewModel) CursorRight(filterRegex *regexp.Regexp) error { node := vm.getAbsPositionNode(filterRegex) if node == nil { return nil } if !node.Data.FileInfo.IsDir { return nil } if len(node.Children) == 0 { return nil } if node.Data.ViewInfo.Collapsed { node.Data.ViewInfo.Collapsed = false } vm.TreeIndex++ if vm.TreeIndex > vm.bufferIndexUpperBound() { vm.bufferIndexLowerBound++ } vm.bufferIndex++ if vm.bufferIndex > vm.height() { vm.bufferIndex = vm.height() } return nil } // PageDown moves to next page putting the cursor on top func (vm *FileTreeViewModel) PageDown() error { nextBufferIndexLowerBound := vm.bufferIndexLowerBound + vm.height() nextBufferIndexUpperBound := nextBufferIndexLowerBound + vm.height() // todo: this work should be saved or passed to render... treeString := vm.ViewTree.StringBetween(nextBufferIndexLowerBound, nextBufferIndexUpperBound, vm.ShowAttributes) lines := strings.Split(treeString, "\n") newLines := len(lines) - 1 if vm.height() >= newLines { nextBufferIndexLowerBound = vm.bufferIndexLowerBound + newLines } vm.bufferIndexLowerBound = nextBufferIndexLowerBound if vm.TreeIndex < nextBufferIndexLowerBound { vm.bufferIndex = 0 vm.TreeIndex = nextBufferIndexLowerBound } else { vm.bufferIndex -= newLines } return nil } // PageUp moves to previous page putting the cursor on top func (vm *FileTreeViewModel) PageUp() error { nextBufferIndexLowerBound := vm.bufferIndexLowerBound - vm.height() nextBufferIndexUpperBound := nextBufferIndexLowerBound + vm.height() // todo: this work should be saved or passed to render... treeString := vm.ViewTree.StringBetween(nextBufferIndexLowerBound, nextBufferIndexUpperBound, vm.ShowAttributes) lines := strings.Split(treeString, "\n") newLines := len(lines) - 2 if vm.height() >= newLines { nextBufferIndexLowerBound = vm.bufferIndexLowerBound - newLines } vm.bufferIndexLowerBound = nextBufferIndexLowerBound if vm.TreeIndex > (nextBufferIndexUpperBound - 1) { vm.bufferIndex = 0 vm.TreeIndex = nextBufferIndexLowerBound } else { vm.bufferIndex += newLines } return nil } // getAbsPositionNode determines the selected screen cursor's location in the file tree, returning the selected FileNode. func (vm *FileTreeViewModel) getAbsPositionNode(filterRegex *regexp.Regexp) (node *filetree.FileNode) { var visitor func(*filetree.FileNode) error var evaluator func(*filetree.FileNode) bool var dfsCounter int visitor = func(curNode *filetree.FileNode) error { if dfsCounter == vm.TreeIndex { node = curNode } dfsCounter++ return nil } evaluator = func(curNode *filetree.FileNode) bool { regexMatch := true if filterRegex != nil { match := filterRegex.Find([]byte(curNode.Path())) regexMatch = match != nil } parentCollapsed := false if curNode.Parent != nil { parentCollapsed = curNode.Parent.Data.ViewInfo.Collapsed } return !parentCollapsed && !curNode.Data.ViewInfo.Hidden && regexMatch } err := vm.ModelTree.VisitDepthParentFirst(visitor, evaluator) if err != nil { log.WithFields("error", err).Debug("unable to propagate tree on getAbsPositionNode") } return node } // ToggleCollapse will collapse/expand the selected FileNode. func (vm *FileTreeViewModel) ToggleCollapse(filterRegex *regexp.Regexp) error { node := vm.getAbsPositionNode(filterRegex) if node != nil && node.Data.FileInfo.IsDir { node.Data.ViewInfo.Collapsed = !node.Data.ViewInfo.Collapsed } return nil } // ToggleCollapseAll will collapse/expand the all directories. func (vm *FileTreeViewModel) ToggleCollapseAll() error { vm.CollapseAll = !vm.CollapseAll visitor := func(curNode *filetree.FileNode) error { curNode.Data.ViewInfo.Collapsed = vm.CollapseAll return nil } evaluator := func(curNode *filetree.FileNode) bool { return curNode.Data.FileInfo.IsDir } err := vm.ModelTree.VisitDepthChildFirst(visitor, evaluator) if err != nil { log.WithFields("error", err).Debug("unable to propagate tree on ToggleCollapseAll") } return nil } // ToggleSortOrder will toggle the sort order in which files are displayed func (vm *FileTreeViewModel) ToggleSortOrder() error { vm.ModelTree.SortOrder = (vm.ModelTree.SortOrder + 1) % filetree.NumSortOrderConventions return nil } func (vm *FileTreeViewModel) ConstrainLayout() { if !vm.constrainedRealEstate { vm.constrainedRealEstate = true vm.unconstrainedShowAttributes = vm.ShowAttributes vm.ShowAttributes = false } } func (vm *FileTreeViewModel) ExpandLayout() { if vm.constrainedRealEstate { vm.ShowAttributes = vm.unconstrainedShowAttributes vm.constrainedRealEstate = false } } // ToggleAttributes will hi func (vm *FileTreeViewModel) ToggleAttributes() error { // ignore any attempt to show the attributes when the layout is constrained if vm.constrainedRealEstate { return nil } vm.ShowAttributes = !vm.ShowAttributes return nil } // ToggleShowDiffType will show/hide the selected DiffType in the filetree pane. func (vm *FileTreeViewModel) ToggleShowDiffType(diffType filetree.DiffType) { vm.HiddenDiffTypes[diffType] = !vm.HiddenDiffTypes[diffType] } // Update refreshes the state objects for future rendering. func (vm *FileTreeViewModel) Update(filterRegex *regexp.Regexp, width, height int) error { vm.refWidth = width vm.refHeight = height // keep the vm selection in parity with the current DiffType selection err := vm.ModelTree.VisitDepthChildFirst(func(node *filetree.FileNode) error { node.Data.ViewInfo.Hidden = vm.HiddenDiffTypes[node.Data.DiffType] visibleChild := false for _, child := range node.Children { if !child.Data.ViewInfo.Hidden { visibleChild = true node.Data.ViewInfo.Hidden = false } } // hide nodes that do not match the current file filter regex (also don't unhide nodes that are already hidden) if filterRegex != nil && !visibleChild && !node.Data.ViewInfo.Hidden { match := filterRegex.FindString(node.Path()) node.Data.ViewInfo.Hidden = len(match) == 0 } return nil }, nil) if err != nil { return fmt.Errorf("unable to propagate vm model tree: %w", err) } // make a new tree with only visible nodes vm.ViewTree = vm.ModelTree.Copy() err = vm.ViewTree.VisitDepthParentFirst(func(node *filetree.FileNode) error { if node.Data.ViewInfo.Hidden { err1 := vm.ViewTree.RemovePath(node.Path()) if err1 != nil { return err1 } } return nil }, nil) if err != nil { return fmt.Errorf("unable to propagate vm view tree: %w", err) } return nil } // Render flushes the state objects (file tree) to the pane. func (vm *FileTreeViewModel) Render() error { treeString := vm.ViewTree.StringBetween(vm.bufferIndexLowerBound, vm.bufferIndexUpperBound(), vm.ShowAttributes) lines := strings.Split(treeString, "\n") // update the contents vm.Buffer.Reset() for idx, line := range lines { if idx == vm.bufferIndex { _, err := fmt.Fprintln(&vm.Buffer, format.Selected(vtclean.Clean(line, false))) if err != nil { return err } } else { _, err := fmt.Fprintln(&vm.Buffer, line) if err != nil { return err } } } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/viewmodel/layer_set_state.go
cmd/dive/cli/internal/ui/v1/viewmodel/layer_set_state.go
package viewmodel import "github.com/wagoodman/dive/dive/image" type LayerSetState struct { LayerIndex int Layers []*image.Layer CompareMode LayerCompareMode CompareStartIndex int } func NewLayerSetState(layers []*image.Layer, compareMode LayerCompareMode) *LayerSetState { return &LayerSetState{ Layers: layers, CompareMode: compareMode, } } // getCompareIndexes determines the layer boundaries to use for comparison (based on the current compare mode) func (state *LayerSetState) GetCompareIndexes() (bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop int) { bottomTreeStart = state.CompareStartIndex topTreeStop = state.LayerIndex if state.LayerIndex == state.CompareStartIndex { bottomTreeStop = state.LayerIndex topTreeStart = state.LayerIndex } else if state.CompareMode == CompareSingleLayer { bottomTreeStop = state.LayerIndex - 1 topTreeStart = state.LayerIndex } else { bottomTreeStop = state.CompareStartIndex topTreeStart = state.CompareStartIndex + 1 } return bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/layout/manager_test.go
cmd/dive/cli/internal/ui/v1/layout/manager_test.go
package layout import ( "testing" "github.com/awesome-gocui/gocui" ) type testElement struct { t *testing.T size int layoutArea Area location Location } func newTestElement(t *testing.T, size int, layoutArea Area, location Location) *testElement { return &testElement{ t: t, size: size, layoutArea: layoutArea, location: location, } } func (te *testElement) Name() string { return "dont care" } func (te *testElement) Layout(g *gocui.Gui, minX, minY, maxX, maxY int) error { actualLayoutArea := Area{ minX: minX, minY: minY, maxX: maxX, maxY: maxY, } if te.layoutArea != actualLayoutArea { te.t.Errorf("expected layout area '%+v', got '%+v'", te.layoutArea, actualLayoutArea) } return nil } func (te *testElement) RequestedSize(available int) *int { if te.size == -1 { return nil } return &te.size } func (te *testElement) IsVisible() bool { return true } func (te *testElement) OnLayoutChange() error { return nil } type layoutReturn struct { area Area err error } func Test_planAndLayoutHeaders(t *testing.T) { table := map[string]struct { headers []*testElement expected layoutReturn }{ "single header": { headers: []*testElement{newTestElement(t, 1, Area{ minX: -1, minY: -1, maxX: 120, maxY: 0, }, LocationHeader)}, expected: layoutReturn{ area: Area{ minX: -1, minY: 0, maxX: 120, maxY: 80, }, err: nil, }, }, "two headers": { headers: []*testElement{ newTestElement(t, 1, Area{ minX: -1, minY: -1, maxX: 120, maxY: 0, }, LocationHeader), newTestElement(t, 1, Area{ minX: -1, minY: 0, maxX: 120, maxY: 1, }, LocationHeader), }, expected: layoutReturn{ area: Area{ minX: -1, minY: 1, maxX: 120, maxY: 80, }, err: nil, }, }, "two odd-sized headers": { headers: []*testElement{ newTestElement(t, 2, Area{ minX: -1, minY: -1, maxX: 120, maxY: 1, }, LocationHeader), newTestElement(t, 3, Area{ minX: -1, minY: 1, maxX: 120, maxY: 4, }, LocationHeader), }, expected: layoutReturn{ area: Area{ minX: -1, minY: 4, maxX: 120, maxY: 80, }, err: nil, }, }, } for name, test := range table { t.Log("case: ", name, " ---") lm := NewManager() for _, element := range test.headers { lm.Add(element, element.location) } area, err := lm.planAndLayoutHeaders(nil, Area{ minX: -1, minY: -1, maxX: 120, maxY: 80, }) if err != test.expected.err { t.Errorf("%s: expected err '%+v', got error '%+v'", name, test.expected.err, err) } if area != test.expected.area { t.Errorf("%s: expected returned area '%+v', got area '%+v'", name, test.expected.area, area) } } } func Test_planAndLayoutColumns(t *testing.T) { table := map[string]struct { columns []*testElement expected layoutReturn }{ "single column": { columns: []*testElement{newTestElement(t, -1, Area{ minX: -1, minY: -1, maxX: 120, maxY: 80, }, LocationColumn)}, expected: layoutReturn{ area: Area{ minX: 120, minY: -1, maxX: 120, maxY: 80, }, err: nil, }, }, "two equal columns": { columns: []*testElement{ newTestElement(t, -1, Area{ minX: -1, minY: -1, maxX: 59, maxY: 80, }, LocationColumn), newTestElement(t, -1, Area{ minX: 59, minY: -1, maxX: 119, maxY: 80, }, LocationColumn), }, expected: layoutReturn{ area: Area{ minX: 119, minY: -1, maxX: 120, maxY: 80, }, err: nil, }, }, "two odd-sized columns": { columns: []*testElement{ newTestElement(t, 30, Area{ minX: -1, minY: -1, maxX: 29, maxY: 80, }, LocationColumn), newTestElement(t, -1, Area{ minX: 29, minY: -1, maxX: 120, maxY: 80, }, LocationColumn), }, expected: layoutReturn{ area: Area{ minX: 120, minY: -1, maxX: 120, maxY: 80, }, err: nil, }, }, } for name, test := range table { t.Log("case: ", name, " ---") lm := NewManager() for _, element := range test.columns { lm.Add(element, element.location) } area, err := lm.planAndLayoutColumns(nil, Area{ minX: -1, minY: -1, maxX: 120, maxY: 80, }) if err != test.expected.err { t.Errorf("%s: expected err '%+v', got error '%+v'", name, test.expected.err, err) } if area != test.expected.area { t.Errorf("%s: expected returned area '%+v', got area '%+v'", name, test.expected.area, area) } } } func Test_layout(t *testing.T) { table := map[string]struct { elements []*testElement }{ "1 header + 1 footer + 1 column": { elements: []*testElement{ newTestElement(t, 1, Area{ minX: -1, minY: -1, maxX: 120, maxY: 0, }, LocationHeader), newTestElement(t, 1, Area{ minX: -1, minY: 78, maxX: 120, maxY: 80, }, LocationFooter), newTestElement(t, -1, Area{ minX: -1, minY: 0, maxX: 120, maxY: 79, }, LocationColumn), }, }, "1 header + 1 footer + 3 column": { elements: []*testElement{ newTestElement(t, 1, Area{ minX: -1, minY: -1, maxX: 120, maxY: 0, }, LocationHeader), newTestElement(t, 1, Area{ minX: -1, minY: 78, maxX: 120, maxY: 80, }, LocationFooter), newTestElement(t, -1, Area{ minX: -1, minY: 0, maxX: 39, maxY: 79, }, LocationColumn), newTestElement(t, -1, Area{ minX: 39, minY: 0, maxX: 79, maxY: 79, }, LocationColumn), newTestElement(t, -1, Area{ minX: 79, minY: 0, maxX: 119, maxY: 79, }, LocationColumn), }, }, "1 header + 1 footer + 2 equal columns + 1 sized column": { elements: []*testElement{ newTestElement(t, 1, Area{ minX: -1, minY: -1, maxX: 120, maxY: 0, }, LocationHeader), newTestElement(t, 1, Area{ minX: -1, minY: 78, maxX: 120, maxY: 80, }, LocationFooter), newTestElement(t, -1, Area{ minX: -1, minY: 0, maxX: 19, maxY: 79, }, LocationColumn), newTestElement(t, 80, Area{ minX: 19, minY: 0, maxX: 99, maxY: 79, }, LocationColumn), newTestElement(t, -1, Area{ minX: 99, minY: 0, maxX: 119, maxY: 79, }, LocationColumn), }, }, } for name, test := range table { t.Log("case: ", name, " ---") lm := NewManager() for _, element := range test.elements { lm.Add(element, element.location) } err := lm.layout(nil, 120, 80) if err != nil { t.Fatalf("%s: unexpected error: %+v", name, err) } } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/layout/location.go
cmd/dive/cli/internal/ui/v1/layout/location.go
package layout const ( LocationFooter Location = iota LocationHeader LocationColumn ) type Location int
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/layout/layout.go
cmd/dive/cli/internal/ui/v1/layout/layout.go
package layout import "github.com/awesome-gocui/gocui" type Layout interface { Name() string Layout(g *gocui.Gui, minX, minY, maxX, maxY int) error RequestedSize(available int) *int IsVisible() bool OnLayoutChange() error }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/layout/area.go
cmd/dive/cli/internal/ui/v1/layout/area.go
package layout type Area struct { minX, minY, maxX, maxY int }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/layout/manager.go
cmd/dive/cli/internal/ui/v1/layout/manager.go
package layout import ( "fmt" "github.com/awesome-gocui/gocui" "github.com/wagoodman/dive/internal/log" ) type Constraint func(int) int type Manager struct { lastX, lastY int lastHeaderArea, lastFooterArea, lastColumnArea Area elements map[Location][]Layout } func NewManager() *Manager { return &Manager{ elements: make(map[Location][]Layout), } } func (lm *Manager) Add(element Layout, location Location) { if _, exists := lm.elements[location]; !exists { lm.elements[location] = make([]Layout, 0) } lm.elements[location] = append(lm.elements[location], element) } func (lm *Manager) planAndLayoutHeaders(g *gocui.Gui, area Area) (Area, error) { // layout headers top down if elements, exists := lm.elements[LocationHeader]; exists { for _, element := range elements { // a visible header cannot take up the whole screen, default to 1. // this eliminates the need to discover a default size based on all element requests height := 0 if element.IsVisible() { requestedHeight := element.RequestedSize(area.maxY) if requestedHeight != nil { height = *requestedHeight } else { height = 1 } } // layout the header within the allocated space err := element.Layout(g, area.minX, area.minY, area.maxX, area.minY+height) if err != nil { log.WithFields("element", element.Name(), "error", err).Error("failed to layout header") return area, err } // restrict the available screen real estate area.minY += height } } return area, nil } func (lm *Manager) planFooters(g *gocui.Gui, area Area) (Area, []int) { var footerHeights = make([]int, 0) // we need to layout the footers last, but account for them when drawing the columns. This block is for planning // out the real estate needed for the footers now (but not laying out yet) if elements, exists := lm.elements[LocationFooter]; exists { footerHeights = make([]int, len(elements)) for idx := range footerHeights { footerHeights[idx] = 1 } for idx, element := range elements { // a visible footer cannot take up the whole screen, default to 1. // this eliminates the need to discover a default size based on all element requests height := 0 if element.IsVisible() { requestedHeight := element.RequestedSize(area.maxY) if requestedHeight != nil { height = *requestedHeight } else { height = 1 } } footerHeights[idx] = height } // restrict the available screen real estate for _, height := range footerHeights { area.maxY -= height } } return area, footerHeights } func (lm *Manager) planAndLayoutColumns(g *gocui.Gui, area Area) (Area, error) { // layout columns left to right if elements, exists := lm.elements[LocationColumn]; exists { widths := make([]int, len(elements)) for idx := range widths { widths[idx] = -1 } variableColumns := len(elements) availableWidth := area.maxX + 1 // first pass: planout the column sizes based on the given requests for idx, element := range elements { if !element.IsVisible() { widths[idx] = 0 variableColumns-- continue } requestedWidth := element.RequestedSize(availableWidth) if requestedWidth != nil { widths[idx] = *requestedWidth variableColumns-- availableWidth -= widths[idx] } } // at least one column must have a variable width, force the last column to be variable if there are no // variable columns if variableColumns == 0 { variableColumns = 1 widths[len(widths)-1] = -1 } defaultWidth := availableWidth / variableColumns // second pass: layout columns left to right (based off predetermined widths) for idx, element := range elements { // use the requested or default width width := widths[idx] if width == -1 { width = defaultWidth } // layout the column within the allocated space err := element.Layout(g, area.minX, area.minY, area.minX+width, area.maxY) if err != nil { return area, fmt.Errorf("failed to layout '%s' column: %w", element.Name(), err) } // move left to right, scratching off real estate as it is taken area.minX += width } } return area, nil } func (lm *Manager) layoutFooters(g *gocui.Gui, area Area, footerHeights []int) error { // layout footers top down (which is why the list is reversed). Top down is needed due to border overlap. if elements, exists := lm.elements[LocationFooter]; exists { for idx := len(elements) - 1; idx >= 0; idx-- { element := elements[idx] height := footerHeights[idx] var topY, bottomY, bottomPadding int for oIdx := 0; oIdx <= idx; oIdx++ { bottomPadding += footerHeights[oIdx] } topY = area.maxY - bottomPadding - height // +1 for border bottomY = topY + height + 1 // layout the footer within the allocated space // note: since the headers and rows are inclusive counting from -1 (to account for a border) we must // do the same vertically, thus a -1 is needed for a starting Y err := element.Layout(g, area.minX, topY, area.maxX, bottomY) if err != nil { return fmt.Errorf("failed to layout %q footer: %w", element.Name(), err) } } } return nil } func (lm *Manager) notifyLayoutChange() error { for _, elements := range lm.elements { for _, element := range elements { err := element.OnLayoutChange() if err != nil { return err } } } return nil } func (lm *Manager) Layout(g *gocui.Gui) error { curMaxX, curMaxY := g.Size() return lm.layout(g, curMaxX, curMaxY) } // layout defines the definition of the window pane size and placement relations to one another. This // is invoked at application start and whenever the screen dimensions change. // A few things to note: // 1. gocui has borders around all views (even if Frame=false). This means there are a lot of +1/-1 magic numbers // needed (but there are comments!). // 2. since there are borders, in order for it to appear as if there aren't any spaces for borders, the views must // overlap. To prevent screen artifacts, all elements must be layedout from the top of the screen to the bottom. func (lm *Manager) layout(g *gocui.Gui, curMaxX, curMaxY int) error { var headerAreaChanged, footerAreaChanged, columnAreaChanged bool // compare current screen size with the last known size at time of layout area := Area{ minX: -1, minY: -1, maxX: curMaxX, maxY: curMaxY, } var hasResized bool if curMaxX != lm.lastX || curMaxY != lm.lastY { hasResized = true } lm.lastX, lm.lastY = curMaxX, curMaxY // pass 1: plan and layout elements // headers... area, err := lm.planAndLayoutHeaders(g, area) if err != nil { return err } if area != lm.lastHeaderArea { headerAreaChanged = true } lm.lastHeaderArea = area // plan footers... don't layout until all columns have been layedout. This is necessary since we must layout from // top to bottom, but we need the real estate planned for the footers to determine the bottom of the columns. var footerArea = area area, footerHeights := lm.planFooters(g, area) if area != lm.lastFooterArea { footerAreaChanged = true } lm.lastFooterArea = area // columns... area, err = lm.planAndLayoutColumns(g, area) if err != nil { return nil } if area != lm.lastColumnArea { columnAreaChanged = true } lm.lastColumnArea = area // footers... layout according to the original available area and planned heights err = lm.layoutFooters(g, footerArea, footerHeights) if err != nil { return nil } // pass 2: notify everyone of a layout change (allow to update and render) // note: this may mean that each element will update and rerender, which may cause a secondary layout call. // the conditions which we notify elements of layout changes must be very selective! if hasResized || headerAreaChanged || footerAreaChanged || columnAreaChanged { return lm.notifyLayoutChange() } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/layout/compound/layer_details_column.go
cmd/dive/cli/internal/ui/v1/layout/compound/layer_details_column.go
package compound import ( "fmt" "github.com/awesome-gocui/gocui" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/view" "github.com/wagoodman/dive/internal/log" "github.com/wagoodman/dive/internal/utils" ) type LayerDetailsCompoundLayout struct { layer *view.Layer layerDetails *view.LayerDetails imageDetails *view.ImageDetails constrainRealEstate bool } func NewLayerDetailsCompoundLayout(layer *view.Layer, layerDetails *view.LayerDetails, imageDetails *view.ImageDetails) *LayerDetailsCompoundLayout { return &LayerDetailsCompoundLayout{ layer: layer, layerDetails: layerDetails, imageDetails: imageDetails, } } func (cl *LayerDetailsCompoundLayout) Name() string { return "layer-details-compound-column" } // OnLayoutChange is called whenever the screen dimensions are changed func (cl *LayerDetailsCompoundLayout) OnLayoutChange() error { err := cl.layer.OnLayoutChange() if err != nil { return fmt.Errorf("unable to setup layer controller onLayoutChange: %w", err) } err = cl.layerDetails.OnLayoutChange() if err != nil { return fmt.Errorf("unable to setup layer details controller onLayoutChange: %w", err) } err = cl.imageDetails.OnLayoutChange() if err != nil { return fmt.Errorf("unable to setup image details controller onLayoutChange: %w", err) } return nil } func (cl *LayerDetailsCompoundLayout) layoutRow(g *gocui.Gui, minX, minY, maxX, maxY int, viewName string, setup func(*gocui.View, *gocui.View) error) error { log.WithFields("ui", cl.Name()).Tracef("layoutRow(g, minX: %d, minY: %d, maxX: %d, maxY: %d, viewName: %s, <setup func>)", minX, minY, maxX, maxY, viewName) // header + border headerHeight := 2 // TODO: investigate overlap // note: maxY needs to account for the (invisible) border, thus a +1 headerView, headerErr := g.SetView(viewName+"Header", minX, minY, maxX, minY+headerHeight+1, 0) // we are going to overlap the view over the (invisible) border (so minY will be one less than expected) bodyView, bodyErr := g.SetView(viewName, minX, minY+headerHeight, maxX, maxY, 0) if utils.IsNewView(bodyErr, headerErr) { err := setup(bodyView, headerView) if err != nil { return fmt.Errorf("unable to setup row layout for %s: %w", viewName, err) } } return nil } func (cl *LayerDetailsCompoundLayout) Layout(g *gocui.Gui, minX, minY, maxX, maxY int) error { log.WithFields("ui", cl.Name()).Tracef("layout(minX: %d, minY: %d, maxX: %d, maxY: %d)", minX, minY, maxX, maxY) layouts := []view.View{ cl.layer, cl.layerDetails, cl.imageDetails, } rowHeight := maxY / 3 for i := 0; i < 3; i++ { if err := cl.layoutRow(g, minX, i*rowHeight, maxX, (i+1)*rowHeight, layouts[i].Name(), layouts[i].Setup); err != nil { return fmt.Errorf("unable to layout %q: %w", layouts[i].Name(), err) } } if g.CurrentView() == nil { if _, err := g.SetCurrentView(cl.layer.Name()); err != nil { return fmt.Errorf("unable to set view to layer %q: %w", cl.layer.Name(), err) } } return nil } func (cl *LayerDetailsCompoundLayout) RequestedSize(available int) *int { // "available" is the entire screen real estate, so we can guess when its a bit too small and take action. // This isn't perfect, but it gets the job done for now without complicated layout constraint solvers if available < 90 { cl.layer.ConstrainLayout() cl.constrainRealEstate = true size := 8 return &size } cl.layer.ExpandLayout() cl.constrainRealEstate = false return nil } // todo: make this variable based on the nested views func (cl *LayerDetailsCompoundLayout) IsVisible() bool { return true }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/renderer.go
cmd/dive/cli/internal/ui/v1/view/renderer.go
package view // Controller defines the a renderable terminal screen pane. type Renderer interface { Update() error Render() error IsVisible() bool } type Helper interface { KeyHelp() string }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/status.go
cmd/dive/cli/internal/ui/v1/view/status.go
package view import ( "fmt" "github.com/anchore/go-logger" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/key" "github.com/wagoodman/dive/internal/log" "github.com/wagoodman/dive/internal/utils" "strings" "github.com/awesome-gocui/gocui" ) // Status holds the UI objects and data models for populating the bottom-most pane. Specifically the panel // shows the user a set of possible actions to take in the window and currently selected pane. type Status struct { name string gui *gocui.Gui view *gocui.View logger logger.Logger selectedView Helper requestedHeight int helpKeys []*key.Binding } // newStatusView creates a new view object attached the global [gocui] screen object. func newStatusView(gui *gocui.Gui) *Status { c := new(Status) // populate main fields c.name = "status" c.gui = gui c.helpKeys = make([]*key.Binding, 0) c.requestedHeight = 1 c.logger = log.Nested("ui", "status") return c } func (v *Status) SetCurrentView(r Helper) { v.selectedView = r } func (v *Status) Name() string { return v.name } func (v *Status) AddHelpKeys(keys ...*key.Binding) { v.helpKeys = append(v.helpKeys, keys...) } // Setup initializes the UI concerns within the context of a global [gocui] view object. func (v *Status) Setup(view *gocui.View) error { v.logger.Trace("setup()") // set controller options v.view = view v.view.Frame = false return v.Render() } // IsVisible indicates if the status view pane is currently initialized. func (v *Status) IsVisible() bool { return v != nil } // Update refreshes the state objects for future rendering (currently does nothing). func (v *Status) Update() error { return nil } // OnLayoutChange is called whenever the screen dimensions are changed func (v *Status) OnLayoutChange() error { err := v.Update() if err != nil { return err } return v.Render() } // Render flushes the state objects to the screen. func (v *Status) Render() error { v.logger.Trace("render()") v.gui.Update(func(g *gocui.Gui) error { v.view.Clear() var selectedHelp string if v.selectedView != nil { selectedHelp = v.selectedView.KeyHelp() } _, err := fmt.Fprintln(v.view, v.KeyHelp()+selectedHelp+format.StatusNormal("▏"+strings.Repeat(" ", 1000))) if err != nil { v.logger.WithFields("error", err).Debug("unable to write to buffer") } return err }) return nil } // KeyHelp indicates all the possible global actions a user can take when any pane is selected. func (v *Status) KeyHelp() string { var help string for _, binding := range v.helpKeys { help += binding.RenderKeyHelp() } return help } func (v *Status) Layout(g *gocui.Gui, minX, minY, maxX, maxY int) error { v.logger.Tracef("layout(minX: %d, minY: %d, maxX: %d, maxY: %d)", minX, minY, maxX, maxY) view, viewErr := g.SetView(v.Name(), minX, minY, maxX, maxY, 0) if utils.IsNewView(viewErr) { err := v.Setup(view) if err != nil { return fmt.Errorf("unable to setup status controller: %w", err) } } return nil } func (v *Status) RequestedSize(available int) *int { return &v.requestedHeight }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/filter.go
cmd/dive/cli/internal/ui/v1/view/filter.go
package view import ( "fmt" "github.com/anchore/go-logger" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" "github.com/wagoodman/dive/internal/log" "github.com/wagoodman/dive/internal/utils" "strings" "github.com/awesome-gocui/gocui" ) type FilterEditListener func(string) error // Filter holds the UI objects and data models for populating the bottom row. Specifically the pane that // allows the user to filter the file tree by path. type Filter struct { gui *gocui.Gui view *gocui.View header *gocui.View logger logger.Logger labelStr string maxLength int hidden bool requestedHeight int filterEditListeners []FilterEditListener } // newFilterView creates a new view object attached the global [gocui] screen object. func newFilterView(gui *gocui.Gui) *Filter { c := new(Filter) c.logger = log.Nested("ui", "filter") c.filterEditListeners = make([]FilterEditListener, 0) // populate main fields c.gui = gui c.labelStr = "Path Filter: " c.hidden = true c.requestedHeight = 1 return c } func (v *Filter) AddFilterEditListener(listener ...FilterEditListener) { v.filterEditListeners = append(v.filterEditListeners, listener...) } func (v *Filter) Name() string { return "filter" } // Setup initializes the UI concerns within the context of a global [gocui] view object. func (v *Filter) Setup(view, header *gocui.View) error { log.Trace("Setup()") // set controller options v.view = view v.maxLength = 200 v.view.Frame = false v.view.BgColor = gocui.AttrReverse v.view.Editable = true v.view.Editor = v v.header = header v.header.BgColor = gocui.AttrReverse v.header.Editable = false v.header.Wrap = false v.header.Frame = false return v.Render() } // ToggleFilterView shows/hides the file tree filter pane. func (v *Filter) ToggleVisible() error { // delete all user input from the tree view v.view.Clear() // toggle hiding v.hidden = !v.hidden if !v.hidden { _, err := v.gui.SetCurrentView(v.Name()) if err != nil { return fmt.Errorf("unable to toggle filter view: %w", err) } return nil } // reset the cursor for the next time it is visible // Note: there is a subtle gocui behavior here where this cannot be called when the view // is newly visible. Is this a problem with dive or gocui? return v.view.SetCursor(0, 0) } // IsVisible indicates if the filter view pane is currently initialized func (v *Filter) IsVisible() bool { if v == nil { return false } return !v.hidden } // Edit intercepts the key press events in the filer view to update the file view in real time. func (v *Filter) Edit(view *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) { if !v.IsVisible() { return } cx, _ := view.Cursor() ox, _ := view.Origin() limit := ox+cx+1 > v.maxLength switch { case ch != 0 && mod == 0 && !limit: view.EditWrite(ch) case key == gocui.KeySpace && !limit: view.EditWrite(' ') case key == gocui.KeyBackspace || key == gocui.KeyBackspace2: view.EditDelete(true) } // notify listeners v.notifyFilterEditListeners() } func (v *Filter) notifyFilterEditListeners() { currentValue := strings.TrimSpace(v.view.Buffer()) for _, listener := range v.filterEditListeners { err := listener(currentValue) if err != nil { // note: cannot propagate error from here since this is from the main gogui thread v.logger.WithFields("error", err).Debug("unable to notify filter edit listeners") } } } // Update refreshes the state objects for future rendering (currently does nothing). func (v *Filter) Update() error { return nil } // Render flushes the state objects to the screen. Currently this is the users path filter input. func (v *Filter) Render() error { v.logger.Trace("render()") v.gui.Update(func(g *gocui.Gui) error { _, err := fmt.Fprintln(v.header, format.Header(v.labelStr)) return err }) return nil } // KeyHelp indicates all the possible actions a user can take while the current pane is selected. func (v *Filter) KeyHelp() string { return format.StatusControlNormal("▏Type to filter the file tree ") } // OnLayoutChange is called whenever the screen dimensions are changed func (v *Filter) OnLayoutChange() error { err := v.Update() if err != nil { return err } return v.Render() } func (v *Filter) Layout(g *gocui.Gui, minX, minY, maxX, maxY int) error { v.logger.Tracef("layout(minX: %d, minY: %d, maxX: %d, maxY: %d)", minX, minY, maxX, maxY) label, labelErr := g.SetView(v.Name()+"label", minX, minY, len(v.labelStr), maxY, 0) view, viewErr := g.SetView(v.Name(), minX+(len(v.labelStr)-1), minY, maxX, maxY, 0) if utils.IsNewView(viewErr, labelErr) { err := v.Setup(view, label) if err != nil { return fmt.Errorf("unable to setup filter controller: %w", err) } } return nil } func (v *Filter) RequestedSize(available int) *int { return &v.requestedHeight }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/views.go
cmd/dive/cli/internal/ui/v1/view/views.go
package view import ( "github.com/awesome-gocui/gocui" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" ) type View interface { Setup(*gocui.View, *gocui.View) error Name() string IsVisible() bool } type Views struct { Tree *FileTree Layer *Layer Status *Status Filter *Filter LayerDetails *LayerDetails ImageDetails *ImageDetails Debug *Debug } func NewViews(g *gocui.Gui, cfg v1.Config) (*Views, error) { layer, err := newLayerView(g, cfg) if err != nil { return nil, err } tree, err := newFileTreeView(g, cfg, 0) if err != nil { return nil, err } status := newStatusView(g) // set the layer view as the first selected view status.SetCurrentView(layer) return &Views{ Tree: tree, Layer: layer, Status: status, Filter: newFilterView(g), ImageDetails: &ImageDetails{ gui: g, imageName: cfg.Analysis.Image, imageSize: cfg.Analysis.SizeBytes, efficiency: cfg.Analysis.Efficiency, inefficiencies: cfg.Analysis.Inefficiencies, kb: cfg.Preferences.KeyBindings, }, LayerDetails: &LayerDetails{gui: g, kb: cfg.Preferences.KeyBindings}, Debug: newDebugView(g), }, nil } func (views *Views) Renderers() []Renderer { return []Renderer{ views.Tree, views.Layer, views.Status, views.Filter, views.LayerDetails, views.ImageDetails, } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/debug.go
cmd/dive/cli/internal/ui/v1/view/debug.go
package view import ( "fmt" "github.com/anchore/go-logger" "github.com/awesome-gocui/gocui" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" "github.com/wagoodman/dive/internal/log" "github.com/wagoodman/dive/internal/utils" ) // Debug is just for me :) type Debug struct { name string gui *gocui.Gui view *gocui.View header *gocui.View logger logger.Logger selectedView Helper } // newDebugView creates a new view object attached the global [gocui] screen object. func newDebugView(gui *gocui.Gui) *Debug { c := new(Debug) // populate main fields c.name = "debug" c.gui = gui c.logger = log.Nested("ui", "debug") return c } func (v *Debug) SetCurrentView(r Helper) { v.selectedView = r } func (v *Debug) Name() string { return v.name } // Setup initializes the UI concerns within the context of a global [gocui] view object. func (v *Debug) Setup(view *gocui.View, header *gocui.View) error { v.logger.Trace("setup()") // set controller options v.view = view v.view.Editable = false v.view.Wrap = false v.view.Frame = false v.header = header v.header.Editable = false v.header.Wrap = false v.header.Frame = false return v.Render() } // IsVisible indicates if the status view pane is currently initialized. func (v *Debug) IsVisible() bool { return v != nil } // Update refreshes the state objects for future rendering (currently does nothing). func (v *Debug) Update() error { return nil } // OnLayoutChange is called whenever the screen dimensions are changed func (v *Debug) OnLayoutChange() error { err := v.Update() if err != nil { return err } return v.Render() } // Render flushes the state objects to the screen. func (v *Debug) Render() error { v.logger.Trace("render()") v.gui.Update(func(g *gocui.Gui) error { // update header... v.header.Clear() width, _ := g.Size() headerStr := format.RenderHeader("Debug", width, false) _, _ = fmt.Fprintln(v.header, headerStr) // update view... v.view.Clear() _, err := fmt.Fprintln(v.view, "blerg") if err != nil { v.logger.WithFields("error", err).Debug("unable to write to buffer") } return nil }) return nil } func (v *Debug) Layout(g *gocui.Gui, minX, minY, maxX, maxY int) error { v.logger.Tracef("layout(minX: %d, minY: %d, maxX: %d, maxY: %d)", minX, minY, maxX, maxY) // header headerSize := 1 // note: maxY needs to account for the (invisible) border, thus a +1 header, headerErr := g.SetView(v.Name()+"header", minX, minY, maxX, minY+headerSize+1, 0) // we are going to overlap the view over the (invisible) border (so minY will be one less than expected). // additionally, maxY will be bumped by one to include the border view, viewErr := g.SetView(v.Name(), minX, minY+headerSize, maxX, maxY+1, 0) if utils.IsNewView(viewErr, headerErr) { err := v.Setup(view, header) if err != nil { return fmt.Errorf("unable to setup debug controller: %w", err) } } return nil } func (v *Debug) RequestedSize(available int) *int { return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/cursor.go
cmd/dive/cli/internal/ui/v1/view/cursor.go
package view import ( "errors" "github.com/awesome-gocui/gocui" ) // CursorDown moves the cursor down in the currently selected gocui pane, scrolling the screen as needed. func CursorDown(g *gocui.Gui, v *gocui.View) error { return CursorStep(g, v, 1) } // CursorUp moves the cursor up in the currently selected gocui pane, scrolling the screen as needed. func CursorUp(g *gocui.Gui, v *gocui.View) error { return CursorStep(g, v, -1) } // Moves the cursor the given step distance, setting the origin to the new cursor line func CursorStep(g *gocui.Gui, v *gocui.View, step int) error { cx, cy := v.Cursor() // if there isn't a next line line, err := v.Line(cy + step) if err != nil { return err } if len(line) == 0 { return errors.New("unable to move the cursor, empty line") } if err := v.SetCursor(cx, cy+step); err != nil { ox, oy := v.Origin() if err := v.SetOrigin(ox, oy+step); err != nil { return err } } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/layer_change_listener.go
cmd/dive/cli/internal/ui/v1/view/layer_change_listener.go
package view import ( "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/viewmodel" ) type LayerChangeListener func(viewmodel.LayerSelection) error
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/layer.go
cmd/dive/cli/internal/ui/v1/view/layer.go
package view import ( "fmt" "github.com/anchore/go-logger" "github.com/awesome-gocui/gocui" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/key" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/viewmodel" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/internal/log" ) // Layer holds the UI objects and data models for populating the lower-left pane. // Specifically the pane that shows the image layers and layer selector. type Layer struct { name string gui *gocui.Gui body *gocui.View header *gocui.View vm *viewmodel.LayerSetState kb key.Bindings logger logger.Logger constrainedRealEstate bool listeners []LayerChangeListener helpKeys []*key.Binding } // newLayerView creates a new view object attached the global [gocui] screen object. func newLayerView(gui *gocui.Gui, cfg v1.Config) (c *Layer, err error) { c = new(Layer) c.logger = log.Nested("ui", "layer") c.listeners = make([]LayerChangeListener, 0) // populate main fields c.name = "layer" c.gui = gui c.kb = cfg.Preferences.KeyBindings var compareMode viewmodel.LayerCompareMode switch mode := cfg.Preferences.ShowAggregatedLayerChanges; mode { case true: compareMode = viewmodel.CompareAllLayers case false: compareMode = viewmodel.CompareSingleLayer default: return nil, fmt.Errorf("unknown layer.show-aggregated-changes value: %v", mode) } c.vm = viewmodel.NewLayerSetState(cfg.Analysis.Layers, compareMode) return c, err } func (v *Layer) AddLayerChangeListener(listener ...LayerChangeListener) { v.listeners = append(v.listeners, listener...) } func (v *Layer) notifyLayerChangeListeners() error { bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop := v.vm.GetCompareIndexes() selection := viewmodel.LayerSelection{ Layer: v.CurrentLayer(), BottomTreeStart: bottomTreeStart, BottomTreeStop: bottomTreeStop, TopTreeStart: topTreeStart, TopTreeStop: topTreeStop, } for _, listener := range v.listeners { err := listener(selection) if err != nil { return fmt.Errorf("error notifying layer change listeners: %w", err) } } // this is hacky, and I do not like it if layerDetails, err := v.gui.View("layerDetails"); err == nil { if err := layerDetails.SetCursor(0, 0); err != nil { v.logger.Debug("Couldn't set cursor to 0,0 for layerDetails") } } return nil } func (v *Layer) Name() string { return v.name } // Setup initializes the UI concerns within the context of a global [gocui] view object. func (v *Layer) Setup(body *gocui.View, header *gocui.View) error { v.logger.Trace("Setup()") // set controller options v.body = body v.body.Editable = false v.body.Wrap = false v.body.Frame = false v.header = header v.header.Editable = false v.header.Wrap = false v.header.Frame = false var infos = []key.BindingInfo{ { Config: v.kb.Layer.CompareLayer, OnAction: func() error { return v.setCompareMode(viewmodel.CompareSingleLayer) }, IsSelected: func() bool { return v.vm.CompareMode == viewmodel.CompareSingleLayer }, Display: "Show layer changes", }, { Config: v.kb.Layer.CompareAll, OnAction: func() error { return v.setCompareMode(viewmodel.CompareAllLayers) }, IsSelected: func() bool { return v.vm.CompareMode == viewmodel.CompareAllLayers }, Display: "Show aggregated changes", }, { Config: v.kb.Navigation.Down, Modifier: gocui.ModNone, OnAction: v.CursorDown, }, { Config: v.kb.Navigation.Up, Modifier: gocui.ModNone, OnAction: v.CursorUp, }, { Config: v.kb.Navigation.PageUp, OnAction: v.PageUp, }, { Config: v.kb.Navigation.PageDown, OnAction: v.PageDown, }, } helpKeys, err := key.GenerateBindings(v.gui, v.name, infos) if err != nil { return err } v.helpKeys = helpKeys return v.Render() } // height obtains the height of the current pane (taking into account the lost space due to the header). func (v *Layer) height() uint { _, height := v.body.Size() return uint(height - 1) } func (v *Layer) CompareMode() viewmodel.LayerCompareMode { return v.vm.CompareMode } // IsVisible indicates if the layer view pane is currently initialized. func (v *Layer) IsVisible() bool { return v != nil } // PageDown moves to next page putting the cursor on top func (v *Layer) PageDown() error { step := int(v.height()) + 1 targetLayerIndex := v.vm.LayerIndex + step if targetLayerIndex > len(v.vm.Layers) { step -= targetLayerIndex - (len(v.vm.Layers) - 1) } if step > 0 { // err := CursorStep(v.gui, v.body, step) err := error(nil) if err == nil { return v.SetCursor(v.vm.LayerIndex + step) } } return nil } // PageUp moves to previous page putting the cursor on top func (v *Layer) PageUp() error { step := int(v.height()) + 1 targetLayerIndex := v.vm.LayerIndex - step if targetLayerIndex < 0 { step += targetLayerIndex } if step > 0 { // err := CursorStep(v.gui, v.body, -step) err := error(nil) if err == nil { return v.SetCursor(v.vm.LayerIndex - step) } } return nil } // CursorDown moves the cursor down in the layer pane (selecting a higher layer). func (v *Layer) CursorDown() error { if v.vm.LayerIndex < len(v.vm.Layers)-1 { // err := CursorDown(v.gui, v.body) err := error(nil) if err == nil { return v.SetCursor(v.vm.LayerIndex + 1) } } return nil } // CursorUp moves the cursor up in the layer pane (selecting a lower layer). func (v *Layer) CursorUp() error { if v.vm.LayerIndex > 0 { // err := CursorUp(v.gui, v.body) err := error(nil) if err == nil { return v.SetCursor(v.vm.LayerIndex - 1) } } return nil } // SetOrigin updates the origin of the layer view pane. func (v *Layer) SetOrigin(x, y int) error { if err := v.body.SetOrigin(x, y); err != nil { return err } return nil } // SetCursor resets the cursor and orients the file tree view based on the given layer index. func (v *Layer) SetCursor(layer int) error { v.vm.LayerIndex = layer err := v.notifyLayerChangeListeners() if err != nil { return err } return v.Render() } // CurrentLayer returns the Layer object currently selected. func (v *Layer) CurrentLayer() *image.Layer { return v.vm.Layers[v.vm.LayerIndex] } // setCompareMode switches the layer comparison between a single-layer comparison to an aggregated comparison. func (v *Layer) setCompareMode(compareMode viewmodel.LayerCompareMode) error { v.vm.CompareMode = compareMode return v.notifyLayerChangeListeners() } // renderCompareBar returns the formatted string for the given layer. func (v *Layer) renderCompareBar(layerIdx int) string { bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop := v.vm.GetCompareIndexes() result := " " if layerIdx >= bottomTreeStart && layerIdx <= bottomTreeStop { result = format.CompareBottom(" ") } if layerIdx >= topTreeStart && layerIdx <= topTreeStop { result = format.CompareTop(" ") } return result } func (v *Layer) ConstrainLayout() { if !v.constrainedRealEstate { v.logger.Debug("constraining layout") v.constrainedRealEstate = true } } func (v *Layer) ExpandLayout() { if v.constrainedRealEstate { v.logger.Debug("expanding layout") v.constrainedRealEstate = false } } // OnLayoutChange is called whenever the screen dimensions are changed func (v *Layer) OnLayoutChange() error { err := v.Update() if err != nil { return err } return v.Render() } // Update refreshes the state objects for future rendering (currently does nothing). func (v *Layer) Update() error { return nil } // Render flushes the state objects to the screen. The layers pane reports: // 1. the layers of the image + metadata // 2. the current selected image func (v *Layer) Render() error { v.logger.Trace("render()") // indicate when selected title := "Layers" isSelected := v.gui.CurrentView() == v.body v.gui.Update(func(g *gocui.Gui) error { var err error // update header v.header.Clear() width, _ := g.Size() if v.constrainedRealEstate { headerStr := format.RenderNoHeader(width, isSelected) headerStr += "\nLayer" _, err := fmt.Fprintln(v.header, headerStr) if err != nil { return err } } else { headerStr := format.RenderHeader(title, width, isSelected) headerStr += fmt.Sprintf("Cmp"+image.LayerFormat, "Size", "Command") _, err := fmt.Fprintln(v.header, headerStr) if err != nil { return err } } // update contents v.body.Clear() for idx, layer := range v.vm.Layers { var layerStr string if v.constrainedRealEstate { layerStr = fmt.Sprintf("%-4d", layer.Index) } else { layerStr = layer.String() } compareBar := v.renderCompareBar(idx) if idx == v.vm.LayerIndex { _, err = fmt.Fprintln(v.body, compareBar+" "+format.Selected(layerStr)) } else { _, err = fmt.Fprintln(v.body, compareBar+" "+layerStr) } if err != nil { return err } } // Adjust origin, if necessary maxBodyDisplayHeight := int(v.height()) if v.vm.LayerIndex > maxBodyDisplayHeight { if err := v.SetOrigin(0, v.vm.LayerIndex-maxBodyDisplayHeight); err != nil { return err } } return nil }) return nil } func (v *Layer) LayerCount() int { return len(v.vm.Layers) } // KeyHelp indicates all the possible actions a user can take while the current pane is selected. func (v *Layer) KeyHelp() string { var help string for _, binding := range v.helpKeys { help += binding.RenderKeyHelp() } return help }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/image_details.go
cmd/dive/cli/internal/ui/v1/view/image_details.go
package view import ( "fmt" "github.com/anchore/go-logger" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/key" "github.com/wagoodman/dive/internal/log" "strconv" "strings" "github.com/awesome-gocui/gocui" "github.com/dustin/go-humanize" "github.com/wagoodman/dive/dive/filetree" ) type ImageDetails struct { gui *gocui.Gui body *gocui.View header *gocui.View logger logger.Logger imageName string imageSize uint64 efficiency float64 inefficiencies filetree.EfficiencySlice kb key.Bindings } func (v *ImageDetails) Name() string { return "imageDetails" } func (v *ImageDetails) Setup(body, header *gocui.View) error { v.logger = log.Nested("ui", "imageDetails") v.logger.Trace("Setup()") v.body = body v.body.Editable = false v.body.Wrap = true v.body.Highlight = true v.body.Frame = false v.header = header v.header.Editable = false v.header.Wrap = true v.header.Highlight = false v.header.Frame = false var infos = []key.BindingInfo{ { Config: v.kb.Navigation.Down, Modifier: gocui.ModNone, OnAction: v.CursorDown, }, { Config: v.kb.Navigation.Up, Modifier: gocui.ModNone, OnAction: v.CursorUp, }, { Config: v.kb.Navigation.PageUp, OnAction: v.PageUp, }, { Config: v.kb.Navigation.PageDown, OnAction: v.PageDown, }, } _, err := key.GenerateBindings(v.gui, v.Name(), infos) if err != nil { return err } return nil } // Render flushes the state objects to the screen. The details pane reports: // 1. the image efficiency score // 2. the estimated wasted image space // 3. a list of inefficient file allocations func (v *ImageDetails) Render() error { analysisTemplate := "%5s %12s %-s\n" inefficiencyReport := fmt.Sprintf(format.Header(analysisTemplate), "Count", "Total Space", "Path") var wastedSpace int64 for idx := 0; idx < len(v.inefficiencies); idx++ { data := v.inefficiencies[len(v.inefficiencies)-1-idx] wastedSpace += data.CumulativeSize inefficiencyReport += fmt.Sprintf(analysisTemplate, strconv.Itoa(len(data.Nodes)), humanize.Bytes(uint64(data.CumulativeSize)), data.Path) } imageNameStr := fmt.Sprintf("%s %s", format.Header("Image name:"), v.imageName) imageSizeStr := fmt.Sprintf("%s %s", format.Header("Total Image size:"), humanize.Bytes(v.imageSize)) efficiencyStr := fmt.Sprintf("%s %d %%", format.Header("Image efficiency score:"), int(100.0*v.efficiency)) wastedSpaceStr := fmt.Sprintf("%s %s", format.Header("Potential wasted space:"), humanize.Bytes(uint64(wastedSpace))) v.gui.Update(func(g *gocui.Gui) error { width, _ := v.body.Size() imageHeaderStr := format.RenderHeader("Image Details", width, v.gui.CurrentView() == v.body) v.header.Clear() _, err := fmt.Fprintln(v.header, imageHeaderStr) if err != nil { log.WithFields("error", err).Debug("unable to write to buffer") } var lines = []string{ imageNameStr, imageSizeStr, wastedSpaceStr, efficiencyStr, " ", // to avoid an empty line so CursorDown can work as expected inefficiencyReport, } v.body.Clear() _, err = fmt.Fprintln(v.body, strings.Join(lines, "\n")) if err != nil { log.WithFields("error", err).Debug("unable to write to buffer") } return err }) return nil } func (v *ImageDetails) OnLayoutChange() error { if err := v.Update(); err != nil { return err } return v.Render() } // IsVisible indicates if the details view pane is currently initialized. func (v *ImageDetails) IsVisible() bool { return v.body != nil } func (v *ImageDetails) PageUp() error { _, height := v.body.Size() if err := CursorStep(v.gui, v.body, -height); err != nil { v.logger.WithFields("error", err).Debugf("couldn't move the cursor up by %d steps", height) } return nil } func (v *ImageDetails) PageDown() error { _, height := v.body.Size() if err := CursorStep(v.gui, v.body, height); err != nil { v.logger.WithFields("error", err).Debugf("couldn't move the cursor down by %d steps", height) } return nil } func (v *ImageDetails) CursorUp() error { if err := CursorUp(v.gui, v.body); err != nil { v.logger.WithFields("error", err).Debug("couldn't move the cursor up") } return nil } func (v *ImageDetails) CursorDown() error { if err := CursorDown(v.gui, v.body); err != nil { v.logger.WithFields("error", err).Debug("couldn't move the cursor down") } return nil } // KeyHelp indicates all the possible actions a user can take while the current pane is selected (currently does nothing). func (v *ImageDetails) KeyHelp() string { return "" } // Update refreshes the state objects for future rendering. func (v *ImageDetails) Update() error { return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/layer_details.go
cmd/dive/cli/internal/ui/v1/view/layer_details.go
package view import ( "fmt" "github.com/anchore/go-logger" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/key" "github.com/wagoodman/dive/internal/log" "strings" "github.com/awesome-gocui/gocui" "github.com/dustin/go-humanize" "github.com/wagoodman/dive/dive/image" ) type LayerDetails struct { gui *gocui.Gui header *gocui.View body *gocui.View CurrentLayer *image.Layer kb key.Bindings logger logger.Logger } func (v *LayerDetails) Name() string { return "layerDetails" } func (v *LayerDetails) Setup(body, header *gocui.View) error { v.logger = log.Nested("ui", "layerDetails") v.logger.Trace("setup()") v.body = body v.body.Editable = false v.body.Wrap = true v.body.Highlight = true v.body.Frame = false v.header = header v.header.Editable = false v.header.Wrap = true v.header.Highlight = false v.header.Frame = false var infos = []key.BindingInfo{ { Config: v.kb.Navigation.Down, Modifier: gocui.ModNone, OnAction: v.CursorDown, }, { Config: v.kb.Navigation.Up, Modifier: gocui.ModNone, OnAction: v.CursorUp, }, } _, err := key.GenerateBindings(v.gui, v.Name(), infos) if err != nil { return err } return nil } // Render flushes the state objects to the screen. // The details pane reports the currently selected layer's: // 1. tags // 2. ID // 3. digest // 4. command func (v *LayerDetails) Render() error { v.gui.Update(func(g *gocui.Gui) error { v.header.Clear() width, _ := v.body.Size() layerHeaderStr := format.RenderHeader("Layer Details", width, v.gui.CurrentView() == v.body) _, err := fmt.Fprintln(v.header, layerHeaderStr) if err != nil { return err } // this is for layer details var lines = make([]string, 0) tags := "(none)" if len(v.CurrentLayer.Names) > 0 { tags = strings.Join(v.CurrentLayer.Names, ", ") } lines = append(lines, []string{ format.Header("Tags: ") + tags, format.Header("Id: ") + v.CurrentLayer.Id, format.Header("Size: ") + humanize.Bytes(v.CurrentLayer.Size), format.Header("Digest: ") + v.CurrentLayer.Digest, format.Header("Command:"), v.CurrentLayer.Command, }...) v.body.Clear() if _, err = fmt.Fprintln(v.body, strings.Join(lines, "\n")); err != nil { log.WithFields("layer", v.CurrentLayer.Id, "error", err).Debug("unable to write to buffer") } return nil }) return nil } func (v *LayerDetails) OnLayoutChange() error { if err := v.Update(); err != nil { return err } return v.Render() } // IsVisible indicates if the details view pane is currently initialized. func (v *LayerDetails) IsVisible() bool { return v.body != nil } // CursorUp moves the cursor up in the details pane func (v *LayerDetails) CursorUp() error { if err := CursorUp(v.gui, v.body); err != nil { v.logger.WithFields("error", err).Debug("couldn't move the cursor up") } return nil } // CursorDown moves the cursor up in the details pane func (v *LayerDetails) CursorDown() error { if err := CursorDown(v.gui, v.body); err != nil { v.logger.WithFields("error", err).Debug("couldn't move the cursor down") } return nil } // KeyHelp indicates all the possible actions a user can take while the current pane is selected (currently does nothing). func (v *LayerDetails) KeyHelp() string { return "" } // Update refreshes the state objects for future rendering. func (v *LayerDetails) Update() error { return nil } func (v *LayerDetails) SetCursor(x, y int) error { return v.body.SetCursor(x, y) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/view/filetree.go
cmd/dive/cli/internal/ui/v1/view/filetree.go
package view import ( "fmt" "github.com/anchore/go-logger" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/format" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/key" "github.com/wagoodman/dive/cmd/dive/cli/internal/ui/v1/viewmodel" "github.com/wagoodman/dive/internal/log" "github.com/wagoodman/dive/internal/utils" "regexp" "github.com/awesome-gocui/gocui" "github.com/wagoodman/dive/dive/filetree" ) type ViewOptionChangeListener func() error type ViewExtractListener func(string) error // FileTree holds the UI objects and data models for populating the right pane. Specifically, the pane that // shows selected layer or aggregate file ASCII tree. type FileTree struct { name string gui *gocui.Gui view *gocui.View header *gocui.View vm *viewmodel.FileTreeViewModel title string kb key.Bindings logger logger.Logger filterRegex *regexp.Regexp listeners []ViewOptionChangeListener extractListeners []ViewExtractListener helpKeys []*key.Binding requestedWidthRatio float64 } // newFileTreeView creates a new view object attached the global [gocui] screen object. func newFileTreeView(gui *gocui.Gui, cfg v1.Config, initial int) (v *FileTree, err error) { v = new(FileTree) v.logger = log.Nested("ui", "filetree") v.listeners = make([]ViewOptionChangeListener, 0) // populate main fields v.name = "filetree" v.gui = gui v.kb = cfg.Preferences.KeyBindings v.vm, err = viewmodel.NewFileTreeViewModel(cfg, initial) if err != nil { return nil, err } requestedWidthRatio := cfg.Preferences.FiletreePaneWidth if requestedWidthRatio >= 1 || requestedWidthRatio <= 0 { v.logger.Warnf("invalid config value: 'filetree.pane-width' should be 0 < value < 1, given '%v'", requestedWidthRatio) requestedWidthRatio = 0.5 } v.requestedWidthRatio = requestedWidthRatio return v, err } func (v *FileTree) AddViewOptionChangeListener(listener ...ViewOptionChangeListener) { v.listeners = append(v.listeners, listener...) } func (v *FileTree) AddViewExtractListener(listener ...ViewExtractListener) { v.extractListeners = append(v.extractListeners, listener...) } func (v *FileTree) SetTitle(title string) { v.title = title } func (v *FileTree) SetFilterRegex(filterRegex *regexp.Regexp) { v.filterRegex = filterRegex } func (v *FileTree) Name() string { return v.name } // Setup initializes the UI concerns within the context of a global [gocui] view object. func (v *FileTree) Setup(view, header *gocui.View) error { log.Trace("setup()") // set controller options v.view = view v.view.Editable = false v.view.Wrap = false v.view.Frame = false v.header = header v.header.Editable = false v.header.Wrap = false v.header.Frame = false var infos = []key.BindingInfo{ { Config: v.kb.Filetree.ToggleCollapseDir, OnAction: v.toggleCollapse, Display: "Collapse dir", }, { Config: v.kb.Filetree.ToggleCollapseAllDir, OnAction: v.toggleCollapseAll, Display: "Collapse all dir", }, { Config: v.kb.Filetree.ToggleSortOrder, OnAction: v.toggleSortOrder, Display: "Toggle sort order", }, { Config: v.kb.Filetree.ExtractFile, OnAction: v.extractFile, Display: "Extract File", }, { Config: v.kb.Filetree.ToggleAddedFiles, OnAction: func() error { return v.toggleShowDiffType(filetree.Added) }, IsSelected: func() bool { return !v.vm.HiddenDiffTypes[filetree.Added] }, Display: "Added", }, { Config: v.kb.Filetree.ToggleRemovedFiles, OnAction: func() error { return v.toggleShowDiffType(filetree.Removed) }, IsSelected: func() bool { return !v.vm.HiddenDiffTypes[filetree.Removed] }, Display: "Removed", }, { Config: v.kb.Filetree.ToggleModifiedFiles, OnAction: func() error { return v.toggleShowDiffType(filetree.Modified) }, IsSelected: func() bool { return !v.vm.HiddenDiffTypes[filetree.Modified] }, Display: "Modified", }, { Config: v.kb.Filetree.ToggleUnmodifiedFiles, OnAction: func() error { return v.toggleShowDiffType(filetree.Unmodified) }, IsSelected: func() bool { return !v.vm.HiddenDiffTypes[filetree.Unmodified] }, Display: "Unmodified", }, { Config: v.kb.Filetree.ToggleTreeAttributes, OnAction: v.toggleAttributes, IsSelected: func() bool { return v.vm.ShowAttributes }, Display: "Attributes", }, { Config: v.kb.Filetree.ToggleWrapTree, OnAction: v.toggleWrapTree, IsSelected: func() bool { return v.view.Wrap }, Display: "Wrap", }, { Config: v.kb.Navigation.PageUp, OnAction: v.PageUp, }, { Config: v.kb.Navigation.PageDown, OnAction: v.PageDown, }, { Config: v.kb.Navigation.Down, Modifier: gocui.ModNone, OnAction: v.CursorDown, }, { Config: v.kb.Navigation.Up, Modifier: gocui.ModNone, OnAction: v.CursorUp, }, { Config: v.kb.Navigation.Left, Modifier: gocui.ModNone, OnAction: v.CursorLeft, }, { Config: v.kb.Navigation.Right, Modifier: gocui.ModNone, OnAction: v.CursorRight, }, } helpKeys, err := key.GenerateBindings(v.gui, v.name, infos) if err != nil { return err } v.helpKeys = helpKeys _, height := v.view.Size() v.vm.Setup(0, height) _ = v.Update() _ = v.Render() return nil } // IsVisible indicates if the file tree view pane is currently initialized func (v *FileTree) IsVisible() bool { return v != nil } // ResetCursor moves the cursor back to the top of the buffer and translates to the top of the buffer. func (v *FileTree) resetCursor() { _ = v.view.SetCursor(0, 0) v.vm.ResetCursor() } // SetTreeByLayer populates the view model by stacking the indicated image layer file trees. func (v *FileTree) SetTree(bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop int) error { err := v.vm.SetTreeByLayer(bottomTreeStart, bottomTreeStop, topTreeStart, topTreeStop) if err != nil { return err } _ = v.Update() return v.Render() } // CursorDown moves the cursor down and renders the view. // Note: we cannot use the gocui buffer since any state change requires writing the entire tree to the buffer. // Instead we are keeping an upper and lower bounds of the tree string to render and only flushing // this range into the view buffer. This is much faster when tree sizes are large. func (v *FileTree) CursorDown() error { if v.vm.CursorDown() { return v.Render() } return nil } // CursorUp moves the cursor up and renders the view. // Note: we cannot use the gocui buffer since any state change requires writing the entire tree to the buffer. // Instead we are keeping an upper and lower bounds of the tree string to render and only flushing // this range into the view buffer. This is much faster when tree sizes are large. func (v *FileTree) CursorUp() error { if v.vm.CursorUp() { return v.Render() } return nil } // CursorLeft moves the cursor up until we reach the Parent Node or top of the tree func (v *FileTree) CursorLeft() error { err := v.vm.CursorLeft(v.filterRegex) if err != nil { return err } _ = v.Update() return v.Render() } // CursorRight descends into directory expanding it if needed func (v *FileTree) CursorRight() error { err := v.vm.CursorRight(v.filterRegex) if err != nil { return err } _ = v.Update() return v.Render() } // PageDown moves to next page putting the cursor on top func (v *FileTree) PageDown() error { err := v.vm.PageDown() if err != nil { return err } return v.Render() } // PageUp moves to previous page putting the cursor on top func (v *FileTree) PageUp() error { err := v.vm.PageUp() if err != nil { return err } return v.Render() } // getAbsPositionNode determines the selected screen cursor's location in the file tree, returning the selected FileNode. // func (controller *FileTree) getAbsPositionNode() (node *filetree.FileNode) { // return controller.vm.getAbsPositionNode(filterRegex()) // } // ToggleCollapse will collapse/expand the selected FileNode. func (v *FileTree) toggleCollapse() error { err := v.vm.ToggleCollapse(v.filterRegex) if err != nil { return err } _ = v.Update() return v.Render() } // ToggleCollapseAll will collapse/expand the all directories. func (v *FileTree) toggleCollapseAll() error { err := v.vm.ToggleCollapseAll() if err != nil { return err } if v.vm.CollapseAll { v.resetCursor() } _ = v.Update() return v.Render() } func (v *FileTree) toggleSortOrder() error { err := v.vm.ToggleSortOrder() if err != nil { return err } v.resetCursor() _ = v.Update() return v.Render() } func (v *FileTree) extractFile() error { node := v.vm.CurrentNode(v.filterRegex) for _, listener := range v.extractListeners { err := listener(node.Path()) if err != nil { return err } } return nil } func (v *FileTree) toggleWrapTree() error { v.view.Wrap = !v.view.Wrap err := v.Update() if err != nil { return err } err = v.Render() if err != nil { return err } // we need to render the changes to the status pane as well (not just this contoller/view) return v.notifyOnViewOptionChangeListeners() } func (v *FileTree) notifyOnViewOptionChangeListeners() error { for _, listener := range v.listeners { err := listener() if err != nil { return fmt.Errorf("notifyOnViewOptionChangeListeners error: %w", err) } } return nil } // ToggleAttributes will show/hide file attributes func (v *FileTree) toggleAttributes() error { err := v.vm.ToggleAttributes() if err != nil { return err } err = v.Update() if err != nil { return err } err = v.Render() if err != nil { return err } // we need to render the changes to the status pane as well (not just this controller/view) return v.notifyOnViewOptionChangeListeners() } // ToggleShowDiffType will show/hide the selected DiffType in the filetree pane. func (v *FileTree) toggleShowDiffType(diffType filetree.DiffType) error { v.vm.ToggleShowDiffType(diffType) err := v.Update() if err != nil { return err } err = v.Render() if err != nil { return err } // we need to render the changes to the status pane as well (not just this controller/view) return v.notifyOnViewOptionChangeListeners() } // OnLayoutChange is called by the UI framework to inform the view-model of the new screen dimensions func (v *FileTree) OnLayoutChange() error { err := v.Update() if err != nil { return err } return v.Render() } // Update refreshes the state objects for future rendering. func (v *FileTree) Update() error { var width, height int if v.view != nil { width, height = v.view.Size() } else { // before the TUI is setup there may not be a controller to reference. Use the entire screen as reference. width, height = v.gui.Size() } // height should account for the header return v.vm.Update(v.filterRegex, width, height-1) } // Render flushes the state objects (file tree) to the pane. func (v *FileTree) Render() error { v.logger.Trace("render()") title := v.title isSelected := v.gui.CurrentView() == v.view v.gui.Update(func(g *gocui.Gui) error { // update the header v.header.Clear() width, _ := g.Size() headerStr := format.RenderHeader(title, width, isSelected) if v.vm.ShowAttributes { headerStr += fmt.Sprintf(filetree.AttributeFormat+" %s", "P", "ermission", "UID:GID", "Size", "Filetree") } _, _ = fmt.Fprintln(v.header, headerStr) // update the contents v.view.Clear() err := v.vm.Render() if err != nil { return err } _, err = fmt.Fprint(v.view, v.vm.Buffer.String()) return err }) return nil } // KeyHelp indicates all the possible actions a user can take while the current pane is selected. func (v *FileTree) KeyHelp() string { var help string for _, binding := range v.helpKeys { help += binding.RenderKeyHelp() } return help } func (v *FileTree) Layout(g *gocui.Gui, minX, minY, maxX, maxY int) error { v.logger.Tracef("layout(minX: %d, minY: %d, maxX: %d, maxY: %d)", minX, minY, maxX, maxY) attributeRowSize := 0 // make the layout responsive to the available realestate. Make more room for the main content by hiding auxiliary // content when there is not enough room if maxX-minX < 60 { v.vm.ConstrainLayout() } else { v.vm.ExpandLayout() } if v.vm.ShowAttributes { attributeRowSize = 1 } // header + attribute header headerSize := 1 + attributeRowSize // note: maxY needs to account for the (invisible) border, thus a +1 header, headerErr := g.SetView(v.Name()+"header", minX, minY, maxX, minY+headerSize+1, 0) // we are going to overlap the view over the (invisible) border (so minY will be one less than expected). // additionally, maxY will be bumped by one to include the border view, viewErr := g.SetView(v.Name(), minX, minY+headerSize, maxX, maxY+1, 0) if utils.IsNewView(viewErr, headerErr) { err := v.Setup(view, header) if err != nil { return fmt.Errorf("unable to setup tree controller: %w", err) } } return nil } func (v *FileTree) RequestedSize(available int) *int { // var requestedWidth = int(float64(available) * (1.0 - v.requestedWidthRatio)) // return &requestedWidth return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/cmd/dive/cli/internal/ui/v1/format/format.go
cmd/dive/cli/internal/ui/v1/format/format.go
package format import ( "fmt" "strings" "github.com/fatih/color" "github.com/lunixbochs/vtclean" ) const ( // selectedLeftBracketStr = " " // selectedRightBracketStr = " " // selectedFillStr = " " // //leftBracketStr = "▏" //rightBracketStr = "▕" //fillStr = "─" // selectedLeftBracketStr = " " // selectedRightBracketStr = " " // selectedFillStr = "━" // //leftBracketStr = "▏" //rightBracketStr = "▕" //fillStr = "─" selectedLeftBracketStr = "┃" selectedRightBracketStr = "┣" selectedFillStr = "━" leftBracketStr = "│" rightBracketStr = "├" fillStr = "─" selectStr = " ● " // selectStr = " " ) var ( Header func(...interface{}) string Selected func(...interface{}) string StatusSelected func(...interface{}) string StatusNormal func(...interface{}) string StatusControlSelected func(...interface{}) string StatusControlNormal func(...interface{}) string CompareTop func(...interface{}) string CompareBottom func(...interface{}) string reset = color.New(color.Reset).Sprint("") ) func init() { wrapper := func(fn func(a ...any) string) func(a ...any) string { return func(a ...any) string { // for some reason not all color formatter functions are not applying RESET, we'll add it manually for now return fn(a...) + reset } } Selected = wrapper(color.New(color.ReverseVideo, color.Bold).SprintFunc()) Header = wrapper(color.New(color.Bold).SprintFunc()) StatusSelected = wrapper(color.New(color.BgMagenta, color.FgWhite).SprintFunc()) StatusNormal = wrapper(color.New(color.ReverseVideo).SprintFunc()) StatusControlSelected = wrapper(color.New(color.BgMagenta, color.FgWhite, color.Bold).SprintFunc()) StatusControlNormal = wrapper(color.New(color.ReverseVideo, color.Bold).SprintFunc()) CompareTop = wrapper(color.New(color.BgMagenta).SprintFunc()) CompareBottom = wrapper(color.New(color.BgGreen).SprintFunc()) } func RenderNoHeader(width int, selected bool) string { if selected { return strings.Repeat(selectedFillStr, width) } return strings.Repeat(fillStr, width) } func RenderHeader(title string, width int, selected bool) string { if selected { body := Header(fmt.Sprintf("%s%s ", selectStr, title)) bodyLen := len(vtclean.Clean(body, false)) repeatCount := width - bodyLen - 2 if repeatCount < 0 { repeatCount = 0 } return fmt.Sprintf("%s%s%s%s\n", selectedLeftBracketStr, body, selectedRightBracketStr, strings.Repeat(selectedFillStr, repeatCount)) // return fmt.Sprintf("%s%s%s%s\n", Selected(selectedLeftBracketStr), body, Selected(selectedRightBracketStr), Selected(strings.Repeat(selectedFillStr, width-bodyLen-2))) // return fmt.Sprintf("%s%s%s%s\n", Selected(selectedLeftBracketStr), body, Selected(selectedRightBracketStr), strings.Repeat(selectedFillStr, width-bodyLen-2)) } body := Header(fmt.Sprintf(" %s ", title)) bodyLen := len(vtclean.Clean(body, false)) repeatCount := width - bodyLen - 2 if repeatCount < 0 { repeatCount = 0 } return fmt.Sprintf("%s%s%s%s\n", leftBracketStr, body, rightBracketStr, strings.Repeat(fillStr, repeatCount)) } func RenderHelpKey(control, title string, selected bool) string { if selected { return StatusSelected("▏") + StatusControlSelected(control) + StatusSelected(" "+title+" ") } else { return StatusNormal("▏") + StatusControlNormal(control) + StatusNormal(" "+title+" ") } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/get_image_resolver.go
dive/get_image_resolver.go
package dive import ( "fmt" "strings" "github.com/wagoodman/dive/dive/image" "github.com/wagoodman/dive/dive/image/docker" "github.com/wagoodman/dive/dive/image/podman" ) const ( SourceUnknown ImageSource = iota SourceDockerEngine SourcePodmanEngine SourceDockerArchive ) type ImageSource int var ImageSources = []string{SourceDockerEngine.String(), SourcePodmanEngine.String(), SourceDockerArchive.String()} func (r ImageSource) String() string { return [...]string{"unknown", "docker", "podman", "docker-archive"}[r] } func ParseImageSource(r string) ImageSource { switch r { case SourceDockerEngine.String(): return SourceDockerEngine case SourcePodmanEngine.String(): return SourcePodmanEngine case SourceDockerArchive.String(): return SourceDockerArchive case "docker-tar": return SourceDockerArchive default: return SourceUnknown } } func DeriveImageSource(image string) (ImageSource, string) { s := strings.SplitN(image, "://", 2) if len(s) < 2 { return SourceUnknown, "" } scheme, imageSource := s[0], s[1] switch scheme { case SourceDockerEngine.String(): return SourceDockerEngine, imageSource case SourcePodmanEngine.String(): return SourcePodmanEngine, imageSource case SourceDockerArchive.String(): return SourceDockerArchive, imageSource case "docker-tar": return SourceDockerArchive, imageSource } return SourceUnknown, "" } func GetImageResolver(r ImageSource) (image.Resolver, error) { switch r { case SourceDockerEngine: return docker.NewResolverFromEngine(), nil case SourcePodmanEngine: return podman.NewResolverFromEngine(), nil case SourceDockerArchive: return docker.NewResolverFromArchive(), nil } return nil, fmt.Errorf("unable to determine image resolver") }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/resolver.go
dive/image/resolver.go
package image import "golang.org/x/net/context" type Resolver interface { Name() string Fetch(ctx context.Context, id string) (*Image, error) Build(ctx context.Context, options []string) (*Image, error) ContentReader } type ContentReader interface { Extract(ctx context.Context, id string, layer string, path string) error }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/image.go
dive/image/image.go
package image import ( "github.com/wagoodman/dive/dive/filetree" ) type Image struct { Request string Trees []*filetree.FileTree Layers []*Layer }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/layer.go
dive/image/layer.go
package image import ( "fmt" "strings" "github.com/dustin/go-humanize" "github.com/wagoodman/dive/dive/filetree" ) const ( LayerFormat = "%7s %s" ) type Layer struct { Id string Index int Command string Size uint64 Tree *filetree.FileTree Names []string Digest string } func (l *Layer) ShortId() string { rangeBound := 15 id := l.Id if length := len(id); length < 15 { rangeBound = length } id = id[0:rangeBound] return id } func (l *Layer) commandPreview() string { // Layers using heredocs can be multiple lines; rendering relies on // Layer.String to be a single line. return strings.Replace(l.Command, "\n", "↵", -1) } func (l *Layer) String() string { if l.Index == 0 { return fmt.Sprintf(LayerFormat, humanize.Bytes(l.Size), "FROM "+l.ShortId()) } return fmt.Sprintf(LayerFormat, humanize.Bytes(l.Size), l.commandPreview()) }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/analysis.go
dive/image/analysis.go
package image import ( "context" "github.com/wagoodman/dive/dive/filetree" ) type Analysis struct { Image string Layers []*Layer RefTrees []*filetree.FileTree Efficiency float64 SizeBytes uint64 UserSizeByes uint64 // this is all bytes except for the base image WastedUserPercent float64 // = wasted-bytes/user-size-bytes WastedBytes uint64 Inefficiencies filetree.EfficiencySlice } func Analyze(ctx context.Context, img *Image) (*Analysis, error) { efficiency, inefficiencies := filetree.Efficiency(img.Trees) var sizeBytes, userSizeBytes uint64 for i, v := range img.Layers { sizeBytes += v.Size if i != 0 { userSizeBytes += v.Size } } var wastedBytes uint64 for _, file := range inefficiencies { wastedBytes += uint64(file.CumulativeSize) } return &Analysis{ Image: img.Request, Layers: img.Layers, RefTrees: img.Trees, Efficiency: efficiency, UserSizeByes: userSizeBytes, SizeBytes: sizeBytes, WastedBytes: wastedBytes, WastedUserPercent: float64(wastedBytes) / float64(userSizeBytes), Inefficiencies: inefficiencies, }, nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/manifest.go
dive/image/docker/manifest.go
package docker import ( "encoding/json" "fmt" ) type manifest struct { ConfigPath string `json:"Config"` RepoTags []string `json:"RepoTags"` LayerTarPaths []string `json:"Layers"` } func newManifest(manifestBytes []byte) manifest { var manifest []manifest err := json.Unmarshal(manifestBytes, &manifest) if err != nil { panic(fmt.Errorf("failed to unmarshal manifest: %w", err)) } return manifest[0] }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/docker_host_windows.go
dive/image/docker/docker_host_windows.go
package docker const ( defaultDockerHost = "npipe:////.pipe/docker_engine" )
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/docker_host_unix.go
dive/image/docker/docker_host_unix.go
//go:build !windows package docker const ( defaultDockerHost = "unix:///var/run/docker.sock" )
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/config.go
dive/image/docker/config.go
package docker import ( "encoding/json" "fmt" ) type config struct { History []historyEntry `json:"history"` RootFs rootFs `json:"rootfs"` } type rootFs struct { Type string `json:"type"` DiffIds []string `json:"diff_ids"` } type historyEntry struct { ID string Size uint64 Created string `json:"created"` Author string `json:"author"` CreatedBy string `json:"created_by"` EmptyLayer bool `json:"empty_layer"` } func newConfig(configBytes []byte) config { var imageConfig config err := json.Unmarshal(configBytes, &imageConfig) if err != nil { panic(fmt.Errorf("failed to unmarshal docker config: %w", err)) } layerIdx := 0 for idx := range imageConfig.History { if imageConfig.History[idx].EmptyLayer { imageConfig.History[idx].ID = "<missing>" } else { imageConfig.History[idx].ID = imageConfig.RootFs.DiffIds[layerIdx] layerIdx++ } } return imageConfig } func isConfig(configBytes []byte) bool { var imageConfig config err := json.Unmarshal(configBytes, &imageConfig) if err != nil { return false } return imageConfig.RootFs.Type == "layers" }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/build.go
dive/image/docker/build.go
package docker import ( "fmt" "path/filepath" "strings" "github.com/scylladb/go-set/strset" "github.com/spf13/afero" ) const ( defaultDockerfileName = "Dockerfile" defaultContainerfileName = "Containerfile" ) func buildImageFromCli(fs afero.Fs, buildArgs []string) (string, error) { iidfile, err := afero.TempFile(fs, "", "dive.*.iid") if err != nil { return "", err } defer fs.Remove(iidfile.Name()) // nolint:errcheck defer iidfile.Close() var allArgs []string if isFileFlagsAreSet(buildArgs, "-f", "--file") { allArgs = append([]string{"--iidfile", iidfile.Name()}, buildArgs...) } else { containerFilePath, err := tryFindContainerfile(fs, buildArgs) if err != nil { return "", err } allArgs = append([]string{"--iidfile", iidfile.Name(), "-f", containerFilePath}, buildArgs...) } err = runDockerCmd("build", allArgs...) if err != nil { return "", err } imageId, err := afero.ReadFile(fs, iidfile.Name()) if err != nil { return "", err } return string(imageId), nil } // isFileFlagsAreSet Checks if specified flags are present in the argument list. func isFileFlagsAreSet(args []string, flags ...string) bool { flagSet := strset.New(flags...) for i, arg := range args { if flagSet.Has(arg) && i+1 < len(args) { return true } } return false } // tryFindContainerfile loops through provided build arguments and tries to find a Containerfile or a Dockerfile. func tryFindContainerfile(fs afero.Fs, buildArgs []string) (string, error) { // Look for a build context within the provided build arguments. // Test build arguments one by one to find a valid path containing default names of `Containerfile` or a `Dockerfile` (in that order). candidates := []string{ defaultContainerfileName, // Containerfile strings.ToLower(defaultContainerfileName), // containerfile defaultDockerfileName, // Dockerfile strings.ToLower(defaultDockerfileName), // dockerfile } for _, arg := range buildArgs { fileInfo, err := fs.Stat(arg) if err == nil && fileInfo.IsDir() { for _, candidate := range candidates { filePath := filepath.Join(arg, candidate) if exists, _ := afero.Exists(fs, filePath); exists { return filePath, nil } } } } return "", fmt.Errorf("could not find Containerfile or Dockerfile\n") }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/cli.go
dive/image/docker/cli.go
package docker import ( "fmt" "github.com/wagoodman/dive/internal/log" "github.com/wagoodman/dive/internal/utils" "os" "os/exec" "strings" ) // runDockerCmd runs a given Docker command in the current tty func runDockerCmd(cmdStr string, args ...string) error { if !isDockerClientBinaryAvailable() { return fmt.Errorf("cannot find docker client executable") } allArgs := utils.CleanArgs(append([]string{cmdStr}, args...)) fullCmd := strings.Join(append([]string{"docker"}, allArgs...), " ") log.WithFields("cmd", fullCmd).Trace("executing") cmd := exec.Command("docker", allArgs...) cmd.Env = os.Environ() cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin return cmd.Run() } func isDockerClientBinaryAvailable() bool { _, err := exec.LookPath("docker") return err == nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/image_archive.go
dive/image/docker/image_archive.go
package docker import ( "archive/tar" "bytes" "compress/gzip" "encoding/json" "fmt" "io" "os" "path" "path/filepath" "strings" "github.com/klauspost/compress/zstd" "github.com/wagoodman/dive/dive/filetree" "github.com/wagoodman/dive/dive/image" ) type ImageArchive struct { manifest manifest config config layerMap map[string]*filetree.FileTree } func NewImageArchive(tarFile io.ReadCloser) (*ImageArchive, error) { img := &ImageArchive{ layerMap: make(map[string]*filetree.FileTree), } tarReader := tar.NewReader(tarFile) // store discovered json files in a map so we can read the image in one pass jsonFiles := make(map[string][]byte) var currentLayer uint for { header, err := tarReader.Next() if err == io.EOF { break } if err != nil { fmt.Println(err) os.Exit(1) } name := header.Name // some layer tars can be relative layer symlinks to other layer tars if header.Typeflag == tar.TypeSymlink || header.Typeflag == tar.TypeReg { // For the Docker image format, use file name conventions if strings.HasSuffix(name, ".tar") { currentLayer++ layerReader := tar.NewReader(tarReader) tree, err := processLayerTar(name, layerReader) if err != nil { return img, err } // add the layer to the image img.layerMap[tree.Name] = tree } else if strings.HasSuffix(name, ".tar.gz") || strings.HasSuffix(name, "tgz") { currentLayer++ // Add gzip reader gz, err := gzip.NewReader(tarReader) if err != nil { return img, err } // Add tar reader layerReader := tar.NewReader(gz) // Process layer tree, err := processLayerTar(name, layerReader) if err != nil { return img, err } // add the layer to the image img.layerMap[tree.Name] = tree } else if strings.HasSuffix(name, ".json") || strings.HasPrefix(name, "sha256:") { fileBuffer, err := io.ReadAll(tarReader) if err != nil { return img, err } jsonFiles[name] = fileBuffer } else if strings.HasPrefix(name, "blobs/") { // For the OCI-compatible image format (used since Docker 25), use mime sniffing // but limit this to only the blobs/ (containing the config, and the layers) // The idea here is that we try various formats in turn, and those tries should // never consume more bytes than this buffer contains so we can start again. // 512 bytes ought to be enough (as that's the size of a TAR entry header), // but play it safe with 1024 bytes. This should also include very small layers. buffer := make([]byte, 1024) n, err := io.ReadFull(tarReader, buffer) if err != nil && err != io.ErrUnexpectedEOF { return img, err } originalReader := func() io.Reader { return io.MultiReader(bytes.NewReader(buffer[:n]), tarReader) } // Try reading a gzip/estargz compressed layer gzipReader, err := gzip.NewReader(originalReader()) if err == nil { layerReader := tar.NewReader(gzipReader) tree, err := processLayerTar(name, layerReader) if err == nil { currentLayer++ // add the layer to the image img.layerMap[tree.Name] = tree continue } } // Try reading a zstd compressed layer zstdReader, err := zstd.NewReader(originalReader()) if err == nil { layerReader := tar.NewReader(zstdReader) tree, err := processLayerTar(name, layerReader) if err == nil { currentLayer++ // add the layer to the image img.layerMap[tree.Name] = tree continue } } // Try reading a plain tar layer layerReader := tar.NewReader(originalReader()) tree, err := processLayerTar(name, layerReader) if err == nil { currentLayer++ // add the layer to the image img.layerMap[tree.Name] = tree continue } // Not a TAR/GZIP/ZSTD, might be a JSON file decoder := json.NewDecoder(bytes.NewReader(buffer[:n])) token, err := decoder.Token() if _, ok := token.(json.Delim); err == nil && ok { // Looks like a JSON object (or array) // XXX: should we add a header.Size check too? fileBuffer, err := io.ReadAll(originalReader()) if err != nil { return img, err } jsonFiles[name] = fileBuffer } // Ignore every other unknown file type } } } manifestContent, exists := jsonFiles["manifest.json"] if exists { img.manifest = newManifest(manifestContent) } else { // manifest.json is not part of the OCI spec, docker includes it for compatibility // Provide compatibility by finding the config and using our layerMap var configPath string for path, content := range jsonFiles { if isConfig(content) { configPath = path break } } if len(configPath) == 0 { return img, fmt.Errorf("could not find image manifest") } var layerPaths []string for k := range img.layerMap { layerPaths = append(layerPaths, k) } img.manifest = manifest{ ConfigPath: configPath, LayerTarPaths: layerPaths, } } configContent, exists := jsonFiles[img.manifest.ConfigPath] if !exists { return img, fmt.Errorf("could not find image config") } img.config = newConfig(configContent) return img, nil } func processLayerTar(name string, reader *tar.Reader) (*filetree.FileTree, error) { tree := filetree.NewFileTree() tree.Name = name fileInfos, err := getFileList(reader) if err != nil { return nil, err } for _, element := range fileInfos { tree.FileSize += uint64(element.Size) _, _, err := tree.AddPath(element.Path, element) if err != nil { return nil, err } } return tree, nil } func getFileList(tarReader *tar.Reader) ([]filetree.FileInfo, error) { var files []filetree.FileInfo for { header, err := tarReader.Next() if err == io.EOF { break } else if err != nil { return nil, err } // always ensure relative path notations are not parsed as part of the filename name := path.Clean(header.Name) if name == "." { continue } switch header.Typeflag { case tar.TypeXGlobalHeader: return nil, fmt.Errorf("unexpected tar file: (XGlobalHeader): type=%v name=%s", header.Typeflag, name) case tar.TypeXHeader: return nil, fmt.Errorf("unexpected tar file (XHeader): type=%v name=%s", header.Typeflag, name) default: files = append(files, filetree.NewFileInfoFromTarHeader(tarReader, header, name)) } } return files, nil } func (img *ImageArchive) ToImage(id string) (*image.Image, error) { trees := make([]*filetree.FileTree, 0) // build the content tree for _, treeName := range img.manifest.LayerTarPaths { tr, exists := img.layerMap[treeName] if exists { trees = append(trees, tr) continue } return nil, fmt.Errorf("could not find '%s' in parsed layers", treeName) } // build the layers array layers := make([]*image.Layer, 0) // note that the engineResolver config stores images in reverse chronological order, so iterate backwards through layers // as you iterate chronologically through history (ignoring history items that have no layer contents) // Note: history is not required metadata in a docker image! histIdx := 0 for idx, tree := range trees { // ignore empty layers, we are only observing layers with content historyObj := historyEntry{ CreatedBy: "(missing)", } for nextHistIdx := histIdx; nextHistIdx < len(img.config.History); nextHistIdx++ { if !img.config.History[nextHistIdx].EmptyLayer { histIdx = nextHistIdx break } } if histIdx < len(img.config.History) && !img.config.History[histIdx].EmptyLayer { historyObj = img.config.History[histIdx] histIdx++ } historyObj.Size = tree.FileSize dockerLayer := layer{ history: historyObj, index: idx, tree: tree, } layers = append(layers, dockerLayer.ToLayer()) } return &image.Image{ Request: id, Trees: trees, Layers: layers, }, nil } func ExtractFromImage(tarFile io.ReadCloser, l string, p string) error { tarReader := tar.NewReader(tarFile) for { header, err := tarReader.Next() if err == io.EOF { break } if err != nil { fmt.Println(err) os.Exit(1) } name := header.Name switch header.Typeflag { case tar.TypeReg: if name == l { err = extractInner(tar.NewReader(tarReader), p) if err != nil { return err } return nil } default: continue } } return nil } func extractInner(reader *tar.Reader, p string) error { target := strings.TrimPrefix(p, "/") for { header, err := reader.Next() if err == io.EOF { break } if err != nil { fmt.Println(err) os.Exit(1) } name := header.Name switch header.Typeflag { case tar.TypeReg: if strings.HasPrefix(name, target) { err := os.MkdirAll(filepath.Dir(name), 0755) if err != nil { return err } out, err := os.Create(name) if err != nil { return err } _, err = io.Copy(out, reader) if err != nil { return err } } default: continue } } return nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/layer.go
dive/image/docker/layer.go
package docker import ( "strings" "github.com/wagoodman/dive/dive/filetree" "github.com/wagoodman/dive/dive/image" ) // Layer represents a Docker image layer and metadata type layer struct { history historyEntry index int tree *filetree.FileTree } // String represents a layer in a columnar format. func (l *layer) ToLayer() *image.Layer { id := strings.Split(l.tree.Name, "/")[0] return &image.Layer{ Id: id, Index: l.index, Command: strings.TrimPrefix(l.history.CreatedBy, "/bin/sh -c "), Size: l.history.Size, Tree: l.tree, // todo: query docker api for tags Names: []string{"(unavailable)"}, Digest: l.history.ID, } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/engine_resolver.go
dive/image/docker/engine_resolver.go
package docker import ( "fmt" "github.com/spf13/afero" "github.com/wagoodman/dive/internal/bus/event/payload" "github.com/wagoodman/dive/internal/log" "io" "net/http" "os" "strings" cliconfig "github.com/docker/cli/cli/config" "github.com/docker/cli/cli/connhelper" ddocker "github.com/docker/cli/cli/context/docker" ctxstore "github.com/docker/cli/cli/context/store" "github.com/docker/docker/client" "golang.org/x/net/context" "github.com/wagoodman/dive/dive/image" ) type engineResolver struct{} func NewResolverFromEngine() *engineResolver { return &engineResolver{} } // Name returns the name of the resolver to display to the user. func (r *engineResolver) Name() string { return "docker-engine" } func (r *engineResolver) Fetch(ctx context.Context, id string) (*image.Image, error) { reader, err := r.fetchArchive(ctx, id) if err != nil { return nil, err } defer reader.Close() img, err := NewImageArchive(reader) if err != nil { return nil, err } return img.ToImage(id) } func (r *engineResolver) Build(ctx context.Context, args []string) (*image.Image, error) { id, err := buildImageFromCli(afero.NewOsFs(), args) if err != nil { return nil, err } return r.Fetch(ctx, id) } func (r *engineResolver) Extract(ctx context.Context, id string, l string, p string) error { reader, err := r.fetchArchive(ctx, id) if err != nil { return err } if err := ExtractFromImage(io.NopCloser(reader), l, p); err == nil { return nil } return fmt.Errorf("unable to extract from image '%s': %+v", id, err) } func (r *engineResolver) fetchArchive(ctx context.Context, id string) (io.ReadCloser, error) { var err error var dockerClient *client.Client host, err := determineDockerHost() if err != nil { return nil, fmt.Errorf("could not determine docker host: %v", err) } clientOpts := []client.Opt{client.FromEnv} clientOpts = append(clientOpts, client.WithHost(host)) switch strings.Split(host, ":")[0] { case "ssh": helper, err := connhelper.GetConnectionHelper(host) if err != nil { return nil, fmt.Errorf("failed to get docker connection helper: %w", err) } clientOpts = append(clientOpts, func(c *client.Client) error { httpClient := &http.Client{ Transport: &http.Transport{ DialContext: helper.Dialer, }, } return client.WithHTTPClient(httpClient)(c) }) clientOpts = append(clientOpts, client.WithHost(host)) clientOpts = append(clientOpts, client.WithDialContext(helper.Dialer)) default: if os.Getenv("DOCKER_TLS_VERIFY") != "" && os.Getenv("DOCKER_CERT_PATH") == "" { os.Setenv("DOCKER_CERT_PATH", "~/.docker") } } clientOpts = append(clientOpts, client.WithAPIVersionNegotiation()) dockerClient, err = client.NewClientWithOpts(clientOpts...) if err != nil { return nil, err } _, err = dockerClient.ImageInspect(ctx, id) if err != nil { // check if the error is due to the image not existing locally if client.IsErrNotFound(err) { mon := payload.GetGenericProgressFromContext(ctx) if mon != nil { mon.AtomicStage.Set("attempting to pull") log.Debugf("the image is not available locally, pulling %q", id) } else { log.Infof("the image is not available locally, pulling %q", id) } err = runDockerCmd("pull", id) if err != nil { return nil, err } } else { // Some other error occurred, return it return nil, err } } readCloser, err := dockerClient.ImageSave(ctx, []string{id}) if err != nil { return nil, err } return readCloser, nil } // determineDockerHost tries to the determine the docker host that we should connect to // in the following order of decreasing precedence: // - value of "DOCKER_HOST" environment variable // - host retrieved from the current context (specified via DOCKER_CONTEXT) // - "default docker host" for the host operating system, otherwise func determineDockerHost() (string, error) { // If the docker host is explicitly set via the "DOCKER_HOST" environment variable, // then its a no-brainer :shrug: if os.Getenv("DOCKER_HOST") != "" { return os.Getenv("DOCKER_HOST"), nil } currentContext := os.Getenv("DOCKER_CONTEXT") if currentContext == "" { cf, err := cliconfig.Load(cliconfig.Dir()) if err != nil { return "", err } currentContext = cf.CurrentContext } if currentContext == "" { // If a docker context is neither specified via the "DOCKER_CONTEXT" environment variable nor via the // $HOME/.docker/config file, then we fall back to connecting to the "default docker host" meant for // the host operating system. return defaultDockerHost, nil } storeConfig := ctxstore.NewConfig( func() interface{} { return &ddocker.EndpointMeta{} }, ctxstore.EndpointTypeGetter(ddocker.DockerEndpoint, func() interface{} { return &ddocker.EndpointMeta{} }), ) st := ctxstore.New(cliconfig.ContextStoreDir(), storeConfig) md, err := st.GetMetadata(currentContext) if err != nil { return "", err } dockerEP, ok := md.Endpoints[ddocker.DockerEndpoint] if !ok { return "", err } dockerEPMeta, ok := dockerEP.(ddocker.EndpointMeta) if !ok { return "", fmt.Errorf("expected docker.EndpointMeta, got %T", dockerEP) } if dockerEPMeta.Host != "" { return dockerEPMeta.Host, nil } // We might end up here, if the context was created with the `host` set to an empty value (i.e. ''). // For example: // ```sh // docker context create foo --docker "host=" // ``` // In such scenario, we mimic the `docker` cli and try to connect to the "default docker host". return defaultDockerHost, nil }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/testing.go
dive/image/docker/testing.go
package docker import ( "github.com/stretchr/testify/require" "golang.org/x/net/context" "os" "testing" "github.com/wagoodman/dive/dive/image" ) func TestLoadArchive(t testing.TB, tarPath string) (*ImageArchive, error) { t.Helper() f, err := os.Open(tarPath) if err != nil { return nil, err } defer f.Close() return NewImageArchive(f) } func TestAnalysisFromArchive(t testing.TB, path string) *image.Analysis { t.Helper() archive, err := TestLoadArchive(t, path) require.NoError(t, err, "unable to load archive") img, err := archive.ToImage(path) require.NoError(t, err, "unable to convert archive to image") result, err := image.Analyze(context.Background(), img) require.NoError(t, err, "unable to analyze image") return result }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false
wagoodman/dive
https://github.com/wagoodman/dive/blob/d6c691947f8fda635c952a17ee3b7555379d58f0/dive/image/docker/image_archive_analysis_test.go
dive/image/docker/image_archive_analysis_test.go
package docker import ( "testing" ) func Test_Analysis(t *testing.T) { table := map[string]struct { efficiency float64 sizeBytes uint64 userSizeBytes uint64 wastedBytes uint64 wastedPercent float64 path string }{ "docker-image": {0.9844212134184309, 1220598, 66237, 32025, 0.4834911001404049, "../../../.data/test-docker-image.tar"}, } for name, test := range table { result := TestAnalysisFromArchive(t, test.path) if result.SizeBytes != test.sizeBytes { t.Errorf("%s.%s: expected sizeBytes=%v, got %v", t.Name(), name, test.sizeBytes, result.SizeBytes) } if result.UserSizeByes != test.userSizeBytes { t.Errorf("%s.%s: expected userSizeBytes=%v, got %v", t.Name(), name, test.userSizeBytes, result.UserSizeByes) } if result.WastedBytes != test.wastedBytes { t.Errorf("%s.%s: expected wasterBytes=%v, got %v", t.Name(), name, test.wastedBytes, result.WastedBytes) } if result.WastedUserPercent != test.wastedPercent { t.Errorf("%s.%s: expected wastedPercent=%v, got %v", t.Name(), name, test.wastedPercent, result.WastedUserPercent) } if result.Efficiency != test.efficiency { t.Errorf("%s.%s: expected efficiency=%v, got %v", t.Name(), name, test.efficiency, result.Efficiency) } } }
go
MIT
d6c691947f8fda635c952a17ee3b7555379d58f0
2026-01-07T08:35:43.531869Z
false