chore: import official kitty sources from upstream

Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty,
vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
BlackAngelTV committed 2026-11-04 11:20:47 +01:00
commit 7e7d249099
1134 files changed
+433629

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
def syntax_aliases(x: str) -> dict[str, str]:
ans = {}
for x in x.split():
k, _, v = x.partition(':')
ans[k] = v
return ans
+178
View File
@@ -0,0 +1,178 @@
package choose_files
import (
"archive/tar"
"compress/bzip2"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/klauspost/compress/gzip"
"github.com/klauspost/compress/zip"
"github.com/klauspost/compress/zstd"
"github.com/nwaples/rardecode/v2"
"github.com/ulikunitz/xz"
"github.com/kovidgoyal/go-parallel"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func IsSupportedArchiveFile(abspath string) bool {
name := strings.ToLower(filepath.Base(abspath))
ext := filepath.Ext(name)
switch ext {
case ".zip", ".tgz", ".tbz2", ".tzst", ".txz", ".rar":
return true
case ".gz", ".bz2", ".zst", ".xz":
name = name[:len(name)-len(ext)]
ext = filepath.Ext(name)
return ext == ".tar"
default:
return false
}
}
type archive_preview struct {
path string
metadata fs.FileInfo
WakeupMainThread func() bool
ch chan *MessagePreview
mp *MessagePreview
}
func displayFilename(s string) string {
if isPrintableUTF8(s) {
return s
}
return fmt.Sprintf("%X", utils.UnsafeStringToBytes(s))
}
func isPrintableUTF8(s string) bool {
for _, r := range s {
if r == '\uFFFD' { // replacement char
return false
}
}
return true
}
// render runs in a worker goroutine. It must send its result only on output
// and never access p.ch or p.mp, as those are owned by the main thread.
func (p *archive_preview) render(output chan<- *MessagePreview, base *MessagePreview) {
var result *MessagePreview
// Send the result from here so that exactly one result is sent even if
// something, including one of the deferred Close() calls below, panics.
defer func() {
if r := recover(); r != nil {
result = NewFileMetadataPreviewWithError(p.path, p.metadata, fmt.Errorf("Failed to read the archive with error: %w", parallel.Format_stacktrace_on_panic(r, 1)))
}
output <- result
close(output)
p.WakeupMainThread()
}()
name := strings.ToLower(filepath.Base(p.path))
ext := filepath.Ext(name)
names := []string{""}
populate_tar := func(r io.Reader) {
tr := tar.NewReader(r)
for len(names) < 500 {
hdr, err := tr.Next()
if err != nil {
break
}
names = append(names, displayFilename(hdr.Name))
}
}
switch ext {
case ".zip":
r, err := zip.OpenReader(p.path)
if err == nil || errors.Is(err, zip.ErrInsecurePath) {
defer r.Close()
for _, f := range r.File {
if f.NonUTF8 {
names = append(names, displayFilename(f.Name))
} else {
names = append(names, f.Name)
}
}
}
case ".rar":
r, err := rardecode.OpenReader(p.path, rardecode.SkipCheck)
if err == nil {
defer r.Close()
for len(names) < 500 {
hdr, err := r.Next()
if err != nil {
break
}
names = append(names, displayFilename(hdr.Name))
}
}
case ".gz", ".tgz":
if f, err := os.Open(p.path); err == nil {
defer f.Close()
if gz, err := gzip.NewReader(f); err == nil {
defer gz.Close()
populate_tar(gz)
}
}
case ".xz", ".txz":
if f, err := os.Open(p.path); err == nil {
defer f.Close()
if gz, err := xz.NewReader(f); err == nil {
populate_tar(gz)
}
}
case ".bz2", ".tbz2":
if f, err := os.Open(p.path); err == nil {
defer f.Close()
populate_tar(bzip2.NewReader(f))
}
case ".zst", ".tzst":
if f, err := os.Open(p.path); err == nil {
defer f.Close()
if gz, err := zstd.NewReader(f); err == nil {
defer gz.Close()
populate_tar(gz)
}
}
}
mp := *base
mp.trailers = append(mp.trailers, names...)
result = &mp
}
func (p *archive_preview) IsReady() bool { return true }
func (p *archive_preview) Unload() {}
func (p *archive_preview) IsValidForColorScheme(light bool) bool { return true }
func (p *archive_preview) String() string { return fmt.Sprintf("ArchivePreview{%s}", p.path) }
func (p *archive_preview) Render(h *Handler, x, y, width, height int) {
if p.ch != nil {
select {
case mp := <-p.ch:
p.mp = mp
p.ch = nil
default:
}
}
p.mp.Render(h, x, y, width, height)
}
func NewArchivePeview(
abspath string, metadata fs.FileInfo, opts Settings, WakeupMainThread func() bool,
) Preview {
mp := NewFileMetadataPreview(abspath, metadata)
ans := &archive_preview{
path: abspath, metadata: metadata, WakeupMainThread: WakeupMainThread, ch: make(chan *MessagePreview, 1), mp: mp,
}
go ans.render(ans.ch, mp)
return ans
}
+102
View File
@@ -0,0 +1,102 @@
package choose_files
import (
"archive/zip"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
var _ = fmt.Print
func new_test_archive_preview(t *testing.T) (*archive_preview, *MessagePreview) {
t.Helper()
path := filepath.Join(t.TempDir(), "test.zip")
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
zw := zip.NewWriter(f)
for _, name := range []string{"a.txt", "dir/b.txt"} {
w, err := zw.Create(name)
if err != nil {
t.Fatal(err)
}
if _, err = w.Write([]byte(name)); err != nil {
t.Fatal(err)
}
}
if err = zw.Close(); err != nil {
t.Fatal(err)
}
if err = f.Close(); err != nil {
t.Fatal(err)
}
st, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
mp := NewFileMetadataPreview(path, st)
p := &archive_preview{
path: path, metadata: st, ch: make(chan *MessagePreview, 1), mp: mp,
WakeupMainThread: func() bool { return true },
}
return p, mp
}
// Run the archive preview worker, failing the test if it panics, blocks or
// does not send exactly one result.
func run_archive_preview_worker(t *testing.T, p *archive_preview, base *MessagePreview) *MessagePreview {
t.Helper()
output := p.ch
woken := false
p.WakeupMainThread = func() bool { woken = true; return true }
done := make(chan any, 1)
go func() {
defer func() { done <- recover() }()
p.render(output, base)
}()
select {
case r := <-done:
if r != nil {
t.Fatalf("worker panicked: %v", r)
}
case <-time.After(10 * time.Second):
t.Fatal("worker did not finish")
}
result, ok := <-output
if !ok || result == nil {
t.Fatal("worker did not send a result")
}
if _, ok = <-output; ok {
t.Fatal("worker sent more than one result")
}
if !woken {
t.Fatal("worker did not wake up the main thread")
}
return result
}
func TestArchivePreviewListsContents(t *testing.T) {
p, base := new_test_archive_preview(t)
result := run_archive_preview_worker(t, p, base)
for _, name := range []string{"a.txt", "dir/b.txt"} {
if !slices.Contains(result.trailers, name) {
t.Fatalf("archive preview does not list %#v: %#v", name, result.trailers)
}
}
}
// A panic in the worker goroutine must be reported in the preview rather than
// crashing the whole program. A nil base preview makes the worker panic.
func TestArchivePreviewWorkerPanic(t *testing.T) {
p, _ := new_test_archive_preview(t)
result := run_archive_preview_worker(t, p, nil)
if !strings.Contains(strings.Join(result.trailers, "\n"), "Failed to read the archive") {
t.Fatalf("archive preview does not report the panic: %#v", result.trailers)
}
}
+247
View File
@@ -0,0 +1,247 @@
package choose_files
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/kovidgoyal/kitty/tools/icons"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/humanize"
"github.com/kovidgoyal/kitty/tools/utils/images"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
var calibre_needs_cleanup atomic.Bool
var calibre_server_load_finished atomic.Bool
type calibre_server_process struct {
proc *exec.Cmd
stdout io.ReadCloser
stdin io.WriteCloser
file_extensions *utils.Set[string]
}
type CalibreMetadata struct {
Title string `json:"title"`
Authors []string `json:"authors"`
Series string `json:"series"`
Series_index float64 `json:"series_index"`
Tags []string `json:"tags"`
Rating float64 `json:"rating"`
Published time.Time `json:"pubdate"`
Timestamp time.Time `json:"timestamp"`
}
type CalibreResponse struct {
Path string `json:"path"`
Filetypes []string `json:"filetypes"`
Cover string `json:"cover"`
Error string `json:"error"`
Metadata CalibreMetadata `json:"metadata"`
}
func ReadLineWithTimeout(r io.Reader, timeout time.Duration) (string, error) {
type result struct {
line string
err error
}
ch := make(chan result, 1)
go func() {
br := bufio.NewReader(r)
line, err := br.ReadString('\n')
ch <- result{strings.TrimRight(line, "\n"), err}
}()
select {
case res := <-ch:
return res.line, res.err
case <-time.After(timeout):
return "", os.ErrDeadlineExceeded
}
}
var calibre_server = sync.OnceValues(func() (ans *calibre_server_process, err error) {
defer func() { calibre_server_load_finished.Store(true) }()
ans = &calibre_server_process{}
ans.proc = exec.Command("calibre-debug", "-c", "from calibre.ebooks.metadata.cli import *; simple_metadata_server()")
ans.proc.Stderr = nil
if ans.stdout, err = ans.proc.StdoutPipe(); err != nil {
return nil, err
}
if ans.stdin, err = ans.proc.StdinPipe(); err != nil {
ans.stdout.Close()
return nil, err
}
ans.proc.SysProcAttr = &unix.SysProcAttr{Setsid: true}
if err = ans.proc.Start(); err != nil {
err = fmt.Errorf("calibre-debug executable not found in PATH, you must install the calibre program to preview these file types: %w", err)
return
}
calibre_needs_cleanup.Store(true)
payload, _ := json.Marshal(map[string]string{"path": ""})
if _, err = ans.stdin.Write(append(payload, '\n')); err != nil {
err = fmt.Errorf("error writing to calibre metadata server: %w", err)
return
}
line, err := ReadLineWithTimeout(ans.stdout, 2*time.Second)
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
err = fmt.Errorf("timed out waiting for response from calibre metadata server, make sure you are using calibre version >= 8.16")
} else {
err = fmt.Errorf("error reading from calibre metadata server: %w", err)
}
return
}
var r CalibreResponse
if err = json.Unmarshal([]byte(line), &r); err != nil {
err = fmt.Errorf("unexpected response from calibre metadata server: %#v", line)
return
}
ans.file_extensions = utils.NewSet[string](len(r.Filetypes))
for _, ft := range r.Filetypes {
ans.file_extensions.Add("." + ft)
}
return
})
func calibre_cleanup() {
if !calibre_needs_cleanup.Load() {
return
}
calibre_needs_cleanup.Store(false)
calibre, _ := calibre_server()
if calibre.stdin != nil {
calibre.stdin.Close()
}
if calibre.stdout != nil {
calibre.stdout.Close()
}
if calibre.proc != nil {
calibre.proc.Wait()
}
}
func IsSupportedByCalibre(path string) bool {
ext := strings.ToLower(filepath.Ext(filepath.Base(path)))
if len(ext) > 1 {
if calibre_server_load_finished.Load() {
if calibre, err := calibre_server(); err == nil {
return calibre.file_extensions.Has(ext)
}
} else {
// we dont want to delay the render loop waiting for data from
// calibre-server as it causes flicker because the atomic update
// timeout expires, so use a default set of extensions.
go func() { _, _ = calibre_server() }()
return slices.Contains([]string{"cb7", "azw3", "kepub", "zip", "htmlz", "rar", "lrf", "cbr", "tpz", "azw1", "mobi", "lit", "pdf", "updb", "pml", "pobi", "fbz", "azw", "fb2", "cbc", "rtf", "snb", "opf", "txt", "epub", "oebzip", "txtz", "imp", "docx", "odt", "pdb", "rb", "prc", "html", "chm", "pmlz", "cbz", "lrx", "azw4"}, ext[1:])
}
}
return false
}
const CALIBRE_METADATA_KEY = "calibre-metadata.json"
type calibre_renderer int
func (c calibre_renderer) Unmarshall(m map[string]string) (any, error) {
data, err := os.ReadFile(m[CALIBRE_METADATA_KEY])
if err != nil {
return nil, err
}
var ans CalibreResponse
if err = json.Unmarshal(data, &ans); err != nil {
return nil, err
}
return &ans, nil
}
func (c calibre_renderer) Render(path string) (m map[string][]byte, mi metadata, img *images.ImageData, err error) {
cpath, err := os.CreateTemp("", "")
if err != nil {
return
}
defer func() {
cpath.Close()
os.Remove(cpath.Name())
}()
calibre, err := calibre_server()
if err != nil {
return
}
payload, err := json.Marshal(map[string]string{"path": path, "cover": cpath.Name()})
if err != nil {
return
}
calibre.stdin.Write(append(payload, '\n'))
line, err := ReadLineWithTimeout(calibre.stdout, 30*time.Second)
if err != nil {
return
}
lb := []byte(line)
var reply CalibreResponse
if err = json.Unmarshal(lb, &reply); err != nil {
return
}
if reply.Cover == cpath.Name() {
var ip ImagePreviewRenderer
if m, mi, img, err = ip.Render(cpath.Name()); err != nil {
return
}
} else {
m = make(map[string][]byte)
}
mi.custom = &reply
m[CALIBRE_METADATA_KEY] = lb
return
}
func (c calibre_renderer) ShowMetadata(h *Handler, s ShowData) (offset int) {
w := func(text string, center bool) {
if s.height > offset {
offset += h.render_wrapped_text_in_region(text, s.x, s.y+offset, s.width, s.height-offset, center)
}
}
ext := filepath.Ext(s.abspath)
text := fmt.Sprintf("%s: %s", ext, humanize.Bytes(uint64(s.metadata.Size())))
icon := icons.IconForPath(s.abspath)
w(icon+" "+text, true)
r := s.custom_metadata.custom.(*CalibreResponse)
w("Title: "+r.Metadata.Title, false)
w("Authors: "+strings.Join(r.Metadata.Authors, " & "), false)
if r.Metadata.Series != "" {
w(fmt.Sprintf("Series: Book %g of %s", r.Metadata.Series_index, r.Metadata.Series), false)
}
if len(r.Metadata.Tags) > 0 {
w("Tags: "+strings.Join(r.Metadata.Authors, ", "), false)
}
return
}
func (c calibre_renderer) String() string {
return "Calibre"
}
func NewCalibrePreview(
abspath string, metadata fs.FileInfo, opts Settings, WakeupMainThread func() bool,
) Preview {
c := calibre_renderer(0)
if ans, err := NewImagePreview(abspath, metadata, opts, WakeupMainThread, c); err == nil {
return ans
} else {
return NewErrorPreview(err)
}
}
+102
View File
@@ -0,0 +1,102 @@
package choose_files
import (
"bytes"
"encoding/json"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"slices"
"github.com/kovidgoyal/kitty/tools/icons"
"github.com/kovidgoyal/kitty/tools/utils/humanize"
"github.com/kovidgoyal/kitty/tools/utils/images"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
const CMD_METADATA_KEY = "cmd-metadata.json"
type cmd_renderer struct {
cmdline []string
}
func (c cmd_renderer) String() string {
return c.cmdline[0]
}
type CmdResult struct {
Lines []string `json:"lines"`
Image string `json:"image"`
TitleExtra string `json:"title_extra"`
}
func (c cmd_renderer) Render(path string) (m map[string][]byte, mi metadata, img *images.ImageData, err error) {
cmdline := append(slices.Clone(c.cmdline), path)
cmd := exec.Command(cmdline[0], cmdline[1:]...)
cmd.Stdin = nil
cmd.SysProcAttr = &unix.SysProcAttr{Setsid: true}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err = cmd.Run(); err != nil {
err = fmt.Errorf("failed to run %v to read metadata from %s with error: %w and stderr: %s", c.cmdline, path, err, stderr.String())
return
}
var md CmdResult
if err = json.Unmarshal(stdout.Bytes(), &md); err != nil {
err = fmt.Errorf("could not decode JSON response from %v for %s: %w", c.cmdline, path, err)
}
if md.Image != "" {
var ip ImagePreviewRenderer
if m, mi, img, err = ip.Render(md.Image); err != nil {
return
}
}
mi.custom = &md
return
}
func (c cmd_renderer) Unmarshall(m map[string]string) (any, error) {
data, err := os.ReadFile(m[CMD_METADATA_KEY])
if err != nil {
return nil, err
}
var ans CmdResult
if err = json.Unmarshal(data, &ans); err != nil {
return nil, err
}
return &ans, nil
}
func (c cmd_renderer) ShowMetadata(h *Handler, s ShowData) (offset int) {
w := func(text string, center bool) {
if s.height > offset {
offset += h.render_wrapped_text_in_region(text, s.x, s.y+offset, s.width, s.height-offset, center)
}
}
ext := filepath.Ext(s.abspath)
r := s.custom_metadata.custom.(*CmdResult)
text := fmt.Sprintf("%s: %s%s", ext, humanize.Bytes(uint64(s.metadata.Size())), r.TitleExtra)
icon := icons.IconForPath(s.abspath)
w(icon+" "+text, true)
for _, line := range r.Lines {
w(line, false)
}
h.lp.QueueWriteString("\x1b[m") // reset SGR attributes
return
}
func NewCmdPreview(
abspath string, metadata fs.FileInfo, opts Settings, WakeupMainThread func() bool, p previewer,
) Preview {
c := cmd_renderer{p.cmdline}
if ans, err := NewImagePreview(abspath, metadata, opts, WakeupMainThread, c); err == nil {
return ans
} else {
return NewErrorPreview(err)
}
}
+402
View File
@@ -0,0 +1,402 @@
package choose_files
import (
"fmt"
"io/fs"
"slices"
"sync"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type CollectionIndex struct {
Slice, Pos int
}
func (c CollectionIndex) Compare(o CollectionIndex) int {
if c.Slice == o.Slice {
return c.Pos - o.Pos
}
return c.Slice - o.Slice
}
func (c CollectionIndex) Less(o CollectionIndex) bool {
return c.Slice < o.Slice || (c.Slice == o.Slice && c.Pos < o.Pos)
}
func (c *CollectionIndex) NextSlice() {
c.Slice++
c.Pos = 0
}
type ResultCollection struct {
slices [][]ResultItem
append_idx CollectionIndex
batch_size int
}
func NewResultCollection(batch_size int) (ans *ResultCollection) {
batch_size = max(1, batch_size)
return &ResultCollection{
batch_size: batch_size,
slices: [][]ResultItem{make([]ResultItem, batch_size)},
}
}
func (c *ResultCollection) Len() int {
return c.batch_size*(len(c.slices)-1) + c.append_idx.Pos
}
func (c *ResultCollection) NextAppendPointer() (ans *ResultItem) {
s := c.slices[c.append_idx.Slice]
ans = &s[c.append_idx.Pos]
if c.append_idx.Pos+1 < len(s) {
c.append_idx.Pos++
} else if c.append_idx.Slice+1 < len(c.slices) {
c.append_idx.NextSlice()
} else {
c.slices = append(c.slices, make([]ResultItem, 4096))
c.append_idx.NextSlice()
}
return
}
func (c *ResultCollection) Batch(offset *CollectionIndex) (ans []ResultItem) {
if offset.Slice == c.append_idx.Slice {
if offset.Pos < c.append_idx.Pos {
ans = c.slices[offset.Slice][offset.Pos:c.append_idx.Pos]
offset.Pos = c.append_idx.Pos
}
} else if offset.Slice < c.append_idx.Slice {
ans = c.slices[offset.Slice][offset.Pos:]
offset.NextSlice()
}
return
}
func (c *ResultCollection) NextDir(offset *CollectionIndex) (ans string, ignore_files []ignore_file_with_prefix) {
for ans == "" && offset.Compare(c.append_idx) < 0 {
if c.slices[offset.Slice][offset.Pos].ftype&fs.ModeDir != 0 {
ans = c.slices[offset.Slice][offset.Pos].text
ignore_files = c.slices[offset.Slice][offset.Pos].ignore_files
}
offset.Pos++
if offset.Pos >= len(c.slices[offset.Slice]) {
offset.NextSlice()
}
}
return
}
type SortedResults struct {
slices [][]*ResultItem
mutex sync.Mutex
len int
}
func NewSortedResults() *SortedResults { return &SortedResults{} }
func (s *SortedResults) lock() { s.mutex.Lock() }
func (s *SortedResults) unlock() { s.mutex.Unlock() }
func (s *SortedResults) Len() int {
s.lock()
defer s.unlock()
return s.len
}
func (s *SortedResults) Clear() {
s.lock()
defer s.unlock()
s.slices = nil
s.len = 0
}
func (s *SortedResults) At(pos CollectionIndex) (ans *ResultItem) {
s.lock()
defer s.unlock()
if pos.Slice < len(s.slices) {
s := s.slices[pos.Slice]
if pos.Pos < len(s) {
ans = s[pos.Pos]
}
}
return
}
func (s *SortedResults) RenderedMatches(pos CollectionIndex, max_num int) (ans []*ResultItem) {
s.lock()
defer s.unlock()
if pos.Slice >= len(s.slices) {
return
}
if max_num < 0 {
max_num = s.len
}
ans = make([]*ResultItem, 0, max_num)
for ; pos.Slice < len(s.slices) && max_num > 0; pos.NextSlice() {
sl := s.slices[pos.Slice]
if pos.Pos >= len(sl) {
continue
}
sl = sl[pos.Pos:min(len(sl), pos.Pos+max_num)]
ans = append(ans, sl...)
max_num -= len(sl)
}
return
}
func (s *SortedResults) merge_slice(idx int, sl []*ResultItem) {
sz := len(s.slices[idx])
maxs := sl[len(sl)-1].score
limit := idx + 1
for limit < len(s.slices) {
q := s.slices[limit]
if q[0].score > maxs {
break
}
sz += len(q)
limit++
}
ans := make([]*ResultItem, 0, sz)
a := 0
b := CollectionIndex{Slice: idx}
ss := s.slices[b.Slice]
for a < len(sl) {
if sl[a].score <= ss[b.Pos].score {
ans = append(ans, sl[a])
a++
} else {
ans = append(ans, ss[b.Pos])
b.Pos++
if b.Pos >= len(ss) {
b.NextSlice()
if b.Slice >= limit {
break
}
ss = s.slices[b.Slice]
}
}
}
ans = append(ans, sl[a:]...)
for ; b.Slice < limit; b.NextSlice() {
ans = append(ans, s.slices[b.Slice][b.Pos:]...)
}
s.slices = slices.Replace(s.slices, idx, limit, ans)
}
func (s *SortedResults) AddSortedSlice(sl []*ResultItem) {
if len(sl) == 0 {
return
}
s.lock()
defer s.unlock()
s.len += len(sl)
if len(s.slices) == 0 {
s.slices = append(s.slices, sl)
return
}
sl_min, sl_max := sl[0].score, sl[len(sl)-1].score
for i, q := range s.slices {
switch {
case sl_max <= q[0].score:
s.slices = slices.Insert(s.slices, i, sl)
return
case sl_min >= q[len(q)-1].score:
continue
default:
s.merge_slice(i, sl)
return
}
}
s.slices = append(s.slices, sl)
}
func (s *SortedResults) Apply(first, last CollectionIndex, action func(*ResultItem) (keep_going bool)) {
s.lock()
defer s.unlock()
if first.Slice >= len(s.slices) || first.Pos >= len(s.slices[first.Slice]) {
return
}
amt := utils.IfElse(first.Less(last), 1, -1)
var did_wrap bool
for {
if !action(s.slices[first.Slice][first.Pos]) {
break
}
if first.Compare(last) == 0 {
break
}
first, did_wrap = s.increment_with_wrap_around(first, amt)
if did_wrap {
break
}
}
}
func (s *SortedResults) Closest(idx CollectionIndex, matches func(*ResultItem) bool) *CollectionIndex {
s.lock()
defer s.unlock()
if idx.Slice >= len(s.slices) || idx.Pos >= len(s.slices[idx.Slice]) {
return nil
}
type result struct {
idx CollectionIndex
count int
}
var a, b result
iterate := func(idx CollectionIndex, amt int, result *result) {
var did_wrap bool
var count int
result.count = -1
for {
idx, did_wrap = s.increment_with_wrap_around(idx, amt)
if did_wrap {
break
}
count++
if matches(s.slices[idx.Slice][idx.Pos]) {
result.idx = idx
result.count = count
break
}
}
}
go func() { iterate(idx, 1, &a) }()
go func() { iterate(idx, -1, &a) }()
if a.count < 0 && b.count < 0 {
return nil
}
return utils.IfElse(a.count < b.count, &b.idx, &a.idx)
}
func (s *SortedResults) IncrementIndexWithWrapAroundAndCheck(idx CollectionIndex, amt int) (ans CollectionIndex, did_wrap bool) {
s.lock()
defer s.unlock()
return s.increment_with_wrap_around(idx, amt)
}
func (s *SortedResults) IncrementIndexWithWrapAround(idx CollectionIndex, amt int) CollectionIndex {
s.lock()
defer s.unlock()
ans, _ := s.increment_with_wrap_around(idx, amt)
return ans
}
func (s *SortedResults) increment_with_wrap_around(idx CollectionIndex, amt int) (CollectionIndex, bool) {
did_wrap := false
if amt > 0 {
for amt > 0 {
if delta := min(amt, len(s.slices[idx.Slice])-1-idx.Pos); delta > 0 {
idx.Pos += delta
amt -= delta
} else {
idx.NextSlice()
if idx.Slice >= len(s.slices) {
idx = CollectionIndex{} // wraparound
did_wrap = true
}
amt--
}
}
} else {
// we use separate code for negative increment instead of doing
// increment = len - increment as it is faster in the common case of
// increment much smaller than len
amt *= -1
for amt > 0 {
if idx.Pos > 0 {
delta := min(amt, idx.Pos)
amt -= delta
idx.Pos -= delta
} else {
if idx.Slice == 0 {
idx = CollectionIndex{Slice: len(s.slices) - 1, Pos: len(s.slices[len(s.slices)-1]) - 1}
did_wrap = true
} else {
idx.Slice--
idx.Pos = len(s.slices[idx.Slice]) - 1
}
amt--
}
}
}
return idx, did_wrap
}
// Return a - b
func (s *SortedResults) SignedDistance(a, b CollectionIndex) (ans int) {
s.lock()
defer s.unlock()
return s.signed_distance(a, b)
}
// Return a - b
func (s *SortedResults) signed_distance(a, b CollectionIndex) (ans int) {
mult := -1
if b.Less(a) {
a, b = b, a
mult = 1
}
limit := min(b.Slice, len(s.slices))
for ; a.Slice < limit; a.NextSlice() {
ans += len(s.slices[a.Slice]) - a.Pos
}
return mult * (ans + (b.Pos - a.Pos))
}
// Return |a - b|
func (s *SortedResults) distance(a, b CollectionIndex) (ans int) {
if b.Less(a) {
a, b = b, a
}
limit := min(b.Slice, len(s.slices))
for ; a.Slice < limit; a.NextSlice() {
ans += len(s.slices[a.Slice]) - a.Pos
}
return ans + (b.Pos - a.Pos)
}
func (s *SortedResults) SplitIntoColumns(calc_num_cols func(int) int, num_per_column, num_before_current int, current CollectionIndex) (ans [][]*ResultItem, num_before int, first_idx CollectionIndex) {
s.lock()
defer s.unlock()
num_cols := calc_num_cols(s.len)
total := num_cols * num_per_column
if total < 1 {
return nil, 0, CollectionIndex{}
}
num_before = min(total-1, num_before_current)
idx, did_wrap := s.increment_with_wrap_around(current, -num_before)
last_slice := s.slices[len(s.slices)-1]
last := CollectionIndex{Slice: len(s.slices) - 1, Pos: len(last_slice) - 1}
if did_wrap {
idx = CollectionIndex{}
} else if s.distance(idx, last) < total-1 {
if idx, did_wrap = s.increment_with_wrap_around(last, 1-total); did_wrap {
idx = CollectionIndex{}
}
}
first_idx = idx
num_before = s.distance(idx, current)
// fmt.Printf("111111 idx: %v current: %v num_before: %d\n", idx, current, num_before)
ans = make([][]*ResultItem, num_cols)
for colidx := range len(ans) {
col := make([]*ResultItem, 0, num_per_column)
for len(col) < num_per_column && idx.Slice < len(s.slices) {
ss := s.slices[idx.Slice]
limit := min(len(ss), idx.Pos+num_per_column-len(col))
col = append(col, ss[idx.Pos:limit]...)
idx.Pos = limit
if idx.Pos >= len(ss) {
idx.NextSlice()
if idx.Slice >= len(s.slices) {
break
}
}
}
ans[colidx] = col
}
return
}
+179
View File
@@ -0,0 +1,179 @@
package choose_files
import (
"bytes"
"encoding/json"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"time"
"github.com/hako/durafmt"
"github.com/kovidgoyal/imaging/magick"
"github.com/kovidgoyal/kitty/tools/icons"
"github.com/kovidgoyal/kitty/tools/utils/humanize"
"github.com/kovidgoyal/kitty/tools/utils/images"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
const FFMPEG_METADATA_KEY = "ffmpeg-metadata.json"
type ffmpeg_renderer int
var (
video_width = 480
video_fps = 10
video_duration = 5.0
video_encoding_quality = 75
)
func ffmpeg_thumbnail_cmd(path, outpath string) *exec.Cmd {
return exec.Command(
"ffmpeg", "-loglevel", "fatal", "-y", "-an", "-sn", "-dn", "-i", path, "-t", fmt.Sprintf("%f", video_duration),
"-vf", fmt.Sprintf("fps=%d,scale=%d:-1:flags=lanczos", video_fps, video_width),
"-c:v", "libwebp", "-lossless", "0", "-compression_level", "0", "-q:v",
fmt.Sprintf("%d", video_encoding_quality), "-loop", "0", "-f", "webp", outpath,
)
}
func ffmpeg_thumbnail(path, tempath string, wg *sync.WaitGroup) (ans *images.ImageData, err error) {
defer wg.Done()
cmd := ffmpeg_thumbnail_cmd(path, tempath)
cmd.Stdin = nil
cmd.SysProcAttr = &unix.SysProcAttr{Setsid: true}
var stderr bytes.Buffer
cmd.Stdout = nil
cmd.Stderr = &stderr
if err = cmd.Run(); err != nil {
return ans, fmt.Errorf("failed to use ffmpeg to render video from %s with error: %w and stderr: %s", path, err, stderr.String())
}
ans, err = images.OpenImageFromPath(tempath)
return
}
type FFMpegFormat struct {
Start_time string `json:"start_time"`
Duration string `json:"duration"`
Tags map[string]any `json:"tags"`
}
type FFMpegStream struct {
Codec_type string `json:"codec_type"`
Width int `json:"width"`
Height int `json:"height"`
}
type FFMpegMetadata struct {
Streams []FFMpegStream `json:"streams"`
Format FFMpegFormat `json:"format"`
}
func ffmpeg_metadata_cmd(path string) *exec.Cmd {
return exec.Command(
"ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", path,
)
}
func ffmpeg_metadata(path string, wg *sync.WaitGroup) (ans FFMpegMetadata, err error) {
defer wg.Done()
cmd := ffmpeg_metadata_cmd(path)
cmd.Stdin = nil
cmd.SysProcAttr = &unix.SysProcAttr{Setsid: true}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err = cmd.Run(); err != nil {
return ans, fmt.Errorf("failed to use ffprobe to read metadata from %s with error: %w and stderr: %s", path, err, stderr.String())
}
if err = json.Unmarshal(stdout.Bytes(), &ans); err != nil {
return ans, fmt.Errorf("could not decode JSON response from ffprobe for %s: %w", path, err)
}
return
}
func (c ffmpeg_renderer) Render(path string) (m map[string][]byte, mi metadata, img *images.ImageData, err error) {
wg := sync.WaitGroup{}
tempfile, err := os.CreateTemp(magick.TempDirInRAMIfPossible(), "kitty-choose-files-*.webp")
if err != nil {
return nil, mi, nil, err
}
defer func() { _ = os.Remove(tempfile.Name()); tempfile.Close() }()
var metadata FFMpegMetadata
var metadata_error error
wg.Add(1)
go func() { metadata, metadata_error = ffmpeg_metadata(path, &wg) }()
wg.Add(1)
go func() { img, err = ffmpeg_thumbnail(path, tempfile.Name(), &wg) }()
wg.Wait()
if metadata_error != nil {
return nil, mi, nil, metadata_error
}
var ip ImagePreviewRenderer
if m, mi, img, err = ip.Render(tempfile.Name()); err != nil {
return
}
mi.custom = &metadata
return
}
func (c ffmpeg_renderer) Unmarshall(m map[string]string) (any, error) {
data, err := os.ReadFile(m[FFMPEG_METADATA_KEY])
if err != nil {
return nil, err
}
var ans FFMpegMetadata
if err = json.Unmarshal(data, &ans); err != nil {
return nil, err
}
return &ans, nil
}
func (c ffmpeg_renderer) ShowMetadata(h *Handler, s ShowData) (offset int) {
w := func(text string, center bool) {
if s.height > offset {
offset += h.render_wrapped_text_in_region(text, s.x, s.y+offset, s.width, s.height-offset, center)
}
}
ext := filepath.Ext(s.abspath)
text := fmt.Sprintf("%s: %s", ext, humanize.Bytes(uint64(s.metadata.Size())))
r := s.custom_metadata.custom.(*FFMpegMetadata)
icon := icons.IconForPath(s.abspath)
var width, height int
for _, s := range r.Streams {
if s.Width > 0 && s.Height > 0 {
width, height = s.Width, s.Height
break
}
}
text += fmt.Sprintf(" %dx%d", width, height)
w(icon+" "+text, true)
st := humanize.Time(s.metadata.ModTime())
if d, perr := strconv.ParseFloat(r.Format.Duration, 64); perr == nil {
duration := time.Duration(d * float64(time.Second))
st += fmt.Sprintf(", %s", durafmt.Parse(duration).LimitFirstN(1).String())
}
w(st, true)
return
}
func (c ffmpeg_renderer) String() string {
return "FFMpeg"
}
func NewFFMpegPreview(
abspath string, metadata fs.FileInfo, opts Settings, WakeupMainThread func() bool,
) Preview {
c := ffmpeg_renderer(0)
if ans, err := NewImagePreview(abspath, metadata, opts, WakeupMainThread, c); err == nil {
return ans
} else {
return NewErrorPreview(err)
}
}
+111
View File
@@ -0,0 +1,111 @@
package choose_files
import (
"fmt"
"path/filepath"
"slices"
"strings"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type Filter struct {
Name, Type, Pattern string
Match func(filename string) bool
// The individual filters making up a combined filter, Type and Pattern are empty for combined filters
sub_filters []Filter
}
func (f Filter) String() string {
if len(f.sub_filters) > 0 {
return strings.Join(utils.Map(Filter.String, f.sub_filters), ", ")
}
return fmt.Sprintf("%s:%s:%s", f.Type, f.Pattern, f.Name)
}
// The sorted, de-duplicated type:pattern specs of the matchers making up this filter
func (f Filter) specs() []string {
if len(f.sub_filters) == 0 {
return []string{f.Type + ":" + f.Pattern}
}
ans := utils.Map(func(sf Filter) string { return sf.Type + ":" + sf.Pattern }, f.sub_filters)
slices.Sort(ans)
return slices.Compact(ans)
}
// Whether the two filters match the same set of files, regardless of their names
func (f Filter) Equal(other Filter) bool {
if f.Match == nil || other.Match == nil {
return f.Match == nil && other.Match == nil
}
return slices.Equal(f.specs(), other.specs())
}
func NewFilter(spec string) (*Filter, error) {
parts := strings.SplitN(spec, ":", 3)
if len(parts) != 3 {
return nil, fmt.Errorf("%#v is not a valid filter specifier, must have at least two colons", spec)
}
ans := &Filter{Name: parts[2], Pattern: parts[1], Type: parts[0]}
if _, err := filepath.Match(ans.Pattern, "test"); err != nil {
return nil, fmt.Errorf("%#v is not a valid glob pattern with error: %w", ans.Pattern, err)
}
if ans.Pattern != "*" && ans.Pattern != "" {
switch ans.Type {
case "glob":
ans.Match = func(filename string) bool {
m, _ := filepath.Match(ans.Pattern, filename)
return m
}
case "mime":
ans.Match = func(filename string) bool {
mime := utils.GuessMimeType(filename)
if mime == "" {
return false
}
for _, q := range utils.MimeTypeAliases(mime) {
if m, _ := filepath.Match(ans.Pattern, q); m {
return true
}
}
return false
}
default:
return nil, fmt.Errorf("%#v is not a valid filter type", ans.Type)
}
}
return ans, nil
}
func CombinedFilter(filters ...Filter) Filter {
if len(filters) == 0 {
return Filter{}
}
var flattened []Filter
for _, f := range filters {
if f.Match == nil {
return f
}
if len(f.sub_filters) > 0 {
flattened = append(flattened, f.sub_filters...)
} else {
flattened = append(flattened, f)
}
}
if len(flattened) == 1 {
return flattened[0]
}
ans := Filter{Name: filters[0].Name, sub_filters: flattened}
matchers := utils.Map(func(f Filter) func(filename string) bool { return f.Match }, flattened)
ans.Match = func(filename string) bool {
for _, m := range matchers {
if m(filename) {
return true
}
}
return false
}
return ans
}
+115
View File
@@ -0,0 +1,115 @@
package choose_files
import (
"fmt"
"path/filepath"
"strings"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/style"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
const HOVER_STYLE = "default fg=red"
type single_line_region struct {
x, width, y int
id string
callback func(string) error
}
func (h *Handler) draw_footer() (num_lines int, err error) {
lines := []string{}
screen_width := h.screen_size.width
sctx := style.Context{AllowEscapeCodes: true}
if h.state.screen == SAVE_FILE {
m := h.state.filter_map
h.state.filter_map = nil
defer func() { h.state.filter_map = m }()
}
if len(h.state.filter_map)+len(h.state.selections) > 0 {
buf := strings.Builder{}
pos := 0
current_style := sctx.SprintFunc("italic fg=green intense")
non_current_style := sctx.SprintFunc("dim")
var crs []single_line_region
w := func(presep, text string, sfunc func(...any) string, id string, cb func(string)) {
sz := len(presep)
if sz+pos >= screen_width {
lines = append(lines, buf.String())
pos = 0
buf.Reset()
} else {
buf.WriteString(presep)
pos += sz
}
sz = wcswidth.Stringwidth(text)
if sz+pos >= screen_width {
lines = append(lines, buf.String())
pos = 0
buf.Reset()
}
if sfunc != nil {
text = sfunc(text)
}
buf.WriteString(text)
if cb != nil {
crs = append(crs, single_line_region{x: pos, width: sz - 1, y: len(lines), id: id, callback: func(filter string) error {
cb(filter)
h.state.redraw_needed = true
return nil
}})
}
pos += sz
}
flush := func() {
if s := buf.String(); s != "" {
lines = append(lines, s)
}
pos = 0
buf.Reset()
}
if len(h.state.filter_map) > 0 {
w("", "󰈲 Filter:", nil, "", nil)
for _, name := range h.state.filter_names {
var cb func(string)
if name != h.state.current_filter {
cb = func(filter string) { h.set_filter(filter) }
}
w(" ", name, utils.IfElse(name == h.state.current_filter, current_style, non_current_style), name, cb)
}
flush()
}
if len(h.state.selections) > 0 {
before := len(lines)
w("", " Selected:", nil, "", nil)
for i, s := range h.state.selections {
text := s
if rel, rerr := filepath.Rel(h.state.CurrentDir(), s); rerr == nil {
text = rel
}
w(" ", text, nil, s, func(abspath string) { h.state.ToggleSelection(abspath) })
if len(lines)-before > 2 && len(h.state.selections)-i-1 > 3 {
w(" ", fmt.Sprintf("and %d more…", len(h.state.selections)-1-i), nil, "", nil)
break
}
}
flush()
}
offset := h.screen_size.height - len(lines)
for _, cr := range crs {
h.state.mouse_state.AddCellRegion(cr.id, cr.x, cr.y+offset, cr.x+cr.width, cr.y+offset, cr.callback).HoverStyle = HOVER_STYLE
}
}
if len(lines) > 0 {
h.lp.MoveCursorTo(1, h.screen_size.height-len(lines)+1)
if h.state.screen == SAVE_FILE {
h.lp.ClearToEndOfScreen()
}
h.lp.QueueWriteString(strings.Join(lines, "\r\n"))
}
return len(lines), err
}
+326
View File
@@ -0,0 +1,326 @@
package choose_files
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/graphics"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/images"
)
var _ = fmt.Print
type placement struct {
gc *graphics.GraphicsCommand
x, y, x_offset int
}
func (p placement) equal(o placement) bool {
return p.x == o.x && p.x_offset == o.x_offset && p.y == o.y
}
type GraphicsHandler struct {
running_in_tmux bool
image_id_counter, detection_file_id uint32
files_to_delete []string
files_supported atomic.Bool
last_rendered_image struct {
p *ImagePreview
width, height int
image_width, image_height int
}
image_transmitted uint32
current_placement, last_transmitted_placement placement
}
func (self *GraphicsHandler) Cleanup() {
for _, f := range self.files_to_delete {
_ = os.Remove(f)
}
}
func (self *GraphicsHandler) new_graphics_command() *graphics.GraphicsCommand {
gc := graphics.GraphicsCommand{}
if self.running_in_tmux {
gc.WrapPrefix = "\033Ptmux;"
gc.WrapSuffix = "\033\\"
gc.EncodeSerializedDataFunc = func(x string) string { return strings.ReplaceAll(x, "\033", "\033\033") }
}
return &gc
}
func (self *GraphicsHandler) Initialize(lp *loop.Loop) error {
tmux := tui.TmuxSocketAddress()
if tmux != "" && tui.TmuxAllowPassthrough() == nil {
self.running_in_tmux = true
}
if !self.running_in_tmux {
g := func(t graphics.GRT_t, payload string) uint32 {
self.image_id_counter++
g1 := self.new_graphics_command()
g1.SetTransmission(t).SetAction(graphics.GRT_action_query).SetImageId(self.image_id_counter).SetDataWidth(1).SetDataHeight(1).SetFormat(
graphics.GRT_format_rgb).SetDataSize(uint64(len(payload)))
_ = g1.WriteWithPayloadToLoop(lp, utils.UnsafeStringToBytes(payload))
return self.image_id_counter
}
tf, err := images.CreateTempInRAM()
if err == nil {
if _, err = tf.Write([]byte{1, 2, 3}); err == nil {
self.detection_file_id = g(graphics.GRT_transmission_tempfile, tf.Name())
self.files_to_delete = append(self.files_to_delete, tf.Name())
}
tf.Close()
}
}
self.image_id_counter++
return nil
}
func (self *GraphicsHandler) free_image_from_terminal(lp *loop.Loop) {
if self.image_transmitted > 0 {
self.new_graphics_command().SetAction(graphics.GRT_action_delete).SetDelete(graphics.GRT_free_by_id).SetImageId(self.image_transmitted).WriteWithPayloadToLoop(lp, nil)
self.image_transmitted = 0
}
}
func (self *GraphicsHandler) Finalize(lp *loop.Loop) {
self.free_image_from_terminal(lp)
}
func (self *GraphicsHandler) ClearPlacements(lp *loop.Loop) {
self.current_placement.gc = nil
}
func (self *GraphicsHandler) ApplyPlacements(lp *loop.Loop) {
if self.current_placement.gc == nil {
g := self.new_graphics_command()
g.SetAction(graphics.GRT_action_delete).SetDelete(graphics.GRT_delete_by_id).SetImageId(self.image_transmitted)
_ = g.WriteWithPayloadToLoop(lp, nil)
self.last_transmitted_placement.gc = nil
} else {
if self.last_transmitted_placement.gc == nil || !self.current_placement.equal(self.last_transmitted_placement) {
lp.MoveCursorTo(self.current_placement.x, self.current_placement.y)
_ = self.current_placement.gc.WriteWithPayloadToLoop(lp, nil)
self.last_transmitted_placement = self.current_placement
}
}
}
func (self *GraphicsHandler) HandleGraphicsCommand(gc *graphics.GraphicsCommand) error {
switch gc.ImageId() {
case self.detection_file_id:
if gc.ResponseMessage() == "OK" {
self.files_supported.Store(true)
}
}
return nil
}
func (self *GraphicsHandler) cache_resized_image(cdir, cache_key string, img *images.ImageData) (m *images.SerializableImageMetadata, cached_data map[string]string, err error) {
s, frames := img.Serialize()
sd, err := json.Marshal(s)
if err != nil {
return nil, nil, err
}
path := filepath.Join(cdir, fmt.Sprintf("rsz-%s-metadata.json", cache_key))
if err = os.WriteFile(path, sd, 0o600); err != nil {
return nil, nil, fmt.Errorf("failed to write resized frame metadata to cache: %w", err)
}
cached_data = make(map[string]string, len(frames)+1)
cached_data[IMAGE_METADATA_KEY] = path
for i, f := range frames {
path := filepath.Join(cdir, fmt.Sprintf("rsz-%s-%d", cache_key, i))
key := IMAGE_DATA_PREFIX + strconv.Itoa(i)
if err = os.WriteFile(path, f, 0o600); err != nil {
return nil, nil, fmt.Errorf("failed to write resized frame %d data to cache: %w", i, err)
}
cached_data[key] = path
}
m = &s
return
}
func (self *GraphicsHandler) cached_resized_image(cdir, cache_key string) (m *images.SerializableImageMetadata, cached_data map[string]string) {
path := filepath.Join(cdir, fmt.Sprintf("rsz-%s-metadata.json", cache_key))
b, err := os.ReadFile(path)
if err != nil {
return
}
var s images.SerializableImageMetadata
if err = json.Unmarshal(b, &s); err != nil {
return
}
m = &s
cached_data = make(map[string]string, len(s.Frames)+1)
cached_data[IMAGE_METADATA_KEY] = path
for i := range len(s.Frames) {
path := filepath.Join(cdir, fmt.Sprintf("rsz-%s-%d", cache_key, i))
key := IMAGE_DATA_PREFIX + strconv.Itoa(i)
cached_data[key] = path
}
return
}
func transmit_by_escape_code(lp *loop.Loop, frame []byte, gc *graphics.GraphicsCommand) {
atomic := lp.IsAtomicUpdateActive()
lp.EndAtomicUpdate()
gc.SetTransmission(graphics.GRT_transmission_direct)
_ = gc.WriteWithPayloadToLoop(lp, frame)
if atomic {
lp.StartAtomicUpdate()
}
}
func transmit_by_file(lp *loop.Loop, frame_path []byte, gc *graphics.GraphicsCommand) {
gc.SetTransmission(graphics.GRT_transmission_file)
_ = gc.WriteWithPayloadToLoop(lp, frame_path)
}
func (self *GraphicsHandler) transmit(lp *loop.Loop, img *images.ImageData, m *images.SerializableImageMetadata, cached_data map[string]string) {
if m == nil {
s := img.SerializeOnlyMetadata()
m = &s
}
self.image_transmitted = self.image_id_counter
self.last_transmitted_placement.gc = nil
self.last_rendered_image.image_width = m.Width
self.last_rendered_image.image_height = m.Height
is_animated := len(m.Frames) > 0
frame_control_cmd := self.new_graphics_command()
frame_control_cmd.SetAction(graphics.GRT_action_animate).SetImageId(self.image_transmitted)
for frame_num, frame := range m.Frames {
gc := self.new_graphics_command()
gc.SetImageId(self.image_transmitted)
gc.SetDataWidth(uint64(frame.Width)).SetDataHeight(uint64(frame.Height))
gc.SetFormat(utils.IfElse(frame.Is_opaque, graphics.GRT_format_rgb, graphics.GRT_format_rgba))
switch frame_num {
case 0:
gc.SetAction(graphics.GRT_action_transmit)
gc.SetCursorMovement(graphics.GRT_cursor_static)
default:
gc.SetAction(graphics.GRT_action_frame)
gc.SetGap(int32(frame.Delay_ms))
if frame.Replace {
gc.SetCompositionMode(graphics.Overwrite)
}
if frame.Compose_onto > 0 {
gc.SetOverlaidFrame(uint64(frame.Compose_onto))
}
gc.SetLeftEdge(uint64(frame.Left)).SetTopEdge(uint64(frame.Top))
}
if cached_data == nil {
_, _, _, data := img.Frames[frame_num].Data()
transmit_by_escape_code(lp, data, gc)
} else {
path := cached_data[IMAGE_DATA_PREFIX+strconv.Itoa(frame_num)]
transmit_by_file(lp, utils.UnsafeStringToBytes(path), gc)
}
if is_animated {
switch frame_num {
case 0:
// set gap for the first frame and number of loops for the animation
c := frame_control_cmd
c.SetTargetFrame(uint64(frame.Number))
c.SetGap(int32(frame.Delay_ms))
c.SetNumberOfLoops(1)
_ = c.WriteWithPayloadToLoop(lp, nil)
case 1:
c := frame_control_cmd
c.SetAnimationControl(2) // set animation to loading mode
_ = c.WriteWithPayloadToLoop(lp, nil)
}
}
}
if is_animated {
c := frame_control_cmd
c.SetAnimationControl(3) // set animation to normal mode
_ = c.WriteWithPayloadToLoop(lp, nil)
}
}
func (self *GraphicsHandler) place_image(x, y, px_width, y_offset int, sz ScreenSize) {
gc := self.new_graphics_command()
gc.SetAction(graphics.GRT_action_display).SetImageId(self.image_transmitted).SetPlacementId(1).SetCursorMovement(graphics.GRT_cursor_static)
if extra := px_width - self.last_rendered_image.image_width; extra > 1 {
extra /= 2
x += extra / sz.cell_width
self.current_placement.x_offset = extra % sz.cell_width
gc.SetXOffset(uint64(self.current_placement.x_offset))
}
gc.SetYOffset(uint64(y_offset))
self.current_placement.x, self.current_placement.y = x, y
self.current_placement.gc = gc
}
func (self *GraphicsHandler) RenderImagePreview(h *Handler, p *ImagePreview, x, y, width, height int) {
sz := h.screen_size
px_width, px_height := width*sz.cell_width, height*sz.cell_height
y_offset := sz.cell_height / 2
px_height -= y_offset
var err error
defer func() {
self.last_rendered_image.p = p
self.last_rendered_image.width, self.last_rendered_image.height = width, height
if err != nil {
NewErrorPreview(fmt.Errorf("Failed to render image: %w", err)).Render(h, x, y, width, height)
} else if self.image_transmitted > 0 {
self.place_image(x, y, px_width, y_offset, sz)
}
}()
if self.last_rendered_image.p == p && self.last_rendered_image.width == width && self.last_rendered_image.height == height {
return
}
files_supported := self.files_supported.Load()
if p.custom_metadata.image.Width <= px_width && p.custom_metadata.image.Height <= px_height {
if files_supported {
self.transmit(h.lp, nil, p.custom_metadata.image, p.cached_data)
} else {
if err = p.ensure_source_image(); err != nil {
return
}
self.transmit(h.lp, p.source_img, p.custom_metadata.image, nil)
}
return
}
cache_key := fmt.Sprintf("%d-%d-%p", width, height, p)
img_metadata, cached_data := self.cached_resized_image(p.disk_cache.ResultsDir(), cache_key)
var img *images.ImageData
if len(cached_data) == 0 {
if err = p.ensure_source_image(); err != nil {
return
}
img = p.source_img
final_width, final_height := images.FitImage(img.Width, img.Height, px_width, px_height)
if final_width != img.Width || final_height != img.Height {
x_frac, y_frac := float64(final_width)/float64(img.Width), float64(final_height)/float64(img.Height)
img = img.Resize(x_frac, y_frac)
}
if img_metadata, cached_data, err = self.cache_resized_image(p.disk_cache.ResultsDir(), cache_key, img); err != nil {
err = fmt.Errorf("failed to cache resized image: %w", err)
return
}
}
if files_supported {
self.transmit(h.lp, img, img_metadata, cached_data)
} else {
if img == nil {
if img, err = load_image(cached_data); err != nil {
err = fmt.Errorf("failed to load resized image from cache: %w", err)
return
}
}
self.transmit(h.lp, img, nil, nil)
}
}
+288
View File
@@ -0,0 +1,288 @@
package choose_files
import (
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/hako/durafmt"
"github.com/kovidgoyal/go-parallel"
"github.com/kovidgoyal/kitty/tools/disk_cache"
"github.com/kovidgoyal/kitty/tools/icons"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/humanize"
"github.com/kovidgoyal/kitty/tools/utils/images"
)
const IMAGE_METADATA_KEY = "image-metadata.json"
const IMAGE_DATA_PREFIX = "image-data-"
var dc_size atomic.Int64
var _ = fmt.Print
var preview_cache = sync.OnceValues(func() (*disk_cache.DiskCache, error) {
cdir := utils.CacheDir()
cdir = filepath.Join(cdir, "choose-files")
return disk_cache.NewDiskCache(cdir, dc_size.Load())
})
type ShowData struct {
abspath string
metadata fs.FileInfo
x, y, width, height int
cached_data map[string]string
custom_metadata metadata
}
type PreviewRenderer interface {
Unmarshall(map[string]string) (any, error)
Render(string) (map[string][]byte, metadata, *images.ImageData, error)
ShowMetadata(h *Handler, s ShowData) int
String() string
}
type render_data struct {
cached_data map[string]string
img *images.ImageData
metadata metadata
err error
}
type metadata struct {
image *images.SerializableImageMetadata
custom any
}
type ImagePreview struct {
abspath string
metadata fs.FileInfo
disk_cache *disk_cache.DiskCache
cached_data map[string]string
render_err Preview
render_channel chan render_data
ready atomic.Bool
source_img *images.ImageData
custom_metadata metadata
renderer PreviewRenderer
file_metadata_preview Preview
WakeupMainThread func() bool
}
func (p *ImagePreview) String() string {
return fmt.Sprintf("ImagePreview{%#v, ready: %v, renderer: %s}", p.abspath, p.ready.Load(), p.renderer.String())
}
func (p *ImagePreview) IsValidForColorScheme(bool) bool { return true }
func (p *ImagePreview) IsReady() bool { return p.ready.Load() || p.render_channel == nil }
func (p *ImagePreview) Unload() {
p.source_img = nil
}
func load_image(cached_data map[string]string) (img *images.ImageData, err error) {
fp := cached_data[IMAGE_METADATA_KEY]
if fp == "" {
return nil, fmt.Errorf("missing cached image metadata")
}
b, err := os.ReadFile(fp)
if err != nil {
return nil, fmt.Errorf("failed to read cached image metadata: %w", err)
}
var m images.SerializableImageMetadata
if err = json.Unmarshal(b, &m); err != nil {
return nil, fmt.Errorf("failed to decode cached image metadata: %w", err)
}
frames := make([][]byte, len(m.Frames))
for i := range m.Frames {
path := cached_data[IMAGE_DATA_PREFIX+strconv.Itoa(i)]
if path == "" {
return nil, fmt.Errorf("missing cached data for frame: %d", i)
}
d, e := os.ReadFile(path)
if e != nil {
return nil, fmt.Errorf("failed to read cached image frame %d data: %w", i, e)
}
m.Frames[i].Size = len(d)
frames[i] = d
}
return images.ImageFromSerialized(m, frames)
}
func (p *ImagePreview) ensure_source_image() (err error) {
if p.source_img != nil {
return
}
defer func() {
if err != nil {
p.render_err = NewErrorPreview(err)
}
}()
p.source_img, err = load_image(p.cached_data)
return
}
func (p *ImagePreview) render_image(h *Handler, x, y, width, height int) {
defer func() {
if r := recover(); r != nil {
h.err_chan <- parallel.Format_stacktrace_on_panic(r, 1)
p.WakeupMainThread()
}
}()
offset := p.renderer.ShowMetadata(h, ShowData{
abspath: p.abspath, metadata: p.metadata, x: x, y: y, width: width, height: height, cached_data: p.cached_data,
custom_metadata: p.custom_metadata,
})
if p.custom_metadata.image != nil {
h.graphics_handler.RenderImagePreview(h, p, x, y+offset, width, height-offset)
}
}
func (p *ImagePreview) Render(h *Handler, x, y, width, height int) {
if p.render_channel == nil {
if p.render_err == nil {
p.render_image(h, x, y, width, height)
} else {
p.render_err.Render(h, x, y, width, height)
}
return
}
select {
case hd := <-p.render_channel:
p.render_channel = nil
p.cached_data = hd.cached_data
p.source_img = hd.img
p.custom_metadata = hd.metadata
if hd.err != nil {
p.render_err = NewFileMetadataPreviewWithError(p.abspath, p.metadata, fmt.Errorf("Failed to render the preview with error: %w", hd.err))
}
p.Render(h, x, y, width, height)
return
default:
}
if p.file_metadata_preview == nil {
p.file_metadata_preview = NewFileMetadataPreview(p.abspath, p.metadata)
m := p.file_metadata_preview.(*MessagePreview)
m.trailers = append(m.trailers, "", "Rendering image preview, please wait…")
}
p.file_metadata_preview.Render(h, x, y, width, height)
}
// start_rendering runs in a worker goroutine. It must send its results only on
// output and never access p.render_channel, as the main thread sets that to nil
// as soon as it receives the result, which can happen before this function
// closes the channel.
func (p *ImagePreview) start_rendering(output chan<- render_data) {
defer func() {
if r := recover(); r != nil {
output <- render_data{err: parallel.Format_stacktrace_on_panic(r, 1)}
}
close(output)
p.ready.Store(true)
p.WakeupMainThread()
}()
key, ans, err := p.disk_cache.GetPath(p.abspath)
if err != nil {
output <- render_data{err: err}
return
}
if len(ans) > 0 {
mi := metadata{}
if mi.custom, err = p.renderer.Unmarshall(ans); err == nil {
if d := ans[IMAGE_METADATA_KEY]; d != "" {
if b, err := os.ReadFile(d); err == nil {
var m images.SerializableImageMetadata
if err = json.Unmarshal(b, &m); err == nil {
mi.image = &m
}
}
}
}
if mi.custom != nil || mi.image != nil {
output <- render_data{cached_data: ans, metadata: mi}
return
}
}
rdata, metadata, img, err := p.renderer.Render(p.abspath)
if err != nil {
output <- render_data{err: err}
} else {
ans, err = p.disk_cache.AddPath(p.abspath, key, rdata)
if err == nil {
output <- render_data{cached_data: ans, metadata: metadata, img: img}
} else {
output <- render_data{err: err}
}
}
}
type ImagePreviewRenderer uint
func (p ImagePreviewRenderer) String() string { return "ImagePreviewRenderer" }
func (p ImagePreviewRenderer) Render(abspath string) (ans map[string][]byte, m metadata, img *images.ImageData, err error) {
if img, err = images.OpenImageFromPath(abspath); err != nil {
return nil, metadata{}, nil, err
}
im, data := img.Serialize()
ans = make(map[string][]byte, len(data)+1)
sm, err := json.Marshal(im)
if err != nil {
return nil, metadata{}, nil, err
}
ans[IMAGE_METADATA_KEY] = sm
m = metadata{image: &im}
for i, d := range data {
key := IMAGE_DATA_PREFIX + strconv.Itoa(i)
ans[key] = d
}
return
}
func (p ImagePreviewRenderer) Unmarshall(map[string]string) (any, error) { return nil, nil }
func (p ImagePreviewRenderer) ShowMetadata(h *Handler, s ShowData) int {
offset := 0
if m := s.custom_metadata.image; m != nil {
text := fmt.Sprintf("%s: %dx%d %s", m.Format_uppercase, m.Width, m.Height, humanize.Bytes(uint64(s.metadata.Size())))
icon := icons.IconForPath("/a.gif")
text = icon + " " + text
offset += h.render_wrapped_text_in_region(text, s.x, s.y, s.width, s.height, true)
}
st := humanize.Time(s.metadata.ModTime())
if s.custom_metadata.image != nil && len(s.custom_metadata.image.Frames) > 0 {
var d time.Duration
for _, f := range s.custom_metadata.image.Frames {
if f.Delay_ms > 0 {
d += time.Duration(time.Duration(f.Delay_ms) * time.Millisecond)
}
}
if d > 0 {
st += fmt.Sprintf(", %s", durafmt.Parse(d).LimitFirstN(1).String())
}
}
offset += h.render_wrapped_text_in_region(st, s.x, s.y+offset, s.width, s.height-offset, true)
return offset
}
func NewImagePreview(
abspath string, metadata fs.FileInfo, opts Settings, WakeupMainThread func() bool, r PreviewRenderer,
) (Preview, error) {
dc_size.Store(opts.DiskCacheSize())
ans := &ImagePreview{
abspath: abspath, metadata: metadata, render_channel: make(chan render_data, 1),
WakeupMainThread: WakeupMainThread, renderer: r,
}
if dc, err := preview_cache(); err != nil {
return nil, err
} else {
ans.disk_cache = dc
}
go ans.start_rendering(ans.render_channel)
return ans, nil
}
+176
View File
@@ -0,0 +1,176 @@
package choose_files
import (
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/kovidgoyal/kitty/tools/disk_cache"
"github.com/kovidgoyal/kitty/tools/utils/images"
)
var _ = fmt.Print
type fake_preview_renderer struct{}
func (r fake_preview_renderer) String() string { return "fake_preview_renderer" }
func (r fake_preview_renderer) Unmarshall(map[string]string) (any, error) {
return nil, nil
}
func (r fake_preview_renderer) Render(string) (map[string][]byte, metadata, *images.ImageData, error) {
return map[string][]byte{"rendered": []byte("data")}, metadata{custom: "rendered"}, nil, nil
}
func (r fake_preview_renderer) ShowMetadata(*Handler, ShowData) int { return 0 }
func new_test_image_preview(t *testing.T) *ImagePreview {
t.Helper()
tdir := t.TempDir()
path := filepath.Join(tdir, "image.png")
if err := os.WriteFile(path, []byte("not really an image"), 0o600); err != nil {
t.Fatal(err)
}
st, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
dc, err := disk_cache.NewDiskCache(filepath.Join(tdir, "cache"), 1024*1024)
if err != nil {
t.Fatal(err)
}
return &ImagePreview{
abspath: path, metadata: st, disk_cache: dc, renderer: fake_preview_renderer{},
render_channel: make(chan render_data, 1), WakeupMainThread: func() bool { return true },
}
}
// The main thread sets render_channel to nil as soon as it receives the result,
// which can happen before the worker is done. Simulate the worst case where
// this happens before the worker even starts: the worker must still deliver its
// result and close the channel it was given, without panicking or blocking.
func TestImagePreviewWorkerDoesNotUseRenderChannelField(t *testing.T) {
p := new_test_image_preview(t)
output := p.render_channel
p.render_channel = nil
done := make(chan any, 1)
go func() {
defer func() { done <- recover() }()
p.start_rendering(output)
}()
select {
case r := <-done:
if r != nil {
t.Fatalf("worker panicked: %v", r)
}
case <-time.After(10 * time.Second):
t.Fatal("worker did not finish, it is probably blocked sending to a nil channel")
}
hd, ok := <-output
if !ok {
t.Fatal("worker closed the channel without sending a result")
}
if hd.err != nil {
t.Fatalf("worker failed: %s", hd.err)
}
if hd.metadata.custom != "rendered" {
t.Fatalf("unexpected metadata from worker: %#v", hd.metadata)
}
if _, ok = <-output; ok {
t.Fatal("worker sent more than one result")
}
if !p.ready.Load() {
t.Fatal("worker did not mark the preview as ready")
}
}
// Consume the result on the main thread concurrently with the worker finishing
// up, as happens in the real program. Run with -race to detect any shared
// state accessed without synchronization.
func TestImagePreviewConcurrentRender(t *testing.T) {
p := new_test_image_preview(t)
woken := make(chan bool, 1)
p.WakeupMainThread = func() bool {
select {
case woken <- true:
default:
}
return true
}
go p.start_rendering(p.render_channel)
// Call Render as soon as the result is available, so that it races with
// the worker closing the channel. Render is only called once the result is
// buffered, as the "please wait" message needs a real event loop.
deadline := time.After(10 * time.Second)
for len(p.render_channel) == 0 {
select {
case <-deadline:
t.Fatal("timed out waiting for the image preview to render")
case <-time.After(time.Millisecond):
}
}
p.Render(&Handler{}, 0, 0, 80, 24)
if p.render_channel != nil {
t.Fatal("Render did not consume the result from the worker")
}
if p.render_err != nil {
t.Fatalf("rendering failed: %#v", p.render_err)
}
if p.custom_metadata.custom != "rendered" {
t.Fatalf("unexpected metadata after render: %#v", p.custom_metadata)
}
select {
case <-woken:
case <-deadline:
t.Fatal("worker never woke up the main thread")
}
if !p.ready.Load() {
t.Fatal("worker did not mark the preview as ready")
}
}
func TestCmdPreviewConcurrentRendering(t *testing.T) {
dir := t.TempDir()
script := filepath.Join(dir, "preview.sh")
body := "#!/bin/sh\nIFS= read -r content < \"$2\"\nprintf '{\"lines\":[\"%s\",\"%s\"]}\\n' \"$1\" \"$content\"\n"
if err := os.WriteFile(script, []byte(body), 0o700); err != nil {
t.Fatal(err)
}
// Configured preview commands can have spare capacity shared by workers.
backing := []string{script, "fixed argument", "unused"}
renderer := cmd_renderer{cmdline: backing[:2]}
start := make(chan struct{})
errors := make(chan error, 2)
for i := range 2 {
path := filepath.Join(dir, fmt.Sprintf("file %d λ.txt", i))
content := fmt.Sprintf("contents of file %d", i)
if err := os.WriteFile(path, []byte(content+"\n"), 0o600); err != nil {
t.Fatal(err)
}
go func() {
<-start
for range 16 {
_, md, _, err := renderer.Render(path)
if err != nil {
errors <- fmt.Errorf("preview %q: %w", path, err)
return
}
result, ok := md.custom.(*CmdResult)
if !ok || len(result.Lines) != 2 || result.Lines[0] != "fixed argument" || result.Lines[1] != content {
errors <- fmt.Errorf("preview %q returned %#v, expected %q", path, md.custom, content)
return
}
}
errors <- nil
}()
}
close(start)
for range 2 {
if err := <-errors; err != nil {
t.Error(err)
}
}
if backing[2] != "unused" {
t.Errorf("rendering modified shared command arguments: %q", backing)
}
}
File diff suppressed because it is too large. Load diff
+371
View File
@@ -0,0 +1,371 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2025, Kovid Goyal <kovid at kovidgoyal.net>
import shlex
import sys
from typing import Any
from kitty.conf.types import Definition
from kitty.constants import appname
from kitty.simple_cli_definitions import CONFIG_HELP, CompletionSpec
from kitty.typing_compat import BossType
from ..tui.handler import result_handler
definition = Definition(
'!kittens.choose_files',
)
agr = definition.add_group
egr = definition.end_group
opt = definition.add_option
map = definition.add_map
mma = definition.add_mouse_map
agr('scanning', 'Filesystem scanning') # {{{
opt(
'show_hidden',
'last',
choices=('last', 'yes', 'y', 'true', 'no', 'n', 'false'),
long_text="""
Whether to show hidden files. The default value of :code:`last` means remember the last
used value. This setting can be toggled within the program.""",
)
opt(
'sort_by_last_modified',
'last',
choices=('last', 'yes', 'y', 'true', 'no', 'n', 'false'),
long_text="""
Whether to sort the list of entries by last modified, instead of name. Note that sorting only applies
before any query is entered. Once a query is entered entries are sorted by their matching score.
The default value of :code:`last` means remember the last
used value. This setting can be toggled within the program.""",
)
opt(
'respect_ignores',
'last',
choices=('last', 'yes', 'y', 'true', 'no', 'n', 'false'),
long_text="""
Whether to respect .gitignore and .ignore files and the :opt:`ignore` setting.
The default value of :code:`last` means remember the last used value.
This setting can be toggled within the program.""",
)
opt(
'+ignore',
'',
add_to_default=False,
long_text="""
An ignore pattern to ignore matched files. Uses the same syntax as :code:`.gitignore` files (see :code:`man gitignore`).
Anchored patterns match with respect to whatever directory is currently being displayed.
Can be specified multiple times to use multiple patterns. Note that every pattern
has to be checked against every file, so use sparingly.
""",
)
egr() # }}}
agr('appearance', 'Appearance') # {{{
opt(
'show_preview',
'last',
choices=('last', 'yes', 'y', 'true', 'no', 'n', 'false'),
long_text="""
Whether to show a preview of the current file/directory. The default value of :code:`last` means remember the last
used value. This setting can be toggled within the program.""",
)
opt(
'pygments_style',
'default',
long_text="""
The pygments color scheme to use for syntax highlighting of file previews. See :link:`pygments
builtin styles <https://pygments.org/styles/>` for a list of schemes.
This sets the colors used for light color schemes, use :opt:`dark_pygments_style` to change the
colors for dark color schemes.
""",
)
opt(
'dark_pygments_style',
'github-dark',
long_text="""
The pygments color scheme to use for syntax highlighting with dark colors. See :link:`pygments
builtin styles <https://pygments.org/styles/>` for a list of schemes.
This sets the colors used for dark color schemes, use :opt:`pygments_style` to change the
colors for light color schemes.""",
)
opt(
'cache_size',
'0.5',
option_type='positive_float',
long_text="""
The maximum size of the disk cache, in gigabytes, used for previews. Zero or negative values
mean no limit.
""",
)
opt(
'syntax_aliases',
'pyj:py pyi:py recipe:py',
ctype='strdict_ _:',
option_type='syntax_aliases',
long_text="""
File extension aliases for syntax highlight. For example, to syntax highlight
:file:`file.xyz` as :file:`file.abc` use a setting of :code:`xyz:abc`.
Multiple aliases must be separated by spaces.
""",
)
opt(
'video_preview',
'width=480 fps=10 duration=5',
long_text="""
Control how videos are sampled for previwing. The width controls
the size of the generated thumbnail from the video. Duration controls
how long the generated thumbnail plays for, in seconds. Note that when
changing these you should also use the :code:`--clear-cache` flag
otherwise it will not affect already cached previews.
""",
)
opt(
'+previewer',
'',
long_text="""
Specify an arbitrary program based preview generator. The syntax is::
pattern program arguments...
Here, pattern can be used to match file names or mimetypes. For example:
:code:`name:*.doc` matches files with the extension :code:`.doc`. Similarly,
:code:`mime:image/*` matches all image files. :code:`program` can be any
executable program in PATH. It will be run with the supplied arguments. The last argument
will be the path to the file for which a preview must be generated.
Can be specified multiple times to setup different previewers for different types of files.
Note that previewers specified using this option take precedence over the builtin
previewers.
The command must output preview data to STDOUT, as a JSON object:
.. code-block:: json
{
"lines": ["line1", "line2", "..."],
"image": "absolute path to generated image preview",
"title_extra": "some text to show on the first line",
}
The lines can contain SGR formatting escape codes and will be displayed as is at the
top of the preview panel. The image is optional and must be in one of the JPEG, PNG, GIF, WEBP, APNG
formats.
""",
)
egr() # }}}
agr('shortcuts', 'Keyboard shortcuts') # {{{
map('Quit', 'quit esc quit')
map('Quit', 'quit ctrl+c quit')
map('Accept current result', 'accept enter accept')
map(
'Select current result',
'select shift+enter select',
long_text="""
When selecting multiple files, this will add the current file to the list of selected files.
You can also toggle the selected status of a file by holding down the :kbd:`Ctrl` key and clicking on
it. Similarly, the :kbd:`Alt` key can be held to click and extend the range of selected files.
""",
)
map(
'Type file name',
'typename ctrl+enter typename',
long_text="""
Type a file name/path rather than filtering the list of existing files.
Useful when specifying a file or directory name for saving that does not yet exist.
When choosing existing directories, will accept the directory whose
contents are being currently displayed as the choice.
Does not work when selecting files to open rather than to save.
""",
)
map(
'Modify file name',
'modifyname alt+enter modifyname',
long_text="""
Modify the name of an existing file and select it for saving.
Useful when specifying a file or directory name for saving that does not yet exist,
but is based on an existing file name.
Does not work when selecting files to open rather than to save.
""",
)
map('Next result', 'next_result down next 1')
map('Previous result', 'prev_result up next -1')
map('Left result', 'left_result left next left')
map('Right result', 'right_result right next right')
map('First result on screen', 'first_result_on_screen home next first_on_screen')
map('Last result on screen', 'last_result_on_screen end next last_on_screen')
map('First result', 'first_result_on_screen ctrl+home next first')
map('Last result', 'last_result_on_screen ctrl+end next last')
map('Change to currently selected dir', 'cd_current tab cd .')
map('Change to parent directory', 'cd_parent shift+tab cd ..')
map('Change to root directory', 'cd_root ctrl+/ cd /')
map('Change to home directory', 'cd_home ctrl+~ cd ~')
map('Change to home directory', 'cd_home ctrl+` cd ~')
map('Change to home directory', 'cd_home ctrl+shift+` cd ~')
map('Change to temp directory', 'cd_tmp --allow-fallback=shifted,ascii ctrl+t cd /tmp')
map('Next filter', 'next_filter --allow-fallback=shifted,ascii ctrl+f 1')
map('Previous filter', 'prev_filter --allow-fallback=shifted,ascii alt+f -1')
map('Toggle showing dotfiles', 'toggle_dotfiles --allow-fallback=shifted,ascii alt+h toggle dotfiles')
map('Toggle showing ignored files', 'toggle_ignorefiles --allow-fallback=shifted,ascii alt+i toggle ignorefiles')
map('Toggle sorting by dates', 'toggle_sort_by_dates --allow-fallback=shifted,ascii alt+d toggle sort_by_dates')
map('Toggle showing preview', 'toggle_preview --allow-fallback=shifted,ascii alt+p toggle preview')
egr() # }}}
def main(args: list[str]) -> None:
raise SystemExit('This must be run as kitten choose-files')
def relative_path_if_possible(path: str, base: str) -> str:
if not base or not path:
return path
from contextlib import suppress
from pathlib import Path
b = Path(base)
q = Path(path)
with suppress(ValueError):
return str(q.relative_to(b))
return path
def format_selection_for_paste(paths: list[str], cwd: str | None, at_prompt: bool) -> str:
items = []
for path in paths:
if cwd:
path = relative_path_if_possible(path, cwd)
if at_prompt:
path = shlex.quote(path)
items.append(path)
return (' ' if at_prompt else '\n').join(items)
@result_handler(has_ready_notification=True)
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
paths: list[str] = data.get('paths', [])
if not paths:
boss.ring_bell_if_allowed()
return
w = boss.window_id_map.get(target_window_id)
if w is None:
boss.ring_bell_if_allowed()
return
w.paste_text(format_selection_for_paste(paths, w.cwd_of_child, w.at_prompt))
usage = '[directory to start choosing files in]'
OPTIONS = """
--mode
type=choices
choices=file,files,all,save-file,dir,save-dir,dirs,save-files
default=file
The type of object(s) to select
--file-filter
type=list
A list of filters to restrict the displayed files. Can be either mimetypes, or glob style patterns. Can be specified multiple times.
The syntax is :code:`type:expression:Descriptive Name`.
For example: :code:`mime:image/png:Images` and :code:`mime:image/gif:Images` and :code:`glob:*.[tT][xX][Tt]:Text files`.
Note that glob patterns are case-sensitive. The mimetype specification is treated as a glob expressions as well, so you can,
for example, use :code:`mime:text/*` to match all text files. The first filter in the list will be applied by default. Use a filter
such as :code:`glob:*:All` to match all files. Note that filtering only applies to files, not directories.
--suggested-save-file-name
A suggested name when picking a save file.
--suggested-save-file-path
Path to an existing file to use as the save file.
--title
Window title to use for this chooser
--display-title
type=bool-set
Show the window title at the top, useful when this kitten is used in an
OS window without a title bar.
--override -o
type=list
Override individual configuration options, can be specified multiple times.
Syntax: :italic:`name=value`.
--config
type=list
completion=type:file ext:conf group:"Config files" kwds:none,NONE
{config_help}
--write-output-to
Path to a file to which the output is written in addition to STDOUT.
--output-format
choices=text,json,shell,shell-relative
default=text
The format in which to write the output. The :code:`text` format is absolute paths separated by newlines,
with a trailing newline. The :code:`shell` format is quoted absolute paths separated by spaces,
quoting is done only if needed. The :code:`shell-relative` format is the same as :code:`shell` except that
it returns paths relative to the starting directory. Note that when invoked from a mapping,
this option is ignored, and either text or shell format is used automatically based on whether
the cursor is at a shell prompt or not.
--write-pid-to
Path to a file to which to write the process ID (PID) of this process to.
--clear-cache
type=bool-set
Clear the caches used by this kitten.
""".format(config_help=CONFIG_HELP.format(conf_name='choose-files', appname=appname)).format
help_text = """\
Select one or more files, quickly, using fuzzy finding, by typing just a few characters from
the file name. Browse matching files, using the arrow keys to navigate matches and press :kbd:`Enter`
to select. The :kbd:`Tab` key can be used to change to a sub-folder. See the :doc:`online docs </kittens/choose-files>`
for full details.
"""
if __name__ == '__main__':
main(sys.argv)
elif __name__ == '__doc__':
cd = sys.cli_docs # type: ignore
cd['usage'] = usage
cd['options'] = OPTIONS
cd['help_text'] = help_text
cd['short_desc'] = 'Choose files, fast'
cd['args_completion'] = CompletionSpec.from_string('type:directory')
elif __name__ == '__conf__':
sys.options_definition = definition # type: ignore
+36
View File
@@ -0,0 +1,36 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package choose_files
import (
"path/filepath"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
)
func TestShellOutput(t *testing.T) {
paths := []string{"simple", "a path", "a;command", "*.txt", "~root", "a>output", `a\b`, "it's"}
actual, err := shlex.Split(shell_output(paths))
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(paths, actual); diff != "" {
t.Fatalf("Shell output did not round-trip paths:\n%s", diff)
}
if q := shell_output([]string{"simple", "a/b"}); q != "simple a/b" {
t.Fatalf("Shell-safe paths were unnecessarily quoted: %q", q)
}
original_cwd := default_cwd
default_cwd = t.TempDir()
t.Cleanup(func() { default_cwd = original_cwd })
relative, err := shlex.Split(for_shell_relative(filepath.Join(default_cwd, "a;command")))
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff([]string{"a;command"}, relative); diff != "" {
t.Fatalf("Shell-relative output did not round-trip the path:\n%s", diff)
}
}
+422
View File
@@ -0,0 +1,422 @@
package choose_files
import (
"fmt"
"io/fs"
"maps"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"sync/atomic"
"unicode/utf8"
"github.com/kovidgoyal/go-parallel"
"github.com/kovidgoyal/kitty/tools/highlight"
"github.com/kovidgoyal/kitty/tools/icons"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/humanize"
"github.com/kovidgoyal/kitty/tools/utils/style"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type Preview interface {
Render(h *Handler, x, y, width, height int)
IsValidForColorScheme(light bool) bool
Unload()
IsReady() bool
String() string
}
type PreviewManager struct {
report_errors chan error
settings Settings
WakeupMainThread func() bool
cache map[string]Preview
lock sync.Mutex
highlighter highlight.Highlighter
}
func NewPreviewManager(err_chan chan error, settings Settings, WakeupMainThread func() bool) (ans *PreviewManager) {
defer func() { sanitize = ans.highlighter.Sanitize }()
return &PreviewManager{
report_errors: err_chan, settings: settings, WakeupMainThread: WakeupMainThread,
cache: make(map[string]Preview), highlighter: highlight.NewHighlighter(nil),
}
}
func (pm *PreviewManager) cached_preview(path string) Preview {
pm.lock.Lock()
defer pm.lock.Unlock()
return pm.cache[path]
}
func (pm *PreviewManager) set_cached_preview(path string, val Preview) {
pm.lock.Lock()
defer pm.lock.Unlock()
pm.cache[path] = val
}
func (h *Handler) render_wrapped_text_in_region(text string, x, y, width, height int, centered bool) int {
lines := style.WrapTextAsLines(text, width, style.WrapOptions{})
for i, line := range lines {
extra := 0
if centered {
extra = max(0, width-wcswidth.Stringwidth(line)) / 2
}
h.lp.MoveCursorTo(x+extra, y+i)
h.lp.QueueWriteString(line)
if i >= height {
break
}
}
return len(lines)
}
type MessagePreview struct {
title string
msg string
trailers []string
}
func (p MessagePreview) String() string { return fmt.Sprintf("MessagePreview{%#v}", p.title) }
func (p MessagePreview) IsValidForColorScheme(bool) bool { return true }
func (p MessagePreview) IsReady() bool { return true }
func (p MessagePreview) Unload() {}
func (p MessagePreview) Render(h *Handler, x, y, width, height int) {
offset := 0
if p.title != "" {
offset += h.render_wrapped_text_in_region(p.title, x, y, width, height, true)
}
offset += h.render_wrapped_text_in_region(p.msg, x, y+offset, width, height-offset, false)
limit := height - offset
if limit > 1 {
for i, line := range p.trailers {
text := wcswidth.TruncateToVisualLength(line, width-1)
if len(text) < len(line) {
text += "…"
}
h.lp.MoveCursorTo(x, y+offset+i-1)
if i >= limit {
h.lp.QueueWriteString("…")
break
}
h.lp.QueueWriteString(text)
}
}
}
func NewErrorPreview(err error) Preview {
sctx := style.Context{AllowEscapeCodes: true}
text := fmt.Sprintf("%s: %s", sctx.SprintFunc("fg=red")("Error"), err)
return &MessagePreview{msg: text}
}
var sanitize func(string) string
func write_file_metadata(abspath string, metadata fs.FileInfo, entries []fs.DirEntry) (header string, trailers []string) {
buf := strings.Builder{}
buf.Grow(4096)
add := func(key, val string) { fmt.Fprintf(&buf, "%s: %s\n", key, val) }
ftype := metadata.Mode().Type()
const file_icon = " "
fmt.Fprintln(&buf, filepath.Base(abspath))
switch ftype {
case 0:
add("Size", humanize.Bytes(uint64(metadata.Size())))
case fs.ModeSymlink:
if tgt, err := os.Readlink(abspath); err == nil {
add("Target", sanitize(tgt))
} else {
add("Target", err.Error())
}
case fs.ModeDir:
num_files, num_dirs := 0, 0
for _, e := range entries {
if e.IsDir() {
num_dirs++
} else {
num_files++
}
}
add("Children", fmt.Sprintf("%d %s %d %s", num_dirs, icons.IconForFileWithMode("dir", fs.ModeDir, false), num_files, file_icon))
}
add("Modified", humanize.Time(metadata.ModTime()))
add("Mode", metadata.Mode().String())
if len(entries) > 0 {
type entry struct {
lname string
ftype fs.FileMode
}
type_map := make(map[string]entry, len(entries))
for _, e := range entries {
type_map[e.Name()] = entry{strings.ToLower(e.Name()), e.Type()}
}
names := utils.Map(func(e fs.DirEntry) string { return e.Name() }, entries)
slices.SortFunc(names, func(a, b string) int { return strings.Compare(type_map[a].lname, type_map[b].lname) })
fmt.Fprintln(&buf, "Contents:")
for _, n := range names {
trailers = append(trailers, icons.IconForFileWithMode(n, type_map[n].ftype, false)+" "+sanitize(n))
}
}
return buf.String(), trailers
}
func NewDirectoryPreview(abspath string, metadata fs.FileInfo) Preview {
entries, err := os.ReadDir(abspath)
if err != nil {
return NewErrorPreview(fmt.Errorf("failed to read the directory %s with error: %w", abspath, err))
}
title := icons.IconForFileWithMode("dir", fs.ModeDir, false) + " Directory\n"
header, extra := write_file_metadata(abspath, metadata, entries)
return &MessagePreview{title: title, msg: header, trailers: extra}
}
func NewFileMetadataPreview(abspath string, metadata fs.FileInfo) *MessagePreview {
ext := filepath.Ext(abspath)
if ext == "" {
ext = "File"
}
title := icons.IconForFileWithMode(filepath.Base(abspath), metadata.Mode().Type(), false) + " " + ext
h, t := write_file_metadata(abspath, metadata, nil)
return &MessagePreview{title: title, msg: h, trailers: t}
}
func NewFileMetadataPreviewWithError(abspath string, metadata fs.FileInfo, err error) *MessagePreview {
ext := filepath.Ext(abspath)
if ext == "" {
ext = "File"
}
title := icons.IconForFileWithMode(filepath.Base(abspath), metadata.Mode().Type(), false) + " " + ext
h, t := write_file_metadata(abspath, metadata, nil)
ans := &MessagePreview{title: title, msg: h, trailers: t}
lines := style.WrapTextAsLines(err.Error(), 30, style.WrapOptions{})
ans.trailers = append(ans.trailers, "")
ans.trailers = append(ans.trailers, lines...)
return ans
}
type highlighed_data struct {
text string
light bool
err error
}
type TextFilePreview struct {
plain_text, highlighted_text string
highlighted_chan chan highlighed_data
ready atomic.Bool
light bool
path string
metadata fs.FileInfo
}
func (p *TextFilePreview) String() string {
return fmt.Sprintf("TextFilePreview{%#v, ready: %v}", p.path, p.ready.Load())
}
func (p *TextFilePreview) IsValidForColorScheme(light bool) bool { return p.light == light }
func (p *TextFilePreview) Unload() {}
func (p *TextFilePreview) IsReady() bool { return p.ready.Load() || p.highlighted_chan == nil }
func (p *TextFilePreview) Render(h *Handler, x, y, width, height int) {
if p.highlighted_chan != nil {
select {
case hd := <-p.highlighted_chan:
p.highlighted_chan = nil
if hd.err == nil {
p.highlighted_text = hd.text
}
default:
}
}
text := p.highlighted_text
if text == "" {
text = p.plain_text
}
s := utils.NewLineScanner(text)
buf := strings.Builder{}
buf.Grow(1024 * height)
title := icons.IconForPath(p.path) + " " + filepath.Base(p.path) + fmt.Sprintf(" %s", humanize.Bytes(uint64(p.metadata.Size())))
for num := 1 + h.render_wrapped_text_in_region(title, x, y, width, height, true); s.Scan() && num < height; num++ {
line := s.Text()
truncated := wcswidth.TruncateToVisualLength(line, width)
buf.WriteString(fmt.Sprintf(loop.MoveCursorToTemplate, y+num, x))
buf.WriteString(truncated)
if len(truncated) < len(line) {
wcswidth.KeepOnlyCSI(line[len(truncated):], &buf)
}
}
buf.WriteString("\x1b[m") // reset any highlight styles
h.lp.QueueWriteString(buf.String())
}
func NewTextFilePreview(abspath string, metadata fs.FileInfo, highlighted_chan chan highlighed_data, sanitize func(string) string) Preview {
data, err := os.ReadFile(abspath)
if err != nil {
return NewFileMetadataPreview(abspath, metadata)
}
text := utils.UnsafeBytesToString(data)
if !utf8.ValidString(text) {
text = "Error: not valid utf-8 text"
}
return &TextFilePreview{
path: abspath, plain_text: sanitize(text), highlighted_chan: highlighted_chan, light: use_light_colors, metadata: metadata}
}
type style_resolver struct {
light bool
light_style, dark_style string
syntax_aliases map[string]string
}
func (s style_resolver) StyleName() string {
return utils.IfElse(s.light, s.light_style, s.dark_style)
}
func (s style_resolver) UseLightColors() bool { return s.light }
func (s style_resolver) SyntaxAliases() map[string]string { return s.syntax_aliases }
func (s style_resolver) TextForPath(path string) (string, error) {
ans, err := os.ReadFile(path)
if err == nil {
return utils.UnsafeBytesToString(ans), nil
}
return "", err
}
func (pm *PreviewManager) highlight_file_async(path string, output chan highlighed_data, ready *atomic.Bool) {
s := style_resolver{light: use_light_colors, syntax_aliases: pm.settings.SyntaxAliases()}
s.light_style, s.dark_style = pm.settings.HighlightStyles()
go func() {
defer func() {
if r := recover(); r != nil {
err := parallel.Format_stacktrace_on_panic(r, 1)
output <- highlighed_data{err: err, light: s.light}
}
close(output)
ready.Store(true)
pm.WakeupMainThread()
}()
highlighted, err := pm.highlighter.HighlightFile(path, &s)
output <- highlighed_data{text: highlighted, err: err, light: s.light}
}()
}
func (pm *PreviewManager) invalidate_color_scheme_based_cached_items() {
pm.lock.Lock()
defer pm.lock.Unlock()
maps.DeleteFunc(pm.cache, func(key string, p Preview) bool { return !p.IsValidForColorScheme(use_light_colors) })
}
func (pm *PreviewManager) preview_for(abspath string, ftype fs.FileMode) (ans Preview) {
if ans = pm.cached_preview(abspath); ans != nil {
return ans
}
defer func() { pm.set_cached_preview(abspath, ans) }()
s, err := os.Lstat(abspath)
if err != nil {
return NewErrorPreview(err)
}
if s.IsDir() {
return NewDirectoryPreview(abspath, s)
}
if is_symlink_to_dir(ftype) {
s, err = os.Stat(abspath)
if err != nil {
return NewErrorPreview(err)
}
return NewDirectoryPreview(abspath, s)
}
fname := filepath.Base(abspath)
mt := utils.GuessMimeType(fname)
for _, q := range previewers {
if q.matches(fname, mt) {
return NewCmdPreview(abspath, s, pm.settings, pm.WakeupMainThread, q)
}
}
const MAX_TEXT_FILE_SIZE = 16 * 1024 * 1024
if s.Size() <= MAX_TEXT_FILE_SIZE && (utils.KnownTextualMimes[mt] || strings.HasPrefix(mt, "text/")) {
ch := make(chan highlighed_data, 2)
ans := NewTextFilePreview(abspath, s, ch, pm.highlighter.Sanitize)
if p, ok := ans.(*TextFilePreview); ok {
pm.highlight_file_async(abspath, ch, &p.ready)
}
return ans
}
switch {
case strings.HasPrefix(mt, "image/"):
var r ImagePreviewRenderer
if ans, err := NewImagePreview(abspath, s, pm.settings, pm.WakeupMainThread, r); err == nil {
return ans
} else {
return NewErrorPreview(err)
}
case strings.HasPrefix(mt, "video/"):
return NewFFMpegPreview(abspath, s, pm.settings, pm.WakeupMainThread)
case IsSupportedArchiveFile(abspath):
return NewArchivePeview(abspath, s, pm.settings, pm.WakeupMainThread)
case IsSupportedByCalibre(abspath):
return NewCalibrePreview(abspath, s, pm.settings, pm.WakeupMainThread)
}
return NewFileMetadataPreview(abspath, s)
}
func (h *Handler) clear_cached_previews() {
if h.last_rendered_preview != nil {
h.last_rendered_preview.Unload()
h.last_rendered_preview = nil
}
if h.prev_preview_for_smooth_transition != nil {
h.prev_preview_for_smooth_transition.Unload()
h.prev_preview_for_smooth_transition = nil
}
}
func (h *Handler) draw_preview_content(x, y, width, height int) {
matches, _ := h.get_results()
r := matches.At(h.state.CurrentIndex())
if r == nil {
h.render_wrapped_text_in_region("No preview available", x, y, width, height, false)
return
}
render := func() {
p := h.last_rendered_preview
if p.IsReady() || h.prev_preview_for_smooth_transition == nil {
p.Render(h, x, y, width, height)
if h.prev_preview_for_smooth_transition != nil {
h.prev_preview_for_smooth_transition.Unload()
h.prev_preview_for_smooth_transition = nil
}
} else {
h.prev_preview_for_smooth_transition.Render(h, x, y, width, height)
}
}
abspath := h.current_abspath()
if h.last_rendered_preview != nil {
if abspath == h.last_rendered_preview_abspath {
render()
return
}
if h.prev_preview_for_smooth_transition != nil {
h.prev_preview_for_smooth_transition.Unload()
}
h.prev_preview_for_smooth_transition = h.last_rendered_preview
h.last_rendered_preview = nil
}
if p := h.preview_manager.preview_for(abspath, r.ftype); p == nil {
h.render_wrapped_text_in_region("No preview available", x, y, width, height, false)
} else {
h.last_rendered_preview = p
h.last_rendered_preview_abspath = abspath
render()
}
}
+385
View File
@@ -0,0 +1,385 @@
package choose_files
import (
"fmt"
"io/fs"
"math"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/kovidgoyal/kitty/tools/icons"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/style"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
func (h *Handler) draw_results_title() {
text := filepath.Clean(h.state.CurrentDir())
home := filepath.Clean(utils.Expanduser("~"))
if strings.HasPrefix(text, home) {
text = "~" + text[len(home):]
}
text = sanitize(text)
available_width := h.screen_size.width - 9
if available_width < 2 {
return
}
tt := wcswidth.TruncateToVisualLength(text, available_width)
if len(tt) < len(text) {
text = wcswidth.TruncateToVisualLength(text, available_width-1)
}
text = fmt.Sprintf(" %s %s ", h.lp.SprintStyled("fg=blue", icons.IconForFileWithMode(text, fs.ModeDir, false)+" "), h.lp.SprintStyled("fg=intense-white bold", text))
extra := available_width - wcswidth.Stringwidth(text)
x := 3
if extra > 1 {
x += extra / 2
}
h.lp.MoveCursorHorizontally(x)
h.lp.QueueWriteString(text)
}
func (h *Handler) draw_no_matches_message(in_progress bool) {
text := "Scanning filesystem, please wait…"
if !in_progress {
text = utils.IfElse(h.state.SearchText() == "", "No files present in this folder", "No matches found")
}
for _, line := range style.WrapTextAsLines(text, h.screen_size.width-2, style.WrapOptions{}) {
h.lp.QueueWriteString("\r")
h.lp.MoveCursorHorizontally(1)
h.lp.QueueWriteString(line)
h.lp.MoveCursorVertically(1)
}
}
const matching_position_style = "fg=green"
const selected_style = "fg=magenta"
const current_style = "fg=intense-white bold"
type text_chunk struct {
text string
emphasize bool
}
func split_up_text(text string, add_ellipsis bool, positions []int) func(func(x text_chunk) bool) {
return func(yield func(x text_chunk) bool) {
if len(positions) == 0 {
if !yield(text_chunk{text, false}) {
return
}
} else {
at := 0
runes := []rune(text)
limit := len(runes)
for _, p := range positions {
if max(p, at) >= limit || p < at {
break
}
if at < p && !yield(text_chunk{string(runes[at:p]), false}) {
return
}
if !yield(text_chunk{string(runes[p]), true}) {
return
}
at = p + 1
}
if at < len(runes) {
if !yield(text_chunk{string(runes[at:]), false}) {
return
}
}
}
if add_ellipsis {
yield(text_chunk{"…", false})
}
}
}
func (h *Handler) render_match_with_positions(text string, add_ellipsis bool, positions []int, is_current bool) {
prefix, suffix, _ := strings.Cut(h.lp.SprintStyled(matching_position_style, " "), " ")
if is_current {
p, s, _ := strings.Cut(h.lp.SprintStyled(current_style, " "), " ")
h.lp.QueueWriteString(p)
defer h.lp.QueueWriteString(s)
suffix += p
}
for chunk := range split_up_text(text, add_ellipsis, positions) {
if chunk.text != "" {
if chunk.emphasize {
h.lp.QueueWriteString(prefix + chunk.text + suffix)
} else {
h.lp.QueueWriteString(chunk.text)
}
}
}
}
var icon_cache map[string]string
func icon_for(path string, x os.FileMode) string {
if icon_cache == nil {
icon_cache = make(map[string]string, 512)
}
if ans := icon_cache[path]; ans != "" {
return ans
}
var ans string
if is_symlink_to_dir(x) {
ans = string(icons.SYMLINK_TO_DIR)
} else {
ans = icons.IconForFileWithMode(path, x, true)
}
if wcswidth.Stringwidth(ans) == 1 {
ans += " "
}
icon_cache[path] = ans
return ans
}
func (h *Handler) draw_column_of_matches(matches ResultsType, current_idx int, x, y, available_width, colnum int) {
root_dir := h.state.CurrentDir()
for i, m := range matches {
h.lp.QueueWriteString("\r")
h.lp.MoveCursorHorizontally(x)
is_selected := h.state.IsSelected(m)
var icon string
if is_selected {
icon = "󰗠 "
} else {
icon = icon_for(filepath.Join(root_dir, m.text), m.ftype)
}
text := sanitize(m.text)
add_ellipsis := false
width := wcswidth.Stringwidth(text)
if width > available_width-3 {
text = wcswidth.TruncateToVisualLength(text, available_width-4)
add_ellipsis = true
width = available_width - 3
}
is_current := i == current_idx
if is_current {
h.lp.QueueWriteString(h.lp.SprintStyled(matching_position_style, icon+" "))
} else {
if is_selected {
h.lp.QueueWriteString(h.lp.SprintStyled(selected_style, icon+" "))
} else {
h.lp.QueueWriteString(icon + " ")
}
}
h.render_match_with_positions(text, add_ellipsis, m.sorted_positions(), is_current)
h.lp.MoveCursorVertically(1)
cr := h.state.mouse_state.AddCellRegion(fmt.Sprintf("result-%d-%d", colnum, i), x, y-1+i, x+width+2, y-1+i)
cr.HoverStyle = HOVER_STYLE
var data struct {
colnum, i int
}
data.colnum, data.i = colnum, i
cr.OnClickEvent = func(id string, ev *loop.MouseEvent, cell_offset tui.Point) error {
if ev.Buttons&loop.LEFT_MOUSE_BUTTON == 0 {
return nil
}
ctrl_mod := utils.IfElse(runtime.GOOS == "darwin", loop.SUPER, loop.CTRL)
mods := ev.Mods & (ctrl_mod | loop.ALT) // shift alone and ctrl+shift are used for kitty bindings
matches, _ := h.get_results()
num_before := h.state.last_render.num_of_slots*data.colnum + data.i
idx, did_wrap := matches.IncrementIndexWithWrapAroundAndCheck(h.state.last_render.first_idx, num_before)
if did_wrap {
h.lp.Beep()
return nil
}
d := matches.SignedDistance(idx, h.state.current_idx)
h.state.SetCurrentIndex(idx)
h.state.last_render.num_before = max(0, h.state.last_render.num_before+d)
switch mods {
case 0:
h.dispatch_action("accept", "")
case ctrl_mod, ctrl_mod | loop.ALT:
h.dispatch_action("select", "")
case loop.ALT:
r := matches.At(idx)
if (r != nil && h.state.IsSelected(r)) || h.result_manager.last_click_anchor == nil {
h.dispatch_action("select", "")
return nil
}
already_selected := utils.NewSetWithItems(h.state.selections...)
cdir := h.state.CurrentDir()
matches.Apply(idx, *h.result_manager.last_click_anchor, func(r *ResultItem) bool {
m := filepath.Join(cdir, r.text)
if !already_selected.Has(m) && h.state.CanSelect(r) {
already_selected.Add(m)
h.state.selections = append(h.state.selections, m)
}
return true
})
return h.draw_screen()
}
return nil
}
}
}
func (h *Handler) draw_list_of_results(matches *SortedResults, y, height int) (num_cols, num_shown, preview_width int) {
const BASE_COL_WIDTH = 40
available_width := h.screen_size.width - 2
show_preview := h.state.ShowPreview()
if show_preview && available_width < BASE_COL_WIDTH+30 {
show_preview = false
}
if show_preview {
switch {
case available_width < BASE_COL_WIDTH*2:
preview_width = max(30, available_width/2)
default:
preview_width = BASE_COL_WIDTH
}
available_width -= preview_width
}
col_width := available_width
num_cols = 1
calc_num_cols := func(num_matches int) int {
if num_matches == 0 || height < 2 {
return 0
}
if num_matches > height {
col_width = BASE_COL_WIDTH
num_cols = max(1, available_width/col_width)
for num_cols > 1 && height*(num_cols-1) >= num_matches {
num_cols--
}
col_width = available_width / num_cols
}
return num_cols
}
columns, num_before, first_idx := matches.SplitIntoColumns(calc_num_cols, height, h.state.last_render.num_before, h.state.CurrentIndex())
h.state.last_render.num_before = num_before
h.state.last_render.num_per_column = height
h.state.last_render.num_columns = num_cols
h.state.last_render.first_idx = first_idx
x := 1
for i, col := range columns {
h.lp.MoveCursorTo(x, y)
h.draw_column_of_matches(col, num_before, x, y, col_width-1, i)
num_before -= height
num_shown += len(col)
x += col_width
}
return len(columns), num_shown, preview_width
}
func (h *Handler) draw_num_of_matches(num_shown, y int, in_progress bool) {
m := ""
switch h.state.last_render.num_matches {
case 0:
m = " no matches "
default:
m = fmt.Sprintf(" %d of %s matches ", min(num_shown, h.state.last_render.num_matches), h.msg_printer.Sprint(h.state.last_render.num_matches))
}
w := int(math.Ceil(float64(wcswidth.Stringwidth(m)) / 2.0))
spinner := ""
spinner_width := 0
if in_progress {
spinner = h.spinner.Tick()
spinner_width = 1 + wcswidth.Stringwidth(spinner)
}
h.lp.MoveCursorTo(h.screen_size.width-w-spinner_width-2, y)
st := loop.SizedText{Subscale_denominator: 2, Subscale_numerator: 1, Vertical_alignment: 2, Width: 1}
graphemes := wcswidth.SplitIntoGraphemes(m)
for len(graphemes) > 0 {
var s strings.Builder
for w := 0; w < 2 && len(graphemes) > 0; {
w += wcswidth.Stringwidth(graphemes[0])
s.WriteString(graphemes[0])
graphemes = graphemes[1:]
}
h.lp.DrawSizedText(s.String(), st)
}
if spinner != "" {
h.lp.QueueWriteString(spinner)
}
}
func (h *Handler) draw_preview(y int) {
x := h.screen_size.width - h.state.last_render.preview_width
height := h.state.last_render.num_of_slots
buf := strings.Builder{}
buf.Grow(16 * height)
buf.WriteString(fmt.Sprintf(loop.MoveCursorToTemplate, y-1, x))
buf.WriteString("┬")
for i := range height {
buf.WriteString(fmt.Sprintf(loop.MoveCursorToTemplate, y+i, x))
buf.WriteString("│")
}
buf.WriteString(fmt.Sprintf(loop.MoveCursorToTemplate, y+height, x))
buf.WriteString("┴")
h.lp.QueueWriteString(buf.String())
h.draw_preview_content(x+1, y, h.state.last_render.preview_width-1, h.state.last_render.num_of_slots)
}
func (h *Handler) draw_results(y, bottom_margin int, matches *SortedResults, in_progress bool) (height int) {
height = h.screen_size.height - y - bottom_margin
h.lp.MoveCursorTo(1, 1+y)
h.draw_frame(h.screen_size.width, height, in_progress)
h.lp.MoveCursorTo(1, 1+y)
h.draw_results_title()
y += 2
h.lp.MoveCursorTo(1, y)
h.state.last_render.num_of_slots = height - 2
num_cols := 0
num := matches.Len()
num_shown := 0
h.state.last_render.preview_width = 0
switch num {
case 0:
h.draw_no_matches_message(in_progress)
default:
num_cols, num_shown, h.state.last_render.preview_width = h.draw_list_of_results(matches, y, h.state.last_render.num_of_slots)
}
h.state.last_render.num_matches = num
h.state.last_render.num_shown = num_shown
h.draw_num_of_matches(h.state.last_render.num_of_slots*num_cols, y+height-2, in_progress)
if h.state.last_render.preview_width > 0 {
h.draw_preview(y)
}
return
}
func (h *Handler) next_result(amt int) {
if h.state.last_render.num_matches > 0 {
idx := h.state.CurrentIndex()
idx = h.result_manager.scorer.sorted_results.IncrementIndexWithWrapAround(idx, amt)
h.state.SetCurrentIndex(idx)
h.state.last_render.num_before = max(0, h.state.last_render.num_before+amt)
}
}
func (h *Handler) move_sideways(leftwards bool) {
r := h.state.last_render
if r.num_matches > 0 && r.num_per_column > 0 {
cidx := h.state.CurrentIndex()
slots := r.num_of_slots
if leftwards {
idx := h.result_manager.scorer.sorted_results.IncrementIndexWithWrapAround(cidx, -slots)
if idx.Less(cidx) {
h.state.SetCurrentIndex(idx)
if r.num_columns > 1 && r.num_before >= r.num_per_column {
h.state.last_render.num_before = max(0, h.state.last_render.num_before-slots)
}
}
} else {
idx := h.result_manager.scorer.sorted_results.IncrementIndexWithWrapAround(cidx, slots)
if cidx.Less(idx) {
h.state.SetCurrentIndex(idx)
if r.num_columns > 1 && r.num_before < (r.num_columns-1)*r.num_per_column {
h.state.last_render.num_before = max(0, h.state.last_render.num_before+slots)
}
}
}
}
}
+41
View File
@@ -0,0 +1,41 @@
package choose_files
import (
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func TestSplitWithPositions(t *testing.T) {
for _, c := range []struct {
src string
positions []int
expected []string
}{
{"abc", nil, []string{"abc"}},
{"abc", []int{0}, []string{"a", "bc"}},
{"abc", []int{1}, []string{"a", "b", "c"}},
{"abc", []int{2}, []string{"ab", "c"}},
{"abc", []int{0, 1}, []string{"a", "b", "c"}},
{"abc", []int{0, 1, 2}, []string{"a", "b", "c"}},
{"abc", []int{0, 2}, []string{"a", "b", "c"}},
// invalid positions
{"abc", []int{-1}, []string{"abc"}},
{"abc", []int{3}, []string{"abc"}},
{"abc", []int{0, 3}, []string{"a", "bc"}},
{"abc", []int{2, 0}, []string{"ab", "c"}},
{"abc", []int{2, 1}, []string{"ab", "c"}},
{"abc", []int{1, 0}, []string{"a", "b", "c"}},
} {
actual := make([]string, 0, len(c.expected))
for ch := range split_up_text(c.src, false, c.positions) {
actual = append(actual, ch.text)
}
if diff := cmp.Diff(c.expected, actual); diff != "" {
t.Fatalf("Failed for src: %#v positions: %v\n%s", c.src, c.positions, diff)
}
}
}
+162
View File
@@ -0,0 +1,162 @@
package choose_files
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/kovidgoyal/go-parallel"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func FilePromptCompleter(getcwd func() string) func(string, string) *cli.Completions {
if getcwd == nil {
getcwd = func() string {
ans, err := os.Getwd()
if err != nil {
ans = "."
}
return ans
}
}
return func(before_cursor, after_cursor string) (ans *cli.Completions) {
defer func() {
if r := recover(); r != nil {
err := parallel.Format_stacktrace_on_panic(r, 1)
debugprintln(err)
}
}()
ans = cli.NewCompletions()
path := before_cursor
prefix := ""
if idx := strings.Index(path, string(os.PathSeparator)); idx > -1 {
d := filepath.Dir(path)
prefix = d + utils.IfElse(strings.HasSuffix(d, string(os.PathSeparator)), "", string(os.PathSeparator))
}
dir := ""
if path == "" {
path = getcwd()
dir = path
} else {
if !filepath.IsAbs(path) {
path = filepath.Join(getcwd(), path)
}
dir = filepath.Dir(path)
if strings.HasSuffix(before_cursor, string(os.PathSeparator)) {
dir = path
}
}
entries, err := os.ReadDir(dir)
if err != nil {
return nil
}
dirs := ans.AddMatchGroup("Directories")
dirs.IsFiles = true
dirs.NoTrailingSpace = true
files := ans.AddMatchGroup("Files")
files.IsFiles = true
files.NoTrailingSpace = true
leading, _ := filepath.Rel(dir, path)
if leading == "." {
leading = ""
}
for _, e := range entries {
word := e.Name()
if leading == "" || strings.HasPrefix(word, leading) {
collection := utils.IfElse(is_directory(resolve_symlink_to_dir(filepath.Join(dir, e.Name()), e.Type())), dirs, files)
if prefix != "" {
word = prefix + word
}
collection.Matches = append(collection.Matches, &cli.Match{Word: word})
}
}
return ans
}
}
func (h *Handler) current_save_file_path() string {
ans := h.rl.AllText()
if ans != "" {
ans = utils.Expanduser(ans)
if !filepath.IsAbs(ans) {
ans = filepath.Join(h.state.CurrentDir(), ans)
}
}
return ans
}
func (h *Handler) save_file_name_handle_key(ev *loop.KeyEvent) (err error) {
ac := h.shortcut_tracker.Match(ev, h.state.keyboard_shortcuts)
if ac != nil {
switch ac.Name {
case "accept":
if p := h.current_save_file_path(); p != "" {
h.state.selections = append(h.state.selections, p)
h.lp.Quit(0)
} else {
h.lp.Beep()
}
ev.Handled = true
return nil
case "select":
if p := h.current_save_file_path(); p != "" {
h.state.selections = append(h.state.selections, p)
}
ev.Handled = true
h.rl.ResetText()
return h.draw_screen()
case "quit":
h.state.screen = NORMAL
ev.Handled = true
return h.draw_screen()
}
}
if err = h.rl.OnKeyEvent(ev); err == nil {
err = h.draw_screen()
}
return
}
func (h *Handler) initialize_save_file_name(fname string) {
h.state.screen = SAVE_FILE
h.rl.ResetText()
if len(h.state.selections) > 0 && fname == "" {
if q, err := filepath.Abs(h.state.selections[0]); err == nil {
if s, err := os.Stat(q); err == nil {
if s.IsDir() == h.state.mode.OnlyDirs() {
if fname, err = filepath.Rel(h.state.CurrentDir(), q); err != nil {
fname = q
}
}
}
}
}
h.rl.SetText(fname)
}
func (h *Handler) draw_save_file_name_screen() (err error) {
h.lp.AllowLineWrapping(true)
desc := utils.IfElse(h.state.mode == SELECT_SAVE_FILE, "file", "directory")
if h.state.DisplayTitle() {
h.lp.Println(h.state.WindowTitle())
}
h.lp.Println("Enter the name of the", desc, "below, relative to:")
h.lp.Println(h.lp.SprintStyled("fg=green", h.state.CurrentDir()))
if h.state.mode.AllowsMultipleSelection() {
h.lp.Println("Use shift+enter (or whatever you mapped the select action to) to enter multiple filenames")
}
h.lp.Println()
h.rl.RedrawNonAtomic()
h.lp.AllowLineWrapping(false)
if len(h.state.selections) > 0 {
h.lp.SaveCursorPosition()
h.draw_footer()
h.lp.RestoreCursorPosition()
}
return
}
+772
View File
@@ -0,0 +1,772 @@
package choose_files
import (
"bytes"
"cmp"
"encoding/binary"
"fmt"
"io/fs"
"math"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"unicode/utf8"
"github.com/kovidgoyal/go-parallel"
"github.com/kovidgoyal/kitty/tools/fzf"
"github.com/kovidgoyal/kitty/tools/ignorefiles"
"github.com/kovidgoyal/kitty/tools/utils"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func (c CombinedScore) String() string {
return fmt.Sprintf("{score: %d length: %d index: %d}", c.Score(), c.Length(), c.Index())
}
type ignore_file_with_prefix struct {
impl ignorefiles.IgnoreFile
prefix string
}
func (i *ignore_file_with_prefix) is_ignored(name string, ftype fs.FileMode) (ans bool, was_match bool) {
ans, linenum, _ := i.impl.IsIgnored(i.prefix+name, ftype)
was_match = linenum > -1
return
}
type ResultItem struct {
text string
ftype fs.FileMode
positions []int // may be nil
score CombinedScore
ignore_files []ignore_file_with_prefix
}
type ResultsType []*ResultItem
func (r *ResultItem) SetScoreResult(x fzf.Result) {
r.positions = x.Positions
r.score.Set_score(uint16(math.MaxUint16 - uint16(x.Score)))
}
func (r ResultItem) IsMatching() bool {
return r.score.Score() < uint16(math.MaxUint16)
}
func (r ResultItem) String() string {
return fmt.Sprintf("{text: %#v, %s, positions: %#v}", r.text, r.score, r.positions)
}
func (r *ResultItem) sorted_positions() []int {
if len(r.positions) > 1 {
sort.Ints(r.positions)
}
return r.positions
}
type FileSystemScanner struct {
listeners []chan bool
in_progress, keep_going atomic.Bool
root_dir string
mutex sync.Mutex
collection *ResultCollection
dir_reader func(path string) ([]fs.DirEntry, error)
file_reader func(path string) ([]byte, error)
filter_func func(filename string) bool
global_gitignore ignorefiles.IgnoreFile
global_ignore ignorefiles.IgnoreFile
respect_ignores, show_hidden bool
sort_by_last_modified bool
err error
}
func new_filesystem_scanner(root_dir string, notify chan bool, filter_func func(string) bool) (fss *FileSystemScanner) {
ans := &FileSystemScanner{root_dir: root_dir, listeners: []chan bool{notify}, collection: NewResultCollection(4096)}
ans.in_progress.Store(true)
ans.keep_going.Store(true)
ans.dir_reader = os.ReadDir
ans.file_reader = os.ReadFile
ans.filter_func = utils.IfElse(filter_func == nil, accept_all, filter_func)
ans.global_gitignore = ignorefiles.NewGitignore()
ans.global_ignore = ignorefiles.NewGitignore()
ans.respect_ignores = true
ans.show_hidden = false
return ans
}
type Scanner interface {
Start()
Cancel()
AddListener(chan bool)
Len() int
Batch(offset *CollectionIndex) []ResultItem
Finished() bool
Error() error
}
func (fss *FileSystemScanner) lock() { fss.mutex.Lock() }
func (fss *FileSystemScanner) unlock() { fss.mutex.Unlock() }
func (fss *FileSystemScanner) Error() error {
fss.lock()
defer fss.unlock()
return fss.err
}
func (fss *FileSystemScanner) Start() {
go fss.worker()
}
func (fss *FileSystemScanner) Cancel() {
fss.keep_going.Store(false)
}
func (fss *FileSystemScanner) AddListener(x chan bool) {
fss.lock()
defer fss.unlock()
if !fss.in_progress.Load() {
close(x)
} else {
fss.listeners = append(fss.listeners, x)
}
}
func (fss *FileSystemScanner) Len() int {
fss.lock()
defer fss.unlock()
return fss.collection.Len()
}
func (fss *FileSystemScanner) Batch(offset *CollectionIndex) []ResultItem {
fss.lock()
defer fss.unlock()
return fss.collection.Batch(offset)
}
func (fss *FileSystemScanner) Finished() bool {
return !fss.in_progress.Load()
}
type sortable_dir_entry struct {
name string
ftype fs.FileMode
sort_key []byte
buf [unix.NAME_MAX + 1]byte
}
const SymlinkToDir = 1
// SymlinkToDir shares its bit with the other-execute permission bit, so it is
// only meaningful when combined with fs.ModeSymlink
func is_symlink_to_dir(ftype fs.FileMode) bool {
return ftype&fs.ModeSymlink != 0 && ftype&SymlinkToDir != 0
}
func is_directory(ftype fs.FileMode) bool {
return ftype.IsDir() || is_symlink_to_dir(ftype)
}
// Mark ftype with SymlinkToDir if it is a symlink pointing to a directory
func resolve_symlink_to_dir(path string, ftype fs.FileMode) fs.FileMode {
if ftype&fs.ModeSymlink != 0 {
if st, err := os.Stat(path); err == nil && st.IsDir() {
ftype |= SymlinkToDir
}
}
return ftype
}
// lowercase a string into a pre-existing byte buffer with speedups for ASCII
func as_lower(s string, output []byte) int {
limit := min(len(s), len(output))
found_non_ascii := false
pos := 0
for i := range limit {
c := s[i]
if 'A' <= c && c <= 'Z' {
c += 'a' - 'A'
if pos < i {
copy(output[pos:i], s[pos:i])
}
output[i] = c
pos = i + 1
} else if c >= utf8.RuneSelf {
if pos < i {
copy(output[pos:i], s[pos:i])
}
found_non_ascii = true
pos = i
break
}
}
if !found_non_ascii {
if pos < limit {
copy(output[pos:limit], s[pos:limit])
}
return limit
}
buf := [4]byte{}
var n int
for _, r := range s[pos:] {
o := output[pos:]
r = unicode.ToLower(r)
if len(o) > 3 {
n = utf8.EncodeRune(o, r)
} else {
n = utf8.EncodeRune(buf[:], r)
n = copy(o, buf[:n])
}
pos += n
if pos >= len(output) {
break
}
}
return pos
}
func accept_all(filename string) bool { return true }
func (fss *FileSystemScanner) worker() {
defer func() {
fss.lock()
defer fss.unlock()
fss.in_progress.Store(false)
if r := recover(); r != nil {
qerr := parallel.Format_stacktrace_on_panic(r, 1)
fss.err = qerr
}
for _, l := range fss.listeners {
close(l)
}
}()
root_dir, _ := filepath.Abs(fss.root_dir)
if !strings.HasSuffix(root_dir, string(os.PathSeparator)) {
root_dir += string(os.PathSeparator)
}
dir := root_dir
var ignore_files []ignore_file_with_prefix
base := ""
pos := &CollectionIndex{}
var arena []sortable_dir_entry
var sortable []*sortable_dir_entry
var ignoreable []*sortable_dir_entry
var idx uint32
dot_git := os.Getenv("GIT_DIR")
if dot_git == "" {
dot_git = ".git"
}
// do a breadth first traversal of the filesystem
is_root := true
for dir != "" {
if !fss.keep_going.Load() {
break
}
entries, err := fss.dir_reader(dir)
if err != nil {
if is_root {
fss.keep_going.Store(false)
fss.lock()
fss.err = err
fss.unlock()
}
entries = nil
}
if cap(arena) < len(entries) {
arena = make([]sortable_dir_entry, 0, max(1024, len(entries), 2*cap(arena)))
sortable = make([]*sortable_dir_entry, 0, cap(arena))
ignoreable = make([]*sortable_dir_entry, 0, cap(arena))
}
arena = arena[:len(entries)]
sortable = sortable[:0]
ignoreable = ignoreable[:0]
ignore_files_copied := false
add_ignore_file_from_impl := func(impl ignorefiles.IgnoreFile) {
// we want ignore_files to be a copy as we dont want to
// change the underlying array of ignore_files as it is
// referenced by multiple ResultItems
if !ignore_files_copied {
ignore_files_copied = true
n := make([]ignore_file_with_prefix, len(ignore_files), len(ignore_files)+4)
copy(n, ignore_files)
ignore_files = n
}
ignore_files = append(ignore_files, ignore_file_with_prefix{impl: impl})
}
add_ignore_file := func(name string) {
if data, rerr := fss.file_reader(dir + name); rerr == nil {
impl := ignorefiles.NewGitignore()
if rerr = impl.LoadString(utils.UnsafeBytesToString(data)); rerr == nil && impl.Len() > 0 {
add_ignore_file_from_impl(impl)
}
}
}
entry_is_ignored := func(name string, ftype fs.FileMode) (is_ignored bool) {
for _, ignore_file := range ignore_files {
if iig, was_match := ignore_file.is_ignored(name, ftype); was_match {
is_ignored = iig
}
}
return
}
has_git_ignore, has_dot_git, has_dot_ignore := false, false, false
sort_order := 1
for i, e := range entries {
name := e.Name()
ftype := e.Type()
// avoid stat() on hidden entries that will be skipped anyway
if fss.show_hidden || name[0] != '.' || name == dot_git {
ftype = resolve_symlink_to_dir(dir+name, ftype)
}
is_dir := is_directory(ftype)
if !is_dir {
switch name {
case ".ignore":
has_dot_ignore = true
case ".gitignore":
has_git_ignore = true
}
if !fss.filter_func(name) {
continue
}
} else {
if name == dot_git {
has_dot_git = true
}
}
if !fss.show_hidden && name[0] == '.' {
continue
}
arena[i].name = name
arena[i].ftype = ftype
if is_dir {
arena[i].buf[0] = '0'
} else {
arena[i].buf[0] = '1'
}
if fss.sort_by_last_modified {
var ts time.Time
if info, err := e.Info(); err == nil {
ts = info.ModTime()
}
binary.BigEndian.PutUint64(arena[i].buf[1:], uint64(ts.UnixNano()))
arena[i].sort_key = arena[i].buf[:1+8]
sort_order = -1
} else {
n := as_lower(arena[i].name, arena[i].buf[1:])
arena[i].sort_key = arena[i].buf[:1+n]
}
sortable = append(sortable, &arena[i])
}
if fss.respect_ignores {
if is_root && fss.global_ignore.Len() > 0 {
add_ignore_file_from_impl(fss.global_ignore)
}
if has_dot_git {
if fss.global_gitignore.Len() > 0 {
add_ignore_file_from_impl(fss.global_gitignore)
}
add_ignore_file(filepath.Join(dot_git, "info", "exclude"))
if has_git_ignore {
add_ignore_file(".gitignore")
}
}
if has_dot_ignore {
add_ignore_file(".ignore")
}
}
final_entries := sortable
if len(ignore_files) > 0 {
for _, e := range sortable {
if !entry_is_ignored(e.name, e.ftype) {
ignoreable = append(ignoreable, e)
}
}
final_entries = ignoreable
}
slices.SortFunc(final_entries, func(a, b *sortable_dir_entry) int { return sort_order * bytes.Compare(a.sort_key, b.sort_key) })
fss.lock()
for _, e := range final_entries {
i := fss.collection.NextAppendPointer()
i.ftype = e.ftype
i.text = base + e.name
i.score.Set_index(idx)
i.ignore_files = ignore_files
idx++
}
listeners := fss.listeners
fss.unlock()
for _, l := range listeners {
select {
case l <- true:
default:
}
}
ignore_files = nil
if relpath, ignf := fss.collection.NextDir(pos); relpath != "" {
base = relpath + string(os.PathSeparator)
dir = root_dir + base
if len(ignf) != 0 {
name := filepath.Base(relpath) + string(os.PathSeparator)
ignore_files = utils.Map(func(ignore_file ignore_file_with_prefix) ignore_file_with_prefix {
return ignore_file_with_prefix{impl: ignore_file.impl, prefix: ignore_file.prefix + name}
}, ignf)
}
} else {
dir = ""
}
is_root = false
}
}
type FileSystemScorer struct {
scanner Scanner
keep_going, is_complete atomic.Bool
root_dir, query string
filter Filter
only_dirs bool
mutex sync.Mutex
sorted_results *SortedResults
on_results func(error, bool)
current_worker_wait *sync.WaitGroup
scorer *fzf.FuzzyMatcher
dir_reader func(path string) ([]fs.DirEntry, error)
file_reader func(path string) ([]byte, error)
global_gitignore, global_ignore ignorefiles.IgnoreFile
respect_ignores, show_hidden bool
sort_by_last_modified bool
}
func NewFileSystemScorer(root_dir, query string, filter Filter, only_dirs bool, on_results func(error, bool)) (ans *FileSystemScorer) {
return &FileSystemScorer{
query: query, root_dir: root_dir, only_dirs: only_dirs, filter: filter, on_results: on_results,
scorer: fzf.NewFuzzyMatcher(fzf.PATH_SCHEME), sorted_results: NewSortedResults(), respect_ignores: true,
}
}
func (fss *FileSystemScorer) lock() { fss.mutex.Lock() }
func (fss *FileSystemScorer) unlock() { fss.mutex.Unlock() }
func (fss *FileSystemScorer) Start() {
on_results := make(chan bool)
fss.is_complete.Store(false)
fss.keep_going.Store(true)
if fss.scanner == nil {
sc := new_filesystem_scanner(fss.root_dir, on_results, fss.filter.Match)
if fss.dir_reader != nil {
sc.dir_reader = fss.dir_reader
}
if fss.file_reader != nil {
sc.file_reader = fss.file_reader
}
if fss.global_gitignore != nil {
sc.global_gitignore = fss.global_gitignore
} else if ignore := ignorefiles.GlobalGitignore(); ignore != nil {
sc.global_gitignore = ignore
}
if fss.global_ignore != nil {
sc.global_ignore = fss.global_ignore
}
sc.show_hidden, sc.respect_ignores = fss.show_hidden, fss.respect_ignores
sc.sort_by_last_modified = fss.sort_by_last_modified
fss.scanner = sc
fss.scanner.Start()
} else {
fss.scanner.AddListener(on_results)
}
fss.current_worker_wait = &sync.WaitGroup{}
fss.current_worker_wait.Add(1)
go fss.worker(on_results, fss.current_worker_wait)
}
func (fss *FileSystemScorer) Change_query(query string) {
if fss.query == query {
return
}
fss.keep_going.Store(false)
if fss.current_worker_wait != nil {
if fss.scanner != nil {
fss.scanner.Cancel()
}
fss.current_worker_wait.Wait()
}
fss.lock()
fss.query = query
fss.sorted_results.Clear()
fss.unlock()
fss.Start()
}
func (fss *FileSystemScorer) change_scanner_setting(callback func()) {
fss.keep_going.Store(false)
if fss.current_worker_wait != nil {
if fss.scanner != nil {
fss.scanner.Cancel()
}
fss.current_worker_wait.Wait()
}
fss.lock()
callback()
fss.sorted_results.Clear()
fss.scanner = nil
fss.unlock()
fss.Start()
}
func (fss *FileSystemScorer) Change_filter(filter Filter) {
if !fss.filter.Equal(filter) {
fss.change_scanner_setting(func() { fss.filter = filter })
}
}
func (fss *FileSystemScorer) Change_show_hidden(val bool) {
if fss.show_hidden != val {
fss.change_scanner_setting(func() { fss.show_hidden = val })
}
}
func (fss *FileSystemScorer) Change_respect_ignores(val bool) {
if fss.respect_ignores != val {
fss.change_scanner_setting(func() { fss.respect_ignores = val })
}
}
func (fss *FileSystemScorer) Change_sort_by_last_modified(val bool) {
if fss.sort_by_last_modified != val {
fss.change_scanner_setting(func() { fss.sort_by_last_modified = val })
}
}
func (fss *FileSystemScorer) worker(on_results chan bool, worker_wait *sync.WaitGroup) {
defer func() {
fss.is_complete.Store(true)
defer worker_wait.Done()
if r := recover(); r != nil {
if fss.keep_going.Load() {
qerr := parallel.Format_stacktrace_on_panic(r, 1)
fss.on_results(qerr, true)
}
} else {
if fss.keep_going.Load() {
fss.on_results(fss.scanner.Error(), true)
}
}
}()
handle_batch := func(results []ResultItem) (err error) {
if err = fss.scanner.Error(); err != nil {
return
}
var rp []*ResultItem
if fss.only_dirs {
rp = make([]*ResultItem, 0, len(results))
for i, r := range results {
if is_directory(r.ftype) {
rp = append(rp, &results[i])
}
}
} else {
if fss.filter.Match == nil {
rp = make([]*ResultItem, len(results))
for i := range len(rp) {
rp[i] = &results[i]
}
} else {
rp = make([]*ResultItem, 0, len(results))
for i, r := range results {
if is_directory(r.ftype) || fss.filter.Match(filepath.Base(r.text)) {
rp = append(rp, &results[i])
}
}
}
}
if len(rp) > 0 {
if fss.query != "" {
scores, err := fss.scorer.Score(utils.Map(func(r *ResultItem) string { return r.text }, rp), fss.query)
if err != nil {
return err
}
for i, r := range rp {
r.SetScoreResult(scores[i])
r.score.Set_length(uint16(len(r.text)))
}
rp = utils.Filter(rp, func(r *ResultItem) bool { return r.IsMatching() })
} else {
for _, r := range rp {
r.score &= 0b11111111111111111111111111111111 // only preserve index
r.positions = nil
}
}
}
if len(rp) > 0 {
slices.SortFunc(rp, func(a, b *ResultItem) int { return cmp.Compare(a.score, b.score) })
}
fss.sorted_results.AddSortedSlice(rp)
return
}
offset := &CollectionIndex{}
for range on_results {
if !fss.keep_going.Load() {
break
}
results := fss.scanner.Batch(offset)
if len(results) > 0 || fss.scanner.Error() != nil {
fss.on_results(handle_batch(results), false)
}
}
for fss.keep_going.Load() {
b := fss.scanner.Batch(offset)
if len(b) == 0 {
break
}
fss.on_results(handle_batch(b), false)
}
}
func (fss *FileSystemScorer) Results() (ans *SortedResults, is_finished bool) {
fss.lock()
defer fss.unlock()
return fss.sorted_results, fss.is_complete.Load()
}
func (fss *FileSystemScorer) Cancel() {
fss.keep_going.Store(false)
fss.scanner.Cancel()
}
type Settings interface {
OnlyDirs() bool
CurrentDir() string
SearchText() string
ShowHidden() bool
RespectIgnores() bool
SortByLastModified() bool
Filter() Filter
GlobalIgnores() ignorefiles.IgnoreFile
HighlightStyles() (string, string)
SyntaxAliases() map[string]string
DiskCacheSize() int64
}
type ResultManager struct {
report_errors chan error
WakeupMainThread func() bool
settings Settings
scorer *FileSystemScorer
mutex sync.Mutex
last_wakeup_at time.Time
last_click_anchor *CollectionIndex
}
func NewResultManager(err_chan chan error, settings Settings, WakeupMainThread func() bool) *ResultManager {
ans := &ResultManager{
report_errors: err_chan,
settings: settings,
WakeupMainThread: WakeupMainThread,
}
return ans
}
func (m *ResultManager) new_scorer() {
root_dir := m.current_root_dir()
query := m.settings.SearchText()
m.scorer = NewFileSystemScorer(root_dir, query, m.settings.Filter(), m.settings.OnlyDirs(), m.on_results)
m.scorer.respect_ignores = m.settings.RespectIgnores()
m.scorer.show_hidden = m.settings.ShowHidden()
m.scorer.global_ignore = m.settings.GlobalIgnores()
m.scorer.sort_by_last_modified = m.settings.SortByLastModified()
m.last_click_anchor = nil
}
func (m *ResultManager) on_results(err error, is_finished bool) {
if err != nil {
m.report_errors <- err
m.WakeupMainThread()
return
}
m.mutex.Lock()
defer m.mutex.Unlock()
if is_finished || time.Since(m.last_wakeup_at) > time.Millisecond*50 {
m.WakeupMainThread()
m.last_wakeup_at = time.Now()
}
}
func (m *ResultManager) current_root_dir() string {
var err error
root_dir := m.settings.CurrentDir()
if root_dir == "" || root_dir == "." {
if root_dir, err = os.Getwd(); err != nil {
return "/"
}
}
root_dir = utils.Expanduser(root_dir)
if root_dir, err = filepath.Abs(root_dir); err != nil {
return "/"
}
return root_dir
}
func (m *ResultManager) set_root_dir() {
if m.scorer != nil {
m.scorer.Cancel()
}
_ = os.Chdir(m.current_root_dir()) // this is so the terminal emulator can read the wd for launch --directory=current
m.new_scorer()
m.mutex.Lock()
m.last_wakeup_at = time.Time{}
m.mutex.Unlock()
m.scorer.Start()
}
func (m *ResultManager) set_something(callback func()) {
m.mutex.Lock()
m.last_wakeup_at = time.Time{}
m.mutex.Unlock()
if m.scorer == nil {
m.new_scorer()
m.scorer.Start()
} else {
m.last_click_anchor = nil
callback()
}
}
func (m *ResultManager) set_query() {
m.set_something(func() { m.scorer.Change_query(m.settings.SearchText()) })
}
func (m *ResultManager) set_filter() {
m.set_something(func() { m.scorer.Change_filter(m.settings.Filter()) })
}
func (m *ResultManager) set_show_hidden() {
m.set_something(func() { m.scorer.Change_show_hidden(m.settings.ShowHidden()) })
}
func (m *ResultManager) set_respect_ignores() {
m.set_something(func() { m.scorer.Change_respect_ignores(m.settings.RespectIgnores()) })
}
func (m *ResultManager) set_sort_by_last_modified() {
m.set_something(func() { m.scorer.Change_sort_by_last_modified(m.settings.SortByLastModified()) })
}
func (h *Handler) get_results() (ans *SortedResults, is_complete bool) {
if h.result_manager.scorer == nil {
return
}
return h.result_manager.scorer.Results()
}
+557
View File
@@ -0,0 +1,557 @@
package choose_files
import (
"fmt"
"io/fs"
"math/rand"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/kovidgoyal/kitty/tools/ignorefiles"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func TestAsLower(t *testing.T) {
buf := [512]byte{}
for _, q := range []string{
"abc", "aBc", "aBCCf83Dx", "mOoseÇa", "89ÇĞxxA", "", "23", "aIİBc",
} {
n := as_lower(q, buf[:])
actual := utils.UnsafeBytesToString(buf[:n])
if diff := cmp.Diff(strings.ToLower(q), actual); diff != "" {
t.Fatalf("Failed to lowercase: %#v\n%s", q, diff)
}
}
}
type node struct {
name string
children map[string]*node
data string
}
func (n node) Name() string {
return n.name
}
func (n node) IsDir() bool {
return n.children != nil
}
func (n node) String() string {
return fmt.Sprintf("{name: %s num_children: %d}", n.name, len(n.children))
}
func (n node) Type() fs.FileMode {
if n.children == nil {
return 0
}
return fs.ModeDir
}
func (n node) Info() (fs.FileInfo, error) {
return nil, fmt.Errorf("Info() not implemented")
}
func random_name(r *rand.Rand) string {
length := 3 + r.Intn(23)
bytes := make([]byte, length)
for i := range length {
bytes[i] = byte(r.Intn(26) + 'a')
}
return string(bytes)
}
func (n *node) generate_random_tree(depth, breadth int) {
r := rand.New(rand.NewSource(111))
n.children = make(map[string]*node)
for range breadth {
c := &node{name: random_name(r)}
n.children[c.name] = c
if depth > 0 && r.Intn(10) < 3 {
c.generate_random_tree(depth-1, breadth)
}
}
}
func (n node) dir_entries() []fs.DirEntry {
entries := make([]fs.DirEntry, 0, len(n.children))
for _, v := range n.children {
entries = append(entries, v)
}
return entries
}
func (n node) ReadFile(name string) ([]byte, error) {
if name == string(os.PathSeparator) {
return nil, fs.ErrNotExist
}
p := &n
for x := range strings.SplitSeq(strings.Trim(name, string(os.PathSeparator)), string(os.PathSeparator)) {
c, found := p.children[x]
if !found {
return nil, fs.ErrNotExist
}
p = c
}
return []byte(p.data), nil
}
func (n node) ReadDir(name string) ([]fs.DirEntry, error) {
if name == string(os.PathSeparator) {
return n.dir_entries(), nil
}
p := &n
for x := range strings.SplitSeq(strings.Trim(name, string(os.PathSeparator)), string(os.PathSeparator)) {
c, found := p.children[x]
if !found {
return nil, fs.ErrNotExist
}
if !c.IsDir() {
return nil, fs.ErrExist
}
p = c
}
return p.dir_entries(), nil
}
func TestChooseFilesIgnore(t *testing.T) {
root := node{name: string(os.PathSeparator), children: map[string]*node{
"a": {name: "a"},
"b": {name: "b"},
"c.png": {name: "c.png"},
".ignore": {name: ".ignore", data: "a\nx/s/n"},
".gitignore": {name: ".gitignore", data: "b"},
"x": {name: "x", children: map[string]*node{
"1": {name: "1"}, "2": {name: "2"}, "3": {name: "3"},
"s": {name: "s", children: map[string]*node{
"m": {name: "m"}, "n": {name: "n"},
}},
}},
"y": {name: "y", children: map[string]*node{
"3": {name: "3"}, "4": {name: "4"}, "5": {name: "5"},
"s": {name: "s", children: map[string]*node{
"3": {name: "3"}, "4": {name: "4"}, "5": {name: "5"}, "6": {name: "6"},
}},
".gitignore": {name: ".gitignore", data: "/s/5"},
".git": {name: ".git", children: map[string]*node{
"info": {name: "info", children: map[string]*node{
"exclude": {name: "exclude", data: "s/4"},
}},
}},
}},
}}
r := func(respect_ignores bool, expected string) {
ch := make(chan bool)
s := new_filesystem_scanner("/", ch, nil)
s.dir_reader = root.ReadDir
s.file_reader = root.ReadFile
s.global_gitignore = ignorefiles.NewGitignore()
s.global_ignore = ignorefiles.NewGitignore()
s.respect_ignores = respect_ignores
if err := s.global_gitignore.LoadLines("*.png", "s/3"); err != nil {
t.Fatal(err)
}
if err := s.global_ignore.LoadLines("x/3"); err != nil {
t.Fatal(err)
}
s.Start()
for range ch {
}
if s.err != nil {
t.Fatal(s.err)
}
ci := CollectionIndex{}
actual := utils.Map(func(x ResultItem) string { return x.text }, s.Batch(&ci))
if diff := cmp.Diff(strings.Split(expected, ` `), actual); diff != "" {
t.Fatalf("Incorrect ignoring:\n%s", diff)
}
}
r(true, `x y b c.png x/s x/1 x/2 y/s y/3 y/4 y/5 x/s/m y/s/6`)
r(false, `x y a b c.png x/s x/1 x/2 x/3 y/s y/3 y/4 y/5 x/s/m x/s/n y/s/3 y/s/4 y/s/5 y/s/6`)
}
func TestChooseFilesScoring(t *testing.T) {
root := node{name: string(os.PathSeparator), children: map[string]*node{
"b": {name: "b"},
"a": {name: "a"},
"c.png": {name: "c.png"},
"x": {name: "x", children: map[string]*node{
"1": {name: "1"}, "2": {name: "2"}, "3": {name: "3"},
"s": {name: "s", children: map[string]*node{
"m": {name: "m"}, "n": {name: "n"},
}},
}},
"y": {name: "y", children: map[string]*node{
"3": {name: "3"}, "4": {name: "4"}, "5": {name: "5"},
}},
}}
wg := sync.WaitGroup{}
wg.Add(1)
s := NewFileSystemScorer(string(os.PathSeparator), "", Filter{}, false, func(err error, is_complete bool) {
if is_complete {
wg.Done()
}
})
s.dir_reader = root.ReadDir
s.global_gitignore = ignorefiles.NewGitignore()
s.Start()
wg.Wait()
results := func() (ans []string) {
rr, _ := s.Results()
for _, r := range rr.RenderedMatches(CollectionIndex{}, -1) {
ans = append(ans, r.text)
}
return
}
ae := func(query string, expected ...string) {
wg.Add(1)
s.Change_query(query)
wg.Wait()
if diff := cmp.Diff(expected, results()); diff != "" {
t.Fatalf("Query less scoring failed\n%s", diff)
}
}
ae("a", "a")
ae("3", "x/3", "y/3")
ae("s", "x/s", "x/s/m", "x/s/n")
ae("sn", "x/s/n")
ae("", "x", "y", "a", "b", "c.png", "x/s", "x/1", "x/2", "x/3", "y/3", "y/4", "y/5", "x/s/m", "x/s/n")
af := func(filter string, expected ...string) {
f, _ := NewFilter(filter)
wg.Add(1)
s.Change_filter(*f)
wg.Wait()
if diff := cmp.Diff(expected, results()); diff != "" {
t.Fatalf("filter %s failed\n%s", filter, diff)
}
}
af("glob:a:A", "x", "y", "a", "x/s")
af("glob:[ab]:A", "x", "y", "a", "b", "x/s")
af("mime:image/png:A", "x", "y", "c.png", "x/s")
af("mime:image/*:A", "x", "y", "c.png", "x/s")
af("glob:*:All", "x", "y", "a", "b", "c.png", "x/s", "x/1", "x/2", "x/3", "y/3", "y/4", "y/5", "x/s/m", "x/s/n")
}
func combined_filter(t *testing.T, specs ...string) Filter {
t.Helper()
filters := make([]Filter, 0, len(specs))
for _, spec := range specs {
f, err := NewFilter(spec)
if err != nil {
t.Fatal(err)
}
filters = append(filters, *f)
}
return CombinedFilter(filters...)
}
func TestChooseFilesFilterEquality(t *testing.T) {
f := func(specs ...string) Filter { return combined_filter(t, specs...) }
for _, tc := range []struct {
a, b Filter
equal bool
}{
{f("glob:*.txt:A"), f("glob:*.txt:B"), true},
{f("glob:*.txt:A"), f("mime:*.txt:A"), false},
{f("glob:*.txt:A", "glob:*.jpg:A"), f("glob:*.jpg:B", "glob:*.txt:B"), true},
{f("glob:*.txt:A", "glob:*.jpg:A"), f("glob:*.txt:A", "glob:*.png:A"), false},
{f("glob:*.txt:A", "glob:*.jpg:A"), f("glob:*.txt:A"), false},
{f("glob:*.txt:A", "glob:*.txt:A"), f("glob:*.txt:A"), true},
{f("mime:image/*:A", "glob:*.mkv:A"), f("mime:image/*:A", "mime:*.mkv:A"), false},
{f("glob:*.txt:A", "glob:*.jpg:A"), CombinedFilter(f("glob:*.jpg:A"), f("glob:*.txt:A", "glob:*.jpg:A")), true},
{f("glob:*:A"), Filter{}, true},
{f("glob:*:A"), f("glob:*.txt:A"), false},
} {
if tc.a.Equal(tc.b) != tc.equal || tc.b.Equal(tc.a) != tc.equal {
t.Errorf("expected Equal(%s, %s) to be %v", tc.a, tc.b, tc.equal)
}
}
if s := f("glob:*.txt:A", "mime:image/*:A").String(); s != "glob:*.txt:A, mime:image/*:A" {
t.Errorf("unexpected string representation of combined filter: %s", s)
}
}
func TestChooseFilesCombinedFilters(t *testing.T) {
root := t.TempDir()
for _, name := range []string{"a.txt", "b.jpg", "c.png"} {
if err := os.WriteFile(filepath.Join(root, name), []byte("data"), 0o600); err != nil {
t.Fatal(err)
}
}
first := combined_filter(t, "glob:*.txt:First", "glob:*.jpg:First")
second := combined_filter(t, "glob:*.txt:Second", "glob:*.png:Second")
var scan_err error
s := NewFileSystemScorer(root, "", first, false, func(err error, complete bool) {
if err != nil {
scan_err = err
}
})
h := Handler{state: State{
current_dir: root, current_filter: "First", filter_map: map[string]Filter{"First": first, "Second": second},
}}
h.result_manager = &ResultManager{settings: &h.state, scorer: s}
check := func(expected ...string) {
t.Helper()
s.current_worker_wait.Wait()
if scan_err != nil {
t.Fatal(scan_err)
}
results, _ := s.Results()
var actual []string
for _, item := range results.RenderedMatches(CollectionIndex{}, -1) {
actual = append(actual, item.text)
}
slices.Sort(actual)
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("incorrect results for filter %s:\n%s", h.state.current_filter, diff)
}
}
s.Start()
check("a.txt", "b.jpg")
h.set_filter("Second")
check("a.txt", "c.png")
h.set_filter("First")
check("a.txt", "b.jpg")
}
func TestChooseFilesDirectorySymlinks(t *testing.T) {
root := t.TempDir()
if err := os.Mkdir(filepath.Join(root, "real-dir"), 0o700); err != nil {
t.Fatal(err)
}
for _, name := range []string{"file.txt", "real-dir/nested.txt"} {
if err := os.WriteFile(filepath.Join(root, name), []byte("data"), 0o600); err != nil {
t.Fatal(err)
}
}
for name, target := range map[string]string{"linked-dir": "real-dir", "linked-file.txt": "file.txt"} {
if err := os.Symlink(target, filepath.Join(root, name)); err != nil {
t.Fatal(err)
}
}
filter, err := NewFilter("glob:*.txt:Text files")
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
mode Mode
filter Filter
want, selected []string
}{
{"directories", SELECT_SINGLE_DIR, Filter{},
[]string{"linked-dir", "real-dir"}, []string{"linked-dir", "real-dir"}},
{"file filter", SELECT_SINGLE_FILE, *filter,
[]string{"file.txt", "linked-dir", "linked-file.txt", "real-dir", "real-dir/nested.txt"},
[]string{"file.txt", "linked-file.txt", "real-dir/nested.txt"}},
} {
t.Run(tc.name, func(t *testing.T) {
done := make(chan struct{})
var scan_err error
s := NewFileSystemScorer(root, "", tc.filter, tc.mode.OnlyDirs(), func(err error, complete bool) {
if err != nil {
scan_err = err
}
if complete {
close(done)
}
})
s.Start()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("file scan did not finish")
}
if scan_err != nil {
t.Fatal(scan_err)
}
results, _ := s.Results()
state := State{mode: tc.mode}
var actual, selected []string
for _, item := range results.RenderedMatches(CollectionIndex{}, -1) {
actual = append(actual, item.text)
if state.CanSelect(item) {
selected = append(selected, item.text)
}
}
slices.Sort(actual)
slices.Sort(selected)
if diff := cmp.Diff(tc.want, actual); diff != "" {
t.Errorf("wrong choices:\n%s", diff)
}
if diff := cmp.Diff(tc.selected, selected); diff != "" {
t.Errorf("wrong selectable choices:\n%s", diff)
}
})
}
}
func TestIsDirectory(t *testing.T) {
for _, tc := range []struct {
ftype fs.FileMode
expected bool
}{
{0, false},
{0o755, false},
{fs.ModeDir, true},
{fs.ModeSymlink, false},
{fs.ModeSymlink | SymlinkToDir, true},
} {
if actual := is_directory(tc.ftype); actual != tc.expected {
t.Fatalf("is_directory(%s) = %v, expected %v", tc.ftype, actual, tc.expected)
}
}
tdir := t.TempDir()
if err := os.Mkdir(filepath.Join(tdir, "dir"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink("dir", filepath.Join(tdir, "link")); err != nil {
t.Fatal(err)
}
if ftype := resolve_symlink_to_dir(filepath.Join(tdir, "link"), fs.ModeSymlink); !is_symlink_to_dir(ftype) {
t.Fatalf("symlink to directory not resolved: %s", ftype)
}
if ftype := resolve_symlink_to_dir(filepath.Join(tdir, "missing"), fs.ModeSymlink); is_directory(ftype) {
t.Fatalf("dangling symlink resolved as directory: %s", ftype)
}
}
func TestSortedResults(t *testing.T) {
r := NewSortedResults()
idx := CollectionIndex{}
m := func(items ...int) []*ResultItem {
ans := make([]*ResultItem, len(items))
for i, x := range items {
ans[i] = &ResultItem{text: strconv.Itoa(x), score: CombinedScore(x)}
}
return ans
}
v := func(slice, pos, num int) []int {
if num == 0 {
num = r.Len()
}
return utils.Map(func(r *ResultItem) int { return int(r.score) }, r.RenderedMatches(CollectionIndex{slice, pos}, num))
}
tv := func(slice, pos, num int, expected ...int) {
if diff := cmp.Diff(expected, v(slice, pos, num)); diff != "" {
t.Fatalf("view failed for %v num:%d\n%s", CollectionIndex{slice, pos}, num, diff)
}
}
tci := func(increment int, expected int) {
orig := idx
idx = r.IncrementIndexWithWrapAround(idx, increment)
actual := int(r.At(idx).score)
if actual != expected {
t.Fatalf("increment: %d on %v failed\nexpected: %d actual: %d idx: %v", increment, orig, expected, actual, idx)
}
}
dt := func(a, b CollectionIndex, expected int) {
actual := r.distance(a, b)
if expected != actual {
t.Fatalf("distance on %v and %v failed\nexpected: %d actual: %d ", a, b, expected, actual)
}
if r.distance(b, a) != actual {
t.Fatalf("distance on %v and %v not commutative %d != %d", a, b, actual, r.distance(b, a))
}
}
tc := func(num_before, expected_new_before int, ci CollectionIndex, expected ...[]int) {
ac, new_num_before, _ := r.SplitIntoColumns(func(int) int { return 2 }, 2, num_before, ci)
actual := make([][]int, len(ac))
for i, x := range ac {
actual[i] = utils.Map(func(r *ResultItem) int { return int(r.score) }, x)
}
if expected_new_before != new_num_before {
t.Fatalf("new_num_before not as expected for num_before: %d ci: %v\n%d != %d", num_before, ci, expected_new_before, new_num_before)
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("wrong columns for num_before: %d ci: %v\n%s", num_before, ci, diff)
}
}
r.AddSortedSlice(m(10, 20, 30))
r.AddSortedSlice(m(40, 50, 60))
r.AddSortedSlice(m(70, 80, 90))
tc(0, 0, CollectionIndex{}, []int{10, 20}, []int{30, 40})
tc(1, 1, CollectionIndex{Pos: 1}, []int{10, 20}, []int{30, 40})
tc(1, 1, CollectionIndex{Pos: 2}, []int{20, 30}, []int{40, 50})
tc(2, 2, CollectionIndex{Pos: 2}, []int{10, 20}, []int{30, 40})
tc(20, 2, CollectionIndex{Pos: 2}, []int{10, 20}, []int{30, 40})
for num_before := range 4 {
tc(num_before, 3, CollectionIndex{2, 2}, []int{60, 70}, []int{80, 90})
}
tc(1, 1, CollectionIndex{1, 1}, []int{40, 50}, []int{60, 70})
dt(CollectionIndex{Pos: 0}, CollectionIndex{Pos: 2}, 2)
dt(CollectionIndex{Pos: 0}, CollectionIndex{Slice: 1}, 3)
dt(CollectionIndex{Pos: 0}, CollectionIndex{Slice: 1, Pos: 1}, 4)
tv(0, 0, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90)
tv(0, 2, 3, 30, 40, 50)
tv(0, 3, 3, 40, 50, 60)
tv(1, 0, 4, 40, 50, 60, 70)
tci(1, 20)
tci(3, 50)
tci(-1, 40)
tci(-3, 10)
tci(-2, 80)
tci(3, 20)
tci(9, 20)
tci(-9, 20)
r.AddSortedSlice(m(100, 110, 120))
r.AddSortedSlice(m(41, 61, 71, 99))
tv(0, 0, 0, 10, 20, 30, 40, 41, 50, 60, 61, 70, 71, 80, 90, 99, 100, 110, 120)
r.AddSortedSlice(m(1, 2, 3))
tv(0, 0, 0, 1, 2, 3, 10, 20, 30, 40, 41, 50, 60, 61, 70, 71, 80, 90, 99, 100, 110, 120)
r.AddSortedSlice(m(1000, 2000))
tv(0, 0, 0, 1, 2, 3, 10, 20, 30, 40, 41, 50, 60, 61, 70, 71, 80, 90, 99, 100, 110, 120, 1000, 2000)
}
func run_scoring(b *testing.B, depth, breadth int, query string) {
root := node{name: string(os.PathSeparator)}
root.generate_random_tree(depth, breadth)
for b.Loop() {
b.StopTimer()
wg := sync.WaitGroup{}
wg.Add(1)
s := NewFileSystemScorer(string(os.PathSeparator), query, Filter{}, false, func(err error, is_complete bool) {
if is_complete {
wg.Done()
}
})
s.dir_reader = root.ReadDir
s.global_gitignore = ignorefiles.NewGitignore()
b.StartTimer()
s.scanner.Start()
s.Start()
wg.Wait()
}
fmt.Println("\nnumber of iterations: ", b.N)
fmt.Println("time per iteration:", b.Elapsed()/time.Duration(b.N))
}
// To run this benchmark with profiling use:
// go test -bench=FileNameScoringWithoutQuery -benchmem -cpuprofile=/tmp/cpu.prof -memprofile=/tmp/mem.prof github.com/kovidgoyal/kitty/kittens/choose_files -o /tmp/cfexe
func BenchmarkFileNameScoringWithoutQuery(b *testing.B) {
run_scoring(b, 5, 20, "")
}
// To run this benchmark with profiling use:
// go test -bench=FileNameScoringWithQuery -benchmem -cpuprofile=/tmp/cpu.prof -memprofile=/tmp/mem.prof github.com/kovidgoyal/kitty/kittens/choose_files -o /tmp/cfexe
func BenchmarkFileNameScoringWithQuery(b *testing.B) {
run_scoring(b, 5, 20, "abc")
}
+239
View File
@@ -0,0 +1,239 @@
package choose_files
import (
"fmt"
"strconv"
"strings"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/tui/readline"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
// Actions that, when matched by a keyboard shortcut, are forwarded to the
// readline instance powering the search/filter text box instead of being
// dispatched as a normal choose_files action. This lets users who prefer
// editing text with the arrow keys, Home, End, etc. rebind those keys away
// from their default job of navigating the list of matches, towards editing
// the search text instead. See the kitten's documentation for details.
var edit_actions = map[string]readline.Action{
"edit_cursor_left": readline.ActionCursorLeft,
"edit_cursor_right": readline.ActionCursorRight,
"edit_start_of_line": readline.ActionMoveToStartOfLine,
"edit_end_of_line": readline.ActionMoveToEndOfLine,
"edit_start_of_document": readline.ActionMoveToStartOfDocument,
"edit_end_of_document": readline.ActionMoveToEndOfDocument,
"edit_forward_word": readline.ActionMoveToEndOfWord,
"edit_backward_word": readline.ActionMoveToStartOfWord,
"edit_backspace": readline.ActionBackspace,
"edit_delete": readline.ActionDelete,
"edit_kill_to_start_of_line": readline.ActionKillToStartOfLine,
"edit_kill_to_end_of_line": readline.ActionKillToEndOfLine,
"edit_kill_word_left": readline.ActionKillPreviousWord,
"edit_kill_word_right": readline.ActionKillNextWord,
"edit_yank": readline.ActionYank,
}
func (h *Handler) draw_frame(width, height int, in_progress bool) {
lp := h.lp
prefix, suffix := "", ""
if in_progress {
x := h.lp.SprintStyled("fg=cyan", " ")
prefix, suffix, _ = strings.Cut(x, " ")
lp.QueueWriteString(prefix)
}
for i := range height {
lp.SaveCursorPosition()
switch i {
case 0:
lp.QueueWriteString("╭")
lp.QueueWriteString(strings.Repeat("─", width-2))
lp.QueueWriteString("╮")
case height - 1:
lp.QueueWriteString("╰")
lp.QueueWriteString(strings.Repeat("─", width-2))
lp.QueueWriteString("╯")
default:
lp.QueueWriteString("│")
lp.MoveCursorHorizontally(width - 2)
lp.QueueWriteString("│")
}
lp.RestoreCursorPosition()
lp.MoveCursorVertically(1)
}
if suffix != "" {
lp.QueueWriteString(suffix)
}
}
func (h *Handler) draw_search_text(available_width int) {
available_width /= 2
if available_width > 0 {
available_width-- // reserve a cell for the space appended after the text, which hosts the cursor at end of line
}
all_graphemes := wcswidth.SplitIntoGraphemes(h.state.SearchText())
n := len(all_graphemes)
widths := make([]int, n)
total_width := 0
for i, g := range all_graphemes {
widths[i] = wcswidth.Stringwidth(g)
total_width += widths[i]
}
width_between := func(s, e int) (w int) {
for _, x := range widths[s:e] {
w += x
}
return
}
cursor_pos := min(n, len(wcswidth.SplitIntoGraphemes(h.search_rl.TextBeforeCursor())))
start, end := 0, n
left_ellipsis, right_ellipsis := false, false
if total_width > available_width && available_width > 0 {
// Grow a window around the cursor, one grapheme at a time on
// alternating sides, without exceeding the available display width.
start, end = cursor_pos, cursor_pos
budget := available_width
for {
grew := false
if start > 0 && widths[start-1] <= budget {
budget -= widths[start-1]
start--
grew = true
}
if end < n && widths[end] <= budget {
budget -= widths[end]
end++
grew = true
}
if !grew {
break
}
}
left_ellipsis = start > 0
right_ellipsis = end < n
ellipsis_width := wcswidth.Stringwidth("…")
reserved := 0
if left_ellipsis {
reserved += ellipsis_width
}
if right_ellipsis {
reserved += ellipsis_width
}
// Make room for the ellipsis marks by shrinking the window on the
// side farther from the cursor first, without ever removing the
// grapheme the cursor is on.
for start < end && width_between(start, end)+reserved > available_width {
if end > cursor_pos && (end-cursor_pos >= cursor_pos-start || start >= cursor_pos) {
end--
} else if start < cursor_pos {
start++
} else {
break
}
}
}
visible := make([]string, 0, end-start+2)
if left_ellipsis {
visible = append(visible, "…")
}
visible = append(visible, all_graphemes[start:end]...)
if right_ellipsis {
visible = append(visible, "…")
}
visible_width_before_cursor := width_between(start, min(cursor_pos, end))
if left_ellipsis {
visible_width_before_cursor += wcswidth.Stringwidth("…")
}
visible_width_total := width_between(start, end)
if left_ellipsis {
visible_width_total += wcswidth.Stringwidth("…")
}
if right_ellipsis {
visible_width_total += wcswidth.Stringwidth("…")
}
h.lp.DrawSizedText(strings.Join(visible, "")+" ", loop.SizedText{Scale: 2})
h.lp.MoveCursorHorizontally(-2 * (visible_width_total - visible_width_before_cursor + 1))
}
const SEARCH_BAR_HEIGHT = 4
func (h *Handler) draw_controls(y int) (max_width int) {
type entry struct {
text string
callback func()
width int
}
lines := make([]entry, 0, SEARCH_BAR_HEIGHT)
add_control := func(icon, text string, callback func()) {
line := icon + " " + text
width := wcswidth.Stringwidth(line)
max_width = max(max_width, width)
lines = append(lines, entry{line, callback, width})
}
add_control(utils.IfElse(h.state.ShowHidden(), " ", " "), utils.IfElse(h.state.ShowHidden(), "hide dotfiles", "show dotfiles"), func() {
h.state.show_hidden = !h.state.show_hidden
h.result_manager.set_show_hidden()
})
add_control("󰑑 ", utils.IfElse(h.state.RespectIgnores(), "show ignored", "hide ignored"), func() {
h.state.respect_ignores = !h.state.respect_ignores
h.result_manager.set_respect_ignores()
})
add_control(" ", utils.IfElse(h.state.ShowPreview(), "hide preview", "show preview"), func() {
h.state.show_preview = !h.state.show_preview
})
add_control(utils.IfElse(h.state.SortByLastModified(), " ", " "), utils.IfElse(h.state.SortByLastModified(), "sort names", "sort dates"), func() {
h.state.sort_by_last_modified = !h.state.sort_by_last_modified
h.result_manager.set_sort_by_last_modified()
})
x := h.screen_size.width - max_width
for i, e := range lines {
h.lp.MoveCursorTo(x+1, y+i+1)
h.lp.QueueWriteString(e.text)
cb := e.callback
h.state.mouse_state.AddCellRegion("rcontrol-"+strconv.Itoa(i), x, y+i, x+e.width, y+i, func(_ string) error {
cb()
h.state.redraw_needed = true
return nil
}).HoverStyle = HOVER_STYLE
}
return max_width + 1
}
func (h *Handler) draw_search_bar(y int) {
left_margin, right_margin := 0, h.draw_controls(y)
h.lp.MoveCursorTo(1+left_margin, 1+y)
available_width := h.screen_size.width - left_margin - right_margin
h.draw_frame(available_width, SEARCH_BAR_HEIGHT, false)
for y1 := y; y1 < y+4; y1++ {
cr := h.state.mouse_state.AddCellRegion("search-bar", left_margin, y1, left_margin+available_width, y1)
cr.PointerShape = loop.TEXT_POINTER
cr.HoverStyle = "none"
}
h.lp.MoveCursorTo(1+left_margin+1, 2+y)
h.draw_search_text(available_width - 2)
}
// perform_edit_action runs a readline editing action against the search text
// box and syncs the resulting text back into the query used to filter results.
func (h *Handler) perform_edit_action(ac readline.Action) (err error) {
if err = h.search_rl.PerformAction(ac, 1); err == nil {
h.set_query(h.search_rl.AllText())
}
return
}
// forward_key_event_to_search_rl is used for keys that are not claimed by any
// configured keyboard shortcut, so that ordinary readline editing (backspace,
// delete, ctrl+k, ctrl+w, etc.) works in the search box without needing
// explicit configuration.
func (h *Handler) forward_key_event_to_search_rl(ev *loop.KeyEvent) (err error) {
if err = h.search_rl.OnKeyEvent(ev); err == nil {
h.set_query(h.search_rl.AllText())
}
return
}