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:
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,461 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ask
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"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"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Choice struct {
|
||||
text string
|
||||
idx int
|
||||
color, letter string
|
||||
}
|
||||
|
||||
func (self Choice) prefix() string {
|
||||
return string([]rune(self.text)[:self.idx])
|
||||
}
|
||||
|
||||
func (self Choice) display_letter() string {
|
||||
return string([]rune(self.text)[self.idx])
|
||||
}
|
||||
|
||||
func (self Choice) suffix() string {
|
||||
return string([]rune(self.text)[self.idx+1:])
|
||||
}
|
||||
|
||||
type Range struct {
|
||||
start, end, y int
|
||||
}
|
||||
|
||||
func (self *Range) has_point(x, y int) bool {
|
||||
return y == self.y && self.start <= x && x <= self.end
|
||||
}
|
||||
|
||||
func truncate_at_space(text string, width int) (string, string) {
|
||||
truncated, p := wcswidth.TruncateToVisualLengthWithWidth(text, width)
|
||||
if len(truncated) == len(text) {
|
||||
return text, ""
|
||||
}
|
||||
i := strings.LastIndexByte(truncated, ' ')
|
||||
if i > 0 && p-i < 12 {
|
||||
p = i + 1
|
||||
}
|
||||
return text[:p], text[p:]
|
||||
}
|
||||
|
||||
func extra_for(width, screen_width int) int {
|
||||
return max(0, screen_width-width)/2 + 1
|
||||
}
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func GetChoices(o *Options) (response string, err error) {
|
||||
response = ""
|
||||
lp, err := loop.New()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
|
||||
|
||||
prefix_style_pat := regexp.MustCompile("^(?:\x1b\\[[^m]*?m)+")
|
||||
choice_order := make([]Choice, 0, len(o.Choices))
|
||||
clickable_ranges := make(map[string][]Range, 16)
|
||||
allowed := utils.NewSet[string](max(2, len(o.Choices)))
|
||||
response_on_accept := o.Default
|
||||
switch o.Type {
|
||||
case "yesno":
|
||||
allowed.AddItems("y", "n")
|
||||
if !allowed.Has(response_on_accept) {
|
||||
response_on_accept = "y"
|
||||
}
|
||||
case "choices":
|
||||
first_choice := ""
|
||||
for i, x := range o.Choices {
|
||||
letter, text, _ := strings.Cut(x, ":")
|
||||
color := ""
|
||||
if strings.Contains(letter, ";") {
|
||||
letter, color, _ = strings.Cut(letter, ";")
|
||||
}
|
||||
letter = strings.ToLower(letter)
|
||||
idx := strings.Index(strings.ToLower(text), letter)
|
||||
if idx < 0 {
|
||||
return "", fmt.Errorf("The choice letter %#v is not present in the choice text: %#v", letter, text)
|
||||
}
|
||||
idx = len([]rune(strings.ToLower(text)[:idx]))
|
||||
allowed.Add(letter)
|
||||
c := Choice{text: text, idx: idx, color: color, letter: letter}
|
||||
choice_order = append(choice_order, c)
|
||||
if i == 0 {
|
||||
first_choice = letter
|
||||
}
|
||||
}
|
||||
if !allowed.Has(response_on_accept) {
|
||||
response_on_accept = first_choice
|
||||
}
|
||||
}
|
||||
message := o.Message
|
||||
hidden_text_start_pos := -1
|
||||
hidden_text_end_pos := -1
|
||||
hidden_text := ""
|
||||
m := markup.New(true)
|
||||
replacement_text := fmt.Sprintf("Press %s or click to show", m.Green(o.UnhideKey))
|
||||
replacement_range := Range{-1, -1, -1}
|
||||
if message != "" && o.HiddenTextPlaceholder != "" {
|
||||
hidden_text_start_pos = strings.Index(message, o.HiddenTextPlaceholder)
|
||||
if hidden_text_start_pos > -1 {
|
||||
raw, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Failed to read hidden text from STDIN: %w", err)
|
||||
}
|
||||
hidden_text = strings.TrimRightFunc(utils.UnsafeBytesToString(raw), unicode.IsSpace)
|
||||
hidden_text_end_pos = hidden_text_start_pos + len(replacement_text)
|
||||
suffix := message[hidden_text_start_pos+len(o.HiddenTextPlaceholder):]
|
||||
message = message[:hidden_text_start_pos] + replacement_text + suffix
|
||||
}
|
||||
}
|
||||
|
||||
draw_long_text := func(screen_width int, text string, msg_lines []string) []string {
|
||||
if screen_width < 3 {
|
||||
return msg_lines
|
||||
}
|
||||
if text == "" {
|
||||
msg_lines = append(msg_lines, "")
|
||||
} else {
|
||||
width := screen_width - 2
|
||||
prefix := prefix_style_pat.FindString(text)
|
||||
for text != "" {
|
||||
var t string
|
||||
t, text = truncate_at_space(text, width)
|
||||
t = strings.TrimSpace(t)
|
||||
msg_lines = append(msg_lines, strings.Repeat(" ", extra_for(wcswidth.Stringwidth(t), width))+m.Bold(prefix+t))
|
||||
}
|
||||
}
|
||||
return msg_lines
|
||||
}
|
||||
|
||||
ctx := style.Context{AllowEscapeCodes: true}
|
||||
|
||||
draw_choice_boxes := func(y, screen_width, _ int, choices ...Choice) {
|
||||
clickable_ranges = map[string][]Range{}
|
||||
width := screen_width - 2
|
||||
current_line_length := 0
|
||||
type Item struct{ letter, text string }
|
||||
type Line = []Item
|
||||
var current_line Line
|
||||
lines := make([]Line, 0, 32)
|
||||
sep := " "
|
||||
sep_sz := len(sep) + 2 // for the borders
|
||||
|
||||
for _, choice := range choices {
|
||||
clickable_ranges[choice.letter] = make([]Range, 0, 4)
|
||||
text := " " + choice.prefix()
|
||||
color := choice.color
|
||||
if choice.color == "" {
|
||||
color = "green"
|
||||
}
|
||||
text += ctx.SprintFunc("fg=" + color)(choice.display_letter())
|
||||
text += choice.suffix() + " "
|
||||
sz := wcswidth.Stringwidth(text)
|
||||
if sz+sep_sz+current_line_length > width {
|
||||
lines = append(lines, current_line)
|
||||
current_line = nil
|
||||
current_line_length = 0
|
||||
}
|
||||
current_line = append(current_line, Item{choice.letter, text})
|
||||
current_line_length += sz + sep_sz
|
||||
}
|
||||
if len(current_line) > 0 {
|
||||
lines = append(lines, current_line)
|
||||
}
|
||||
|
||||
highlight := func(text string) string {
|
||||
return m.Yellow(text)
|
||||
}
|
||||
|
||||
top := func(text string, highlight_frame bool) (ans string) {
|
||||
ans = "╭" + strings.Repeat("─", wcswidth.Stringwidth(text)) + "╮"
|
||||
if highlight_frame {
|
||||
ans = highlight(ans)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
middle := func(text string, highlight_frame bool) (ans string) {
|
||||
f := "│"
|
||||
if highlight_frame {
|
||||
f = highlight(f)
|
||||
}
|
||||
return f + text + f
|
||||
}
|
||||
|
||||
bottom := func(text string, highlight_frame bool) (ans string) {
|
||||
ans = "╰" + strings.Repeat("─", wcswidth.Stringwidth(text)) + "╯"
|
||||
if highlight_frame {
|
||||
ans = highlight(ans)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
print_line := func(add_borders func(string, bool) string, is_last bool, items ...Item) {
|
||||
type Position struct {
|
||||
letter string
|
||||
x, size int
|
||||
}
|
||||
texts := make([]string, 0, 8)
|
||||
positions := make([]Position, 0, 8)
|
||||
x := 0
|
||||
for _, item := range items {
|
||||
text := item.text
|
||||
positions = append(positions, Position{item.letter, x, wcswidth.Stringwidth(text) + 2})
|
||||
text = add_borders(text, item.letter == response_on_accept)
|
||||
text += sep
|
||||
x += wcswidth.Stringwidth(text)
|
||||
texts = append(texts, text)
|
||||
}
|
||||
line := strings.TrimRightFunc(strings.Join(texts, ""), unicode.IsSpace)
|
||||
offset := extra_for(wcswidth.Stringwidth(line), width)
|
||||
for _, pos := range positions {
|
||||
x = pos.x
|
||||
x += offset
|
||||
clickable_ranges[pos.letter] = append(clickable_ranges[pos.letter], Range{x, x + pos.size - 1, y})
|
||||
}
|
||||
end := "\r\n"
|
||||
if is_last {
|
||||
end = ""
|
||||
}
|
||||
lp.QueueWriteString(strings.Repeat(" ", offset) + line + end)
|
||||
y++
|
||||
}
|
||||
lp.AllowLineWrapping(false)
|
||||
defer func() { lp.AllowLineWrapping(true) }()
|
||||
for i, boxed_line := range lines {
|
||||
print_line(top, false, boxed_line...)
|
||||
print_line(middle, false, boxed_line...)
|
||||
is_last := i == len(lines)-1
|
||||
print_line(bottom, is_last, boxed_line...)
|
||||
}
|
||||
}
|
||||
|
||||
draw_yesno := func(y, screen_width, screen_height int) {
|
||||
yes := m.Green("Y") + "es"
|
||||
no := m.BrightRed("N") + "o"
|
||||
if y+3 <= screen_height {
|
||||
draw_choice_boxes(y, screen_width, screen_height, Choice{"Yes", 0, "green", "y"}, Choice{"No", 0, "red", "n"})
|
||||
} else {
|
||||
sep := strings.Repeat(" ", 3)
|
||||
text := yes + sep + no
|
||||
w := wcswidth.Stringwidth(text)
|
||||
x := extra_for(w, screen_width-2)
|
||||
nx := x + wcswidth.Stringwidth(yes) + len(sep)
|
||||
clickable_ranges = map[string][]Range{
|
||||
"y": {{x, x + wcswidth.Stringwidth(yes) - 1, y}},
|
||||
"n": {{nx, nx + wcswidth.Stringwidth(no) - 1, y}},
|
||||
}
|
||||
lp.QueueWriteString(strings.Repeat(" ", x) + text)
|
||||
}
|
||||
}
|
||||
|
||||
draw_choice := func(y, screen_width, screen_height int) {
|
||||
if y+3 <= screen_height {
|
||||
draw_choice_boxes(y, screen_width, screen_height, choice_order...)
|
||||
return
|
||||
}
|
||||
clickable_ranges = map[string][]Range{}
|
||||
current_line := ""
|
||||
current_ranges := map[string]int{}
|
||||
width := screen_width - 2
|
||||
|
||||
commit_line := func(add_newline bool) {
|
||||
x := extra_for(wcswidth.Stringwidth(current_line), width)
|
||||
text := strings.Repeat(" ", x) + current_line
|
||||
if add_newline {
|
||||
lp.Println(text)
|
||||
} else {
|
||||
lp.QueueWriteString(text)
|
||||
}
|
||||
for letter, sz := range current_ranges {
|
||||
clickable_ranges[letter] = []Range{{x, x + sz - 3, y}}
|
||||
x += sz
|
||||
}
|
||||
current_ranges = map[string]int{}
|
||||
y++
|
||||
current_line = ""
|
||||
}
|
||||
for _, choice := range choice_order {
|
||||
text := choice.prefix()
|
||||
spec := ""
|
||||
if choice.color != "" {
|
||||
spec = "fg=" + choice.color
|
||||
} else {
|
||||
spec = "fg=green"
|
||||
}
|
||||
if choice.letter == response_on_accept {
|
||||
spec += " u=straight"
|
||||
}
|
||||
text += ctx.SprintFunc(spec)(choice.display_letter())
|
||||
text += choice.suffix()
|
||||
text += " "
|
||||
sz := wcswidth.Stringwidth(text)
|
||||
if sz+wcswidth.Stringwidth(current_line) >= width {
|
||||
commit_line(true)
|
||||
}
|
||||
current_line += text
|
||||
current_ranges[choice.letter] = sz
|
||||
}
|
||||
if current_line != "" {
|
||||
commit_line(false)
|
||||
}
|
||||
}
|
||||
|
||||
draw_screen := func() error {
|
||||
lp.StartAtomicUpdate()
|
||||
defer lp.EndAtomicUpdate()
|
||||
lp.ClearScreen()
|
||||
msg_lines := make([]string, 0, 8)
|
||||
sz, err := lp.ScreenSize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if message != "" {
|
||||
scanner := utils.NewLineScanner(message)
|
||||
for scanner.Scan() {
|
||||
msg_lines = draw_long_text(int(sz.WidthCells), scanner.Text(), msg_lines)
|
||||
}
|
||||
}
|
||||
y := int(sz.HeightCells) - len(msg_lines)
|
||||
y = max(0, (y/2)-2)
|
||||
lp.QueueWriteString(strings.Repeat("\r\n", y))
|
||||
for _, line := range msg_lines {
|
||||
if replacement_text != "" {
|
||||
before, _, ok := strings.Cut(line, replacement_text)
|
||||
if ok {
|
||||
x := wcswidth.Stringwidth(before)
|
||||
replacement_range = Range{x, x + wcswidth.Stringwidth(replacement_text), y}
|
||||
}
|
||||
}
|
||||
lp.Println(line)
|
||||
y++
|
||||
}
|
||||
if sz.HeightCells > 2 {
|
||||
lp.Println()
|
||||
y++
|
||||
}
|
||||
switch o.Type {
|
||||
case "yesno":
|
||||
draw_yesno(y, int(sz.WidthCells), int(sz.HeightCells))
|
||||
case "choices":
|
||||
draw_choice(y, int(sz.WidthCells), int(sz.HeightCells))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
unhide := func() {
|
||||
if hidden_text != "" && message != "" {
|
||||
message = message[:hidden_text_start_pos] + hidden_text + message[hidden_text_end_pos:]
|
||||
hidden_text = ""
|
||||
_ = draw_screen()
|
||||
}
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
if o.Title != "" {
|
||||
lp.SetWindowTitle(o.Title)
|
||||
}
|
||||
return "", draw_screen()
|
||||
}
|
||||
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
return ""
|
||||
}
|
||||
|
||||
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error {
|
||||
text = strings.ToLower(text)
|
||||
if allowed.Has(text) {
|
||||
response = text
|
||||
lp.Quit(0)
|
||||
} else if hidden_text != "" && text == o.UnhideKey {
|
||||
unhide()
|
||||
} else if o.Type == "yesno" {
|
||||
lp.Quit(1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnKeyEvent = func(ev *loop.KeyEvent) error {
|
||||
if ev.MatchesPressOrRepeat("esc") || ev.MatchesPressOrRepeat("ctrl+c") {
|
||||
ev.Handled = true
|
||||
lp.Quit(1)
|
||||
} else if ev.MatchesPressOrRepeat("enter") || ev.MatchesPressOrRepeat("kp_enter") {
|
||||
ev.Handled = true
|
||||
response = response_on_accept
|
||||
lp.Quit(0)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnMouseEvent = func(ev *loop.MouseEvent) error {
|
||||
on_letter := ""
|
||||
for letter, ranges := range clickable_ranges {
|
||||
for _, r := range ranges {
|
||||
if r.has_point(ev.Cell.X, ev.Cell.Y) {
|
||||
on_letter = letter
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if on_letter != "" {
|
||||
if s, has_shape := lp.CurrentPointerShape(); !has_shape && s != loop.POINTER_POINTER {
|
||||
lp.PushPointerShape(loop.POINTER_POINTER)
|
||||
}
|
||||
} else {
|
||||
if _, has_shape := lp.CurrentPointerShape(); has_shape {
|
||||
lp.PopPointerShape()
|
||||
}
|
||||
}
|
||||
|
||||
if ev.Event_type == loop.MOUSE_CLICK {
|
||||
if on_letter != "" {
|
||||
response = on_letter
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
if hidden_text != "" && replacement_range.has_point(ev.Cell.X, ev.Cell.Y) {
|
||||
unhide()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnResize = func(old, news loop.ScreenSize) error {
|
||||
return draw_screen()
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return "", fmt.Errorf("Filled by signal: %s", ds)
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ask
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/kittens/choose_files"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/readline"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func get_line(o *Options, complete_file_names bool) (result string, err error) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cwd, _ := os.Getwd()
|
||||
ropts := readline.RlInit{Prompt: o.Prompt}
|
||||
if complete_file_names {
|
||||
ropts.Completer = choose_files.FilePromptCompleter(nil)
|
||||
}
|
||||
if o.Name != "" {
|
||||
base := filepath.Join(utils.CacheDir(), "ask")
|
||||
ropts.HistoryPath = filepath.Join(base, o.Name+".history.json")
|
||||
os.MkdirAll(base, 0o755)
|
||||
}
|
||||
rl := readline.New(lp, ropts)
|
||||
if o.Default != "" {
|
||||
rl.SetText(o.Default)
|
||||
}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
rl.Start()
|
||||
return "", nil
|
||||
}
|
||||
lp.OnFinalize = func() string { rl.End(); return "" }
|
||||
|
||||
lp.OnResumeFromStop = func() error {
|
||||
rl.Start()
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnResize = rl.OnResize
|
||||
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
return fmt.Errorf("Canceled by user")
|
||||
}
|
||||
err := rl.OnKeyEvent(event)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
if err == readline.ErrAcceptInput {
|
||||
hi := readline.HistoryItem{Timestamp: time.Now(), Cmd: rl.AllText(), ExitCode: 0, Cwd: cwd}
|
||||
rl.AddHistoryItem(hi)
|
||||
result = rl.AllText()
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if event.Handled {
|
||||
rl.Redraw()
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error {
|
||||
err := rl.OnText(text, from_key_event, in_bracketed_paste)
|
||||
if err == nil {
|
||||
rl.Redraw()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
rl.Shutdown()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
return "", fmt.Errorf("Killed by signal: %s", ds)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package ask
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Response struct {
|
||||
Items []string `json:"items"`
|
||||
Response string `json:"response"`
|
||||
}
|
||||
|
||||
func show_message(msg, title string) {
|
||||
if title != "" {
|
||||
fmt.Printf("%s", loop.EscapeCodeToSetWindowTitle(title))
|
||||
}
|
||||
if msg != "" {
|
||||
m := markup.New(true)
|
||||
fmt.Println(m.Bold(msg))
|
||||
}
|
||||
}
|
||||
|
||||
func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
output := tui.KittenOutputSerializer()
|
||||
result := &Response{Items: args}
|
||||
if len(o.Prompt) > 2 && o.Prompt[0] == o.Prompt[len(o.Prompt)-1] && (o.Prompt[0] == '"' || o.Prompt[0] == '\'') {
|
||||
o.Prompt = o.Prompt[1 : len(o.Prompt)-1]
|
||||
}
|
||||
switch o.Type {
|
||||
case "yesno", "choices":
|
||||
result.Response, err = GetChoices(o)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
case "password":
|
||||
show_message(o.Message, o.Title)
|
||||
pw, err := tui.ReadPassword(o.Prompt, false)
|
||||
if err != nil {
|
||||
if errors.Is(err, tui.Canceled) {
|
||||
pw = ""
|
||||
} else {
|
||||
return 1, err
|
||||
}
|
||||
}
|
||||
result.Response = pw
|
||||
case "line":
|
||||
show_message(o.Message, o.Title)
|
||||
result.Response, err = get_line(o, false)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
case "file":
|
||||
show_message(o.Message, o.Title)
|
||||
result.Response, err = get_line(o, true)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
default:
|
||||
return 1, fmt.Errorf("Unknown type: %s", o.Type)
|
||||
}
|
||||
s, err := output(result)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
_, err = fmt.Println(s)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
|
||||
from kitty.typing_compat import BossType, TypedDict
|
||||
|
||||
from ..tui.handler import result_handler
|
||||
|
||||
|
||||
def option_text() -> str:
|
||||
return """\
|
||||
--type -t
|
||||
choices=line,yesno,choices,password,file
|
||||
default=line
|
||||
Type of input. Defaults to asking for a line of text.
|
||||
|
||||
|
||||
--message -m
|
||||
The message to display to the user. If not specified a default
|
||||
message is shown.
|
||||
|
||||
|
||||
--name -n
|
||||
The name for this question. Used to store history of previous answers which can
|
||||
be used for completions and via the browse history readline bindings.
|
||||
|
||||
|
||||
--title --window-title
|
||||
The title for the window in which the question is displayed. Only implemented
|
||||
for yesno and choices types.
|
||||
|
||||
|
||||
--choice -c
|
||||
type=list
|
||||
dest=choices
|
||||
A choice for the choices type. Can be specified multiple times. Every choice has
|
||||
the syntax: ``letter[;color]:text``, where :italic:`text` is the choice
|
||||
text and :italic:`letter` is the selection key. :italic:`letter` is a single letter
|
||||
belonging to :italic:`text`. This letter is highlighted within the choice text.
|
||||
There can be an optional color specification after the letter
|
||||
to indicate what color it should be.
|
||||
For example: :code:`y:Yes` and :code:`n;red:No`
|
||||
|
||||
|
||||
--default -d
|
||||
A default choice or text. If unspecified, it is :code:`y` for the type
|
||||
:code:`yesno`, the first choice for :code:`choices` and empty for others types.
|
||||
The default choice is selected when the user presses the :kbd:`Enter` key.
|
||||
|
||||
|
||||
--prompt -p
|
||||
default="> "
|
||||
The prompt to use when inputting a line of text or a password.
|
||||
|
||||
|
||||
--unhide-key
|
||||
default=u
|
||||
The key to be pressed to unhide hidden text
|
||||
|
||||
|
||||
--hidden-text-placeholder
|
||||
The text in the message to be replaced by hidden text. The hidden text is read via STDIN.
|
||||
"""
|
||||
|
||||
|
||||
class Response(TypedDict):
|
||||
items: list[str]
|
||||
response: str | None
|
||||
|
||||
|
||||
def main(args: list[str]) -> Response:
|
||||
raise SystemExit('This must be run as kitten ask')
|
||||
|
||||
|
||||
@result_handler()
|
||||
def handle_result(args: list[str], data: Response, target_window_id: int, boss: BossType) -> None:
|
||||
if data['response'] is not None:
|
||||
func, *args = data['items']
|
||||
getattr(boss, func)(data['response'], *args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
elif __name__ == '__doc__':
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = ''
|
||||
cd['options'] = option_text
|
||||
cd['help_text'] = 'Ask the user for input'
|
||||
cd['short_desc'] = 'Ask the user for input'
|
||||
Whitespace-only changes.
@@ -0,0 +1,80 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package broadcast
|
||||
|
||||
import "github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
|
||||
// Minimal line editor: covers the subset of kittens/tui/line_edit.py that
|
||||
// the broadcast kitten actually uses (insert, backspace, arrows, home/end).
|
||||
type line_edit struct {
|
||||
text []rune
|
||||
cursor int
|
||||
}
|
||||
|
||||
func (l *line_edit) String() string { return string(l.text) }
|
||||
|
||||
func (l *line_edit) on_text(t string) {
|
||||
r := []rune(t)
|
||||
l.text = append(l.text[:l.cursor], append(r, l.text[l.cursor:]...)...)
|
||||
l.cursor += len(r)
|
||||
}
|
||||
|
||||
func (l *line_edit) backspace() bool {
|
||||
if l.cursor == 0 {
|
||||
return false
|
||||
}
|
||||
l.text = append(l.text[:l.cursor-1], l.text[l.cursor:]...)
|
||||
l.cursor--
|
||||
return true
|
||||
}
|
||||
|
||||
func (l *line_edit) left() {
|
||||
if l.cursor > 0 {
|
||||
l.cursor--
|
||||
}
|
||||
}
|
||||
func (l *line_edit) right() {
|
||||
if l.cursor < len(l.text) {
|
||||
l.cursor++
|
||||
}
|
||||
}
|
||||
func (l *line_edit) home() { l.cursor = 0 }
|
||||
func (l *line_edit) end() { l.cursor = len(l.text) }
|
||||
func (l *line_edit) clear() {
|
||||
l.text = l.text[:0]
|
||||
l.cursor = 0
|
||||
}
|
||||
|
||||
// on_key returns true if the key was consumed as an editing action.
|
||||
func (l *line_edit) on_key(e *loop.KeyEvent) bool {
|
||||
switch {
|
||||
case e.MatchesPressOrRepeat("backspace"):
|
||||
e.Handled = true
|
||||
return l.backspace()
|
||||
case e.MatchesPressOrRepeat("left"):
|
||||
e.Handled = true
|
||||
l.left()
|
||||
return true
|
||||
case e.MatchesPressOrRepeat("right"):
|
||||
e.Handled = true
|
||||
l.right()
|
||||
return true
|
||||
case e.MatchesPressOrRepeat("home"), e.MatchesPressOrRepeat("ctrl+a"):
|
||||
e.Handled = true
|
||||
l.home()
|
||||
return true
|
||||
case e.MatchesPressOrRepeat("end"), e.MatchesPressOrRepeat("ctrl+e"):
|
||||
e.Handled = true
|
||||
l.end()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// write draws the current line and positions the cursor.
|
||||
func (l *line_edit) write(lp *loop.Loop) {
|
||||
lp.QueueWriteString(string(l.text))
|
||||
if diff := len(l.text) - l.cursor; diff > 0 {
|
||||
lp.MoveCursorHorizontally(-diff)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package broadcast
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestLineEdit(t *testing.T) {
|
||||
le := line_edit{}
|
||||
le.on_text("hello")
|
||||
if le.String() != "hello" || le.cursor != 5 {
|
||||
t.Fatalf("insert failed: %q cursor=%d", le.String(), le.cursor)
|
||||
}
|
||||
le.backspace()
|
||||
if le.String() != "hell" {
|
||||
t.Fatalf("backspace failed: %q", le.String())
|
||||
}
|
||||
le.left()
|
||||
le.left()
|
||||
le.on_text("X")
|
||||
if le.String() != "heXll" || le.cursor != 3 {
|
||||
t.Fatalf("mid-insert failed: %q cursor=%d", le.String(), le.cursor)
|
||||
}
|
||||
le.home()
|
||||
if le.cursor != 0 {
|
||||
t.Fatal("home failed")
|
||||
}
|
||||
le.end()
|
||||
if le.cursor != 5 {
|
||||
t.Fatal("end failed")
|
||||
}
|
||||
le.clear()
|
||||
if le.String() != "" || le.cursor != 0 {
|
||||
t.Fatal("clear failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package broadcast
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"os"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
type handler struct {
|
||||
lp *loop.Loop
|
||||
opts *Options
|
||||
ctx *markup.Context
|
||||
payload broadcast_payload
|
||||
initial_strings []string
|
||||
hide_input bool
|
||||
session_started bool
|
||||
line_edit line_edit
|
||||
}
|
||||
|
||||
func b64text(text string) string {
|
||||
return "base64:" + base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(text))
|
||||
}
|
||||
|
||||
func (h *handler) broadcast_data(data string) error {
|
||||
p := h.payload
|
||||
p.Data = data
|
||||
ec, err := send_text_escape_code(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.lp.QueueWriteString(ec)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *handler) broadcast_text(text string) error { return h.broadcast_data(b64text(text)) }
|
||||
|
||||
func (h *handler) commit_line() {
|
||||
h.lp.RestoreCursorPosition()
|
||||
h.lp.SaveCursorPosition()
|
||||
h.lp.ClearToEndOfScreen()
|
||||
h.line_edit.write(h.lp)
|
||||
}
|
||||
|
||||
func (h *handler) end_line() {
|
||||
h.lp.Println()
|
||||
h.line_edit.clear()
|
||||
h.lp.SaveCursorPosition()
|
||||
}
|
||||
|
||||
func (h *handler) initialize() (string, error) {
|
||||
h.session_started = true
|
||||
ec, err := session_escape_code(h.payload, true)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
h.lp.QueueWriteString(ec)
|
||||
h.lp.Println("Type the text to broadcast below, press", h.ctx.Yellow(h.opts.EndSession), "to quit:")
|
||||
for _, x := range h.initial_strings {
|
||||
if err := h.broadcast_text(x); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
h.lp.SaveCursorPosition()
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (h *handler) on_text(text string) error {
|
||||
if err := h.broadcast_text(text); err != nil {
|
||||
return err
|
||||
}
|
||||
if !h.hide_input {
|
||||
h.line_edit.on_text(text)
|
||||
}
|
||||
h.commit_line()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *handler) on_key(e *loop.KeyEvent) error {
|
||||
if e.MatchesPressOrRepeat(h.opts.HideInputToggle) {
|
||||
e.Handled = true
|
||||
h.hide_input = !h.hide_input
|
||||
h.lp.SetCursorVisible(!h.hide_input)
|
||||
if h.hide_input {
|
||||
h.end_line()
|
||||
h.lp.Println("Input hidden, press", h.ctx.Yellow(h.opts.HideInputToggle), "to unhide:")
|
||||
h.end_line()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if e.MatchesPressOrRepeat(h.opts.EndSession) {
|
||||
e.Handled = true
|
||||
h.lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
if e.MatchesPressOrRepeat("ctrl+c") {
|
||||
e.Handled = true
|
||||
if err := h.broadcast_text("\x03"); err != nil {
|
||||
return err
|
||||
}
|
||||
h.line_edit.clear()
|
||||
h.commit_line()
|
||||
return nil
|
||||
}
|
||||
if e.MatchesPressOrRepeat("ctrl+d") {
|
||||
e.Handled = true
|
||||
return h.broadcast_text("\x04")
|
||||
}
|
||||
if !h.hide_input && h.line_edit.on_key(e) {
|
||||
h.commit_line()
|
||||
}
|
||||
if e.MatchesPressOrRepeat("enter") {
|
||||
e.Handled = true
|
||||
if err := h.broadcast_text("\r"); err != nil {
|
||||
return err
|
||||
}
|
||||
h.end_line()
|
||||
return nil
|
||||
}
|
||||
if e.Text == "" { // non-text key: forward in kitty-key encoding
|
||||
e.Handled = true
|
||||
return h.broadcast_data("kitty-key:" + base64.StdEncoding.EncodeToString([]byte(e.AsCSI())))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func run_loop(opts *Options, args []string) (rc int, err error) {
|
||||
lp, err := loop.New(loop.FullKeyboardProtocol, loop.NoAlternateScreen)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
h := &handler{lp: lp, opts: opts, ctx: markup.New(true), initial_strings: args}
|
||||
h.payload = broadcast_payload{
|
||||
ExcludeActive: true, Match: opts.Match, MatchTab: opts.MatchTab, SessionId: new_session_id(),
|
||||
}
|
||||
if opts.Match == "" && opts.MatchTab == "" {
|
||||
h.payload.All = true
|
||||
}
|
||||
lp.OnInitialize = h.initialize
|
||||
lp.OnResize = func(old, new loop.ScreenSize) error { h.commit_line(); return nil }
|
||||
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error { return h.on_text(text) }
|
||||
lp.OnKeyEvent = h.on_key
|
||||
err = lp.Run()
|
||||
if h.session_started {
|
||||
if ec, err2 := session_escape_code(h.payload, false); err2 == nil {
|
||||
os.Stdout.WriteString(ec)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
lp.KillIfSignalled()
|
||||
return lp.ExitCode(), nil
|
||||
}
|
||||
|
||||
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
return run_loop(opts, args)
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
|
||||
from kitty.rc.base import MATCH_TAB_OPTION, MATCH_WINDOW_OPTION
|
||||
|
||||
OPTIONS = (
|
||||
"""
|
||||
--hide-input-toggle
|
||||
default=Ctrl+Alt+Esc
|
||||
Key to press that will toggle hiding of the input in the broadcast window itself.
|
||||
Useful while typing a password, prevents the password from being visible on the screen.
|
||||
|
||||
|
||||
--end-session
|
||||
default=Ctrl+Esc
|
||||
Key to press to end the broadcast session.
|
||||
|
||||
|
||||
"""
|
||||
+ MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
|
||||
).format
|
||||
help_text = 'Broadcast typed text to kitty windows. By default text is sent to all windows, unless one of the matching options is specified'
|
||||
usage = '[initial text to send ...]'
|
||||
|
||||
|
||||
def main(args: list[str]) -> None:
|
||||
raise SystemExit('This should be run as kitten broadcast')
|
||||
|
||||
|
||||
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'] = 'Broadcast typed text to kitty windows'
|
||||
@@ -0,0 +1,45 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package broadcast
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/at"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
type broadcast_payload struct {
|
||||
ExcludeActive bool `json:"exclude_active"`
|
||||
Data string `json:"data"`
|
||||
Match string `json:"match,omitempty"`
|
||||
MatchTab string `json:"match_tab,omitempty"`
|
||||
SessionId string `json:"session_id"`
|
||||
All bool `json:"all,omitempty"`
|
||||
}
|
||||
|
||||
func send_text_escape_code(p broadcast_payload) (string, error) {
|
||||
rc := utils.RemoteControlCmd{Cmd: "send-text", Version: at.ProtocolVersion, NoResponse: true, Payload: p}
|
||||
data, err := json.Marshal(rc)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "\x1bP@kitty-cmd" + string(data) + "\x1b\\", nil
|
||||
}
|
||||
|
||||
func session_escape_code(p broadcast_payload, start bool) (string, error) {
|
||||
if start {
|
||||
p.Data = "session:start"
|
||||
} else {
|
||||
p.Data = "session:end"
|
||||
}
|
||||
return send_text_escape_code(p)
|
||||
}
|
||||
|
||||
func new_session_id() string {
|
||||
b := make([]byte, 16)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package broadcast
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func decode(t *testing.T, ec string) map[string]any {
|
||||
t.Helper()
|
||||
if !strings.HasPrefix(ec, "\x1bP@kitty-cmd") || !strings.HasSuffix(ec, "\x1b\\") {
|
||||
t.Fatalf("bad framing: %q", ec)
|
||||
}
|
||||
body := strings.TrimSuffix(strings.TrimPrefix(ec, "\x1bP@kitty-cmd"), "\x1b\\")
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestSendTextEscapeCode(t *testing.T) {
|
||||
p := broadcast_payload{ExcludeActive: true, Data: "base64:aGk=", SessionId: "abc", All: true}
|
||||
ec, err := send_text_escape_code(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := decode(t, ec)
|
||||
if m["cmd"] != "send-text" || m["no_response"] != true {
|
||||
t.Fatalf("bad cmd: %v", m)
|
||||
}
|
||||
payload := m["payload"].(map[string]any)
|
||||
if payload["data"] != "base64:aGk=" || payload["exclude_active"] != true || payload["all"] != true || payload["session_id"] != "abc" {
|
||||
t.Fatalf("bad payload: %v", payload)
|
||||
}
|
||||
if _, has := payload["match"]; has {
|
||||
t.Fatal("empty match should be omitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionEscapeCode(t *testing.T) {
|
||||
p := broadcast_payload{SessionId: "abc"}
|
||||
ec, err := session_escape_code(p, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := decode(t, ec)["payload"].(map[string]any)
|
||||
if payload["data"] != "session:end" {
|
||||
t.Fatalf("bad session data: %v", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSessionId(t *testing.T) {
|
||||
a, b := new_session_id(), new_session_id()
|
||||
if a == b || len(a) != 32 {
|
||||
t.Fatalf("bad session ids: %q %q", a, b)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,168 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type kitty_font_backend_type struct {
|
||||
from io.ReadCloser
|
||||
to io.WriteCloser
|
||||
json_decoder *json.Decoder
|
||||
cmd *exec.Cmd
|
||||
stderr strings.Builder
|
||||
lock sync.Mutex
|
||||
r io.ReadCloser
|
||||
w io.WriteCloser
|
||||
wait_for_exit chan error
|
||||
started, exited, failed bool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func (k *kitty_font_backend_type) start() (err error) {
|
||||
exe := utils.KittyExe()
|
||||
if exe == "" {
|
||||
exe = utils.Which("kitty")
|
||||
}
|
||||
if exe == "" {
|
||||
return fmt.Errorf("Failed to find the kitty executable, this kitten requires the kitty executable to be present. You can use the environment variable KITTY_PATH_TO_KITTY_EXE to specify the path to the kitty executable")
|
||||
}
|
||||
|
||||
k.cmd = exec.Command(exe, "+runpy", "from kittens.choose_fonts.backend import main; main()")
|
||||
k.cmd.Stderr = &k.stderr
|
||||
|
||||
if k.r, k.to, err = os.Pipe(); err != nil {
|
||||
return err
|
||||
}
|
||||
k.cmd.Stdin = k.r
|
||||
if k.from, k.w, err = os.Pipe(); err != nil {
|
||||
return err
|
||||
}
|
||||
k.cmd.Stdout = k.w
|
||||
k.json_decoder = json.NewDecoder(k.from)
|
||||
if err = k.cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
k.started = true
|
||||
k.timeout = 60 * time.Second
|
||||
k.wait_for_exit = make(chan error)
|
||||
go func() {
|
||||
k.wait_for_exit <- k.cmd.Wait()
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
var kitty_font_backend kitty_font_backend_type
|
||||
|
||||
func (k *kitty_font_backend_type) send(v any) error {
|
||||
if k.to == nil {
|
||||
return fmt.Errorf("Trying to send data when to pipe is nil")
|
||||
}
|
||||
data, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not encode message to kitty with error: %w", err)
|
||||
}
|
||||
c := make(chan error)
|
||||
go func() {
|
||||
if _, err = k.to.Write(data); err != nil {
|
||||
c <- fmt.Errorf("Failed to send message to kitty with I/O error: %w", err)
|
||||
return
|
||||
}
|
||||
if _, err = k.to.Write([]byte{'\n'}); err != nil {
|
||||
c <- fmt.Errorf("Failed to send message to kitty with I/O error: %w", err)
|
||||
return
|
||||
}
|
||||
c <- nil
|
||||
}()
|
||||
select {
|
||||
case err := <-c:
|
||||
return err
|
||||
case <-time.After(k.timeout):
|
||||
return fmt.Errorf("Timed out waiting to write to kitty font backend after %v", k.timeout)
|
||||
case err := <-k.wait_for_exit:
|
||||
k.exited = true
|
||||
if err == nil {
|
||||
err = fmt.Errorf("kitty font backend exited with no error while waiting for a response from it")
|
||||
} else {
|
||||
k.failed = true
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (k *kitty_font_backend_type) query(action string, cmd map[string]any, result any) error {
|
||||
k.lock.Lock()
|
||||
defer k.lock.Unlock()
|
||||
if cmd == nil {
|
||||
cmd = make(map[string]any)
|
||||
}
|
||||
cmd["action"] = action
|
||||
if err := k.send(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
c := make(chan error)
|
||||
go func() {
|
||||
if err := k.json_decoder.Decode(result); err != nil {
|
||||
c <- fmt.Errorf("Failed to decode JSON from kitty with error: %w", err)
|
||||
}
|
||||
c <- nil
|
||||
}()
|
||||
select {
|
||||
case err := <-c:
|
||||
return err
|
||||
case <-time.After(k.timeout):
|
||||
return fmt.Errorf("Timed out waiting for response from kitty font backend after %v", k.timeout)
|
||||
case err := <-k.wait_for_exit:
|
||||
k.exited = true
|
||||
if err == nil {
|
||||
err = fmt.Errorf("kitty font backed exited with no error while waiting for a response from it")
|
||||
} else {
|
||||
k.failed = true
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (k *kitty_font_backend_type) release() (err error) {
|
||||
if k.r != nil {
|
||||
k.r.Close()
|
||||
k.r = nil
|
||||
}
|
||||
if k.to != nil {
|
||||
k.to.Close()
|
||||
k.to = nil
|
||||
}
|
||||
if k.w != nil {
|
||||
k.w.Close()
|
||||
k.w = nil
|
||||
}
|
||||
if k.from != nil {
|
||||
k.from.Close()
|
||||
k.from = nil
|
||||
}
|
||||
if k.started && !k.exited {
|
||||
timeout := 2 * time.Second
|
||||
select {
|
||||
case err = <-k.wait_for_exit:
|
||||
k.exited = true
|
||||
if err != nil {
|
||||
k.failed = true
|
||||
}
|
||||
case <-time.After(timeout):
|
||||
k.failed = true
|
||||
err = fmt.Errorf("Timed out waiting for kitty font backend to exit for %v", timeout)
|
||||
}
|
||||
}
|
||||
os.Stderr.WriteString(k.stderr.String())
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import json
|
||||
import os
|
||||
import string
|
||||
import sys
|
||||
import tempfile
|
||||
from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict
|
||||
|
||||
from kitty.cli import create_default_opts
|
||||
from kitty.conf.utils import to_color
|
||||
from kitty.constants import kitten_exe
|
||||
from kitty.fonts import Descriptor
|
||||
from kitty.fonts.common import (
|
||||
face_from_descriptor,
|
||||
get_axis_map,
|
||||
get_font_files,
|
||||
get_named_style,
|
||||
get_variable_data_for_descriptor,
|
||||
get_variable_data_for_face,
|
||||
is_variable,
|
||||
spec_for_face,
|
||||
)
|
||||
from kitty.fonts.features import Type, known_features
|
||||
from kitty.fonts.list import create_family_groups
|
||||
from kitty.fonts.render import display_bitmap
|
||||
from kitty.options.types import Options
|
||||
from kitty.options.utils import parse_font_spec
|
||||
from kitty.typing_compat import NotRequired
|
||||
from kitty.utils import screen_size_function
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.fast_data_types import FeatureData
|
||||
|
||||
|
||||
def setup_debug_print() -> bool:
|
||||
if 'KITTY_STDIO_FORWARDED' in os.environ:
|
||||
try:
|
||||
fd = int(os.environ['KITTY_STDIO_FORWARDED'])
|
||||
except Exception:
|
||||
return False
|
||||
try:
|
||||
sys.stdout = open(fd, 'w', closefd=False)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def send_to_kitten(x: Any) -> None:
|
||||
f = sys.__stdout__
|
||||
assert f is not None
|
||||
try:
|
||||
f.buffer.write(json.dumps(x).encode())
|
||||
f.buffer.write(b'\n')
|
||||
f.buffer.flush()
|
||||
except BrokenPipeError:
|
||||
raise SystemExit('Pipe to kitten was broken while sending data to it')
|
||||
|
||||
|
||||
class TextStyle(TypedDict):
|
||||
font_size: float
|
||||
dpi_x: float
|
||||
dpi_y: float
|
||||
foreground: str
|
||||
background: str
|
||||
|
||||
|
||||
OptNames = Literal['font_family', 'bold_font', 'italic_font', 'bold_italic_font']
|
||||
FamilyKey = tuple[OptNames, ...]
|
||||
|
||||
|
||||
def opts_from_cmd(cmd: dict[str, Any]) -> tuple[Options, FamilyKey, float, float]:
|
||||
opts = Options()
|
||||
ts: TextStyle = cmd['text_style']
|
||||
opts.font_size = ts['font_size']
|
||||
opts.foreground = to_color(ts['foreground'])
|
||||
opts.background = to_color(ts['background'])
|
||||
family_key = []
|
||||
|
||||
def d(k: OptNames) -> None:
|
||||
if k in cmd:
|
||||
setattr(opts, k, parse_font_spec(cmd[k]))
|
||||
family_key.append(k)
|
||||
|
||||
d('font_family')
|
||||
d('bold_font')
|
||||
d('italic_font')
|
||||
d('bold_italic_font')
|
||||
return opts, tuple(family_key), ts['dpi_x'], ts['dpi_y']
|
||||
|
||||
|
||||
BaseKey = tuple[str, int, int]
|
||||
FaceKey = tuple[str, BaseKey]
|
||||
RenderedSample = tuple[bytes, dict[str, Any]]
|
||||
RenderedSampleTransmit = dict[str, Any]
|
||||
SAMPLE_TEXT = string.ascii_lowercase + ' ' + string.digits + ' ' + string.ascii_uppercase + ' ' + string.punctuation
|
||||
|
||||
|
||||
class FD(TypedDict):
|
||||
is_index: bool
|
||||
name: NotRequired[str]
|
||||
tooltip: NotRequired[str]
|
||||
sample: NotRequired[str]
|
||||
params: NotRequired[tuple[str, ...]]
|
||||
|
||||
|
||||
def get_features(features: dict[str, Optional['FeatureData']]) -> dict[str, FD]:
|
||||
ans = {}
|
||||
for tag, data in features.items():
|
||||
kf = known_features.get(tag)
|
||||
if kf is None or kf.type is Type.hidden:
|
||||
continue
|
||||
fd: FD = {'is_index': kf.type is Type.index}
|
||||
ans[tag] = fd
|
||||
if data is not None:
|
||||
if n := data.get('name'):
|
||||
fd['name'] = n
|
||||
if n := data.get('tooltip'):
|
||||
fd['tooltip'] = n
|
||||
if n := data.get('sample'):
|
||||
fd['sample'] = n
|
||||
if p := data.get('params'):
|
||||
fd['params'] = p
|
||||
return ans
|
||||
|
||||
|
||||
def render_face_sample(font: Descriptor, opts: Options, dpi_x: float, dpi_y: float, width: int, height: int, sample_text: str = '') -> RenderedSample:
|
||||
face = face_from_descriptor(font, opts.font_size, dpi_x, dpi_y)
|
||||
face.set_size(opts.font_size, dpi_x, dpi_y)
|
||||
metadata = {
|
||||
'variable_data': get_variable_data_for_face(face),
|
||||
'style': font['style'],
|
||||
'psname': face.postscript_name(),
|
||||
'features': get_features(face.get_features()),
|
||||
'applied_features': face.applied_features(),
|
||||
'spec': spec_for_face(font['family'], face).as_setting,
|
||||
'cell_width': 0,
|
||||
'cell_height': 0,
|
||||
'canvas_height': 0,
|
||||
'canvas_width': width,
|
||||
}
|
||||
if is_variable(font):
|
||||
ns = get_named_style(face)
|
||||
if ns:
|
||||
metadata['variable_named_style'] = ns
|
||||
metadata['variable_axis_map'] = get_axis_map(face)
|
||||
bitmap, cell_width, cell_height = face.render_sample_text(sample_text or SAMPLE_TEXT, width, height, opts.foreground.rgb)
|
||||
metadata['cell_width'] = cell_width
|
||||
metadata['cell_height'] = cell_height
|
||||
metadata['canvas_height'] = len(bitmap) // (4 * width)
|
||||
return bitmap, metadata
|
||||
|
||||
|
||||
def render_family_sample(
|
||||
opts: Options, family_key: FamilyKey, dpi_x: float, dpi_y: float, width: int, height: int, output_dir: str, cache: dict[FaceKey, RenderedSampleTransmit]
|
||||
) -> dict[str, RenderedSampleTransmit]:
|
||||
base_key: BaseKey = opts.font_family.created_from_string, width, height
|
||||
ans: dict[str, RenderedSampleTransmit] = {}
|
||||
font_files = get_font_files(opts)
|
||||
for x in family_key:
|
||||
key: FaceKey = x + ': ' + str(getattr(opts, x)), base_key
|
||||
if x == 'font_family':
|
||||
desc = font_files['medium']
|
||||
elif x == 'bold_font':
|
||||
desc = font_files['bold']
|
||||
elif x == 'italic_font':
|
||||
desc = font_files['italic']
|
||||
elif x == 'bold_italic_font':
|
||||
desc = font_files['bi']
|
||||
cached = cache.get(key)
|
||||
if cached is not None:
|
||||
ans[x] = cached
|
||||
else:
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix='.rgba', dir=output_dir) as tf:
|
||||
bitmap, metadata = render_face_sample(desc, opts, dpi_x, dpi_y, width, height)
|
||||
tf.write(bitmap)
|
||||
metadata['path'] = tf.name
|
||||
cache[key] = ans[x] = metadata
|
||||
return ans
|
||||
|
||||
|
||||
ResolvedFace = dict[Literal['family', 'spec', 'setting'], str]
|
||||
|
||||
|
||||
def spec_for_descriptor(d: Descriptor, font_size: float) -> str:
|
||||
face = face_from_descriptor(d, font_size, 288, 288)
|
||||
return spec_for_face(d['family'], face).as_setting
|
||||
|
||||
|
||||
def resolved_faces(opts: Options) -> dict[OptNames, ResolvedFace]:
|
||||
font_files = get_font_files(opts)
|
||||
ans: dict[OptNames, ResolvedFace] = {}
|
||||
|
||||
def d(key: Literal['medium', 'bold', 'italic', 'bi'], opt_name: OptNames) -> None:
|
||||
descriptor = font_files[key]
|
||||
ans[opt_name] = {
|
||||
'family': descriptor['family'],
|
||||
'spec': spec_for_descriptor(descriptor, opts.font_size),
|
||||
'setting': getattr(opts, opt_name).created_from_string,
|
||||
}
|
||||
|
||||
d('medium', 'font_family')
|
||||
d('bold', 'bold_font')
|
||||
d('italic', 'italic_font')
|
||||
d('bi', 'bold_italic_font')
|
||||
return ans
|
||||
|
||||
|
||||
def main() -> None:
|
||||
setup_debug_print()
|
||||
cache: dict[FaceKey, RenderedSampleTransmit] = {}
|
||||
for line in sys.stdin.buffer:
|
||||
cmd = json.loads(line)
|
||||
action = cmd.get('action', '')
|
||||
if action == 'list_monospaced_fonts':
|
||||
opts = create_default_opts()
|
||||
send_to_kitten({'fonts': create_family_groups(), 'resolved_faces': resolved_faces(opts)})
|
||||
elif action == 'read_variable_data':
|
||||
ans = []
|
||||
for descriptor in cmd['descriptors']:
|
||||
ans.append(get_variable_data_for_descriptor(descriptor))
|
||||
send_to_kitten(ans)
|
||||
elif action == 'render_family_samples':
|
||||
opts, family_key, dpi_x, dpi_y = opts_from_cmd(cmd)
|
||||
send_to_kitten(render_family_sample(opts, family_key, dpi_x, dpi_y, cmd['width'], cmd['height'], cmd['output_dir'], cache))
|
||||
else:
|
||||
raise SystemExit(f'Unknown action: {action}')
|
||||
|
||||
|
||||
def query_kitty() -> dict[str, str]:
|
||||
import subprocess
|
||||
|
||||
ans = {}
|
||||
for line in subprocess.check_output([kitten_exe(), 'query-terminal']).decode().splitlines():
|
||||
k, sep, v = line.partition(':')
|
||||
if sep == ':':
|
||||
ans[k] = v.strip()
|
||||
return ans
|
||||
|
||||
|
||||
def showcase(family: str = 'family="Fira Code"', sample_text: str = '') -> None:
|
||||
q = query_kitty()
|
||||
opts = Options()
|
||||
opts.foreground = to_color(q['foreground'])
|
||||
opts.background = to_color(q['background'])
|
||||
opts.font_size = float(q['font_size'])
|
||||
opts.font_family = parse_font_spec(family)
|
||||
font_files = get_font_files(opts)
|
||||
desc = font_files['medium']
|
||||
ss = screen_size_function()()
|
||||
width = ss.cell_width * ss.cols
|
||||
height = 5 * ss.cell_height
|
||||
bitmap, m = render_face_sample(desc, opts, float(q['dpi_x']), float(q['dpi_y']), width, height, sample_text=sample_text)
|
||||
display_bitmap(bitmap, m['canvas_width'], m['canvas_height'])
|
||||
|
||||
|
||||
def test_render(spec: str = 'family="Fira Code"', width: int = 1560, height: int = 116, font_size: float = 12, dpi: float = 288) -> None:
|
||||
opts = Options()
|
||||
opts.font_family = parse_font_spec(spec)
|
||||
opts.font_size = font_size
|
||||
opts.foreground = to_color('white')
|
||||
desc = get_font_files(opts)['medium']
|
||||
bitmap, m = render_face_sample(desc, opts, float(dpi), float(dpi), width, height)
|
||||
display_bitmap(bitmap, m['canvas_width'], m['canvas_height'])
|
||||
@@ -0,0 +1,489 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type face_panel struct {
|
||||
handler *handler
|
||||
|
||||
family, which string
|
||||
settings faces_settings
|
||||
current_preview *RenderedSampleTransmit
|
||||
current_preview_key faces_preview_key
|
||||
preview_cache map[faces_preview_key]map[string]RenderedSampleTransmit
|
||||
preview_cache_mutex sync.Mutex
|
||||
}
|
||||
|
||||
// Create a new FontSpec that keeps features and axis values and named styles
|
||||
// same as the current setting. Names are all reset apart from style name.
|
||||
func (self *face_panel) new_font_spec() (*FontSpec, error) {
|
||||
fs, err := NewFontSpec(self.get(), self.current_preview.Features)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fs.system.val == "auto" {
|
||||
if fs, err = NewFontSpec(self.current_preview.Spec, self.current_preview.Features); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// reset these selectors as we will be using some style/axis based selector instead
|
||||
fs.family = settable_string{self.family, true}
|
||||
fs.postscript_name = settable_string{}
|
||||
fs.full_name = settable_string{}
|
||||
if len(self.current_preview.Variable_data.Axes) > 0 {
|
||||
fs.variable_name = settable_string{self.current_preview.Variable_data.Variations_postscript_name_prefix, true}
|
||||
} else {
|
||||
fs.variable_name = settable_string{}
|
||||
}
|
||||
return &fs, nil
|
||||
}
|
||||
|
||||
func (self *face_panel) set_variable_spec(named_style string, axis_overrides map[string]float64) error {
|
||||
fs, err := self.new_font_spec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if axis_overrides != nil {
|
||||
axis_values := self.current_preview.current_axis_values()
|
||||
maps.Copy(axis_values, axis_overrides)
|
||||
fs.axes = axis_values
|
||||
fs.style = settable_string{"", false}
|
||||
} else if named_style != "" {
|
||||
fs.style = settable_string{named_style, true}
|
||||
fs.axes = nil
|
||||
}
|
||||
self.set(fs.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *face_panel) set_style(named_style string) error {
|
||||
fs, err := self.new_font_spec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fs.style = settable_string{named_style, true}
|
||||
self.set(fs.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *face_panel) render_lines(start_y int, lines ...string) (y int) {
|
||||
sz, _ := self.handler.lp.ScreenSize()
|
||||
_, y, str := self.handler.render_lines.InRectangle(lines, 0, start_y, int(sz.WidthCells), int(sz.HeightCells)-y, &self.handler.mouse_state, self.on_click)
|
||||
self.handler.lp.QueueWriteString(str)
|
||||
return
|
||||
}
|
||||
|
||||
const current_val_style = "fg=cyan bold"
|
||||
const control_name_style = "fg=yellow bright bold"
|
||||
|
||||
func (self *face_panel) draw_axis(sz loop.ScreenSize, y int, ax VariableAxis, axis_value float64) int {
|
||||
lp := self.handler.lp
|
||||
buf := strings.Builder{}
|
||||
buf.WriteString(fmt.Sprintf("%s: ", lp.SprintStyled(control_name_style, utils.IfElse(ax.Strid != "", ax.Strid, ax.Tag))))
|
||||
num_of_cells := int(sz.WidthCells) - wcswidth.Stringwidth(buf.String())
|
||||
if num_of_cells < 5 {
|
||||
return y
|
||||
}
|
||||
frac := (min(axis_value, ax.Maximum) - ax.Minimum) / (ax.Maximum - ax.Minimum)
|
||||
current_cell := int(math.Floor(frac * float64(num_of_cells-1)))
|
||||
for i := range num_of_cells {
|
||||
buf.WriteString(utils.IfElse(i == current_cell, lp.SprintStyled(current_val_style, `⬤`),
|
||||
tui.InternalHyperlink("•", fmt.Sprintf("axis:%d/%d:%s", i, num_of_cells-1, ax.Tag))))
|
||||
}
|
||||
return self.render_lines(y, buf.String())
|
||||
}
|
||||
|
||||
func is_current_named_style(style_group_name, style_name string, vd VariableData, ns NamedStyle) bool {
|
||||
for _, dax := range vd.Design_axes {
|
||||
if dax.Name == style_group_name {
|
||||
if val, found := ns.Axis_values[dax.Tag]; found {
|
||||
for _, v := range dax.Values {
|
||||
if v.Value == val {
|
||||
return v.Name == style_name
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *face_panel) draw_variable_fine_tune(sz loop.ScreenSize, start_y int, preview RenderedSampleTransmit) (y int, err error) {
|
||||
s := styles_for_variable_data(preview.Variable_data)
|
||||
lines := []string{}
|
||||
lp := self.handler.lp
|
||||
for _, sg := range s.style_groups {
|
||||
if len(sg.styles) < 2 {
|
||||
continue
|
||||
}
|
||||
formatted := make([]string, len(sg.styles))
|
||||
for i, style_name := range sg.styles {
|
||||
if is_current_named_style(sg.name, style_name, preview.Variable_data, preview.Variable_named_style) {
|
||||
formatted[i] = self.handler.lp.SprintStyled(current_val_style, style_name)
|
||||
} else {
|
||||
formatted[i] = tui.InternalHyperlink(style_name, "variable_style:"+style_name)
|
||||
}
|
||||
}
|
||||
line := lp.SprintStyled(control_name_style, sg.name) + ": " + strings.Join(formatted, ", ")
|
||||
lines = append(lines, line)
|
||||
}
|
||||
y = self.render_lines(start_y, lines...)
|
||||
sub_title := "Fine tune the appearance by clicking in the variable axes below:"
|
||||
axis_values := self.current_preview.current_axis_values()
|
||||
for _, ax := range self.current_preview.Variable_data.Axes {
|
||||
if ax.Hidden {
|
||||
continue
|
||||
}
|
||||
if sub_title != "" {
|
||||
y = self.render_lines(y+1, sub_title, "")
|
||||
sub_title = ``
|
||||
}
|
||||
y = self.draw_axis(sz, y, ax, axis_values[ax.Tag])
|
||||
}
|
||||
return y, nil
|
||||
}
|
||||
|
||||
func (self *face_panel) draw_family_style_select(_ loop.ScreenSize, start_y int, preview RenderedSampleTransmit) (y int, err error) {
|
||||
lp := self.handler.lp
|
||||
s := styles_in_family(self.family, self.handler.listing.fonts[self.family])
|
||||
lines := []string{}
|
||||
for _, sg := range s.style_groups {
|
||||
formatted := make([]string, len(sg.styles))
|
||||
for i, style_name := range sg.styles {
|
||||
if style_name == preview.Style {
|
||||
formatted[i] = lp.SprintStyled(current_val_style, style_name)
|
||||
} else {
|
||||
formatted[i] = tui.InternalHyperlink(style_name, "style:"+style_name)
|
||||
}
|
||||
}
|
||||
line := lp.SprintStyled(control_name_style, sg.name) + ": " + strings.Join(formatted, ", ")
|
||||
lines = append(lines, line)
|
||||
}
|
||||
y = self.render_lines(start_y, lines...)
|
||||
return y, nil
|
||||
}
|
||||
|
||||
func (self *face_panel) draw_font_features(_ loop.ScreenSize, start_y int, preview RenderedSampleTransmit) (y int, err error) {
|
||||
lp := self.handler.lp
|
||||
y = start_y
|
||||
if len(preview.Features) == 0 {
|
||||
return
|
||||
}
|
||||
formatted := make([]string, 0, len(preview.Features))
|
||||
sort_keys := make(map[string]string)
|
||||
for feat_tag, data := range preview.Features {
|
||||
var text, sort_key string
|
||||
|
||||
if preview.Applied_features[feat_tag] != "" {
|
||||
text = preview.Applied_features[feat_tag]
|
||||
sort_key = text
|
||||
if sort_key[0] == '-' || sort_key[1] == '+' {
|
||||
sort_key = sort_key[1:]
|
||||
}
|
||||
text = strings.Replace(text, "+", lp.SprintStyled("fg=green", "+"), 1)
|
||||
text = strings.Replace(text, "-", lp.SprintStyled("fg=red", "-"), 1)
|
||||
text = strings.Replace(text, "=", lp.SprintStyled("fg=cyan", "="), 1)
|
||||
if data.Name != "" {
|
||||
text = data.Name + ": " + text
|
||||
sort_key = data.Name
|
||||
}
|
||||
} else {
|
||||
if data.Name != "" {
|
||||
text = data.Name
|
||||
sort_key = data.Name + ": " + text
|
||||
} else {
|
||||
text = feat_tag
|
||||
sort_key = text
|
||||
}
|
||||
text = lp.SprintStyled("dim", text)
|
||||
}
|
||||
f := tui.InternalHyperlink(text, "feature:"+feat_tag)
|
||||
sort_keys[f] = strings.ToLower(sort_key)
|
||||
formatted = append(formatted, f)
|
||||
}
|
||||
utils.StableSortWithKey(formatted, func(a string) string { return sort_keys[a] })
|
||||
line := lp.SprintStyled(control_name_style, `Features`) + ": " + strings.Join(formatted, ", ")
|
||||
y = self.render_lines(start_y, ``, line)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *handler) draw_preview_header(x int) {
|
||||
sz, _ := self.lp.ScreenSize()
|
||||
width := int(sz.WidthCells) - x
|
||||
p := center_string(self.lp.SprintStyled("italic", " preview "), width, "─")
|
||||
self.lp.QueueWriteString(self.lp.SprintStyled("dim", p))
|
||||
}
|
||||
|
||||
func (self *face_panel) render_preview(key faces_preview_key) {
|
||||
var r map[string]RenderedSampleTransmit
|
||||
s := key.settings
|
||||
self.handler.set_worker_error(kitty_font_backend.query("render_family_samples", map[string]any{
|
||||
"text_style": self.handler.text_style, "font_family": s.font_family,
|
||||
"bold_font": s.bold_font, "italic_font": s.italic_font, "bold_italic_font": s.bold_italic_font,
|
||||
"width": key.width, "height": key.height, "output_dir": self.handler.temp_dir,
|
||||
}, &r))
|
||||
self.preview_cache_mutex.Lock()
|
||||
defer self.preview_cache_mutex.Unlock()
|
||||
self.preview_cache[key] = r
|
||||
}
|
||||
|
||||
func (self *face_panel) draw_screen() (err error) {
|
||||
lp := self.handler.lp
|
||||
lp.SetCursorVisible(false)
|
||||
sz, _ := lp.ScreenSize()
|
||||
styled := lp.SprintStyled
|
||||
wt := "Regular"
|
||||
switch self.which {
|
||||
case "bold_font":
|
||||
wt = "Bold"
|
||||
case "italic_font":
|
||||
wt = "Italic"
|
||||
case "bold_italic_font":
|
||||
wt = "Bold-Italic font"
|
||||
}
|
||||
|
||||
lp.QueueWriteString(self.handler.format_title(fmt.Sprintf("%s: %s face", self.family, wt), 0))
|
||||
|
||||
lines := []string{
|
||||
fmt.Sprintf("Press %s to accept any changes or %s to cancel. Click on a style name below to switch to it.", styled("fg=green", "Enter"), styled("fg=red", "Esc")), "",
|
||||
fmt.Sprintf("Current setting: %s", self.get()), "",
|
||||
}
|
||||
y := self.render_lines(2, lines...)
|
||||
|
||||
num_lines_per_font := (int(sz.HeightCells) - y - 1) - 2
|
||||
num_lines := max(1, num_lines_per_font)
|
||||
key := faces_preview_key{settings: self.settings, width: int(sz.WidthCells * sz.CellWidth), height: int(sz.CellHeight) * num_lines}
|
||||
self.current_preview_key = key
|
||||
self.preview_cache_mutex.Lock()
|
||||
defer self.preview_cache_mutex.Unlock()
|
||||
previews, found := self.preview_cache[key]
|
||||
if !found {
|
||||
self.preview_cache[key] = make(map[string]RenderedSampleTransmit)
|
||||
go func() {
|
||||
self.render_preview(key)
|
||||
self.handler.lp.WakeupMainThread()
|
||||
}()
|
||||
return
|
||||
}
|
||||
if len(previews) < 4 {
|
||||
return
|
||||
}
|
||||
preview := previews[self.which]
|
||||
self.current_preview = &preview
|
||||
if len(preview.Variable_data.Axes) > 0 {
|
||||
y, err = self.draw_variable_fine_tune(sz, y, preview)
|
||||
} else {
|
||||
y, err = self.draw_family_style_select(sz, y, preview)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if y, err = self.draw_font_features(sz, y, preview); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
num_lines = int(math.Ceil(float64(preview.Canvas_height) / float64(sz.CellHeight)))
|
||||
if int(sz.HeightCells)-y >= num_lines+2 {
|
||||
y++
|
||||
lp.MoveCursorTo(1, y+1)
|
||||
self.handler.draw_preview_header(0)
|
||||
y++
|
||||
lp.MoveCursorTo(1, y+1)
|
||||
self.handler.graphics_manager.display_image(0, preview.Path, preview.Canvas_width, preview.Canvas_height)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *face_panel) initialize(h *handler) (err error) {
|
||||
self.handler = h
|
||||
self.preview_cache = make(map[faces_preview_key]map[string]RenderedSampleTransmit)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *face_panel) on_wakeup() error {
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
|
||||
func (self *face_panel) get() string {
|
||||
switch self.which {
|
||||
case "font_family":
|
||||
return self.settings.font_family
|
||||
case "bold_font":
|
||||
return self.settings.bold_font
|
||||
case "italic_font":
|
||||
return self.settings.italic_font
|
||||
case "bold_italic_font":
|
||||
return self.settings.bold_italic_font
|
||||
}
|
||||
panic(fmt.Sprintf("Unknown self.which value: %s", self.which))
|
||||
}
|
||||
|
||||
func (self *face_panel) set(setting string) {
|
||||
switch self.which {
|
||||
case "font_family":
|
||||
self.settings.font_family = setting
|
||||
case "bold_font":
|
||||
self.settings.bold_font = setting
|
||||
case "italic_font":
|
||||
self.settings.italic_font = setting
|
||||
case "bold_italic_font":
|
||||
self.settings.bold_italic_font = setting
|
||||
}
|
||||
}
|
||||
|
||||
func (self *face_panel) update_feature_in_setting(pff ParsedFontFeature) error {
|
||||
fs, err := self.new_font_spec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
found := false
|
||||
for _, f := range fs.features {
|
||||
if f.tag == pff.tag {
|
||||
f.val = pff.val
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
fs.features = append(fs.features, &pff)
|
||||
}
|
||||
self.set(fs.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *face_panel) remove_feature_in_setting(tag string) error {
|
||||
fs, err := self.new_font_spec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(fs.features) > 0 {
|
||||
fs.features = slices.DeleteFunc(fs.features, func(x *ParsedFontFeature) bool {
|
||||
return x.tag == tag
|
||||
})
|
||||
}
|
||||
self.set(fs.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *face_panel) change_feature_value(tag string, val uint, remove bool) error {
|
||||
if remove {
|
||||
return self.remove_feature_in_setting(tag)
|
||||
}
|
||||
pff := ParsedFontFeature{tag: tag, val: val}
|
||||
return self.update_feature_in_setting(pff)
|
||||
}
|
||||
|
||||
func (self *face_panel) handle_click_on_feature(feat_tag string) error {
|
||||
d := self.current_preview.Features[feat_tag]
|
||||
if d.Is_index {
|
||||
var current_val uint
|
||||
for q, serialized := range self.current_preview.Applied_features {
|
||||
if q == feat_tag && serialized != "" {
|
||||
if _, num, found := strings.Cut(serialized, "="); found {
|
||||
if v, err := strconv.ParseUint(num, 10, 0); err == nil {
|
||||
current_val = uint(v)
|
||||
}
|
||||
} else {
|
||||
current_val = utils.IfElse(serialized[0] == '-', uint(0), uint(1))
|
||||
}
|
||||
return self.handler.if_pane.on_enter(self.family, self.which, self.settings, feat_tag, d, current_val)
|
||||
}
|
||||
}
|
||||
return self.handler.if_pane.on_enter(self.family, self.which, self.settings, feat_tag, d, current_val)
|
||||
} else {
|
||||
for q, serialized := range self.current_preview.Applied_features {
|
||||
if q == feat_tag && serialized != "" {
|
||||
if serialized[0] == '-' {
|
||||
return self.remove_feature_in_setting(feat_tag)
|
||||
}
|
||||
return self.update_feature_in_setting(ParsedFontFeature{tag: feat_tag, is_bool: true, val: 0})
|
||||
}
|
||||
}
|
||||
return self.update_feature_in_setting(ParsedFontFeature{tag: feat_tag, is_bool: true, val: 1})
|
||||
}
|
||||
}
|
||||
|
||||
func (self *face_panel) on_click(id string) (err error) {
|
||||
scheme, val, _ := strings.Cut(id, ":")
|
||||
switch scheme {
|
||||
case "style":
|
||||
if err = self.set_style(val); err != nil {
|
||||
return err
|
||||
}
|
||||
case "variable_style":
|
||||
if err = self.set_variable_spec(val, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
case "feature":
|
||||
if err = self.handle_click_on_feature(val); err != nil {
|
||||
return err
|
||||
}
|
||||
case "axis":
|
||||
p, tag, _ := strings.Cut(val, ":")
|
||||
num, den, _ := strings.Cut(p, "/")
|
||||
n, _ := strconv.Atoi(num)
|
||||
d, _ := strconv.Atoi(den)
|
||||
frac := float64(n) / float64(d)
|
||||
for _, ax := range self.current_preview.Variable_data.Axes {
|
||||
if ax.Tag == tag {
|
||||
axval := ax.Minimum + (ax.Maximum-ax.Minimum)*frac
|
||||
if err = self.set_variable_spec("", map[string]float64{tag: axval}); err != nil {
|
||||
return err
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
// Render preview synchronously to void flashing
|
||||
key := self.current_preview_key
|
||||
key.settings = self.settings
|
||||
self.preview_cache_mutex.Lock()
|
||||
previews := self.preview_cache[key]
|
||||
self.preview_cache_mutex.Unlock()
|
||||
if len(previews) < 4 {
|
||||
self.render_preview(key)
|
||||
}
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
|
||||
func (self *face_panel) on_key_event(event *loop.KeyEvent) (err error) {
|
||||
if event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
self.handler.current_pane = &self.handler.faces
|
||||
return self.handler.draw_screen()
|
||||
} else if event.MatchesPressOrRepeat("enter") {
|
||||
event.Handled = true
|
||||
self.handler.current_pane = &self.handler.faces
|
||||
self.handler.faces.settings = self.settings
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *face_panel) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (self *face_panel) on_enter(family, which string, settings faces_settings) error {
|
||||
self.family = family
|
||||
self.settings = settings
|
||||
self.which = which
|
||||
self.handler.current_pane = self
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type faces_settings struct {
|
||||
font_family, bold_font, italic_font, bold_italic_font string
|
||||
}
|
||||
|
||||
type faces_preview_key struct {
|
||||
settings faces_settings
|
||||
width, height int
|
||||
}
|
||||
|
||||
type faces struct {
|
||||
handler *handler
|
||||
|
||||
family string
|
||||
settings faces_settings
|
||||
preview_cache map[faces_preview_key]map[string]RenderedSampleTransmit
|
||||
preview_cache_mutex sync.Mutex
|
||||
}
|
||||
|
||||
const highlight_key_style = "fg=magenta bold"
|
||||
|
||||
func (self *faces) draw_screen() (err error) {
|
||||
lp := self.handler.lp
|
||||
lp.SetCursorVisible(false)
|
||||
sz, _ := lp.ScreenSize()
|
||||
styled := lp.SprintStyled
|
||||
lp.QueueWriteString(self.handler.format_title(self.family, 0))
|
||||
lines := []string{
|
||||
fmt.Sprintf("Press %s to select this font, %s to go back to the font list or any of the %s keys below to fine-tune the appearance of the individual font styles.", styled("fg=green", "Enter"), styled("fg=red", "Esc"), styled(highlight_key_style, "highlighted")), "",
|
||||
}
|
||||
_, y, str := self.handler.render_lines.InRectangle(lines, 0, 2, int(sz.WidthCells), int(sz.HeightCells), &self.handler.mouse_state, self.on_click)
|
||||
|
||||
lp.QueueWriteString(str)
|
||||
|
||||
num_lines_per_font := ((int(sz.HeightCells) - y - 1) / 4) - 2
|
||||
num_lines := max(1, num_lines_per_font)
|
||||
key := faces_preview_key{settings: self.settings, width: int(sz.WidthCells * sz.CellWidth), height: int(sz.CellHeight) * num_lines}
|
||||
self.preview_cache_mutex.Lock()
|
||||
defer self.preview_cache_mutex.Unlock()
|
||||
previews, found := self.preview_cache[key]
|
||||
if !found {
|
||||
self.preview_cache[key] = make(map[string]RenderedSampleTransmit)
|
||||
if self.handler.text_style.Foreground == "" || self.handler.text_style.Background == "" {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
var r map[string]RenderedSampleTransmit
|
||||
s := key.settings
|
||||
self.handler.set_worker_error(kitty_font_backend.query("render_family_samples", map[string]any{
|
||||
"text_style": self.handler.text_style, "font_family": s.font_family,
|
||||
"bold_font": s.bold_font, "italic_font": s.italic_font, "bold_italic_font": s.bold_italic_font,
|
||||
"width": key.width, "height": key.height, "output_dir": self.handler.temp_dir,
|
||||
}, &r))
|
||||
self.preview_cache_mutex.Lock()
|
||||
defer self.preview_cache_mutex.Unlock()
|
||||
self.preview_cache[key] = r
|
||||
self.handler.lp.WakeupMainThread()
|
||||
}()
|
||||
return
|
||||
}
|
||||
if len(previews) < 4 {
|
||||
return
|
||||
}
|
||||
|
||||
slot := 0
|
||||
d := func(setting, title string) {
|
||||
r := previews[setting]
|
||||
num_lines := int(math.Ceil(float64(r.Canvas_height) / float64(sz.CellHeight)))
|
||||
if int(sz.HeightCells)-y < num_lines+1 {
|
||||
return
|
||||
}
|
||||
lp.MoveCursorTo(1, y+1)
|
||||
_, y, str = self.handler.render_lines.InRectangle([]string{title + ": " + previews[setting].Psname}, 0, y, int(sz.WidthCells), int(sz.HeightCells), &self.handler.mouse_state, self.on_click)
|
||||
lp.QueueWriteString(str)
|
||||
if y+num_lines < int(sz.HeightCells) {
|
||||
lp.MoveCursorTo(1, y+1)
|
||||
self.handler.graphics_manager.display_image(slot, r.Path, r.Canvas_width, r.Canvas_height)
|
||||
slot++
|
||||
y += num_lines + 1
|
||||
}
|
||||
}
|
||||
d(`font_family`, styled(highlight_key_style, "R")+`egular`)
|
||||
d(`bold_font`, styled(highlight_key_style, "B")+`old`)
|
||||
d(`italic_font`, styled(highlight_key_style, "I")+`talic`)
|
||||
d(`bold_italic_font`, "B"+styled(highlight_key_style, "o")+`ld-Italic`)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (self *faces) initialize(h *handler) (err error) {
|
||||
self.handler = h
|
||||
self.preview_cache = make(map[faces_preview_key]map[string]RenderedSampleTransmit)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *faces) on_wakeup() error {
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
|
||||
func (self *faces) on_click(id string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (self *faces) on_key_event(event *loop.KeyEvent) (err error) {
|
||||
if event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
self.handler.current_pane = &self.handler.listing
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
if event.MatchesPressOrRepeat("enter") {
|
||||
event.Handled = true
|
||||
return self.handler.final_pane.on_enter(self.family, self.settings)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *faces) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
|
||||
if from_key_event {
|
||||
which := ""
|
||||
switch text {
|
||||
case "r", "R":
|
||||
which = "font_family"
|
||||
case "b", "B":
|
||||
which = "bold_font"
|
||||
case "i", "I":
|
||||
which = "italic_font"
|
||||
case "o", "O":
|
||||
which = "bold_italic_font"
|
||||
}
|
||||
if which != "" {
|
||||
return self.handler.face_pane.on_enter(self.family, which, self.settings)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *faces) on_enter(family string) error {
|
||||
if family != "" {
|
||||
self.family = family
|
||||
r := self.handler.listing.resolved_faces_from_kitty_conf
|
||||
d := func(conf ResolvedFace, setting *string, defval string) {
|
||||
s := utils.IfElse(conf.Setting == "auto", "auto", conf.Spec)
|
||||
*setting = utils.IfElse(family == conf.Family, s, defval)
|
||||
}
|
||||
d(r.Font_family, &self.settings.font_family, fmt.Sprintf(`family="%s"`, family))
|
||||
d(r.Bold_font, &self.settings.bold_font, "auto")
|
||||
d(r.Italic_font, &self.settings.italic_font, "auto")
|
||||
d(r.Bold_italic_font, &self.settings.bold_italic_font, "auto")
|
||||
}
|
||||
self.handler.current_pane = self
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/subseq"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type FamilyList struct {
|
||||
families, all_families []string
|
||||
current_search string
|
||||
display_strings []string
|
||||
widths []int
|
||||
max_width, current_idx int
|
||||
}
|
||||
|
||||
func (self *FamilyList) Len() int {
|
||||
return len(self.families)
|
||||
}
|
||||
|
||||
func (self *FamilyList) Select(family string) bool {
|
||||
for idx, q := range self.families {
|
||||
if q == family {
|
||||
self.current_idx = idx
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *FamilyList) Next(delta int, allow_wrapping bool) bool {
|
||||
l := func() int { return self.Len() }
|
||||
if l() == 0 {
|
||||
return false
|
||||
}
|
||||
idx := self.current_idx + delta
|
||||
if !allow_wrapping && (idx < 0 || idx > l()) {
|
||||
return false
|
||||
}
|
||||
for idx < 0 {
|
||||
idx += l()
|
||||
}
|
||||
self.current_idx = idx % l()
|
||||
return true
|
||||
}
|
||||
|
||||
func limit_lengths(text string) string {
|
||||
t, _ := wcswidth.TruncateToVisualLengthWithWidth(text, 31)
|
||||
if len(t) >= len(text) {
|
||||
return text
|
||||
}
|
||||
return t + "…"
|
||||
}
|
||||
|
||||
func match(expression string, items []string) []*subseq.Match {
|
||||
matches := subseq.ScoreItems(expression, items, subseq.Options{Level1: " "})
|
||||
matches = utils.StableSort(matches, func(a, b *subseq.Match) int {
|
||||
if b.Score < a.Score {
|
||||
return -1
|
||||
}
|
||||
if b.Score > a.Score {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
return matches
|
||||
}
|
||||
|
||||
const (
|
||||
MARK_BEFORE = "\033[33m"
|
||||
MARK_AFTER = "\033[39m"
|
||||
)
|
||||
|
||||
func apply_search(families []string, expression string, marks ...string) (matched_families []string, display_strings []string) {
|
||||
mark_before, mark_after := MARK_BEFORE, MARK_AFTER
|
||||
if len(marks) == 2 {
|
||||
mark_before, mark_after = marks[0], marks[1]
|
||||
}
|
||||
results := utils.Filter(match(expression, families), func(x *subseq.Match) bool { return x.Score > 0 })
|
||||
matched_families = make([]string, 0, len(results))
|
||||
display_strings = make([]string, 0, len(results))
|
||||
for _, m := range results {
|
||||
text := m.Text
|
||||
positions := m.Positions
|
||||
for i := len(positions) - 1; i >= 0; i-- {
|
||||
p := positions[i]
|
||||
text = text[:p] + mark_before + text[p:p+1] + mark_after + text[p+1:]
|
||||
}
|
||||
display_strings = append(display_strings, text)
|
||||
matched_families = append(matched_families, m.Text)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func make_family_names_clickable(family string) string {
|
||||
id := wcswidth.StripEscapeCodes(family)
|
||||
return tui.InternalHyperlink(family, "family-chosen:"+id)
|
||||
}
|
||||
|
||||
func (self *FamilyList) UpdateFamilies(families []string) {
|
||||
self.families, self.all_families = families, families
|
||||
if self.current_search != "" {
|
||||
self.families, self.display_strings = apply_search(self.all_families, self.current_search)
|
||||
self.display_strings = utils.Map(limit_lengths, self.display_strings)
|
||||
} else {
|
||||
self.display_strings = utils.Map(limit_lengths, families)
|
||||
}
|
||||
self.display_strings = utils.Map(make_family_names_clickable, self.display_strings)
|
||||
self.widths = utils.Map(wcswidth.Stringwidth, self.display_strings)
|
||||
self.max_width = utils.Max(0, self.widths...)
|
||||
self.current_idx = 0
|
||||
}
|
||||
|
||||
func (self *FamilyList) UpdateSearch(query string) bool {
|
||||
if query == self.current_search || len(self.all_families) == 0 {
|
||||
return false
|
||||
}
|
||||
self.current_search = query
|
||||
self.UpdateFamilies(self.all_families)
|
||||
return true
|
||||
}
|
||||
|
||||
type Line struct {
|
||||
text string
|
||||
width int
|
||||
is_current bool
|
||||
}
|
||||
|
||||
func (self *FamilyList) Lines(num_rows int) []Line {
|
||||
if num_rows < 1 {
|
||||
return nil
|
||||
}
|
||||
ans := make([]Line, 0, len(self.display_strings))
|
||||
before_num := utils.Min(self.current_idx, num_rows-1)
|
||||
start := self.current_idx - before_num
|
||||
for i := start; i < utils.Min(start+num_rows, len(self.display_strings)); i++ {
|
||||
ans = append(ans, Line{self.display_strings[i], self.widths[i], i == self.current_idx})
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *FamilyList) SelectFamily(family string) bool {
|
||||
for i, f := range self.families {
|
||||
if f == family {
|
||||
self.current_idx = i
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *FamilyList) CurrentFamily() string {
|
||||
if self.current_idx >= 0 && self.current_idx < len(self.families) {
|
||||
return self.families[self.current_idx]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type final_pane struct {
|
||||
handler *handler
|
||||
settings faces_settings
|
||||
family string
|
||||
lp *loop.Loop
|
||||
}
|
||||
|
||||
func (self *final_pane) render_lines(start_y int, lines ...string) (y int) {
|
||||
sz, _ := self.handler.lp.ScreenSize()
|
||||
_, y, str := self.handler.render_lines.InRectangle(lines, 0, start_y, int(sz.WidthCells), int(sz.HeightCells)-y, &self.handler.mouse_state, self.on_click)
|
||||
self.handler.lp.QueueWriteString(str)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *final_pane) draw_screen() (err error) {
|
||||
s := self.lp.SprintStyled
|
||||
h := func(x string) string { return s(highlight_key_style, x) }
|
||||
|
||||
self.render_lines(0,
|
||||
fmt.Sprintf("You have chosen the %s family", s(current_val_style, self.family)),
|
||||
"",
|
||||
"What would you like to do?",
|
||||
"",
|
||||
fmt.Sprintf("%s to modify %s and use the new fonts", h("Enter"), s("italic", self.handler.opts.Config_file_name)),
|
||||
"",
|
||||
fmt.Sprintf("%s to abort and return to font selection", h("Esc")),
|
||||
"",
|
||||
fmt.Sprintf("%s to write the new font settings to %s", h("s"), s("italic", `STDOUT`)),
|
||||
"",
|
||||
fmt.Sprintf("%s to quit", h("Ctrl+c")),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *final_pane) initialize(h *handler) (err error) {
|
||||
self.handler = h
|
||||
self.lp = h.lp
|
||||
return
|
||||
}
|
||||
|
||||
func (self *final_pane) on_wakeup() error {
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
|
||||
func (self *final_pane) on_click(id string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (self faces_settings) serialized() string {
|
||||
return strings.Join([]string{
|
||||
"font_family " + self.font_family,
|
||||
"bold_font " + self.bold_font,
|
||||
"italic_font " + self.italic_font,
|
||||
"bold_italic_font " + self.bold_italic_font,
|
||||
}, "\n")
|
||||
}
|
||||
|
||||
func (self *final_pane) on_key_event(event *loop.KeyEvent) (err error) {
|
||||
if event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
self.handler.current_pane = &self.handler.faces
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
if event.MatchesPressOrRepeat("enter") {
|
||||
event.Handled = true
|
||||
patcher := config.Patcher{Write_backup: true}
|
||||
path := ""
|
||||
if filepath.IsAbs(self.handler.opts.Config_file_name) {
|
||||
path = self.handler.opts.Config_file_name
|
||||
} else {
|
||||
path = filepath.Join(utils.ConfigDir(), self.handler.opts.Config_file_name)
|
||||
}
|
||||
updated, err := patcher.Patch(path, "KITTY_FONTS", self.settings.serialized(), "font_family", "bold_font", "italic_font", "bold_italic_font")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if updated {
|
||||
switch self.handler.opts.Reload_in {
|
||||
case "parent":
|
||||
config.ReloadConfigInKitty(true)
|
||||
case "all":
|
||||
config.ReloadConfigInKitty(false)
|
||||
}
|
||||
}
|
||||
self.lp.Quit(0)
|
||||
return nil
|
||||
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *final_pane) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
|
||||
if from_key_event {
|
||||
switch text {
|
||||
case "s", "S":
|
||||
output_on_exit = self.settings.serialized() + "\n"
|
||||
self.lp.Quit(0)
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *final_pane) on_enter(family string, settings faces_settings) error {
|
||||
self.settings = settings
|
||||
self.family = family
|
||||
self.handler.current_pane = self
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/graphics"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type image struct {
|
||||
id, image_number uint32
|
||||
current_file string
|
||||
}
|
||||
|
||||
func (i image) new_graphics_command() *graphics.GraphicsCommand {
|
||||
gc := &graphics.GraphicsCommand{}
|
||||
if i.id > 0 {
|
||||
gc.SetImageId(i.id)
|
||||
} else {
|
||||
gc.SetImageNumber(i.image_number)
|
||||
}
|
||||
return gc
|
||||
}
|
||||
|
||||
type graphics_manager struct {
|
||||
main, bold, italic, bi, extra image
|
||||
lp *loop.Loop
|
||||
images [5]*image
|
||||
}
|
||||
|
||||
func (g *graphics_manager) initialize(lp *loop.Loop) {
|
||||
g.images = [5]*image{&g.main, &g.bold, &g.italic, &g.bi, &g.extra}
|
||||
g.lp = lp
|
||||
payload := []byte("123")
|
||||
buf := strings.Builder{}
|
||||
gc := &graphics.GraphicsCommand{}
|
||||
gc.SetImageNumber(7891230).SetTransmission(graphics.GRT_transmission_direct).SetDataWidth(1).SetDataHeight(1).SetFormat(
|
||||
graphics.GRT_format_rgb).SetDataSize(uint64(len(payload)))
|
||||
d := func() uint32 {
|
||||
im := gc.ImageNumber()
|
||||
im++
|
||||
gc.SetImageNumber(im)
|
||||
_ = gc.WriteWithPayloadTo(&buf, payload)
|
||||
return im
|
||||
|
||||
}
|
||||
for _, img := range g.images {
|
||||
img.image_number = d()
|
||||
}
|
||||
lp.QueueWriteString(buf.String())
|
||||
}
|
||||
|
||||
func (g *graphics_manager) clear_placements() {
|
||||
buf := strings.Builder{}
|
||||
for _, img := range g.images {
|
||||
if img.current_file == "" {
|
||||
continue
|
||||
}
|
||||
gc := img.new_graphics_command()
|
||||
gc.SetAction(graphics.GRT_action_delete)
|
||||
gc.SetDelete(utils.IfElse(img.id > 0, graphics.GRT_delete_by_id, graphics.GRT_delete_by_number))
|
||||
gc.WriteWithPayloadTo(&buf, nil)
|
||||
}
|
||||
g.lp.QueueWriteString(buf.String())
|
||||
}
|
||||
|
||||
func (g *graphics_manager) display_image(slot int, path string, img_width, img_height int) {
|
||||
img := g.images[slot]
|
||||
if img.current_file != path {
|
||||
gc := img.new_graphics_command()
|
||||
gc.SetAction(graphics.GRT_action_transmit).SetDataWidth(uint64(img_width)).SetDataHeight(uint64(img_height)).SetTransmission(graphics.GRT_transmission_file)
|
||||
gc.WriteWithPayloadToLoop(g.lp, []byte(path))
|
||||
img.current_file = path
|
||||
}
|
||||
gc := img.new_graphics_command()
|
||||
gc.SetAction(graphics.GRT_action_display).SetCursorMovement(graphics.GRT_cursor_static)
|
||||
gc.WriteWithPayloadToLoop(g.lp, nil)
|
||||
}
|
||||
|
||||
func (g *graphics_manager) on_response(gc *graphics.GraphicsCommand) (err error) {
|
||||
if gc.ResponseMessage() != "OK" {
|
||||
return fmt.Errorf("Failed to load image with error: %s\n\nNote that the choose-fonts kitten does not work over SSH as it is meant to select a locally available font to use in kitty.", gc.ResponseMessage())
|
||||
}
|
||||
for _, img := range g.images {
|
||||
if img.image_number == gc.ImageNumber() {
|
||||
img.id = gc.ImageId()
|
||||
break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (g *graphics_manager) finalize() {
|
||||
buf := strings.Builder{}
|
||||
for _, img := range g.images {
|
||||
gc := img.new_graphics_command()
|
||||
gc.SetAction(graphics.GRT_action_delete)
|
||||
gc.SetDelete(utils.IfElse(img.id > 0, graphics.GRT_free_by_id, graphics.GRT_free_by_number))
|
||||
gc.WriteWithPayloadTo(&buf, nil)
|
||||
}
|
||||
g.lp.QueueWriteString(buf.String())
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/readline"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type if_panel struct {
|
||||
handler *handler
|
||||
rl *readline.Readline
|
||||
|
||||
family, which, feat_tag string
|
||||
settings faces_settings
|
||||
feature_data FeatureData
|
||||
current_val uint
|
||||
}
|
||||
|
||||
func (self *if_panel) render_lines(start_y int, lines ...string) (y int) {
|
||||
sz, _ := self.handler.lp.ScreenSize()
|
||||
_, y, str := self.handler.render_lines.InRectangle(lines, 0, start_y, int(sz.WidthCells), int(sz.HeightCells)-y, &self.handler.mouse_state, self.on_click)
|
||||
self.handler.lp.QueueWriteString(str)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *if_panel) draw_screen() (err error) {
|
||||
lp := self.handler.lp
|
||||
feat_name := utils.IfElse(self.feature_data.Name == "", self.feat_tag, self.feature_data.Name)
|
||||
lp.QueueWriteString(self.handler.format_title("Edit "+feat_name, 0))
|
||||
lines := []string{
|
||||
fmt.Sprintf("Enter a value for the '%s' feature of the %s font. Values are non-negative integers. Leaving it blank will cause the feature value to be not set, i.e. take its default value.", feat_name, self.family),
|
||||
}
|
||||
if self.feature_data.Tooltip != "" {
|
||||
lines = append(lines, "")
|
||||
lines = append(lines, self.feature_data.Tooltip)
|
||||
}
|
||||
if len(self.feature_data.Params) > 0 {
|
||||
lines = append(lines, "")
|
||||
lines = append(lines, "You can also click on any of the feature names below to choose the corresponding value.")
|
||||
} else {
|
||||
lines = append(lines, "")
|
||||
lines = append(lines, "Consult the documentation for this font to find out what values are valid for this feature.")
|
||||
}
|
||||
lines = append(lines, "")
|
||||
cursor_y := self.render_lines(2, lines...)
|
||||
if len(self.feature_data.Params) > 0 {
|
||||
lp.MoveCursorTo(1, cursor_y+3)
|
||||
num := 1
|
||||
strings.Join(utils.Map(func(x string) string {
|
||||
ans := tui.InternalHyperlink(x, fmt.Sprintf("fval:%d", num))
|
||||
num++
|
||||
return ans
|
||||
}, self.feature_data.Params), ", ")
|
||||
}
|
||||
lp.MoveCursorTo(1, cursor_y+1)
|
||||
lp.ClearToEndOfLine()
|
||||
self.rl.RedrawNonAtomic()
|
||||
lp.SetCursorVisible(true)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *if_panel) initialize(h *handler) (err error) {
|
||||
self.handler = h
|
||||
self.rl = readline.New(h.lp, readline.RlInit{DontMarkPrompts: true, Prompt: "Value: "})
|
||||
return
|
||||
}
|
||||
|
||||
func (self *if_panel) on_wakeup() error {
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
|
||||
func (self *if_panel) on_click(id string) (err error) {
|
||||
scheme, val, _ := strings.Cut(id, ":")
|
||||
if scheme != "fval" {
|
||||
return
|
||||
}
|
||||
v, _ := strconv.ParseUint(val, 10, 0)
|
||||
if err = self.handler.face_pane.change_feature_value(self.feat_tag, uint(v), false); err != nil {
|
||||
return err
|
||||
}
|
||||
self.handler.current_pane = &self.handler.face_pane
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
|
||||
func (self *if_panel) on_key_event(event *loop.KeyEvent) (err error) {
|
||||
if event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
self.handler.current_pane = &self.handler.face_pane
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
if event.MatchesPressOrRepeat("enter") {
|
||||
event.Handled = true
|
||||
text := strings.TrimSpace(self.rl.AllText())
|
||||
remove := false
|
||||
var val uint64
|
||||
if text == "" {
|
||||
remove = true
|
||||
} else {
|
||||
val, err = strconv.ParseUint(text, 10, 0)
|
||||
}
|
||||
if err != nil {
|
||||
self.rl.ResetText()
|
||||
self.handler.lp.Beep()
|
||||
} else {
|
||||
if err = self.handler.face_pane.change_feature_value(self.feat_tag, uint(val), remove); err != nil {
|
||||
return err
|
||||
}
|
||||
self.handler.current_pane = &self.handler.face_pane
|
||||
}
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
if err = self.rl.OnKeyEvent(event); err != nil {
|
||||
if err == readline.ErrAcceptInput {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return self.draw_screen()
|
||||
}
|
||||
|
||||
func (self *if_panel) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
|
||||
if err = self.rl.OnText(text, from_key_event, in_bracketed_paste); err != nil {
|
||||
return err
|
||||
}
|
||||
return self.draw_screen()
|
||||
}
|
||||
|
||||
func (self *if_panel) on_enter(family, which string, settings faces_settings, feat_tag string, fd FeatureData, current_val uint) error {
|
||||
self.family = family
|
||||
self.feat_tag = feat_tag
|
||||
self.settings = settings
|
||||
self.which = which
|
||||
self.handler.current_pane = self
|
||||
self.feature_data = fd
|
||||
self.current_val = current_val
|
||||
self.rl.ResetText()
|
||||
if self.current_val > 0 {
|
||||
self.rl.SetText(strconv.FormatUint(uint64(self.current_val), 10))
|
||||
}
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"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/utils/style"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type preview_cache_key struct {
|
||||
family string
|
||||
width, height int
|
||||
}
|
||||
|
||||
type preview_cache_value struct {
|
||||
path string
|
||||
width, height int
|
||||
}
|
||||
|
||||
type FontList struct {
|
||||
rl *readline.Readline
|
||||
family_list FamilyList
|
||||
fonts map[string][]ListedFont
|
||||
family_list_updated bool
|
||||
resolved_faces_from_kitty_conf ResolvedFaces
|
||||
handler *handler
|
||||
variable_data_requested_for *utils.Set[string]
|
||||
preview_cache map[preview_cache_key]preview_cache_value
|
||||
preview_cache_mutex sync.Mutex
|
||||
}
|
||||
|
||||
func (self *FontList) initialize(h *handler) error {
|
||||
self.handler = h
|
||||
self.preview_cache = make(map[preview_cache_key]preview_cache_value)
|
||||
self.rl = readline.New(h.lp, readline.RlInit{DontMarkPrompts: true, Prompt: "Family: "})
|
||||
self.variable_data_requested_for = utils.NewSet[string](256)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FontList) draw_search_bar() {
|
||||
lp := self.handler.lp
|
||||
lp.SetCursorVisible(true)
|
||||
lp.SetCursorShape(loop.BAR_CURSOR, true)
|
||||
sz, err := lp.ScreenSize()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
lp.MoveCursorTo(1, int(sz.HeightCells))
|
||||
lp.ClearToEndOfLine()
|
||||
self.rl.RedrawNonAtomic()
|
||||
}
|
||||
|
||||
const SEPARATOR = "║"
|
||||
|
||||
func center_string(x string, width int, filler ...string) string {
|
||||
space := " "
|
||||
if len(filler) > 0 {
|
||||
space = filler[0]
|
||||
}
|
||||
l := wcswidth.Stringwidth(x)
|
||||
spaces := int(float64(width-l) / 2)
|
||||
space = strings.Repeat(space, utils.Max(0, spaces))
|
||||
return space + x + space
|
||||
}
|
||||
|
||||
func (self *handler) format_title(title string, start_x int) string {
|
||||
sz, _ := self.lp.ScreenSize()
|
||||
return self.lp.SprintStyled("fg=green bold", center_string(title, int(sz.WidthCells)-start_x))
|
||||
}
|
||||
|
||||
func (self *FontList) draw_family_summary(start_x int, sz loop.ScreenSize) (err error) {
|
||||
lp := self.handler.lp
|
||||
family := self.family_list.CurrentFamily()
|
||||
if family == "" || int(sz.WidthCells) < start_x+2 {
|
||||
return nil
|
||||
}
|
||||
lines := []string{self.handler.format_title(family, start_x), ""}
|
||||
width := int(sz.WidthCells) - start_x - 1
|
||||
add_line := func(x string) {
|
||||
lines = append(lines, style.WrapTextAsLines(x, width, style.WrapOptions{})...)
|
||||
}
|
||||
fonts := self.fonts[family]
|
||||
if len(fonts) == 0 {
|
||||
return fmt.Errorf("The family: %s has no fonts", family)
|
||||
}
|
||||
if has_variable_data_for_font(fonts[0]) {
|
||||
s := styles_in_family(family, fonts)
|
||||
for _, sg := range s.style_groups {
|
||||
styles := lp.SprintStyled(control_name_style, sg.name) + ": " + strings.Join(sg.styles, ", ")
|
||||
add_line(styles)
|
||||
add_line("")
|
||||
}
|
||||
if s.has_variable_faces {
|
||||
add_line(fmt.Sprintf("This font is %s allowing for finer style control", lp.SprintStyled("fg=magenta", "variable")))
|
||||
}
|
||||
add_line(fmt.Sprintf("Press the %s key to choose this family", lp.SprintStyled("fg=yellow", "Enter")))
|
||||
} else {
|
||||
lines = append(lines, "Reading font data, please wait…")
|
||||
key := fonts[0].cache_key()
|
||||
if !self.variable_data_requested_for.Has(key) {
|
||||
self.variable_data_requested_for.Add(key)
|
||||
go func() {
|
||||
self.handler.set_worker_error(ensure_variable_data_for_fonts(fonts...))
|
||||
lp.WakeupMainThread()
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
y := 0
|
||||
for _, line := range lines {
|
||||
if y >= int(sz.HeightCells)-1 {
|
||||
break
|
||||
}
|
||||
lp.MoveCursorTo(start_x+1, y+1)
|
||||
lp.QueueWriteString(line)
|
||||
y++
|
||||
}
|
||||
if self.handler.text_style.Foreground != "" && self.handler.text_style.Background != "" {
|
||||
return self.draw_preview(start_x, y, sz)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *FontList) draw_preview(x, y int, sz loop.ScreenSize) (err error) {
|
||||
width_cells, height_cells := int(sz.WidthCells)-x, int(sz.HeightCells)-y
|
||||
if height_cells < 3 {
|
||||
return
|
||||
}
|
||||
y++
|
||||
self.handler.lp.MoveCursorTo(x+1, y+1)
|
||||
self.handler.draw_preview_header(x)
|
||||
y++
|
||||
height_cells -= 2
|
||||
self.handler.lp.MoveCursorTo(x+1, y+1)
|
||||
key := preview_cache_key{
|
||||
family: self.family_list.CurrentFamily(), width: int(sz.CellWidth) * width_cells, height: int(sz.CellHeight) * height_cells,
|
||||
}
|
||||
if key.family == "" {
|
||||
return
|
||||
}
|
||||
self.preview_cache_mutex.Lock()
|
||||
defer self.preview_cache_mutex.Unlock()
|
||||
cc := self.preview_cache[key]
|
||||
switch cc.path {
|
||||
case "":
|
||||
self.preview_cache[key] = preview_cache_value{path: "requested"}
|
||||
go func() {
|
||||
var r map[string]RenderedSampleTransmit
|
||||
self.handler.set_worker_error(kitty_font_backend.query("render_family_samples", map[string]any{
|
||||
"text_style": self.handler.text_style, "font_family": key.family, "width": key.width, "height": key.height,
|
||||
"output_dir": self.handler.temp_dir,
|
||||
}, &r))
|
||||
self.preview_cache_mutex.Lock()
|
||||
defer self.preview_cache_mutex.Unlock()
|
||||
self.preview_cache[key] = preview_cache_value{path: r["font_family"].Path, width: r["font_family"].Canvas_width, height: r["font_family"].Canvas_height}
|
||||
self.handler.lp.WakeupMainThread()
|
||||
}()
|
||||
return
|
||||
case "requested":
|
||||
return
|
||||
}
|
||||
self.handler.graphics_manager.display_image(0, cc.path, cc.width, cc.height)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *FontList) on_wakeup() error {
|
||||
if !self.family_list_updated {
|
||||
self.family_list_updated = true
|
||||
self.family_list.UpdateFamilies(utils.StableSortWithKey(utils.Keys(self.fonts), strings.ToLower))
|
||||
self.family_list.SelectFamily(self.resolved_faces_from_kitty_conf.Font_family.Family)
|
||||
}
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
|
||||
func (self *FontList) draw_screen() (err error) {
|
||||
lp := self.handler.lp
|
||||
sz, err := lp.ScreenSize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
num_rows := max(0, int(sz.HeightCells)-1)
|
||||
mw := self.family_list.max_width + 1
|
||||
green_fg, _, _ := strings.Cut(lp.SprintStyled("fg=green", "|"), "|")
|
||||
lines := make([]string, 0, num_rows)
|
||||
for _, l := range self.family_list.Lines(num_rows) {
|
||||
line := l.text
|
||||
if l.is_current {
|
||||
line = strings.ReplaceAll(line, MARK_AFTER, green_fg)
|
||||
line = lp.SprintStyled("fg=green", ">") + lp.SprintStyled("fg=green bold", line)
|
||||
} else {
|
||||
line = " " + line
|
||||
}
|
||||
lines = append(lines, line)
|
||||
}
|
||||
_, _, str := self.handler.render_lines.InRectangle(lines, 0, 0, 0, num_rows, &self.handler.mouse_state, self.on_click)
|
||||
lp.QueueWriteString(str)
|
||||
seps := strings.Repeat(SEPARATOR, num_rows)
|
||||
seps = strings.TrimSpace(seps)
|
||||
_, _, str = self.handler.render_lines.InRectangle(strings.Split(seps, ""), mw+1, 0, 0, num_rows, &self.handler.mouse_state)
|
||||
lp.QueueWriteString(str)
|
||||
|
||||
if self.family_list.Len() > 0 {
|
||||
if err = self.draw_family_summary(mw+3, sz); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
self.draw_search_bar()
|
||||
return
|
||||
}
|
||||
|
||||
func (self *FontList) on_click(id string) error {
|
||||
which, data, found := strings.Cut(id, ":")
|
||||
if !found {
|
||||
return fmt.Errorf("Not a valid click id: %s", id)
|
||||
}
|
||||
switch which {
|
||||
case "family-chosen":
|
||||
if self.handler.state == LISTING_FAMILIES {
|
||||
if self.family_list.Select(data) {
|
||||
self.handler.draw_screen()
|
||||
} else {
|
||||
self.handler.lp.Beep()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FontList) update_family_search() {
|
||||
text := self.rl.AllText()
|
||||
if self.family_list.UpdateSearch(text) {
|
||||
self.handler.draw_screen()
|
||||
} else {
|
||||
self.draw_search_bar()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *FontList) next(delta int, allow_wrapping bool) error {
|
||||
if self.family_list.Next(delta, allow_wrapping) {
|
||||
return self.handler.draw_screen()
|
||||
}
|
||||
self.handler.lp.Beep()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *FontList) on_key_event(event *loop.KeyEvent) (err error) {
|
||||
if event.MatchesPressOrRepeat("enter") {
|
||||
event.Handled = true
|
||||
if family := self.family_list.CurrentFamily(); family != "" {
|
||||
return self.handler.faces.on_enter(family)
|
||||
}
|
||||
self.handler.lp.Beep()
|
||||
return
|
||||
}
|
||||
if event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
if self.rl.AllText() != "" {
|
||||
self.rl.ResetText()
|
||||
self.update_family_search()
|
||||
self.handler.draw_screen()
|
||||
} else {
|
||||
return fmt.Errorf("canceled by user")
|
||||
}
|
||||
return
|
||||
}
|
||||
ev := event
|
||||
if ev.MatchesPressOrRepeat("down") {
|
||||
ev.Handled = true
|
||||
return self.next(1, true)
|
||||
}
|
||||
if ev.MatchesPressOrRepeat("up") {
|
||||
ev.Handled = true
|
||||
return self.next(-1, true)
|
||||
}
|
||||
if ev.MatchesPressOrRepeat("page_down") {
|
||||
ev.Handled = true
|
||||
sz, err := self.handler.lp.ScreenSize()
|
||||
if err == nil {
|
||||
err = self.next(int(sz.HeightCells)-3, false)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if ev.MatchesPressOrRepeat("page_up") {
|
||||
ev.Handled = true
|
||||
sz, err := self.handler.lp.ScreenSize()
|
||||
if err == nil {
|
||||
err = self.next(3-int(sz.HeightCells), false)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if err = self.rl.OnKeyEvent(event); err != nil {
|
||||
if err == readline.ErrAcceptInput {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if event.Handled {
|
||||
self.update_family_search()
|
||||
}
|
||||
self.draw_search_bar()
|
||||
return
|
||||
}
|
||||
|
||||
func (self *FontList) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
|
||||
if err = self.rl.OnText(text, from_key_event, in_bracketed_paste); err != nil {
|
||||
return err
|
||||
}
|
||||
self.update_family_search()
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var output_on_exit string
|
||||
|
||||
func main(opts *Options) (rc int, err error) {
|
||||
if err = kitty_font_backend.start(); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
defer func() {
|
||||
if werr := kitty_font_backend.release(); werr != nil {
|
||||
if err == nil {
|
||||
err = werr
|
||||
}
|
||||
if rc == 0 {
|
||||
rc = 1
|
||||
}
|
||||
}
|
||||
}()
|
||||
lp, err := loop.New()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
lp.MouseTrackingMode(loop.FULL_MOUSE_TRACKING)
|
||||
h := &handler{lp: lp, opts: opts}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.AllowLineWrapping(false)
|
||||
lp.SetWindowTitle(`Choose a font for kitty`)
|
||||
return "", h.initialize()
|
||||
}
|
||||
lp.OnWakeup = h.on_wakeup
|
||||
lp.OnEscapeCode = h.on_escape_code
|
||||
lp.OnFinalize = func() string {
|
||||
h.finalize()
|
||||
lp.SetCursorVisible(true)
|
||||
return ``
|
||||
}
|
||||
lp.OnMouseEvent = h.on_mouse_event
|
||||
lp.OnResize = func(_, _ loop.ScreenSize) error {
|
||||
return h.draw_screen()
|
||||
}
|
||||
lp.OnKeyEvent = h.on_key_event
|
||||
lp.OnText = h.on_text
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return 1, nil
|
||||
}
|
||||
if output_on_exit != "" {
|
||||
os.Stdout.WriteString(output_on_exit)
|
||||
}
|
||||
return lp.ExitCode(), nil
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Reload_in string
|
||||
Config_file_name string
|
||||
}
|
||||
|
||||
func EntryPoint(root *cli.Command) {
|
||||
ans := root.AddSubCommand(&cli.Command{
|
||||
Name: "choose-fonts",
|
||||
ShortDescription: "Choose the fonts used in kitty",
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
opts := Options{}
|
||||
if err = cmd.GetOptionValues(&opts); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return main(&opts)
|
||||
},
|
||||
})
|
||||
ans.Add(cli.OptionSpec{
|
||||
Name: "--reload-in",
|
||||
Dest: "Reload_in",
|
||||
Type: "choices",
|
||||
Choices: "parent, all, none",
|
||||
Default: "parent",
|
||||
Help: `By default, this kitten will signal only the parent kitty instance it is
|
||||
running in to reload its config, after making changes. Use this option to
|
||||
instead either not reload the config at all or in all running kitty instances.`,
|
||||
})
|
||||
ans.Add(cli.OptionSpec{
|
||||
Name: "--config-file-name",
|
||||
Dest: "Config_file_name",
|
||||
Type: "str",
|
||||
Default: "kitty.conf",
|
||||
Help: `The name or path to the config file to edit. Relative paths are interpreted
|
||||
with respect to the kitty config directory. By default the kitty config
|
||||
file, kitty.conf is edited. This is most useful if you add include
|
||||
fonts.conf to your kitty.conf and then have the kitten operate only on
|
||||
fonts.conf, allowing kitty.conf to remain unchanged.`,
|
||||
})
|
||||
|
||||
clone := root.AddClone(ans.Group, ans)
|
||||
clone.Hidden = true
|
||||
clone.Name = "choose_fonts"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
if __name__ == '__main__':
|
||||
import os
|
||||
import sys
|
||||
|
||||
from kitty.constants import kitten_exe
|
||||
|
||||
os.execlp(kitten_exe(), 'kitten', *sys.argv)
|
||||
@@ -0,0 +1,125 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
type style_group struct {
|
||||
name string
|
||||
ordering int
|
||||
styles []string
|
||||
style_sort_map map[string]float64
|
||||
}
|
||||
|
||||
type family_style_data struct {
|
||||
style_groups []style_group
|
||||
has_variable_faces bool
|
||||
has_style_attribute_data bool
|
||||
}
|
||||
|
||||
func styles_with_attribute_data(ans *family_style_data, items ...VariableData) {
|
||||
// Multi axis styles are kept in their own group, separate from any design axis that happens to be named Styles
|
||||
type group_key struct {
|
||||
name string
|
||||
multi_axis_style bool
|
||||
}
|
||||
// Store indices, not pointers, as appending to ans.style_groups can reallocate it
|
||||
groups := make(map[group_key]int)
|
||||
get := func(key group_key, ordering int) *style_group {
|
||||
idx, found := groups[key]
|
||||
if found {
|
||||
// Use the lowest ordering from any face so that the result does not depend on the order of the faces
|
||||
ans.style_groups[idx].ordering = min(ans.style_groups[idx].ordering, ordering)
|
||||
} else {
|
||||
idx = len(ans.style_groups)
|
||||
ans.style_groups = append(ans.style_groups, style_group{name: key.name, ordering: ordering, styles: make([]string, 0), style_sort_map: make(map[string]float64)})
|
||||
groups[key] = idx
|
||||
}
|
||||
return &ans.style_groups[idx]
|
||||
}
|
||||
has := func(n string, m map[string]float64) bool {
|
||||
_, found := m[n]
|
||||
return found
|
||||
}
|
||||
for _, vd := range items {
|
||||
for _, ax := range vd.Design_axes {
|
||||
if ax.Name == "" {
|
||||
continue
|
||||
}
|
||||
sg := get(group_key{name: ax.Name}, ax.Ordering)
|
||||
for _, v := range ax.Values {
|
||||
if v.Name != "" && !has(v.Name, sg.style_sort_map) {
|
||||
sg.style_sort_map[v.Name] = v.Value
|
||||
sg.styles = append(sg.styles, v.Name)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
for _, ma := range vd.Multi_axis_styles {
|
||||
sg := get(group_key{name: "Styles", multi_axis_style: true}, 0)
|
||||
if ma.Name != "" && !has(ma.Name, sg.style_sort_map) {
|
||||
sg.style_sort_map[ma.Name] = 0
|
||||
sg.styles = append(sg.styles, ma.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
ans.style_groups = utils.StableSortWithKey(ans.style_groups, func(sg style_group) int { return sg.ordering })
|
||||
for i := range ans.style_groups {
|
||||
sg := &ans.style_groups[i]
|
||||
slices.SortStableFunc(sg.styles, func(a, b string) int {
|
||||
if c := cmp.Compare(sg.style_sort_map[a], sg.style_sort_map[b]); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(strings.ToLower(a), strings.ToLower(b))
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func styles_for_variable_data(vd VariableData) (ans *family_style_data) {
|
||||
ans = &family_style_data{style_groups: make([]style_group, 0)}
|
||||
styles_with_attribute_data(ans, vd)
|
||||
return
|
||||
}
|
||||
|
||||
func styles_in_family(family string, fonts []ListedFont) (ans *family_style_data) {
|
||||
_ = family
|
||||
vds := make([]VariableData, len(fonts))
|
||||
for i, f := range fonts {
|
||||
vds[i] = variable_data_for(f)
|
||||
}
|
||||
return styles_in_family_from_variable_data(fonts, vds)
|
||||
}
|
||||
|
||||
// vds must contain the variable data for each font in fonts, in the same order
|
||||
func styles_in_family_from_variable_data(fonts []ListedFont, vds []VariableData) (ans *family_style_data) {
|
||||
ans = &family_style_data{style_groups: make([]style_group, 0)}
|
||||
for _, vd := range vds {
|
||||
if len(vd.Design_axes) > 0 {
|
||||
ans.has_style_attribute_data = true
|
||||
}
|
||||
if len(vd.Axes) > 0 {
|
||||
ans.has_variable_faces = true
|
||||
}
|
||||
}
|
||||
if ans.has_style_attribute_data {
|
||||
styles_with_attribute_data(ans, vds...)
|
||||
} else {
|
||||
ans.style_groups = append(ans.style_groups, style_group{name: "Styles", styles: make([]string, 0)})
|
||||
sg := &ans.style_groups[0]
|
||||
seen := utils.NewSet[string]()
|
||||
for _, f := range fonts {
|
||||
if f.Style != "" && !seen.Has(f.Style) {
|
||||
seen.Add(f.Style)
|
||||
sg.styles = append(sg.styles, f.Style)
|
||||
}
|
||||
}
|
||||
// styles_with_attribute_data has already sorted by axis value, only sort by name here
|
||||
slices.Sort(sg.styles)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// License: GPLv3 Copyright: 2026, kitty contributors
|
||||
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
type group_result struct {
|
||||
Name string
|
||||
Styles []string
|
||||
}
|
||||
|
||||
func group_results(ans *family_style_data) []group_result {
|
||||
ret := make([]group_result, len(ans.style_groups))
|
||||
for i, sg := range ans.style_groups {
|
||||
ret[i] = group_result{sg.name, sg.styles}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func TestStylesWithAttributeData(t *testing.T) {
|
||||
axis := func(name string, ordering int, style string, value float64) DesignAxis {
|
||||
return DesignAxis{Name: name, Ordering: ordering, Values: []DesignAxisValue{{Name: style, Value: value}}}
|
||||
}
|
||||
face := func(axes ...DesignAxis) VariableData { return VariableData{Design_axes: axes} }
|
||||
check := func(expected []group_result, items ...VariableData) {
|
||||
t.Helper()
|
||||
ans := &family_style_data{}
|
||||
styles_with_attribute_data(ans, items...)
|
||||
if diff := cmp.Diff(expected, group_results(ans)); diff != "" {
|
||||
t.Fatalf("Unexpected styles:\n%s", diff)
|
||||
}
|
||||
}
|
||||
|
||||
// Styles added by later faces to groups created by earlier faces must not be lost
|
||||
check([]group_result{{"Weight", []string{"Regular", "Bold"}}, {"Italic", []string{"Upright", "Italic"}}},
|
||||
face(axis("Weight", 0, "Regular", 400), axis("Italic", 1, "Upright", 0)),
|
||||
face(axis("Weight", 0, "Bold", 700), axis("Italic", 1, "Italic", 1)))
|
||||
|
||||
// Group order must not depend on the order of the faces
|
||||
a := face(axis("Weight", 1, "Regular", 400), axis("Italic", 2, "Upright", 0))
|
||||
b := face(axis("Weight", 2, "Bold", 700), axis("Italic", 1, "Italic", 1))
|
||||
expected := []group_result{{"Weight", []string{"Regular", "Bold"}}, {"Italic", []string{"Upright", "Italic"}}}
|
||||
check(expected, a, b)
|
||||
check(expected, b, a)
|
||||
|
||||
// Multi axis styles are kept separate from a design axis named Styles
|
||||
ma := face(axis("Styles", 1, "Wide", 2))
|
||||
ma.Multi_axis_styles = []MultiAxisStyle{{Name: "Light Condensed"}, {Name: "Bold Expanded"}}
|
||||
mb := face(axis("Styles", 1, "Narrow", 1))
|
||||
mb.Multi_axis_styles = []MultiAxisStyle{{Name: "Light Condensed"}, {Name: "Black"}}
|
||||
check([]group_result{{"Styles", []string{"Black", "Bold Expanded", "Light Condensed"}}, {"Styles", []string{"Narrow", "Wide"}}}, ma, mb)
|
||||
}
|
||||
|
||||
func TestStyleAxisValueOrder(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
values []DesignAxisValue
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "negative slant values",
|
||||
values: []DesignAxisValue{
|
||||
{Name: "Oblique", Value: -5}, {Name: "Upright", Value: 0},
|
||||
{Name: "Backslant", Value: 5}, {Name: "More oblique", Value: -15},
|
||||
{Name: "Medium oblique", Value: -10},
|
||||
},
|
||||
want: []string{"More oblique", "Medium oblique", "Oblique", "Upright", "Backslant"},
|
||||
},
|
||||
{
|
||||
name: "fractional values",
|
||||
values: []DesignAxisValue{
|
||||
{Name: "Zero", Value: 0},
|
||||
{Name: "A positive", Value: 2.0 / 65536}, {Name: "Z positive", Value: 1.0 / 65536},
|
||||
{Name: "A negative", Value: -1.0 / 65536}, {Name: "Z negative", Value: -2.0 / 65536},
|
||||
},
|
||||
want: []string{"Z negative", "A negative", "Zero", "Z positive", "A positive"},
|
||||
},
|
||||
{
|
||||
name: "large negative values",
|
||||
values: []DesignAxisValue{
|
||||
{Name: "Zero", Value: 0}, {Name: "Minimum", Value: -32768},
|
||||
{Name: "Maximum", Value: 32767 + 65535.0/65536},
|
||||
{Name: "Minus ten thousand", Value: -10000}, {Name: "Minus one", Value: -1},
|
||||
},
|
||||
want: []string{"Minimum", "Minus ten thousand", "Minus one", "Zero", "Maximum"},
|
||||
},
|
||||
{
|
||||
name: "equal values use stable case insensitive name order",
|
||||
values: []DesignAxisValue{
|
||||
{Name: "beta", Value: -10}, {Name: "alpha", Value: -10},
|
||||
{Name: "Alpha", Value: -10},
|
||||
},
|
||||
want: []string{"alpha", "Alpha", "beta"},
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
vd := VariableData{Design_axes: []DesignAxis{{Name: "Slant", Values: tt.values}}}
|
||||
fonts := make([]ListedFont, len(tt.values))
|
||||
vds := make([]VariableData, len(tt.values))
|
||||
for i, v := range tt.values {
|
||||
fonts[i].Style = v.Name
|
||||
vds[i].Design_axes = []DesignAxis{{Name: "Slant", Values: []DesignAxisValue{v}}}
|
||||
}
|
||||
for name, ans := range map[string]*family_style_data{
|
||||
"single face": styles_for_variable_data(vd),
|
||||
"family": styles_in_family_from_variable_data(fonts, vds),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if diff := cmp.Diff([]group_result{{"Slant", tt.want}}, group_results(ans)); diff != "" {
|
||||
t.Fatalf("Unexpected styles (-want +got):\n%s", diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStylesInFamily(t *testing.T) {
|
||||
check := func(expected []group_result, fonts []ListedFont, vds []VariableData) {
|
||||
t.Helper()
|
||||
if diff := cmp.Diff(expected, group_results(styles_in_family_from_variable_data(fonts, vds))); diff != "" {
|
||||
t.Fatalf("Unexpected styles:\n%s", diff)
|
||||
}
|
||||
}
|
||||
// Without style attribute data, the de-duplicated style names of the fonts are used
|
||||
fonts := []ListedFont{{Style: "Regular"}, {Style: "Bold"}, {Style: ""}, {Style: "Bold"}, {Style: "Italic"}}
|
||||
check([]group_result{{"Styles", []string{"Bold", "Italic", "Regular"}}}, fonts, make([]VariableData, len(fonts)))
|
||||
|
||||
// With style attribute data, styles are sorted by axis value, not by name
|
||||
vd := func(weight string, weight_value float64, italic string, italic_value float64) VariableData {
|
||||
return VariableData{Design_axes: []DesignAxis{
|
||||
{Name: "Weight", Ordering: 0, Values: []DesignAxisValue{{Name: weight, Value: weight_value}}},
|
||||
{Name: "Italic", Ordering: 1, Values: []DesignAxisValue{{Name: italic, Value: italic_value}}},
|
||||
}}
|
||||
}
|
||||
fonts = []ListedFont{{Style: "Bold"}, {Style: "Regular"}, {Style: "Light"}}
|
||||
check([]group_result{{"Weight", []string{"Light", "Regular", "Bold"}}, {"Italic", []string{"Upright", "Italic"}}},
|
||||
fonts, []VariableData{vd("Bold", 700, "Italic", 1), vd("Regular", 400, "Upright", 0), vd("Light", 300, "Upright", 0)})
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type VariableAxis struct {
|
||||
Minimum float64 `json:"minimum"`
|
||||
Maximum float64 `json:"maximum"`
|
||||
Default float64 `json:"default"`
|
||||
Hidden bool `json:"hidden"`
|
||||
Tag string `json:"tag"`
|
||||
Strid string `json:"strid"`
|
||||
}
|
||||
|
||||
type NamedStyle struct {
|
||||
Axis_values map[string]float64 `json:"axis_values"`
|
||||
Name string `json:"name"`
|
||||
Postscript_name string `json:"psname"`
|
||||
}
|
||||
|
||||
type DesignAxisValue struct {
|
||||
Format int `json:"format"`
|
||||
Flags int `json:"flags"`
|
||||
Name string `json:"name"`
|
||||
Value float64 `json:"value"`
|
||||
Minimum float64 `json:"minimum"`
|
||||
Maximum float64 `json:"maximum"`
|
||||
Linked_value float64 `json:"linked_value"`
|
||||
}
|
||||
|
||||
type DesignAxis struct {
|
||||
Tag string `json:"tag"`
|
||||
Name string `json:"name"`
|
||||
Ordering int `json:"ordering"`
|
||||
Values []DesignAxisValue `json:"values"`
|
||||
}
|
||||
|
||||
type AxisValue struct {
|
||||
Design_index int `json:"design_index"`
|
||||
Value float64 `json:"value"`
|
||||
}
|
||||
|
||||
type MultiAxisStyle struct {
|
||||
Flags int `json:"flags"`
|
||||
Name string `json:"name"`
|
||||
Values []AxisValue `json:"values"`
|
||||
}
|
||||
|
||||
type ListedFont struct {
|
||||
Family string `json:"family"`
|
||||
Style string `json:"style"`
|
||||
Fullname string `json:"full_name"`
|
||||
Postscript_name string `json:"postscript_name"`
|
||||
Is_monospace bool `json:"is_monospace"`
|
||||
Is_variable bool `json:"is_variable"`
|
||||
Descriptor map[string]any `json:"descriptor"`
|
||||
}
|
||||
|
||||
type VariableData struct {
|
||||
Axes []VariableAxis `json:"axes"`
|
||||
Named_styles []NamedStyle `json:"named_styles"`
|
||||
Variations_postscript_name_prefix string `json:"variations_postscript_name_prefix"`
|
||||
Elided_fallback_name string `json:"elided_fallback_name"`
|
||||
Design_axes []DesignAxis `json:"design_axes"`
|
||||
Multi_axis_styles []MultiAxisStyle `json:"multi_axis_styles"`
|
||||
}
|
||||
|
||||
type ResolvedFace struct {
|
||||
Family string `json:"family"`
|
||||
Spec string `json:"spec"`
|
||||
Setting string `json:"setting"`
|
||||
}
|
||||
|
||||
type ResolvedFaces struct {
|
||||
Font_family ResolvedFace `json:"font_family"`
|
||||
Bold_font ResolvedFace `json:"bold_font"`
|
||||
Italic_font ResolvedFace `json:"italic_font"`
|
||||
Bold_italic_font ResolvedFace `json:"bold_italic_font"`
|
||||
}
|
||||
|
||||
type ListResult struct {
|
||||
Fonts map[string][]ListedFont `json:"fonts"`
|
||||
Resolved_faces ResolvedFaces `json:"resolved_faces"`
|
||||
}
|
||||
|
||||
type FeatureData struct {
|
||||
Is_index bool `json:"is_index"`
|
||||
Name string `json:"name"`
|
||||
Tooltip string `json:"tooltip"`
|
||||
Sample string `json:"sample"`
|
||||
Params []string `json:"params"`
|
||||
}
|
||||
|
||||
type RenderedSampleTransmit struct {
|
||||
Path string `json:"path"`
|
||||
Variable_data VariableData `json:"variable_data"`
|
||||
Style string `json:"style"`
|
||||
Psname string `json:"psname"`
|
||||
Spec string `json:"spec"`
|
||||
Features map[string]FeatureData `json:"features"`
|
||||
Applied_features map[string]string `json:"applied_features"`
|
||||
Variable_named_style NamedStyle `json:"variable_named_style"`
|
||||
Variable_axis_map map[string]float64 `json:"variable_axis_map"`
|
||||
Cell_width int `json:"cell_width"`
|
||||
Cell_height int `json:"cell_height"`
|
||||
Canvas_width int `json:"canvas_width"`
|
||||
Canvas_height int `json:"canvas_height"`
|
||||
}
|
||||
|
||||
func (self RenderedSampleTransmit) default_axis_values() (ans map[string]float64) {
|
||||
ans = make(map[string]float64)
|
||||
for _, ax := range self.Variable_data.Axes {
|
||||
ans[ax.Tag] = ax.Default
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self RenderedSampleTransmit) current_axis_values() (ans map[string]float64) {
|
||||
ans = make(map[string]float64, len(self.Variable_data.Axes))
|
||||
for _, ax := range self.Variable_data.Axes {
|
||||
ans[ax.Tag] = ax.Default
|
||||
}
|
||||
if self.Variable_named_style.Name != "" {
|
||||
maps.Copy(ans, self.Variable_named_style.Axis_values)
|
||||
} else {
|
||||
maps.Copy(ans, self.Variable_axis_map)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var variable_data_cache map[string]VariableData
|
||||
var variable_data_cache_mutex sync.Mutex
|
||||
|
||||
func (f ListedFont) cache_key() string {
|
||||
key := f.Postscript_name
|
||||
if key == "" {
|
||||
key = "path:" + f.Descriptor["path"].(string)
|
||||
} else {
|
||||
key = "psname:" + key
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func ensure_variable_data_for_fonts(fonts ...ListedFont) error {
|
||||
descriptors := make([]map[string]any, 0, len(fonts))
|
||||
keys := make([]string, 0, len(fonts))
|
||||
variable_data_cache_mutex.Lock()
|
||||
for _, f := range fonts {
|
||||
key := f.cache_key()
|
||||
if _, found := variable_data_cache[key]; !found {
|
||||
descriptors = append(descriptors, f.Descriptor)
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
variable_data_cache_mutex.Unlock()
|
||||
var data []VariableData
|
||||
if err := kitty_font_backend.query("read_variable_data", map[string]any{"descriptors": descriptors}, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
variable_data_cache_mutex.Lock()
|
||||
for i, key := range keys {
|
||||
variable_data_cache[key] = data[i]
|
||||
}
|
||||
variable_data_cache_mutex.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func initialize_variable_data_cache() {
|
||||
variable_data_cache = make(map[string]VariableData)
|
||||
}
|
||||
|
||||
func _cached_vd(key string) (ans VariableData, found bool) {
|
||||
variable_data_cache_mutex.Lock()
|
||||
defer variable_data_cache_mutex.Unlock()
|
||||
ans, found = variable_data_cache[key]
|
||||
return
|
||||
}
|
||||
|
||||
func variable_data_for(f ListedFont) VariableData {
|
||||
key := f.cache_key()
|
||||
ans, found := _cached_vd(key)
|
||||
if found {
|
||||
return ans
|
||||
}
|
||||
if err := ensure_variable_data_for_fonts(f); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ans, found = _cached_vd(key)
|
||||
return ans
|
||||
}
|
||||
|
||||
func has_variable_data_for_font(font ListedFont) bool {
|
||||
_, found := _cached_vd(font.cache_key())
|
||||
return found
|
||||
}
|
||||
|
||||
type ParsedFontFeature struct {
|
||||
tag string
|
||||
val uint
|
||||
is_bool bool
|
||||
}
|
||||
|
||||
func (self ParsedFontFeature) String() string {
|
||||
if self.is_bool {
|
||||
return utils.IfElse(self.val == 0, "-", "+") + self.tag
|
||||
}
|
||||
return fmt.Sprintf("%s=%d", self.tag, self.val)
|
||||
}
|
||||
|
||||
type settable_string struct {
|
||||
val string
|
||||
is_set bool
|
||||
}
|
||||
|
||||
type FontSpec struct {
|
||||
family, style, postscript_name, full_name, system, variable_name settable_string
|
||||
axes map[string]float64
|
||||
features []*ParsedFontFeature
|
||||
}
|
||||
|
||||
func (self FontSpec) String() string {
|
||||
if self.system.val != "" {
|
||||
return self.system.val
|
||||
}
|
||||
ans := strings.Builder{}
|
||||
a := func(k string, v settable_string) {
|
||||
if v.is_set {
|
||||
ans.WriteString(fmt.Sprintf(" %s=%s", k, shlex.Quote(v.val)))
|
||||
}
|
||||
}
|
||||
a(`family`, self.family)
|
||||
a(`style`, self.style)
|
||||
a(`postscript_name`, self.postscript_name)
|
||||
a(`full_name`, self.full_name)
|
||||
a(`variable_name`, self.variable_name)
|
||||
for name, val := range self.axes {
|
||||
a(name, settable_string{strconv.FormatFloat(val, 'f', -1, 64), true})
|
||||
}
|
||||
if len(self.features) > 0 {
|
||||
buf := strings.Builder{}
|
||||
for _, f := range self.features {
|
||||
buf.WriteString(f.String())
|
||||
buf.WriteString(" ")
|
||||
}
|
||||
a(`features`, settable_string{strings.TrimSpace(buf.String()), true})
|
||||
}
|
||||
return strings.TrimSpace(ans.String())
|
||||
}
|
||||
|
||||
func NewParsedFontFeature(x string, features map[string]FeatureData) (ans ParsedFontFeature, err error) {
|
||||
if x != "" {
|
||||
if x[0] == '+' || x[0] == '-' {
|
||||
return ParsedFontFeature{x[1:], utils.IfElse(x[0] == '+', uint(1), uint(0)), true}, nil
|
||||
} else {
|
||||
tag, val, found := strings.Cut(x, "=")
|
||||
fd, defn_found := features[tag]
|
||||
if defn_found && !fd.Is_index {
|
||||
return ParsedFontFeature{tag, 1, true}, nil
|
||||
}
|
||||
pff := ParsedFontFeature{tag: tag}
|
||||
if found {
|
||||
v, err := strconv.ParseUint(val, 10, 0)
|
||||
if err != nil {
|
||||
return ans, err
|
||||
}
|
||||
pff.val = uint(v)
|
||||
}
|
||||
return pff, nil
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func NewFontSpec(spec string, features map[string]FeatureData) (ans FontSpec, err error) {
|
||||
if spec == "" || spec == "auto" {
|
||||
ans.system = settable_string{"auto", true}
|
||||
return
|
||||
}
|
||||
parts, err := shlex.Split(spec)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if !strings.Contains(parts[0], "=") {
|
||||
ans.system = settable_string{spec, true}
|
||||
return
|
||||
}
|
||||
for _, item := range parts {
|
||||
k, v, found := strings.Cut(item, "=")
|
||||
if !found {
|
||||
return ans, fmt.Errorf("The font specification %s is invalid as %s does not contain an =", spec, item)
|
||||
}
|
||||
switch k {
|
||||
case "family":
|
||||
ans.family = settable_string{v, true}
|
||||
case "style":
|
||||
ans.style = settable_string{v, true}
|
||||
case "full_name":
|
||||
ans.full_name = settable_string{v, true}
|
||||
case "postscript_name":
|
||||
ans.postscript_name = settable_string{v, true}
|
||||
case "variable_name":
|
||||
ans.variable_name = settable_string{v, true}
|
||||
case "features":
|
||||
for _, x := range utils.NewSeparatorScanner(v, " ").Split(v) {
|
||||
pff, err := NewParsedFontFeature(x, features)
|
||||
if err != nil {
|
||||
return ans, err
|
||||
}
|
||||
ans.features = append(ans.features, &pff)
|
||||
}
|
||||
default:
|
||||
if ans.axes == nil {
|
||||
ans.axes = make(map[string]float64)
|
||||
}
|
||||
f, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil {
|
||||
return ans, err
|
||||
}
|
||||
ans.axes[k] = f
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package choose_fonts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type State int
|
||||
|
||||
const (
|
||||
SCANNING_FAMILIES State = iota
|
||||
LISTING_FAMILIES
|
||||
CHOOSING_FACES
|
||||
)
|
||||
|
||||
type TextStyle struct {
|
||||
Font_sz float64 `json:"font_size"`
|
||||
Dpi_x float64 `json:"dpi_x"`
|
||||
Dpi_y float64 `json:"dpi_y"`
|
||||
Foreground string `json:"foreground"`
|
||||
Background string `json:"background"`
|
||||
}
|
||||
|
||||
type pane interface {
|
||||
initialize(*handler) error
|
||||
draw_screen() error
|
||||
on_wakeup() error
|
||||
on_key_event(event *loop.KeyEvent) error
|
||||
on_text(text string, from_key_event bool, in_bracketed_paste bool) error
|
||||
on_click(id string) error
|
||||
}
|
||||
|
||||
type handler struct {
|
||||
opts *Options
|
||||
lp *loop.Loop
|
||||
state State
|
||||
err_mutex sync.Mutex
|
||||
err_in_worker_thread error
|
||||
mouse_state tui.MouseState
|
||||
render_count uint
|
||||
render_lines tui.RenderLines
|
||||
text_style TextStyle
|
||||
graphics_manager graphics_manager
|
||||
temp_dir string
|
||||
|
||||
listing FontList
|
||||
faces faces
|
||||
face_pane face_panel
|
||||
if_pane if_panel
|
||||
final_pane final_pane
|
||||
|
||||
panes []pane
|
||||
current_pane pane
|
||||
}
|
||||
|
||||
func (h *handler) set_worker_error(err error) {
|
||||
h.err_mutex.Lock()
|
||||
defer h.err_mutex.Unlock()
|
||||
h.err_in_worker_thread = err
|
||||
}
|
||||
|
||||
func (h *handler) get_worker_error() error {
|
||||
h.err_mutex.Lock()
|
||||
defer h.err_mutex.Unlock()
|
||||
return h.err_in_worker_thread
|
||||
}
|
||||
|
||||
// Events {{{
|
||||
func (h *handler) initialize() (err error) {
|
||||
h.lp.SetCursorVisible(false)
|
||||
h.lp.OnQueryResponse = h.on_query_response
|
||||
h.lp.QueryTerminal("font_size", "dpi_x", "dpi_y", "foreground", "background")
|
||||
h.panes = []pane{&h.listing, &h.faces, &h.face_pane, &h.if_pane, &h.final_pane}
|
||||
for _, pane := range h.panes {
|
||||
if err = pane.initialize(h); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// dont use /tmp as it may be mounted in RAM, Le Sigh
|
||||
if h.temp_dir, err = os.MkdirTemp(utils.CacheDir(), "kitten-choose-fonts-*"); err != nil {
|
||||
return
|
||||
}
|
||||
initialize_variable_data_cache()
|
||||
h.graphics_manager.initialize(h.lp)
|
||||
go func() {
|
||||
var r ListResult
|
||||
h.set_worker_error(kitty_font_backend.query("list_monospaced_fonts", nil, &r))
|
||||
h.listing.fonts = r.Fonts
|
||||
h.listing.resolved_faces_from_kitty_conf = r.Resolved_faces
|
||||
h.lp.WakeupMainThread()
|
||||
}()
|
||||
h.draw_screen()
|
||||
return
|
||||
}
|
||||
|
||||
func (h *handler) finalize() {
|
||||
if h.temp_dir != "" {
|
||||
os.RemoveAll(h.temp_dir)
|
||||
h.temp_dir = ""
|
||||
}
|
||||
h.lp.SetCursorVisible(true)
|
||||
h.lp.SetCursorShape(loop.BLOCK_CURSOR, true)
|
||||
h.graphics_manager.finalize()
|
||||
}
|
||||
|
||||
func (h *handler) on_query_response(key, val string, valid bool) error {
|
||||
if !valid {
|
||||
return fmt.Errorf("Terminal does not support querying the: %s", key)
|
||||
}
|
||||
set_float := func(k, v string, dest *float64) error {
|
||||
if fs, err := strconv.ParseFloat(v, 64); err == nil {
|
||||
*dest = fs
|
||||
} else {
|
||||
return fmt.Errorf("Invalid response from terminal to %s query: %#v", k, v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
switch key {
|
||||
case "font_size":
|
||||
if err := set_float(key, val, &h.text_style.Font_sz); err != nil {
|
||||
return err
|
||||
}
|
||||
case "dpi_x":
|
||||
if err := set_float(key, val, &h.text_style.Dpi_x); err != nil {
|
||||
return err
|
||||
}
|
||||
case "dpi_y":
|
||||
if err := set_float(key, val, &h.text_style.Dpi_y); err != nil {
|
||||
return err
|
||||
}
|
||||
case "foreground":
|
||||
h.text_style.Foreground = val
|
||||
if h.text_style.Background != "" {
|
||||
return h.draw_screen()
|
||||
}
|
||||
case "background":
|
||||
h.text_style.Background = val
|
||||
if h.text_style.Foreground != "" {
|
||||
return h.draw_screen()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *handler) draw_screen() (err error) {
|
||||
h.render_count++
|
||||
h.lp.StartAtomicUpdate()
|
||||
defer func() {
|
||||
h.mouse_state.UpdateHoveredIds()
|
||||
h.mouse_state.ApplyHoverStyles(h.lp)
|
||||
h.lp.EndAtomicUpdate()
|
||||
}()
|
||||
h.graphics_manager.clear_placements()
|
||||
h.lp.ClearScreenButNotGraphics()
|
||||
h.lp.AllowLineWrapping(false)
|
||||
h.mouse_state.ClearCellRegions()
|
||||
if h.current_pane == nil {
|
||||
h.lp.Println("Scanning system for fonts, please wait...")
|
||||
} else {
|
||||
return h.current_pane.draw_screen()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (h *handler) on_wakeup() (err error) {
|
||||
if err = h.get_worker_error(); err != nil {
|
||||
return
|
||||
}
|
||||
if h.current_pane == nil {
|
||||
h.current_pane = &h.listing
|
||||
}
|
||||
return h.listing.on_wakeup()
|
||||
}
|
||||
|
||||
func (h *handler) on_mouse_event(event *loop.MouseEvent) (err error) {
|
||||
rc := h.render_count
|
||||
redraw_needed := false
|
||||
if h.mouse_state.UpdateState(event) {
|
||||
redraw_needed = true
|
||||
}
|
||||
if event.Event_type == loop.MOUSE_CLICK && event.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
|
||||
if err = h.mouse_state.ClickHoveredRegions(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if redraw_needed && rc == h.render_count {
|
||||
err = h.draw_screen()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (h *handler) on_key_event(event *loop.KeyEvent) (err error) {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
event.Handled = true
|
||||
return fmt.Errorf("canceled by user")
|
||||
}
|
||||
if h.current_pane != nil {
|
||||
err = h.current_pane.on_key_event(event)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (h *handler) on_text(text string, from_key_event bool, in_bracketed_paste bool) (err error) {
|
||||
if h.current_pane != nil {
|
||||
err = h.current_pane.on_text(text, from_key_event, in_bracketed_paste)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (h *handler) on_escape_code(etype loop.EscapeCodeType, payload []byte) error {
|
||||
switch etype {
|
||||
case loop.APC:
|
||||
gc := graphics.GraphicsCommandFromAPC(payload)
|
||||
if gc != nil {
|
||||
return h.graphics_manager.on_response(gc)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// }}}
|
||||
Whitespace-only changes.
@@ -0,0 +1,245 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func encode_read_from_clipboard(use_primary bool) string {
|
||||
dest := "c"
|
||||
if use_primary {
|
||||
dest = "p"
|
||||
}
|
||||
return fmt.Sprintf("\x1b]52;%s;?\x1b\\", dest)
|
||||
}
|
||||
|
||||
type base64_streaming_enc struct {
|
||||
output func(string) loop.IdType
|
||||
last_written_id loop.IdType
|
||||
}
|
||||
|
||||
func (self *base64_streaming_enc) Write(p []byte) (int, error) {
|
||||
if len(p) > 0 {
|
||||
self.last_written_id = self.output(string(p))
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
var ErrTooMuchPipedData = errors.New("Too much piped data")
|
||||
|
||||
func read_all_with_max_size(r io.Reader, max_size int) ([]byte, error) {
|
||||
b := make([]byte, 0, utils.Min(8192, max_size))
|
||||
for {
|
||||
if len(b) == cap(b) {
|
||||
new_size := utils.Min(2*cap(b), max_size)
|
||||
if new_size <= cap(b) {
|
||||
return b, ErrTooMuchPipedData
|
||||
}
|
||||
b = append(make([]byte, 0, new_size), b...)
|
||||
}
|
||||
n, err := r.Read(b[len(b):cap(b)])
|
||||
b = b[:len(b)+n]
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
err = nil
|
||||
}
|
||||
return b, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func preread_stdin() (data_src io.Reader, tempfile *os.File, err error) {
|
||||
// we pre-read STDIN because otherwise if the output of a command is being piped in
|
||||
// and that command itself transmits on the tty we will break. For example
|
||||
// kitten @ ls | kitten clipboard
|
||||
var stdin_data []byte
|
||||
stdin_data, err = read_all_with_max_size(os.Stdin, 2*1024*1024)
|
||||
if err == nil {
|
||||
os.Stdin.Close()
|
||||
} else if err != ErrTooMuchPipedData {
|
||||
os.Stdin.Close()
|
||||
err = fmt.Errorf("Failed to read from STDIN pipe with error: %w", err)
|
||||
return
|
||||
}
|
||||
if err == ErrTooMuchPipedData {
|
||||
tempfile, err = utils.CreateAnonymousTemp("")
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("Failed to create a temporary from STDIN pipe with error: %w", err)
|
||||
}
|
||||
tempfile.Write(stdin_data)
|
||||
_, err = io.Copy(tempfile, os.Stdin)
|
||||
os.Stdin.Close()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("Failed to copy data from STDIN pipe to temp file with error: %w", err)
|
||||
}
|
||||
tempfile.Seek(0, io.SeekStart)
|
||||
data_src = tempfile
|
||||
} else if stdin_data != nil {
|
||||
data_src = bytes.NewBuffer(stdin_data)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func run_plain_text_loop(opts *Options) (err error) {
|
||||
stdin_is_tty := tty.IsTerminal(os.Stdin.Fd())
|
||||
var data_src io.Reader
|
||||
var tempfile *os.File
|
||||
if !stdin_is_tty && !opts.GetClipboard {
|
||||
// we dont read STDIN when getting clipboard as it makes it hard to use the kitten in contexts where
|
||||
// the user does not control STDIN such as being execed from other programs.
|
||||
data_src, tempfile, err = preread_stdin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tempfile != nil {
|
||||
defer tempfile.Close()
|
||||
}
|
||||
}
|
||||
lp, err := loop.NewForSimpleInteraction()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dest := "c"
|
||||
if opts.UsePrimary {
|
||||
dest = "p"
|
||||
}
|
||||
|
||||
send_to_loop := func(data string) loop.IdType {
|
||||
return lp.QueueWriteString(data)
|
||||
}
|
||||
enc_writer := base64_streaming_enc{output: send_to_loop}
|
||||
enc := base64.NewEncoder(base64.StdEncoding, &enc_writer)
|
||||
transmitting := true
|
||||
|
||||
after_read_from_stdin := func() {
|
||||
transmitting = false
|
||||
if opts.GetClipboard {
|
||||
lp.QueueWriteString(encode_read_from_clipboard(opts.UsePrimary))
|
||||
} else if opts.WaitForCompletion {
|
||||
lp.QueueWriteString("\x1bP+q544e\x1b\\")
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
}
|
||||
}
|
||||
|
||||
buf := make([]byte, 8192)
|
||||
write_one_chunk := func() error {
|
||||
orig := enc_writer.last_written_id
|
||||
for enc_writer.last_written_id == orig {
|
||||
n, err := data_src.Read(buf[:cap(buf)])
|
||||
if n > 0 {
|
||||
enc.Write(buf[:n])
|
||||
}
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
enc.Close()
|
||||
send_to_loop("\x1b\\")
|
||||
after_read_from_stdin()
|
||||
return nil
|
||||
}
|
||||
send_to_loop("\x1b\\")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
if data_src != nil {
|
||||
send_to_loop(fmt.Sprintf("\x1b]52;%s;", dest))
|
||||
return "", write_one_chunk()
|
||||
}
|
||||
after_read_from_stdin()
|
||||
return "", nil
|
||||
}
|
||||
|
||||
lp.OnWriteComplete = func(id loop.IdType, has_pending_writes bool) error {
|
||||
if id == enc_writer.last_written_id {
|
||||
return write_one_chunk()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var clipboard_contents []byte
|
||||
|
||||
lp.OnEscapeCode = func(etype loop.EscapeCodeType, data []byte) (err error) {
|
||||
switch etype {
|
||||
case loop.DCS:
|
||||
if strings.HasPrefix(utils.UnsafeBytesToString(data), "1+r") {
|
||||
lp.Quit(0)
|
||||
}
|
||||
case loop.OSC:
|
||||
q := utils.UnsafeBytesToString(data)
|
||||
if strings.HasPrefix(q, "52;") {
|
||||
parts := strings.SplitN(q, ";", 3)
|
||||
if len(parts) < 3 {
|
||||
lp.Quit(0)
|
||||
return
|
||||
}
|
||||
data, err := base64.StdEncoding.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return fmt.Errorf("Invalid base64 encoded data from terminal with error: %w", err)
|
||||
}
|
||||
clipboard_contents = data
|
||||
lp.Quit(0)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
esc_count := 0
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
if transmitting {
|
||||
return nil
|
||||
}
|
||||
event.Handled = true
|
||||
esc_count++
|
||||
if esc_count < 2 {
|
||||
key := "Esc"
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
key = "Ctrl+C"
|
||||
}
|
||||
lp.QueueWriteString(fmt.Sprintf("Waiting for response from terminal, press %s again to abort. This could cause garbage to be spewed to the screen.\r\n", key))
|
||||
} else {
|
||||
return fmt.Errorf("Aborted by user!")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
if len(clipboard_contents) > 0 {
|
||||
_, err = os.Stdout.Write(clipboard_contents)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Failed to write to STDOUT with error: %w", err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
)
|
||||
|
||||
func run_mime_loop(opts *Options, args []string) (err error) {
|
||||
cwd, err = os.Getwd()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.GetClipboard {
|
||||
return run_get_loop(opts, args)
|
||||
}
|
||||
return run_set_loop(opts, args)
|
||||
}
|
||||
|
||||
func clipboard_main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
if opts.Password != "" {
|
||||
if opts.HumanName == "" {
|
||||
return 1, fmt.Errorf("must specify --human-name when using a password")
|
||||
}
|
||||
ptype, val, found := strings.Cut(opts.Password, ":")
|
||||
if !found {
|
||||
return 1, fmt.Errorf("invalid password: %#v no password type specified", opts.Password)
|
||||
}
|
||||
switch ptype {
|
||||
case "text":
|
||||
opts.Password = val
|
||||
case "fd":
|
||||
if fd, err := strconv.Atoi(val); err == nil {
|
||||
if f := os.NewFile(uintptr(fd), "password-fd"); f == nil {
|
||||
return 1, fmt.Errorf("invalid file descriptor: %d", fd)
|
||||
} else {
|
||||
data, err := io.ReadAll(f)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("failed to read from file descriptor: %d with error: %w", fd, err)
|
||||
}
|
||||
opts.Password = strings.TrimRightFunc(string(data), unicode.IsSpace)
|
||||
}
|
||||
|
||||
} else {
|
||||
return 1, fmt.Errorf("not a valid file descriptor number: %#v", val)
|
||||
}
|
||||
case "file":
|
||||
if data, err := os.ReadFile(val); err == nil {
|
||||
opts.Password = strings.TrimRightFunc(string(data), unicode.IsSpace)
|
||||
} else {
|
||||
return 1, fmt.Errorf("failed to read from file: %#v with error: %w", val, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(args) > 0 {
|
||||
return 0, run_mime_loop(opts, args)
|
||||
}
|
||||
if opts.Password != "" || opts.HumanName != "" {
|
||||
return 1, fmt.Errorf("cannot use --human-name or --password in filter mode")
|
||||
}
|
||||
return 0, run_plain_text_loop(opts)
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, clipboard_main)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
|
||||
OPTIONS = r"""
|
||||
--get-clipboard -g
|
||||
type=bool-set
|
||||
Output the current contents of the clipboard to STDOUT. Note that by default
|
||||
kitty will prompt for permission to access the clipboard. Can be controlled
|
||||
by :opt:`clipboard_control`.
|
||||
|
||||
|
||||
--use-primary -p
|
||||
type=bool-set
|
||||
Use the primary selection rather than the clipboard on systems that support it,
|
||||
such as Linux.
|
||||
|
||||
|
||||
--mime -m
|
||||
type=list
|
||||
The mimetype of the specified file. Useful when the auto-detected mimetype is
|
||||
likely to be incorrect or the filename has no extension and therefore no mimetype
|
||||
can be detected. If more than one file is specified, this option should be specified multiple
|
||||
times, once for each specified file. When copying data from the clipboard, you can use wildcards
|
||||
to match MIME types. For example: :code:`--mime 'text/*'` will match any textual MIME type
|
||||
available on the clipboard, usually the first matching MIME type is copied. The special MIME
|
||||
type :code:`.` will return the list of available MIME types currently on the system clipboard.
|
||||
|
||||
|
||||
--alias -a
|
||||
type=list
|
||||
Specify aliases for MIME types. Aliased MIME types are considered equivalent.
|
||||
When copying to clipboard both the original and alias are made available on the
|
||||
clipboard. When copying from clipboard if the original is not found, the alias
|
||||
is used, as a fallback. Can be specified multiple times to create multiple
|
||||
aliases. For example: :code:`--alias text/plain=text/x-rst` makes :code:`text/plain` an alias
|
||||
of :code:`text/x-rst`. Aliases are not used in filter mode. An alias for
|
||||
:code:`text/plain` is automatically created if :code:`text/plain` is not present in the input data, but some
|
||||
other :code:`text/*` MIME is present.
|
||||
|
||||
|
||||
--wait-for-completion
|
||||
type=bool-set
|
||||
Wait till the copy to clipboard is complete before exiting. Useful if running
|
||||
the kitten in a dedicated, ephemeral window. Only needed in filter mode.
|
||||
|
||||
|
||||
--password
|
||||
A password to use when accessing the clipboard. If the user chooses to accept the password
|
||||
future invocations of the kitten will not have a permission prompt in this tty session. Does not
|
||||
work in filter mode. Must be of the form: text:actual-password or fd:integer (a file descriptor
|
||||
number to read the password from) or file:path-to-file (a file from which to read the password).
|
||||
Note that you must also specify a human friendly name using the :option:`--human-name` flag.
|
||||
|
||||
|
||||
--human-name
|
||||
A human friendly name to show the user when asking for permission to access the clipboard.
|
||||
""".format
|
||||
help_text = """\
|
||||
Read or write to the system clipboard.
|
||||
|
||||
This kitten operates most simply in :italic:`filter mode`.
|
||||
To set the clipboard text, pipe in the new text on :file:`STDIN`. Use the
|
||||
:option:`--get-clipboard` option to instead output the current clipboard text content to
|
||||
:file:`STDOUT`. Note that copying from the clipboard will cause a permission
|
||||
popup, see :opt:`clipboard_control` for details.
|
||||
|
||||
For more control, specify filename arguments. Then, different MIME types can be copied to/from
|
||||
the clipboard. Some examples:
|
||||
|
||||
.. code:: sh
|
||||
|
||||
# Copy an image to the clipboard:
|
||||
kitten clipboard picture.png
|
||||
|
||||
# Copy an image and some text to the clipboard:
|
||||
kitten clipboard picture.jpg text.txt
|
||||
|
||||
# Copy text from STDIN and an image to the clipboard:
|
||||
echo hello | kitten clipboard picture.png /dev/stdin
|
||||
|
||||
# Copy any raster image available on the clipboard to a PNG file:
|
||||
kitten clipboard -g picture.png
|
||||
|
||||
# Copy an image to a file and text to STDOUT:
|
||||
kitten clipboard -g picture.png /dev/stdout
|
||||
|
||||
# List the formats available on the system clipboard
|
||||
kitten clipboard -g -m . /dev/stdout
|
||||
"""
|
||||
|
||||
usage = '[files to copy to/from]'
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit('This should be run as kitten clipboard')
|
||||
elif __name__ == '__doc__':
|
||||
from kitty.simple_cli_definitions import CompletionSpec
|
||||
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = usage
|
||||
cd['options'] = OPTIONS
|
||||
cd['help_text'] = help_text
|
||||
cd['short_desc'] = 'Copy/paste with the system clipboard, even over SSH'
|
||||
cd['args_completion'] = CompletionSpec.from_string('type:file mime:* group:Files')
|
||||
@@ -0,0 +1,663 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/images"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
var cwd string
|
||||
|
||||
const OSC_NUMBER = "5522"
|
||||
|
||||
type Output struct {
|
||||
arg string
|
||||
ext string
|
||||
arg_is_stream bool
|
||||
mime_type string
|
||||
remote_mime_type string
|
||||
image_needs_conversion bool
|
||||
is_stream bool
|
||||
dest_is_tty bool
|
||||
dest *os.File
|
||||
err error
|
||||
started bool
|
||||
all_data_received bool
|
||||
}
|
||||
|
||||
func (self *Output) cleanup() {
|
||||
if self.dest != nil {
|
||||
self.dest.Close()
|
||||
if !self.is_stream {
|
||||
os.Remove(self.dest.Name())
|
||||
}
|
||||
self.dest = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Output) add_data(data []byte) {
|
||||
if self.err != nil {
|
||||
return
|
||||
}
|
||||
if self.dest == nil {
|
||||
if !self.image_needs_conversion && self.arg_is_stream {
|
||||
self.is_stream = true
|
||||
self.dest = os.Stdout
|
||||
if self.arg == "/dev/stderr" {
|
||||
self.dest = os.Stderr
|
||||
}
|
||||
self.dest_is_tty = tty.IsTerminal(self.dest.Fd())
|
||||
} else {
|
||||
d := cwd
|
||||
if strings.ContainsRune(self.arg, os.PathSeparator) && !self.arg_is_stream {
|
||||
d = filepath.Dir(self.arg)
|
||||
}
|
||||
f, err := os.CreateTemp(d, "."+filepath.Base(self.arg))
|
||||
if err != nil {
|
||||
self.err = err
|
||||
return
|
||||
}
|
||||
self.dest = f
|
||||
}
|
||||
self.started = true
|
||||
}
|
||||
if self.dest_is_tty {
|
||||
data = bytes.ReplaceAll(data, utils.UnsafeStringToBytes("\n"), utils.UnsafeStringToBytes("\r\n"))
|
||||
}
|
||||
_, self.err = self.dest.Write(data)
|
||||
}
|
||||
|
||||
func (self *Output) write_image(img image.Image) (err error) {
|
||||
if self.arg_is_stream {
|
||||
output := os.Stdout
|
||||
if self.arg == "/dev/stderr" {
|
||||
output = os.Stderr
|
||||
}
|
||||
return images.Encode(output, img, self.mime_type)
|
||||
}
|
||||
// Encode into memory first so that an encoding failure leaves any
|
||||
// existing destination file untouched.
|
||||
var buf bytes.Buffer
|
||||
if err = images.Encode(&buf, img, self.mime_type); err != nil {
|
||||
return err
|
||||
}
|
||||
return utils.AtomicUpdateFile(self.arg, &buf)
|
||||
}
|
||||
|
||||
// The downloaded data for a remote MIME type, shared by all outputs saved from it
|
||||
type downloaded_data struct {
|
||||
file *os.File
|
||||
img image.Image
|
||||
img_err error
|
||||
img_decoded bool
|
||||
}
|
||||
|
||||
func (self *downloaded_data) image() (image.Image, error) {
|
||||
if !self.img_decoded {
|
||||
self.img_decoded = true
|
||||
if _, self.img_err = self.file.Seek(0, io.SeekStart); self.img_err == nil {
|
||||
self.img, _, self.img_err = image.Decode(self.file)
|
||||
}
|
||||
}
|
||||
return self.img, self.img_err
|
||||
}
|
||||
|
||||
func (self *Output) save(src *downloaded_data) {
|
||||
if self.image_needs_conversion {
|
||||
img, err := src.image()
|
||||
if err == nil {
|
||||
err = self.write_image(img)
|
||||
}
|
||||
if err != nil {
|
||||
self.err = fmt.Errorf("Failed to encode image data to %s with error: %w", self.mime_type, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
// Copy the downloaded data into place atomically, preserving the
|
||||
// permissions of and following symlinks at the destination.
|
||||
_, err := src.file.Seek(0, io.SeekStart)
|
||||
if err == nil {
|
||||
err = utils.AtomicUpdateFile(self.arg, src.file)
|
||||
}
|
||||
if err != nil {
|
||||
self.err = fmt.Errorf("Failed to write downloaded data to destination: %s with error: %w", self.arg, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Output) commit() {
|
||||
if self.err != nil {
|
||||
return
|
||||
}
|
||||
if self.is_stream {
|
||||
self.dest = nil
|
||||
return
|
||||
}
|
||||
self.save(&downloaded_data{file: self.dest})
|
||||
self.cleanup()
|
||||
}
|
||||
|
||||
func (self *Output) write_mime_list(available_mimes []string) {
|
||||
self.add_data(utils.UnsafeStringToBytes(strings.Join(available_mimes, "\n")))
|
||||
self.all_data_received = true
|
||||
self.commit()
|
||||
}
|
||||
|
||||
func (self *Output) assign_mime_type(available_mimes []string, aliases map[string][]string) (err error) {
|
||||
if self.mime_type == "." {
|
||||
self.remote_mime_type = "."
|
||||
return
|
||||
}
|
||||
if slices.Contains(available_mimes, self.mime_type) {
|
||||
self.remote_mime_type = self.mime_type
|
||||
return
|
||||
}
|
||||
if len(aliases[self.mime_type]) > 0 {
|
||||
for _, alias := range aliases[self.mime_type] {
|
||||
if slices.Contains(available_mimes, alias) {
|
||||
self.remote_mime_type = alias
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, mt := range available_mimes {
|
||||
if matched, _ := filepath.Match(self.mime_type, mt); matched {
|
||||
self.remote_mime_type = mt
|
||||
return
|
||||
}
|
||||
}
|
||||
if images.EncodableImageTypes[self.mime_type] {
|
||||
for _, mt := range available_mimes {
|
||||
if images.DecodableImageTypes[mt] {
|
||||
self.remote_mime_type = mt
|
||||
self.image_needs_conversion = true
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if is_textual_mime(self.mime_type) {
|
||||
for _, mt := range available_mimes {
|
||||
if mt == "text/plain" {
|
||||
self.remote_mime_type = mt
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("The MIME type %s for %s not available on the clipboard", self.mime_type, self.arg)
|
||||
}
|
||||
|
||||
func escape_metadata_value(k, x string) (ans string) {
|
||||
if k == "mime" {
|
||||
x = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(x))
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func unescape_metadata_value(k, x string) (ans string) {
|
||||
if k == "mime" {
|
||||
b, err := base64.StdEncoding.DecodeString(x)
|
||||
if err == nil {
|
||||
x = string(b)
|
||||
}
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func Encode_bytes(metadata map[string]string, payload []byte) string {
|
||||
ans := strings.Builder{}
|
||||
enc_payload := ""
|
||||
if len(payload) > 0 {
|
||||
enc_payload = base64.StdEncoding.EncodeToString(payload)
|
||||
}
|
||||
ans.Grow(2048 + len(enc_payload))
|
||||
ans.WriteString("\x1b]")
|
||||
ans.WriteString(OSC_NUMBER)
|
||||
ans.WriteString(";")
|
||||
for k, v := range metadata {
|
||||
if !strings.HasSuffix(ans.String(), ";") {
|
||||
ans.WriteString(":")
|
||||
}
|
||||
ans.WriteString(k)
|
||||
ans.WriteString("=")
|
||||
ans.WriteString(escape_metadata_value(k, v))
|
||||
}
|
||||
if len(payload) > 0 {
|
||||
ans.WriteString(";")
|
||||
ans.WriteString(enc_payload)
|
||||
}
|
||||
ans.WriteString("\x1b\\")
|
||||
return ans.String()
|
||||
}
|
||||
|
||||
func encode(metadata map[string]string, payload string) string {
|
||||
return Encode_bytes(metadata, utils.UnsafeStringToBytes(payload))
|
||||
}
|
||||
|
||||
func error_from_status(status string) error {
|
||||
switch status {
|
||||
case "ENOSYS":
|
||||
return fmt.Errorf("no primary selection available on this system")
|
||||
case "EPERM":
|
||||
return fmt.Errorf("permission denied")
|
||||
case "EBUSY":
|
||||
return fmt.Errorf("a temporary error occurred, try again later.")
|
||||
default:
|
||||
return fmt.Errorf("%s", status)
|
||||
}
|
||||
}
|
||||
|
||||
func parse_escape_code(etype loop.EscapeCodeType, data []byte) (metadata map[string]string, payload []byte, err error) {
|
||||
if etype != loop.OSC || !bytes.HasPrefix(data, utils.UnsafeStringToBytes(OSC_NUMBER+";")) {
|
||||
return
|
||||
}
|
||||
parts := bytes.SplitN(data, utils.UnsafeStringToBytes(";"), 3)
|
||||
metadata = make(map[string]string)
|
||||
if len(parts) > 2 && len(parts[2]) > 0 {
|
||||
payload, err = base64.StdEncoding.DecodeString(utils.UnsafeBytesToString(parts[2]))
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Received OSC %s packet from terminal with invalid base64 encoded payload", OSC_NUMBER)
|
||||
return
|
||||
}
|
||||
}
|
||||
if len(parts) > 1 {
|
||||
for record := range bytes.SplitSeq(parts[1], utils.UnsafeStringToBytes(":")) {
|
||||
rp := bytes.SplitN(record, utils.UnsafeStringToBytes("="), 2)
|
||||
v := ""
|
||||
if len(rp) == 2 {
|
||||
v = string(rp[1])
|
||||
}
|
||||
k := string(rp[0])
|
||||
metadata[k] = unescape_metadata_value(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func parse_aliases(raw []string) (map[string][]string, error) {
|
||||
ans := make(map[string][]string, len(raw))
|
||||
for _, x := range raw {
|
||||
k, v, found := strings.Cut(x, "=")
|
||||
if !found {
|
||||
return nil, fmt.Errorf("%s is not valid MIME alias specification", x)
|
||||
}
|
||||
ans[k] = append(ans[k], v)
|
||||
ans[v] = append(ans[v], k)
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func (self *Output) writes_directly_to_stream() bool {
|
||||
return self.arg_is_stream && !self.image_needs_conversion
|
||||
}
|
||||
|
||||
// All the outputs for a single remote MIME type. Outputs that write directly
|
||||
// to a stream receive data as it arrives, all others are saved from a single
|
||||
// temporary file holding the downloaded data, once all of it is received.
|
||||
type read_group struct {
|
||||
outputs []*Output
|
||||
downloaded *os.File
|
||||
err error
|
||||
all_data_received bool
|
||||
}
|
||||
|
||||
// Create the temporary file in the directory of the first output where that
|
||||
// is possible, so a missing output directory does not affect other outputs
|
||||
func (self *read_group) create_download_file() (f *os.File, err error) {
|
||||
for _, o := range self.outputs {
|
||||
if o.writes_directly_to_stream() {
|
||||
continue
|
||||
}
|
||||
d := cwd
|
||||
if strings.ContainsRune(o.arg, os.PathSeparator) && !o.arg_is_stream {
|
||||
d = filepath.Dir(o.arg)
|
||||
}
|
||||
if f, err = os.CreateTemp(d, "."+filepath.Base(o.arg)); err == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *read_group) add_data(data []byte) {
|
||||
if self.all_data_received {
|
||||
return
|
||||
}
|
||||
needs_download := false
|
||||
for _, o := range self.outputs {
|
||||
if o.writes_directly_to_stream() {
|
||||
o.add_data(data)
|
||||
} else {
|
||||
// Any errors are reported for this output when committing
|
||||
o.started = true
|
||||
needs_download = true
|
||||
}
|
||||
}
|
||||
if !needs_download || self.err != nil {
|
||||
return
|
||||
}
|
||||
if self.downloaded == nil {
|
||||
if self.downloaded, self.err = self.create_download_file(); self.err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
_, self.err = self.downloaded.Write(data)
|
||||
}
|
||||
|
||||
func (self *read_group) commit() {
|
||||
defer self.cleanup()
|
||||
src := downloaded_data{file: self.downloaded}
|
||||
for _, o := range self.outputs {
|
||||
switch {
|
||||
case o.writes_directly_to_stream():
|
||||
case self.err != nil:
|
||||
o.err = self.err
|
||||
case self.downloaded != nil:
|
||||
o.save(&src)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *read_group) cleanup() {
|
||||
if self.downloaded != nil {
|
||||
self.downloaded.Close()
|
||||
os.Remove(self.downloaded.Name())
|
||||
self.downloaded = nil
|
||||
}
|
||||
}
|
||||
|
||||
type read_outputs map[string]*read_group
|
||||
|
||||
func (self read_outputs) add(o *Output) error {
|
||||
g := self[o.remote_mime_type]
|
||||
if g == nil {
|
||||
g = &read_group{}
|
||||
self[o.remote_mime_type] = g
|
||||
}
|
||||
if o.arg_is_stream {
|
||||
// Stream outputs write data as it arrives, so two of them sharing a
|
||||
// remote MIME type would interleave their data in the same stream.
|
||||
for _, x := range g.outputs {
|
||||
if x.arg_is_stream && x.arg == o.arg {
|
||||
return fmt.Errorf("Cannot write the clipboard MIME type %s to %s more than once", o.remote_mime_type, o.arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
g.outputs = append(g.outputs, o)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self read_outputs) add_data(mime_type string, data []byte) {
|
||||
if g := self[mime_type]; g != nil {
|
||||
g.add_data(data)
|
||||
}
|
||||
}
|
||||
|
||||
func (self read_outputs) commit(mime_type string, wg *sync.WaitGroup) {
|
||||
if g := self[mime_type]; g != nil && !g.all_data_received {
|
||||
g.all_data_received = true
|
||||
for _, o := range g.outputs {
|
||||
o.all_data_received = true
|
||||
}
|
||||
wg.Go(g.commit)
|
||||
}
|
||||
}
|
||||
|
||||
func (self read_outputs) cleanup() {
|
||||
for _, g := range self {
|
||||
g.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the path in the same order as utils.AtomicUpdateFile, then resolve
|
||||
// symlinks in the absolute working-directory prefix as well.
|
||||
func resolved_output_path(path string) (string, error) {
|
||||
path, err := utils.EvalSymlinksThatExist(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path, err = filepath.Abs(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return utils.EvalSymlinksThatExist(path)
|
||||
}
|
||||
|
||||
func check_for_duplicate_output_files(outputs []*Output) error {
|
||||
type resolved_output struct {
|
||||
path, arg string
|
||||
}
|
||||
seen := make(map[string]string, len(outputs))
|
||||
resolved := make([]resolved_output, 0, len(outputs))
|
||||
for _, o := range outputs {
|
||||
if o.arg_is_stream {
|
||||
continue
|
||||
}
|
||||
path, err := resolved_output_path(o.arg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to resolve the output path %s with error: %w", o.arg, err)
|
||||
}
|
||||
if prev, found := seen[path]; found {
|
||||
return fmt.Errorf("The output files %s and %s are the same file", prev, o.arg)
|
||||
}
|
||||
seen[path] = o.arg
|
||||
resolved = append(resolved, resolved_output{path, o.arg})
|
||||
}
|
||||
if len(resolved) < 2 {
|
||||
// Avoid creating probe files when there is nothing to compare
|
||||
return nil
|
||||
}
|
||||
|
||||
// Let the destination filesystem compare the names, including case
|
||||
// and Unicode normalization, without touching the output files.
|
||||
type created_probe struct {
|
||||
info os.FileInfo
|
||||
arg string
|
||||
}
|
||||
probe_prefix := "." + utils.RandomFilename() + "-"
|
||||
probes := make([]created_probe, 0, len(resolved))
|
||||
for _, r := range resolved {
|
||||
probe := filepath.Join(filepath.Dir(r.path), probe_prefix+filepath.Base(r.path))
|
||||
f, err := os.OpenFile(probe, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err != nil {
|
||||
if os.IsExist(err) {
|
||||
if s, serr := os.Stat(probe); serr == nil {
|
||||
for _, p := range probes {
|
||||
if os.SameFile(p.info, s) {
|
||||
return fmt.Errorf("The output files %s and %s are the same file", p.arg, r.arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("The output file %s refers to the same file as another output", r.arg)
|
||||
}
|
||||
// If no temporary file can be created, let this output report
|
||||
// its write error without preventing other outputs.
|
||||
continue
|
||||
}
|
||||
defer os.Remove(probe)
|
||||
s, err := f.Stat()
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to stat the temporary file %s with error: %w", probe, err)
|
||||
}
|
||||
probes = append(probes, created_probe{s, r.arg})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func run_get_loop(opts *Options, args []string) (err error) {
|
||||
lp, err := loop.NewForSimpleInteraction()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var available_mimes []string
|
||||
var wg sync.WaitGroup
|
||||
var getting_data_for string
|
||||
requested_mimes := make(read_outputs)
|
||||
reading_available_mimes := true
|
||||
outputs := make([]*Output, len(args))
|
||||
aliases, merr := parse_aliases(opts.Alias)
|
||||
if merr != nil {
|
||||
return merr
|
||||
}
|
||||
|
||||
for i, arg := range args {
|
||||
outputs[i] = &Output{arg: arg, arg_is_stream: arg == "/dev/stdout" || arg == "/dev/stderr", ext: filepath.Ext(arg)}
|
||||
if len(opts.Mime) > i {
|
||||
outputs[i].mime_type = opts.Mime[i]
|
||||
} else {
|
||||
if outputs[i].arg_is_stream {
|
||||
outputs[i].mime_type = "text/plain"
|
||||
} else {
|
||||
outputs[i].mime_type = utils.GuessMimeType(outputs[i].arg)
|
||||
}
|
||||
}
|
||||
if outputs[i].mime_type == "" {
|
||||
return fmt.Errorf("Could not detect the MIME type for: %s use --mime to specify it manually", arg)
|
||||
}
|
||||
}
|
||||
if err = check_for_duplicate_output_files(outputs); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
requested_mimes.cleanup()
|
||||
for _, o := range outputs {
|
||||
if o.dest != nil {
|
||||
o.cleanup()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
basic_metadata := map[string]string{"type": "read"}
|
||||
if opts.UsePrimary {
|
||||
basic_metadata["loc"] = "primary"
|
||||
}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.QueueWriteString(encode(basic_metadata, "."))
|
||||
if opts.Password != "" {
|
||||
basic_metadata["pw"] = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(opts.Password))
|
||||
}
|
||||
if opts.HumanName != "" {
|
||||
basic_metadata["name"] = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(opts.HumanName))
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
lp.OnEscapeCode = func(etype loop.EscapeCodeType, data []byte) (err error) {
|
||||
metadata, payload, err := parse_escape_code(etype, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if metadata == nil {
|
||||
return nil
|
||||
}
|
||||
if reading_available_mimes {
|
||||
switch metadata["status"] {
|
||||
case "DATA":
|
||||
available_mimes = utils.Map(strings.TrimSpace, strings.Split(utils.UnsafeBytesToString(payload), " "))
|
||||
case "OK":
|
||||
case "DONE":
|
||||
reading_available_mimes = false
|
||||
if len(available_mimes) == 0 {
|
||||
return fmt.Errorf("The clipboard is empty")
|
||||
}
|
||||
for _, o := range outputs {
|
||||
err = o.assign_mime_type(available_mimes, aliases)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if o.remote_mime_type == "." {
|
||||
o.write_mime_list(available_mimes)
|
||||
} else if err = requested_mimes.add(o); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(requested_mimes) > 0 {
|
||||
lp.QueueWriteString(encode(basic_metadata, strings.Join(utils.Keys(requested_mimes), " ")))
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("Failed to read list of available data types in the clipboard with error: %w", error_from_status(metadata["status"]))
|
||||
}
|
||||
} else {
|
||||
switch metadata["status"] {
|
||||
case "DATA":
|
||||
current_mime := metadata["mime"]
|
||||
if _, found := requested_mimes[current_mime]; found {
|
||||
if getting_data_for != current_mime {
|
||||
requested_mimes.commit(getting_data_for, &wg)
|
||||
getting_data_for = current_mime
|
||||
}
|
||||
requested_mimes.add_data(current_mime, payload)
|
||||
}
|
||||
case "OK":
|
||||
case "DONE":
|
||||
requested_mimes.commit(getting_data_for, &wg)
|
||||
getting_data_for = ""
|
||||
lp.Quit(0)
|
||||
default:
|
||||
return fmt.Errorf("Failed to read data from the clipboard with error: %w", error_from_status(metadata["status"]))
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
esc_count := 0
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
esc_count++
|
||||
if esc_count < 2 {
|
||||
key := "Esc"
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
key = "Ctrl+C"
|
||||
}
|
||||
lp.QueueWriteString(fmt.Sprintf("Waiting for response from terminal, press %s again to abort. This could cause garbage to be spewed to the screen.\r\n", key))
|
||||
} else {
|
||||
return fmt.Errorf("Aborted by user!")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
wg.Wait()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
for _, o := range outputs {
|
||||
if o.err != nil {
|
||||
err = fmt.Errorf("Failed to get %s with error: %w", o.arg, o.err)
|
||||
return
|
||||
}
|
||||
if !o.started {
|
||||
err = fmt.Errorf("No data for %s with MIME type: %s", o.arg, o.mime_type)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,675 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClipboardReadMultipleOutputs(t *testing.T) {
|
||||
var png_data bytes.Buffer
|
||||
bounds := image.Rect(0, 0, 2, 3)
|
||||
if err := png.Encode(&png_data, image.NewRGBA(bounds)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
available_mimes []string
|
||||
output_mimes []string
|
||||
aliases []string
|
||||
}{
|
||||
{"text", []string{"text/plain"}, []string{"text/plain", "text/plain"}, nil},
|
||||
{"images", []string{"image/png"}, []string{"image/png", "image/jpeg"}, nil},
|
||||
{"images reversed", []string{"image/png"}, []string{"image/jpeg", "image/png"}, nil},
|
||||
{"mixed", []string{"image/png", "text/plain"}, []string{"text/plain", "image/png", "text/plain", "image/jpeg"}, nil},
|
||||
{"alias", []string{"text/x-custom"}, []string{"text/plain", "text/x-custom"}, []string{"text/plain=text/x-custom"}},
|
||||
{"wildcard", []string{"text/plain"}, []string{"text/*", "text/plain"}, nil},
|
||||
{"text fallback", []string{"text/plain"}, []string{"text/html", "text/plain"}, nil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
requested := make(read_outputs)
|
||||
defer requested.cleanup()
|
||||
aliases, err := parse_aliases(tc.aliases)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var outputs []*Output
|
||||
var names []string
|
||||
for i, mime_type := range tc.output_mimes {
|
||||
name := fmt.Sprintf("output-%d", i)
|
||||
names = append(names, name)
|
||||
o := &Output{arg: filepath.Join(dir, name), mime_type: mime_type}
|
||||
defer o.cleanup()
|
||||
if err := o.assign_mime_type(tc.available_mimes, aliases); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outputs = append(outputs, o)
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if len(requested) != len(tc.available_mimes) {
|
||||
t.Fatalf("Expected one request per remote MIME type, got %d", len(requested))
|
||||
}
|
||||
text_data := []byte("first line\nsecond line\n")
|
||||
var wg sync.WaitGroup
|
||||
for _, mime_type := range tc.available_mimes {
|
||||
data := text_data
|
||||
if mime_type == "image/png" {
|
||||
data = png_data.Bytes()
|
||||
}
|
||||
for chunk := range slices.Chunk(data, 7) {
|
||||
requested.add_data(mime_type, chunk)
|
||||
}
|
||||
requested.commit(mime_type, &wg)
|
||||
// Completed outputs must ignore further data and not be committed twice.
|
||||
requested.add_data(mime_type, []byte("ignored"))
|
||||
requested.commit(mime_type, &wg)
|
||||
}
|
||||
wg.Wait()
|
||||
for _, o := range outputs {
|
||||
if o.err != nil {
|
||||
t.Fatal(o.err)
|
||||
}
|
||||
if !o.started || !o.all_data_received {
|
||||
t.Fatalf("Output %s was not completed", o.arg)
|
||||
}
|
||||
data, err := os.ReadFile(o.arg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch o.mime_type {
|
||||
case "image/jpeg":
|
||||
img, format, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if format != "jpeg" || img.Bounds() != bounds {
|
||||
t.Fatalf("Incorrect converted image: %s %v", format, img.Bounds())
|
||||
}
|
||||
case "image/png":
|
||||
if !bytes.Equal(data, png_data.Bytes()) {
|
||||
t.Fatal("PNG output differs from clipboard data")
|
||||
}
|
||||
default:
|
||||
if !bytes.Equal(data, text_data) {
|
||||
t.Fatalf("Incorrect text output: %q", data)
|
||||
}
|
||||
}
|
||||
}
|
||||
if actual := list_dir(t, dir); !slices.Equal(actual, names) {
|
||||
t.Fatalf("Unexpected output files: %v", actual)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadOutputFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
failed := &Output{arg: filepath.Join(dir, "missing", "output"), remote_mime_type: "text/plain"}
|
||||
succeeded := &Output{arg: filepath.Join(dir, "output"), remote_mime_type: "text/plain"}
|
||||
defer failed.cleanup()
|
||||
defer succeeded.cleanup()
|
||||
if err := check_for_duplicate_output_files([]*Output{failed, succeeded}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requested := make(read_outputs)
|
||||
for _, o := range []*Output{failed, succeeded} {
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
requested.add_data("text/plain", []byte("clipboard contents"))
|
||||
var wg sync.WaitGroup
|
||||
requested.commit("text/plain", &wg)
|
||||
wg.Wait()
|
||||
if failed.err == nil {
|
||||
t.Fatal("Expected an error writing to a missing directory")
|
||||
}
|
||||
if succeeded.err != nil {
|
||||
t.Fatal(succeeded.err)
|
||||
}
|
||||
if data, err := os.ReadFile(succeeded.arg); err != nil || string(data) != "clipboard contents" {
|
||||
t.Fatalf("Other output was not saved after a write failure: %q %v", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDuplicateStreamOutputs(t *testing.T) {
|
||||
stream := func(arg, remote_mime_type string) *Output {
|
||||
return &Output{arg: arg, arg_is_stream: true, remote_mime_type: remote_mime_type}
|
||||
}
|
||||
requested := make(read_outputs)
|
||||
for _, o := range []*Output{
|
||||
stream("/dev/stdout", "text/plain"),
|
||||
stream("/dev/stderr", "text/plain"),
|
||||
stream("/dev/stdout", "text/html"),
|
||||
{arg: filepath.Join(t.TempDir(), "output"), remote_mime_type: "text/plain"},
|
||||
} {
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, o := range []*Output{stream("/dev/stdout", "text/plain"), stream("/dev/stderr", "text/plain")} {
|
||||
if err := requested.add(o); err == nil {
|
||||
t.Fatalf("Duplicate stream output to %s for %s was not rejected", o.arg, o.remote_mime_type)
|
||||
}
|
||||
}
|
||||
if len(requested["text/plain"].outputs) != 3 || len(requested["text/html"].outputs) != 1 {
|
||||
t.Fatalf("Rejected outputs were added: %d %d", len(requested["text/plain"].outputs), len(requested["text/html"].outputs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadSharedDownload(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
requested := make(read_outputs)
|
||||
defer requested.cleanup()
|
||||
var outputs []*Output
|
||||
for _, name := range []string{"a", "b", "c"} {
|
||||
o := &Output{arg: filepath.Join(dir, name), remote_mime_type: "text/plain"}
|
||||
outputs = append(outputs, o)
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
requested.add_data("text/plain", []byte("clipboard "))
|
||||
// All outputs share a single temporary file for the downloaded data
|
||||
if actual := list_dir(t, dir); len(actual) != 1 {
|
||||
t.Fatalf("Expected a single temporary file, got: %v", actual)
|
||||
}
|
||||
requested.add_data("text/plain", []byte("contents"))
|
||||
var wg sync.WaitGroup
|
||||
requested.commit("text/plain", &wg)
|
||||
wg.Wait()
|
||||
for _, o := range outputs {
|
||||
if o.err != nil {
|
||||
t.Fatal(o.err)
|
||||
}
|
||||
if data, err := os.ReadFile(o.arg); err != nil || string(data) != "clipboard contents" {
|
||||
t.Fatalf("Incorrect contents for %s: %q %v", o.arg, data, err)
|
||||
}
|
||||
}
|
||||
if actual := list_dir(t, dir); !slices.Equal(actual, []string{"a", "b", "c"}) {
|
||||
t.Fatalf("Temporary file not removed: %v", actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDownloadFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
outputs := []*Output{
|
||||
{arg: filepath.Join(dir, "missing", "a"), remote_mime_type: "text/plain"},
|
||||
{arg: filepath.Join(dir, "missing", "b"), remote_mime_type: "text/plain"},
|
||||
}
|
||||
requested := make(read_outputs)
|
||||
defer requested.cleanup()
|
||||
for _, o := range outputs {
|
||||
if err := requested.add(o); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
requested.add_data("text/plain", []byte("clipboard contents"))
|
||||
var wg sync.WaitGroup
|
||||
requested.commit("text/plain", &wg)
|
||||
wg.Wait()
|
||||
for _, o := range outputs {
|
||||
if o.err == nil {
|
||||
t.Fatalf("Expected an error for %s when no temporary file can be created", o.arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDuplicateOutputFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Chdir(dir)
|
||||
if err := os.Symlink("target", "link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir("sub", 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outputs := func(args ...string) (ans []*Output) {
|
||||
for _, arg := range args {
|
||||
ans = append(ans, &Output{arg: arg, arg_is_stream: arg == "/dev/stdout" || arg == "/dev/stderr"})
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"a", "b", "sub/a", "/dev/stdout", "/dev/stdout", "/dev/stderr"},
|
||||
{"link", "sub/target"},
|
||||
} {
|
||||
if err := check_for_duplicate_output_files(outputs(args...)); err != nil {
|
||||
t.Fatalf("Unexpected error for %v: %s", args, err)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"a", "a"},
|
||||
{"a", "./a"},
|
||||
{"a", filepath.Join(dir, "a")},
|
||||
{"sub/../a", "a"},
|
||||
{"link", "target"},
|
||||
{"target", filepath.Join(dir, "link")},
|
||||
} {
|
||||
if err := check_for_duplicate_output_files(outputs(args...)); err == nil {
|
||||
t.Fatalf("Duplicate output files not rejected: %v", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadCaseAliasedOutputFiles(t *testing.T) {
|
||||
for _, existing := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("existing=%t", existing), func(t *testing.T) {
|
||||
t.Chdir(t.TempDir())
|
||||
for _, dir := range []string{"destination", "DESTINATION"} {
|
||||
if err := os.Mkdir(dir, 0o755); err != nil && !os.IsExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
lower, err := os.Stat("destination")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upper, err := os.Stat("DESTINATION")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case_insensitive := os.SameFile(lower, upper)
|
||||
if err := os.Symlink("destination/OUTPUT.TXT", "link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
paths := []string{"destination/output.txt", "destination/OUTPUT.TXT", "DESTINATION/output.txt", "DESTINATION/OUTPUT.TXT"}
|
||||
if existing {
|
||||
for _, path := range paths {
|
||||
if err := os.WriteFile(path, []byte("original contents"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
before := map[string][]string{"destination": list_dir(t, "destination"), "DESTINATION": list_dir(t, "DESTINATION")}
|
||||
for _, path := range append(paths[1:], "link") {
|
||||
err := check_for_duplicate_output_files([]*Output{{arg: paths[0]}, {arg: path}})
|
||||
if (err != nil) != case_insensitive {
|
||||
t.Errorf("Incorrect duplicate detection for %s and %s: case_insensitive=%t error=%v", paths[0], path, case_insensitive, err)
|
||||
}
|
||||
if err != nil {
|
||||
if expected := fmt.Sprintf("The output files %s and %s are the same file", paths[0], path); err.Error() != expected {
|
||||
t.Errorf("Incorrect error message: %q != %q", err.Error(), expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
for dir, files := range before {
|
||||
if actual := list_dir(t, dir); !slices.Equal(actual, files) {
|
||||
t.Errorf("Duplicate detection left files behind in %s: %v", dir, actual)
|
||||
}
|
||||
}
|
||||
for _, path := range paths {
|
||||
data, err := os.ReadFile(path)
|
||||
if existing {
|
||||
if err != nil || string(data) != "original contents" {
|
||||
t.Errorf("Duplicate detection changed %s: %q %v", path, data, err)
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
t.Errorf("Duplicate detection created %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadHardLinkedOutputFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, b := filepath.Join(dir, "output.txt"), filepath.Join(dir, "hardlink.txt")
|
||||
if err := os.WriteFile(a, []byte("original contents"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Link(a, b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Atomic replacement writes to distinct directory entries even when the
|
||||
// original files share an inode.
|
||||
if err := check_for_duplicate_output_files([]*Output{{arg: a}, {arg: b}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDuplicateOutputFilesSymlinkParent(t *testing.T) {
|
||||
for _, existing := range []bool{false, true} {
|
||||
for _, absolute_link := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("existing=%t/absolute_link=%t", existing, absolute_link), func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Chdir(dir)
|
||||
if err := os.MkdirAll("real/sub", 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := "real/sub"
|
||||
if absolute_link {
|
||||
link = filepath.Join(dir, link)
|
||||
}
|
||||
if err := os.Symlink(link, "link"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if existing {
|
||||
for _, path := range []string{"target", "real/target"} {
|
||||
if err := os.WriteFile(path, []byte("old contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Concatenate to preserve link/.. in the absolute path as well.
|
||||
for _, path := range []string{"link/../target", dir + "/link/../target"} {
|
||||
outputs := []*Output{{arg: path}, {arg: "real/target"}}
|
||||
if err := check_for_duplicate_output_files(outputs); err == nil {
|
||||
t.Errorf("Duplicate output files not rejected: %s and real/target", path)
|
||||
}
|
||||
outputs[1].arg = "target"
|
||||
if err := check_for_duplicate_output_files(outputs); err != nil {
|
||||
t.Errorf("Distinct output files rejected: %s and target: %s", path, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardReadDuplicateOutputFilesSymlinkCwd(t *testing.T) {
|
||||
for _, existing := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("existing=%t", existing), func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(dir, "real", "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(dir, "link")
|
||||
if err := os.Symlink("real/sub", link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(link)
|
||||
t.Setenv("PWD", link)
|
||||
paths := []string{filepath.Join(dir, "target"), filepath.Join(dir, "real", "target")}
|
||||
if existing {
|
||||
for _, path := range paths {
|
||||
if err := os.WriteFile(path, []byte("old contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
output := &Output{arg: "../target"}
|
||||
defer output.cleanup()
|
||||
output.add_data([]byte("clipboard contents"))
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
// Compare detection with the actual write, including when PWD
|
||||
// names a symlink rather than the physical working directory.
|
||||
for _, path := range paths {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
written := string(data) == "clipboard contents"
|
||||
err = check_for_duplicate_output_files([]*Output{output, {arg: path}})
|
||||
if (err != nil) != written {
|
||||
t.Errorf("Duplicate detection disagrees with write to %s: written=%t error=%v", path, written, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitAtomic(t *testing.T) {
|
||||
dest := filepath.Join(t.TempDir(), "output")
|
||||
old_data := bytes.Repeat([]byte("old contents\n"), 1024)
|
||||
new_data := bytes.Repeat([]byte("new contents\n"), 1024)
|
||||
if err := os.WriteFile(dest, old_data, 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
started, stop := make(chan struct{}), make(chan struct{})
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
data, err := os.ReadFile(dest)
|
||||
close(started)
|
||||
for {
|
||||
if err != nil {
|
||||
result <- fmt.Errorf("Concurrent read failed: %w", err)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(data, old_data) && !bytes.Equal(data, new_data) {
|
||||
result <- fmt.Errorf("Concurrent read returned incomplete contents: %q", data)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-stop:
|
||||
result <- nil
|
||||
return
|
||||
default:
|
||||
}
|
||||
data, err = os.ReadFile(dest)
|
||||
}
|
||||
}()
|
||||
<-started
|
||||
t.Cleanup(func() {
|
||||
close(stop)
|
||||
if err := <-result; err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
|
||||
for i := range 100 {
|
||||
data := new_data
|
||||
if i%2 != 0 {
|
||||
data = old_data
|
||||
}
|
||||
output := Output{arg: dest}
|
||||
output.add_data(data)
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
temp_name := output.dest.Name()
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
actual, err := os.ReadFile(dest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(actual, data) {
|
||||
t.Fatal("Committed file has incorrect contents")
|
||||
}
|
||||
if st, err := os.Stat(dest); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if st.Mode().Perm() != 0o640 {
|
||||
t.Fatalf("Committed file has incorrect permissions: %o", st.Mode().Perm())
|
||||
}
|
||||
if _, err := os.Stat(temp_name); !os.IsNotExist(err) {
|
||||
t.Fatalf("Temporary file still exists after commit: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func list_dir(t *testing.T, dir string) (ans []string) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, e := range entries {
|
||||
ans = append(ans, e.Name())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
// Renaming a file over a non-empty directory fails even when running as root
|
||||
dest := filepath.Join(dir, "output")
|
||||
if err := os.MkdirAll(filepath.Join(dest, "child"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := Output{arg: dest}
|
||||
defer output.cleanup()
|
||||
output.add_data([]byte("new contents"))
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
output.commit()
|
||||
if output.err == nil {
|
||||
t.Fatal("Expected commit to fail when destination is a non-empty directory")
|
||||
}
|
||||
if st, err := os.Stat(filepath.Join(dest, "child")); err != nil || !st.IsDir() {
|
||||
t.Fatalf("Original destination changed after failed commit: %v", err)
|
||||
}
|
||||
if names := list_dir(t, dir); !slices.Equal(names, []string{"output"}) {
|
||||
t.Fatalf("Stray files left behind after failed commit: %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitNewFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
dest := filepath.Join(dir, "output")
|
||||
output := Output{arg: dest}
|
||||
output.add_data([]byte("new contents"))
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
if actual, err := os.ReadFile(dest); err != nil || string(actual) != "new contents" {
|
||||
t.Fatalf("Incorrect contents in new file: %q %v", actual, err)
|
||||
}
|
||||
if names := list_dir(t, dir); !slices.Equal(names, []string{"output"}) {
|
||||
t.Fatalf("Stray files left behind after commit: %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitSymlink(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "target")
|
||||
dest := filepath.Join(dir, "link")
|
||||
if err := os.WriteFile(target, []byte("old contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(target, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := Output{arg: dest}
|
||||
output.add_data([]byte("new contents"))
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
if st, err := os.Lstat(dest); err != nil || st.Mode()&os.ModeSymlink == 0 {
|
||||
t.Fatalf("Symlink at destination was replaced: %v", err)
|
||||
}
|
||||
if actual, err := os.ReadFile(target); err != nil || string(actual) != "new contents" {
|
||||
t.Fatalf("Symlink target not updated: %q %v", actual, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputCommitDanglingSymlink(t *testing.T) {
|
||||
for _, link_type := range []string{"absolute", "relative"} {
|
||||
for _, data_type := range []string{"text", "image"} {
|
||||
t.Run(link_type+"/"+data_type, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "target")
|
||||
dest := filepath.Join(dir, "link")
|
||||
link := target
|
||||
if link_type == "relative" {
|
||||
link = "target"
|
||||
}
|
||||
if err := os.Symlink(link, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := []byte("new contents")
|
||||
output := Output{arg: dest}
|
||||
defer output.cleanup()
|
||||
if data_type == "image" {
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 2, 3))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data = buf.Bytes()
|
||||
output.image_needs_conversion = true
|
||||
output.mime_type = "image/jpeg"
|
||||
}
|
||||
output.add_data(data)
|
||||
output.commit()
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
if actual, err := os.Readlink(dest); err != nil || actual != link {
|
||||
t.Errorf("Symlink at destination changed: %q %v", actual, err)
|
||||
}
|
||||
actual, err := os.ReadFile(target)
|
||||
if err != nil {
|
||||
t.Fatalf("Symlink target not created: %v", err)
|
||||
}
|
||||
if data_type == "image" {
|
||||
img, format, err := image.Decode(bytes.NewReader(actual))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if format != "jpeg" || img.Bounds() != image.Rect(0, 0, 2, 3) {
|
||||
t.Fatalf("Incorrect converted image: %s %v", format, img.Bounds())
|
||||
}
|
||||
} else if !bytes.Equal(actual, data) {
|
||||
t.Fatalf("Incorrect contents in symlink target: %q", actual)
|
||||
}
|
||||
if names := list_dir(t, dir); !slices.Equal(names, []string{"link", "target"}) {
|
||||
t.Fatalf("Stray files left behind after commit: %v", names)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputImageEncodeFailure(t *testing.T) {
|
||||
dest := filepath.Join(t.TempDir(), "output")
|
||||
old_data := []byte("old contents")
|
||||
if err := os.WriteFile(dest, old_data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var png_data bytes.Buffer
|
||||
if err := png.Encode(&png_data, image.NewRGBA(image.Rect(0, 0, 1, 1))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := Output{arg: dest, image_needs_conversion: true, mime_type: "image/x-unsupported"}
|
||||
defer output.cleanup()
|
||||
output.add_data(png_data.Bytes())
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
output.commit()
|
||||
if output.err == nil {
|
||||
t.Fatal("Expected commit to fail with an unsupported image type")
|
||||
}
|
||||
if actual, err := os.ReadFile(dest); err != nil || !bytes.Equal(actual, old_data) {
|
||||
t.Fatalf("Original destination changed after failed image encode: %q %v", actual, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardOutputMimeList(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
dest := filepath.Join(dir, "formats.txt")
|
||||
output := Output{arg: dest, mime_type: ".", remote_mime_type: "."}
|
||||
defer output.cleanup()
|
||||
output.write_mime_list([]string{"text/plain", "image/png"})
|
||||
if output.err != nil {
|
||||
t.Fatal(output.err)
|
||||
}
|
||||
if !output.started || !output.all_data_received {
|
||||
t.Fatal("MIME list output not marked as complete")
|
||||
}
|
||||
if actual, err := os.ReadFile(dest); err != nil || string(actual) != "text/plain\nimage/png" {
|
||||
t.Fatalf("Incorrect MIME list saved: %q %v", actual, err)
|
||||
}
|
||||
if names := list_dir(t, dir); !slices.Equal(names, []string{"formats.txt"}) {
|
||||
t.Fatalf("Stray files left behind after saving MIME list: %v", names)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package clipboard
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Input struct {
|
||||
src io.Reader
|
||||
arg string
|
||||
ext string
|
||||
is_stream bool
|
||||
mime_type string
|
||||
extra_mime_types []string
|
||||
}
|
||||
|
||||
func is_textual_mime(x string) bool {
|
||||
return strings.HasPrefix(x, "text/") || utils.KnownTextualMimes[x]
|
||||
}
|
||||
|
||||
func is_text_plain_mime(x string) bool {
|
||||
return x == "text/plain"
|
||||
}
|
||||
|
||||
func (self *Input) has_mime_matching(predicate func(string) bool) bool {
|
||||
if predicate(self.mime_type) {
|
||||
return true
|
||||
}
|
||||
return slices.ContainsFunc(self.extra_mime_types, predicate)
|
||||
}
|
||||
|
||||
func write_loop(inputs []*Input, opts *Options) (err error) {
|
||||
lp, err := loop.NewForSimpleInteraction()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var waiting_for_write loop.IdType
|
||||
var buf [4096]byte
|
||||
aliases, aerr := parse_aliases(opts.Alias)
|
||||
if aerr != nil {
|
||||
return aerr
|
||||
}
|
||||
num_text_mimes := 0
|
||||
has_text_plain := false
|
||||
for _, i := range inputs {
|
||||
i.extra_mime_types = aliases[i.mime_type]
|
||||
if i.has_mime_matching(is_textual_mime) {
|
||||
num_text_mimes++
|
||||
if !has_text_plain && i.has_mime_matching(is_text_plain_mime) {
|
||||
has_text_plain = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if num_text_mimes > 0 && !has_text_plain {
|
||||
for _, i := range inputs {
|
||||
if i.has_mime_matching(is_textual_mime) {
|
||||
i.extra_mime_types = append(i.extra_mime_types, "text/plain")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
make_metadata := func(ptype, mime string) map[string]string {
|
||||
ans := map[string]string{"type": ptype}
|
||||
if opts.UsePrimary {
|
||||
ans["loc"] = "primary"
|
||||
}
|
||||
if mime != "" {
|
||||
ans["mime"] = mime
|
||||
}
|
||||
if ptype == "write" {
|
||||
if opts.Password != "" {
|
||||
ans["pw"] = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(opts.Password))
|
||||
}
|
||||
if opts.HumanName != "" {
|
||||
ans["name"] = base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(opts.HumanName))
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
waiting_for_write = lp.QueueWriteString(encode(make_metadata("write", ""), ""))
|
||||
return "", nil
|
||||
}
|
||||
|
||||
write_chunk := func() error {
|
||||
if len(inputs) == 0 {
|
||||
return nil
|
||||
}
|
||||
i := inputs[0]
|
||||
n, err := i.src.Read(buf[:])
|
||||
if n > 0 {
|
||||
waiting_for_write = lp.QueueWriteString(Encode_bytes(make_metadata("wdata", i.mime_type), buf[:n]))
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
if len(i.extra_mime_types) > 0 {
|
||||
lp.QueueWriteString(encode(make_metadata("walias", i.mime_type), strings.Join(i.extra_mime_types, " ")))
|
||||
}
|
||||
inputs = inputs[1:]
|
||||
if len(inputs) == 0 {
|
||||
lp.QueueWriteString(encode(make_metadata("wdata", ""), ""))
|
||||
waiting_for_write = 0
|
||||
}
|
||||
return lp.OnWriteComplete(waiting_for_write, false)
|
||||
}
|
||||
return fmt.Errorf("Failed to read from %s with error: %w", i.arg, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnWriteComplete = func(msg_id loop.IdType, has_pending_writes bool) error {
|
||||
if waiting_for_write == msg_id {
|
||||
return write_chunk()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnEscapeCode = func(etype loop.EscapeCodeType, data []byte) (err error) {
|
||||
metadata, _, err := parse_escape_code(etype, data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if metadata != nil && metadata["type"] == "write" {
|
||||
switch metadata["status"] {
|
||||
case "DONE":
|
||||
lp.Quit(0)
|
||||
case "EIO":
|
||||
return fmt.Errorf("Could not write to clipboard an I/O error occurred while the terminal was processing the data")
|
||||
case "EINVAL":
|
||||
return fmt.Errorf("Could not write to clipboard base64 encoding invalid")
|
||||
case "ENOSYS":
|
||||
return fmt.Errorf("Could not write to primary selection as the system does not support it")
|
||||
case "EPERM":
|
||||
return fmt.Errorf("Could not write to clipboard as permission was denied")
|
||||
case "EBUSY":
|
||||
return fmt.Errorf("Could not write to clipboard, a temporary error occurred, try again later.")
|
||||
case "EFBIG":
|
||||
return fmt.Errorf("Could not write to clipboard as there is too much data, see the clipboard_max_size option in the terminal")
|
||||
default:
|
||||
return fmt.Errorf("Could not write to clipboard unknowns status returned from terminal: %#v", metadata["status"])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
esc_count := 0
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
esc_count++
|
||||
if esc_count < 2 {
|
||||
key := "Esc"
|
||||
if event.MatchesPressOrRepeat("ctrl+c") {
|
||||
key = "Ctrl+C"
|
||||
}
|
||||
lp.QueueWriteString(fmt.Sprintf("Waiting for response from terminal, press %s again to abort. This could cause garbage to be spewed to the screen.\r\n", key))
|
||||
} else {
|
||||
return fmt.Errorf("Aborted by user!")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func run_set_loop(opts *Options, args []string) (err error) {
|
||||
inputs := make([]*Input, len(args))
|
||||
to_process := make([]*Input, len(args))
|
||||
defer func() {
|
||||
for _, i := range inputs {
|
||||
if i != nil && i.src != nil {
|
||||
rc, ok := i.src.(io.Closer)
|
||||
if ok {
|
||||
rc.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for i, arg := range args {
|
||||
if arg == "/dev/stdin" {
|
||||
f, _, err := preread_stdin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inputs[i] = &Input{arg: arg, src: f, is_stream: true}
|
||||
} else {
|
||||
f, err := os.Open(arg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to open %s with error: %w", arg, err)
|
||||
}
|
||||
inputs[i] = &Input{arg: arg, src: f, ext: filepath.Ext(arg)}
|
||||
}
|
||||
if i < len(opts.Mime) {
|
||||
inputs[i].mime_type = opts.Mime[i]
|
||||
} else if inputs[i].is_stream {
|
||||
inputs[i].mime_type = "text/plain"
|
||||
} else if inputs[i].ext != "" {
|
||||
inputs[i].mime_type = utils.GuessMimeType(inputs[i].arg)
|
||||
}
|
||||
if inputs[i].mime_type == "" {
|
||||
return fmt.Errorf("Could not guess MIME type for %s use the --mime option to specify a MIME type", arg)
|
||||
}
|
||||
to_process[i] = inputs[i]
|
||||
}
|
||||
return write_loop(to_process, opts)
|
||||
}
|
||||
Whitespace-only changes.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,353 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
# Entry point: collect_keys_data(opts) — collects all keybinding, alias, and
|
||||
# mouse data into a JSON-serializable dict consumed by the Go TUI.
|
||||
|
||||
import sys
|
||||
from functools import partial
|
||||
from typing import Any
|
||||
|
||||
from kitty.conf.types import Definition
|
||||
from kitty.fast_data_types import add_timer, get_boss
|
||||
from kitty.typing_compat import BossType
|
||||
|
||||
from ..tui.handler import result_handler
|
||||
|
||||
definition = Definition(
|
||||
'!kittens.command_palette',
|
||||
)
|
||||
|
||||
agr = definition.add_group
|
||||
egr = definition.end_group
|
||||
map = definition.add_map
|
||||
|
||||
# shortcuts {{{
|
||||
agr('shortcuts', 'Keyboard shortcuts')
|
||||
|
||||
map(
|
||||
'Move selection up',
|
||||
'selection_up --allow-fallback=shifted,ascii ctrl+k selection_up',
|
||||
)
|
||||
map(
|
||||
'Move selection up',
|
||||
'selection_up --allow-fallback=shifted,ascii ctrl+p selection_up',
|
||||
)
|
||||
map(
|
||||
'Move selection down',
|
||||
'selection_down --allow-fallback=shifted,ascii ctrl+j selection_down',
|
||||
)
|
||||
map(
|
||||
'Move selection down',
|
||||
'selection_down --allow-fallback=shifted,ascii ctrl+n selection_down',
|
||||
)
|
||||
|
||||
egr() # }}}
|
||||
|
||||
|
||||
def classify_action(definition: str, alias_map: Any, action_to_group: dict[str, str]) -> tuple[str, str, str]:
|
||||
"""Classify a keybinding definition into (action_name, category, alias).
|
||||
|
||||
Returns the resolved action name, the category it belongs to, and the alias
|
||||
name if the definition uses one (empty string otherwise).
|
||||
"""
|
||||
raw_action = definition.split()[0] if definition else 'no_op'
|
||||
if raw_action == 'combine':
|
||||
return 'combine', 'Combined actions', ''
|
||||
if raw_action in action_to_group or raw_action == 'no_op':
|
||||
return raw_action, action_to_group.get(raw_action, 'Miscellaneous'), ''
|
||||
# Not a known action — try alias resolution
|
||||
resolved = alias_map.resolve_aliases(definition)
|
||||
if resolved:
|
||||
action_name = resolved[0].func
|
||||
return action_name, 'Action aliases', raw_action
|
||||
return raw_action, 'Miscellaneous', ''
|
||||
|
||||
|
||||
def build_action_lookups() -> tuple[dict[str, str], dict[str, str], dict[str, str]]:
|
||||
"""Build action->group, action->help, and action->long_help lookups."""
|
||||
from kitty.actions import get_all_actions, groups
|
||||
|
||||
action_to_group: dict[str, str] = {}
|
||||
action_to_help: dict[str, str] = {}
|
||||
action_to_long_help: dict[str, str] = {}
|
||||
for group_key, actions in get_all_actions().items():
|
||||
for action in actions:
|
||||
action_to_group[action.name] = groups[group_key]
|
||||
action_to_help[action.name] = action.short_help
|
||||
action_to_long_help[action.name] = action.long_help
|
||||
return action_to_group, action_to_help, action_to_long_help
|
||||
|
||||
|
||||
def deduplicate_definitions(defns: list[Any]) -> list[Any]:
|
||||
"""Return unique definitions, keeping the last occurrence of each."""
|
||||
seen: set[tuple[Any, ...]] = set()
|
||||
uniq: list[Any] = []
|
||||
for d in reversed(defns):
|
||||
uid = d.unique_identity_within_keymap
|
||||
if uid not in seen:
|
||||
seen.add(uid)
|
||||
uniq.append(d)
|
||||
return uniq
|
||||
|
||||
|
||||
def build_binding_entry(
|
||||
key_repr: str,
|
||||
action_repr: str,
|
||||
definition: str,
|
||||
alias_map: Any,
|
||||
action_to_group: dict[str, str],
|
||||
action_to_help: dict[str, str],
|
||||
action_to_long_help: dict[str, str],
|
||||
) -> tuple[dict[str, str], str]:
|
||||
"""Build a single binding entry dict and return it with its category."""
|
||||
action_name, category, alias = classify_action(definition, alias_map, action_to_group)
|
||||
entry: dict[str, str] = {
|
||||
'key': key_repr,
|
||||
'action': action_name,
|
||||
'action_display': action_repr,
|
||||
'definition': definition or action_name,
|
||||
'help': action_to_help.get(action_name, ''),
|
||||
'long_help': action_to_long_help.get(action_name, ''),
|
||||
}
|
||||
if alias:
|
||||
entry['alias'] = alias
|
||||
return entry, category
|
||||
|
||||
|
||||
def order_categories(categories: dict[str, list[dict[str, str]]], group_order: list[str]) -> dict[str, list[dict[str, str]]]:
|
||||
"""Order categories by the groups order, with remaining categories sorted at the end."""
|
||||
ordered: dict[str, list[dict[str, str]]] = {}
|
||||
for group_title in group_order:
|
||||
if group_title in categories:
|
||||
ordered[group_title] = categories.pop(group_title)
|
||||
for cat_name, binds in sorted(categories.items()):
|
||||
ordered[cat_name] = binds
|
||||
return ordered
|
||||
|
||||
|
||||
def collect_keyboard_bindings(
|
||||
opts: Any,
|
||||
action_to_group: dict[str, str],
|
||||
action_to_help: dict[str, str],
|
||||
action_to_long_help: dict[str, str],
|
||||
) -> dict[str, dict[str, list[dict[str, str]]]]:
|
||||
"""Collect keybindings from all keyboard modes into categorized dicts."""
|
||||
from kitty.actions import groups
|
||||
from kitty.options.utils import KeyDefinition
|
||||
from kitty.types import Shortcut
|
||||
|
||||
def as_sc(k: 'Any', v: KeyDefinition) -> Shortcut:
|
||||
if v.is_sequence:
|
||||
return Shortcut((v.trigger,) + v.rest)
|
||||
return Shortcut((k,))
|
||||
|
||||
modes: dict[str, dict[str, list[dict[str, str]]]] = {}
|
||||
for mode_name, mode in opts.keyboard_modes.items():
|
||||
categories: dict[str, list[dict[str, str]]] = {}
|
||||
for key, defns in mode.keymap.items():
|
||||
for d in deduplicate_definitions(defns):
|
||||
sc = as_sc(key, d)
|
||||
entry, category = build_binding_entry(
|
||||
sc.human_repr(opts.kitty_mod), d.human_repr(), d.definition or '', opts.alias_map, action_to_group, action_to_help, action_to_long_help
|
||||
)
|
||||
categories.setdefault(category, []).append(entry)
|
||||
for cat in categories:
|
||||
categories[cat].sort(key=lambda b: b['key'])
|
||||
modes[mode_name] = order_categories(categories, list(groups.values()))
|
||||
return modes
|
||||
|
||||
|
||||
def relocate_mode_entry_bindings(modes: dict[str, dict[str, list[dict[str, str]]]]) -> None:
|
||||
"""Move push_keyboard_mode bindings into their target mode's section."""
|
||||
if '' not in modes:
|
||||
return
|
||||
new_default_cats: dict[str, list[dict[str, str]]] = {}
|
||||
for cat_name, bindings in modes[''].items():
|
||||
keep: list[dict[str, str]] = []
|
||||
for b in bindings:
|
||||
if b['action'] == 'push_keyboard_mode':
|
||||
parts = b['definition'].split()
|
||||
target = parts[1] if len(parts) > 1 else ''
|
||||
if target and target in modes:
|
||||
if 'Enter mode' not in modes[target]:
|
||||
new_target: dict[str, list[dict[str, str]]] = {'Enter mode': [b]}
|
||||
new_target.update(modes[target])
|
||||
modes[target] = new_target
|
||||
else:
|
||||
modes[target]['Enter mode'].append(b)
|
||||
continue
|
||||
keep.append(b)
|
||||
if keep:
|
||||
new_default_cats[cat_name] = keep
|
||||
modes[''] = new_default_cats
|
||||
|
||||
|
||||
def add_unmapped_actions(modes: dict[str, dict[str, list[dict[str, str]]]]) -> None:
|
||||
"""Add actions with no keyboard shortcut to the default mode."""
|
||||
from kitty.actions import get_all_actions, groups
|
||||
|
||||
mapped_actions: set[str] = set()
|
||||
for mode_cats in modes.values():
|
||||
for bindings in mode_cats.values():
|
||||
for b in bindings:
|
||||
mapped_actions.add(b['action'])
|
||||
|
||||
default_mode_cats = modes.setdefault('', {})
|
||||
for group_key, actions in get_all_actions().items():
|
||||
category = groups[group_key]
|
||||
for action in actions:
|
||||
if action.name not in mapped_actions:
|
||||
default_mode_cats.setdefault(category, []).append(
|
||||
{
|
||||
'key': '',
|
||||
'action': action.name,
|
||||
'action_display': action.name,
|
||||
'definition': action.name,
|
||||
'help': action.short_help,
|
||||
'long_help': action.long_help,
|
||||
}
|
||||
)
|
||||
|
||||
# Re-sort: mapped entries (non-empty key) first, then unmapped by action name.
|
||||
for cat in default_mode_cats:
|
||||
default_mode_cats[cat].sort(key=lambda b: (b['key'] == '', b['key'] or b['action']))
|
||||
|
||||
# Re-order by groups ordering
|
||||
modes[''] = order_categories(default_mode_cats, list(groups.values()))
|
||||
|
||||
|
||||
def collect_bound_aliases(modes: dict[str, dict[str, list[dict[str, str]]]]) -> set[str]:
|
||||
"""Collect alias names that are already present from keybindings."""
|
||||
bound: set[str] = set()
|
||||
for mode_cats in modes.values():
|
||||
for bindings in mode_cats.values():
|
||||
bound.update(b['alias'] for b in bindings if 'alias' in b)
|
||||
return bound
|
||||
|
||||
|
||||
def build_alias_entry(alias_map: Any, display: str, expansion: str) -> dict[str, str]:
|
||||
"""Build a single alias section entry."""
|
||||
resolved = alias_map.resolve_aliases(display)
|
||||
resolved_action = resolved[0].func if resolved else display.split()[0]
|
||||
return {
|
||||
'key': '',
|
||||
'action': resolved_action,
|
||||
'action_display': display,
|
||||
'definition': expansion,
|
||||
'help': f'Alias for: {expansion}',
|
||||
'long_help': '',
|
||||
'alias': display,
|
||||
}
|
||||
|
||||
|
||||
def add_alias_sections(opts: Any, modes: dict[str, dict[str, list[dict[str, str]]]]) -> None:
|
||||
"""Add Action aliases and Kitten aliases sections for unbound aliases."""
|
||||
bound_aliases = collect_bound_aliases(modes)
|
||||
|
||||
action_alias_entries: list[dict[str, str]] = []
|
||||
kitten_alias_entries: list[dict[str, str]] = []
|
||||
for alias_name, alias_list in opts.alias_map.aliases.items():
|
||||
for aa in alias_list:
|
||||
if aa.replace_second_arg:
|
||||
display = f'{alias_name} {aa.name}'
|
||||
expansion = f'{alias_name} {aa.value}'
|
||||
target_list = kitten_alias_entries
|
||||
else:
|
||||
display = aa.name
|
||||
expansion = aa.value
|
||||
target_list = action_alias_entries
|
||||
if display not in bound_aliases:
|
||||
target_list.append(build_alias_entry(opts.alias_map, display, expansion))
|
||||
|
||||
default_mode_cats = modes.setdefault('', {})
|
||||
|
||||
def sort_key(b: dict[str, str]) -> tuple[bool, str]:
|
||||
return (b['key'] == '', b['key'] or b['action_display'])
|
||||
|
||||
for section_name, entries in (('Action aliases', action_alias_entries), ('Kitten aliases', kitten_alias_entries)):
|
||||
if entries:
|
||||
existing = default_mode_cats.get(section_name, [])
|
||||
existing.extend(entries)
|
||||
existing.sort(key=sort_key)
|
||||
default_mode_cats[section_name] = existing
|
||||
|
||||
|
||||
def move_alias_sections_to_top(modes: dict[str, dict[str, list[dict[str, str]]]]) -> None:
|
||||
"""Put the user defined alias sections first in the default mode."""
|
||||
default_mode_cats = modes.get('')
|
||||
if not default_mode_cats:
|
||||
return
|
||||
ordered: dict[str, list[dict[str, str]]] = {}
|
||||
for section_name in ('Action aliases', 'Kitten aliases'):
|
||||
if section_name in default_mode_cats:
|
||||
ordered[section_name] = default_mode_cats.pop(section_name)
|
||||
ordered.update(default_mode_cats)
|
||||
modes[''] = ordered
|
||||
|
||||
|
||||
def collect_mouse_bindings(opts: Any) -> list[dict[str, str]]:
|
||||
"""Collect mouse mappings."""
|
||||
mouse: list[dict[str, str]] = []
|
||||
for event, action in opts.mousemap.items():
|
||||
key_repr = event.human_repr(opts.kitty_mod)
|
||||
mouse.append({'key': key_repr, 'action': action, 'action_display': action, 'help': '', 'long_help': ''})
|
||||
mouse.sort(key=lambda b: b['key'])
|
||||
return mouse
|
||||
|
||||
|
||||
def collect_keys_data(opts: Any) -> dict[str, Any]:
|
||||
"""Collect all keybinding data from options into a JSON-serializable dict."""
|
||||
action_to_group, action_to_help, action_to_long_help = build_action_lookups()
|
||||
modes = collect_keyboard_bindings(opts, action_to_group, action_to_help, action_to_long_help)
|
||||
relocate_mode_entry_bindings(modes)
|
||||
add_unmapped_actions(modes)
|
||||
add_alias_sections(opts, modes)
|
||||
move_alias_sections_to_top(modes)
|
||||
|
||||
mode_order = list(modes.keys())
|
||||
category_order: dict[str, list[str]] = {}
|
||||
for mode_name, cats in modes.items():
|
||||
category_order[mode_name] = list(cats.keys())
|
||||
|
||||
return {
|
||||
'modes': modes,
|
||||
'mouse': collect_mouse_bindings(opts),
|
||||
'mode_order': mode_order,
|
||||
'category_order': category_order,
|
||||
}
|
||||
|
||||
|
||||
def main(args: list[str]) -> None:
|
||||
raise SystemExit('This kitten must be used only from a kitty.conf mapping')
|
||||
|
||||
|
||||
def callback(target_window_id: int, action: str, timer_id: int | None) -> None:
|
||||
boss = get_boss()
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
boss.combine(action, w)
|
||||
|
||||
|
||||
@result_handler(has_ready_notification=True)
|
||||
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
|
||||
if data and (action := data.get('action')):
|
||||
# run action after event loop tick so command palette overlay is closed
|
||||
add_timer(partial(callback, target_window_id, action), 0, False)
|
||||
|
||||
|
||||
help_text = 'Browse and trigger keyboard shortcuts and actions'
|
||||
usage = ''
|
||||
OPTIONS = r"""
|
||||
""".format
|
||||
|
||||
|
||||
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'] = help_text
|
||||
elif __name__ == '__conf__':
|
||||
sys.options_definition = definition # type: ignore
|
||||
File diff suppressed because it is too large.
Load diff
Whitespace-only changes.
@@ -0,0 +1,206 @@
|
||||
package desktop_ui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/dbus"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type ServerOptions struct {
|
||||
Config []string
|
||||
Override []string
|
||||
}
|
||||
|
||||
const server_conf_name = "desktop-ui-portal"
|
||||
|
||||
func load_server_config(opts *ServerOptions) (ans *Config, err error) {
|
||||
ans = NewConfig()
|
||||
p := config.ConfigParser{LineHandler: ans.Parse}
|
||||
err = p.LoadConfig(server_conf_name+".conf", opts.Config, opts.Override)
|
||||
return
|
||||
}
|
||||
|
||||
func run_server(opts *ServerOptions) (err error) {
|
||||
config, err := load_server_config(opts)
|
||||
if err == nil {
|
||||
portal, err := NewPortal(config, opts)
|
||||
if err == nil {
|
||||
err = portal.Start()
|
||||
if err == nil {
|
||||
defer portal.Cleanup()
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c := make(chan string)
|
||||
<-c
|
||||
return
|
||||
}
|
||||
|
||||
func specialize_command(parent *cli.Command) {
|
||||
parent.Run = func(cmd *cli.Command, args []string) (int, error) {
|
||||
cmd.ShowHelp()
|
||||
return 1, nil
|
||||
}
|
||||
parent.ShortDescription = "Implement various desktop components for use with lightweight compositors/window managers on Linux"
|
||||
|
||||
rs := parent.AddSubCommand(&cli.Command{
|
||||
Name: "run-server",
|
||||
ShortDescription: "Start the various servers used to integrate with the Linux desktop",
|
||||
HelpText: "This should be run very early in the startup sequence of your window manager, before any other programs are run.",
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
opts := ServerOptions{}
|
||||
err = cmd.GetOptionValues(&opts)
|
||||
if err == nil {
|
||||
err = run_server(&opts)
|
||||
}
|
||||
return utils.IfElse(err == nil, 0, 1), err
|
||||
},
|
||||
})
|
||||
rs.Add(cli.OptionSpec{
|
||||
Name: `--override -o`, Type: "list", Dest: `Override`,
|
||||
Help: "Override individual configuration options, can be specified multiple times. Syntax: :italic:`name=value`. For example: :italic:`-o color_scheme=dark`",
|
||||
})
|
||||
rs.Add(cli.OptionSpec{
|
||||
Name: `--config -c`, Type: "list", Dest: `Config`,
|
||||
Help: strings.ReplaceAll(strings.ReplaceAll(kitty.ConfigHelp, "{appname}", "kitty"), "{conf_name}", server_conf_name),
|
||||
})
|
||||
|
||||
parent.AddSubCommand(&cli.Command{
|
||||
Name: "enable-portal",
|
||||
ShortDescription: "This will create or edit the various files needed so that the portal from this kitten is used by xdg-desktop-portal",
|
||||
HelpText: "Once you run this command, add :code:`kitten desktop-ui run-server` to your window manager startup sequence and reboot your computer (or logout and restart your session) and hopefully xdg-desktop-portal should now delegate to kitty for the portals implemented here. If it doesn't try running :code:`/usr/lib/xdg-desktop-portal -r -v` it will provide a lot of logging about why it is choosing different portal backends. That combined with a careful reading of :code:`man portals.conf` should be enough to learn how to convince xdg-desktop-portal to use kitty.\n\nYou can change the system color-scheme dynamically by running::\n\n:code:`kitten desktop-ui set-color-scheme dark`",
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
err = enable_portal()
|
||||
return utils.IfElse(err == nil, 0, 1), err
|
||||
},
|
||||
})
|
||||
parent.AddSubCommand(&cli.Command{
|
||||
Name: "set-color-scheme",
|
||||
ShortDescription: "Change the color scheme",
|
||||
ArgCompleter: cli.NamesCompleter("Choices for color-scheme", "no-preference", "light", "dark", "toggle"),
|
||||
Usage: " light|dark|no-preference|toggle",
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
if len(args) != 1 {
|
||||
cmd.ShowHelp()
|
||||
return 1, fmt.Errorf("must specify the new color scheme value")
|
||||
}
|
||||
err = set_color_scheme(args[0])
|
||||
return utils.IfElse(err == nil, 0, 1), err
|
||||
},
|
||||
})
|
||||
parent.AddSubCommand(&cli.Command{
|
||||
Name: "set-accent-color",
|
||||
ShortDescription: "Change the accent color",
|
||||
Usage: " color_as_hex_or_name",
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
if len(args) != 1 {
|
||||
cmd.ShowHelp()
|
||||
return 1, fmt.Errorf("must specify the new accent color value")
|
||||
}
|
||||
var v dbus.Variant
|
||||
if v, err = to_color(args[0]); err == nil {
|
||||
err = set_variant_setting(PORTAL_APPEARANCE_NAMESPACE, PORTAL_ACCENT_COLOR_KEY, v, false)
|
||||
}
|
||||
return utils.IfElse(err == nil, 0, 1), err
|
||||
},
|
||||
})
|
||||
parent.AddSubCommand(&cli.Command{
|
||||
Name: "set-contrast",
|
||||
ShortDescription: "Change the contrast. Can be high or normal.",
|
||||
Usage: " high|normal",
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
if len(args) != 1 {
|
||||
cmd.ShowHelp()
|
||||
return 1, fmt.Errorf("must specify the new contrast value")
|
||||
}
|
||||
|
||||
var v dbus.Variant
|
||||
switch args[0] {
|
||||
case "normal":
|
||||
v = dbus.MakeVariant(uint32(0))
|
||||
case "high":
|
||||
v = dbus.MakeVariant(uint32(1))
|
||||
default:
|
||||
return 1, fmt.Errorf("%s is not a valid contrast value", args[0])
|
||||
}
|
||||
err = set_variant_setting(PORTAL_APPEARANCE_NAMESPACE, PORTAL_CONTRAST_KEY, v, false)
|
||||
return utils.IfElse(err == nil, 0, 1), err
|
||||
},
|
||||
})
|
||||
st := parent.AddSubCommand(&cli.Command{
|
||||
Name: "set-setting",
|
||||
ShortDescription: "Change an arbitrary setting",
|
||||
Usage: " key [value]",
|
||||
HelpText: "Set an arbitrary setting. If you want to set the color-scheme use the dedicated command for it. Use this command with care as it does no validation for the type of value. The syntax for specifying values is described at: :link:`the glib docs <https://docs.gtk.org/glib/gvariant-text-format.html>`. Leaving out the value or specifying an empty value, will delete the setting.",
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
val := ""
|
||||
if len(args) < 1 {
|
||||
cmd.ShowHelp()
|
||||
return 1, fmt.Errorf("must specify the key")
|
||||
}
|
||||
if len(args) > 1 {
|
||||
val = args[1]
|
||||
}
|
||||
opts := SetOptions{}
|
||||
if err = cmd.GetOptionValues(&opts); err == nil {
|
||||
err = set_setting(args[0], val, &opts)
|
||||
}
|
||||
return utils.IfElse(err == nil, 0, 1), err
|
||||
},
|
||||
})
|
||||
st.Add(cli.OptionSpec{
|
||||
Name: "--namespace -n",
|
||||
Help: "The namespace in which to change the setting.",
|
||||
Default: PORTAL_APPEARANCE_NAMESPACE,
|
||||
})
|
||||
st.Add(cli.OptionSpec{
|
||||
Name: "--data-type",
|
||||
Help: "The DBUS data type signature of the value. The default is to guess from the textual representation, see :link:`the glib docs <https://docs.gtk.org/glib/gvariant-text-format.html>` for details.",
|
||||
})
|
||||
|
||||
ss := parent.AddSubCommand(&cli.Command{
|
||||
Name: "show-settings",
|
||||
ShortDescription: "Print the current values of the desktop settings",
|
||||
Run: func(cmd *cli.Command, args []string) (rc int, err error) {
|
||||
if len(args) != 0 {
|
||||
cmd.ShowHelp()
|
||||
return 1, fmt.Errorf("no arguments allowed")
|
||||
}
|
||||
opts := ShowSettingsOptions{}
|
||||
err = cmd.GetOptionValues(&opts)
|
||||
if err == nil {
|
||||
err = show_settings(&opts)
|
||||
}
|
||||
return utils.IfElse(err == nil, 0, 1), err
|
||||
},
|
||||
})
|
||||
ss.Add(cli.OptionSpec{
|
||||
Name: "--as-json",
|
||||
Help: "Show the settings as JSON for machine consumption",
|
||||
Type: "bool-set",
|
||||
})
|
||||
ss.Add(cli.OptionSpec{
|
||||
Name: "--in-namespace",
|
||||
Help: "Show only settings in the specified names. Can be specified multiple times. When unspecified all namespaces are returned.",
|
||||
Type: "list",
|
||||
})
|
||||
ss.Add(cli.OptionSpec{
|
||||
Name: "--allow-other-backends",
|
||||
Help: "Normally, after printing the settings, if the settings did not come from the desktop-ui kitten the command prints an error and exits. This prevents that.",
|
||||
Type: "bool-set",
|
||||
})
|
||||
}
|
||||
|
||||
func EntryPoint(root *cli.Command) {
|
||||
create_cmd(root, nil)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2025, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
from kitty.conf.types import Definition
|
||||
|
||||
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('Appearance')
|
||||
opt(
|
||||
'color_scheme',
|
||||
'no-preference',
|
||||
choices=('no-preference', 'dark', 'light'),
|
||||
long_text="""\
|
||||
The color scheme for your system. This sets the initial value of the color scheme. It can be changed subsequently
|
||||
by using :code:`kitten desktop-ui color-scheme`.
|
||||
""",
|
||||
)
|
||||
opt(
|
||||
'accent_color',
|
||||
'cyan',
|
||||
option_type='to_color',
|
||||
long_text='The RGB accent color for your system, can be specified as a color name or in hex a decimal format.',
|
||||
)
|
||||
opt('contrast', 'normal', choices=('normal', 'high'), long_text='The preferred contrast level.')
|
||||
opt(
|
||||
'file_chooser_size',
|
||||
'',
|
||||
long_text="""
|
||||
The size in lines and columns of the file chooser popup window. By default it is full screen. For example:
|
||||
:code:`file_chooser_size 25 80` will cause the popup to be of size 25 lines and 80 columns. Note that if you
|
||||
use this option, depending on the compositor you are running, the popup window may not be properly modal.
|
||||
""",
|
||||
)
|
||||
opt(
|
||||
'+file_chooser_kitty_conf',
|
||||
'',
|
||||
long_text='Path to config file to use for kitty when drawing the file chooser window. Can be specified multiple times. By default, the'
|
||||
' normal kitty.conf is used. Relative paths are resolved with respect to the kitty config directory.',
|
||||
)
|
||||
opt(
|
||||
'+file_chooser_kitty_override',
|
||||
'',
|
||||
long_text='Override individual kitty configuration options, for the file chooser window.'
|
||||
' Can be specified multiple times. Syntax: :italic:`name=value`. For example: :code:`font_size=20`.',
|
||||
)
|
||||
|
||||
egr()
|
||||
|
||||
|
||||
def main(args: list[str]) -> None:
|
||||
raise SystemExit('This must be run as kitten desktop-ui')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
elif __name__ == '__conf__':
|
||||
sys.options_definition = definition # type: ignore
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,47 @@
|
||||
// License: GPLv3 Copyright: 2026, kitty contributors
|
||||
|
||||
package desktop_ui
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInvalidAccentColor(t *testing.T) {
|
||||
if _, err := to_color("cyan"); err != nil {
|
||||
t.Fatalf("Valid accent color rejected: %s", err)
|
||||
}
|
||||
if v, err := to_color("not-a-color"); err == nil {
|
||||
t.Fatalf("Invalid accent color accepted as: %#v", v)
|
||||
}
|
||||
c := NewConfig()
|
||||
if err := c.Parse("accent_color", "not-a-color"); err == nil {
|
||||
t.Fatalf("Invalid accent_color accepted in config as: %#v", c.Accent_color)
|
||||
}
|
||||
if c.Accent_color != NewConfig().Accent_color {
|
||||
t.Fatalf("Invalid accent_color in config changed the default to: %#v", c.Accent_color)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDBusServiceExecLine(t *testing.T) {
|
||||
for _, tc := range []struct{ exe, want string }{
|
||||
{"/opt/kitty/kitten", `/opt/kitty/kitten a`},
|
||||
{"/opt/kitty app/kitten", `'/opt/kitty app/kitten' a`},
|
||||
{"/opt/kitty'app/kitten", `'/opt/kitty'"'"'app/kitten' a`},
|
||||
{`/opt/kitty"app/kitten`, `'/opt/kitty"app/kitten' a`},
|
||||
{`/opt/kitty\app/kitten`, `'/opt/kitty\\app/kitten' a`},
|
||||
{"/opt/kitty$app/kitten", `'/opt/kitty$app/kitten' a`},
|
||||
{"/opt/kitty\tapp/kitten", `'/opt/kitty\tapp/kitten' a`},
|
||||
{"/opt/kitty\napp/kitten", `'/opt/kitty\napp/kitten' a`},
|
||||
} {
|
||||
got, err := dbus_service_exec_line(tc.exe, "a")
|
||||
if err != nil {
|
||||
t.Fatalf("Unexpected error for %#v: %s", tc.exe, err)
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Fatalf("Exec line for %#v: got %#v want %#v", tc.exe, got, tc.want)
|
||||
}
|
||||
}
|
||||
if _, err := dbus_service_exec_line("/opt/kitty\rapp/kitten"); err == nil {
|
||||
t.Fatalf("No error for path containing a carriage return")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,402 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
var path_name_map, remote_dirs map[string]string
|
||||
|
||||
var mimetypes_cache, data_cache, hash_cache *utils.LRUCache[string, string]
|
||||
var size_cache *utils.LRUCache[string, int64]
|
||||
var lines_cache *utils.LRUCache[string, []string]
|
||||
var light_highlighted_lines_cache *utils.LRUCache[string, []string]
|
||||
var dark_highlighted_lines_cache *utils.LRUCache[string, []string]
|
||||
var is_text_cache *utils.LRUCache[string, bool]
|
||||
|
||||
func init_caches() {
|
||||
path_name_map = make(map[string]string, 32)
|
||||
remote_dirs = make(map[string]string, 32)
|
||||
const sz = 4096
|
||||
size_cache = utils.NewLRUCache[string, int64](sz)
|
||||
mimetypes_cache = utils.NewLRUCache[string, string](sz)
|
||||
data_cache = utils.NewLRUCache[string, string](sz)
|
||||
is_text_cache = utils.NewLRUCache[string, bool](sz)
|
||||
lines_cache = utils.NewLRUCache[string, []string](sz)
|
||||
light_highlighted_lines_cache = utils.NewLRUCache[string, []string](sz)
|
||||
dark_highlighted_lines_cache = utils.NewLRUCache[string, []string](sz)
|
||||
hash_cache = utils.NewLRUCache[string, string](sz)
|
||||
}
|
||||
|
||||
func add_remote_dir(val string) {
|
||||
x := filepath.Base(val)
|
||||
idx := strings.LastIndex(x, "-")
|
||||
if idx > -1 {
|
||||
x = x[idx+1:]
|
||||
} else {
|
||||
x = ""
|
||||
}
|
||||
remote_dirs[val] = x
|
||||
}
|
||||
|
||||
func mimetype_for_path(path string) string {
|
||||
return mimetypes_cache.MustGetOrCreate(path, func(path string) string {
|
||||
mt := utils.GuessMimeTypeWithFileSystemAccess(path)
|
||||
if mt == "" {
|
||||
mt = "application/octet-stream"
|
||||
}
|
||||
if utils.KnownTextualMimes[mt] {
|
||||
if _, a, found := strings.Cut(mt, "/"); found {
|
||||
mt = "text/" + a
|
||||
}
|
||||
}
|
||||
return mt
|
||||
})
|
||||
}
|
||||
|
||||
func data_for_path(path string) (string, error) {
|
||||
return data_cache.GetOrCreate(path, func(path string) (string, error) {
|
||||
ans, err := os.ReadFile(path)
|
||||
return utils.UnsafeBytesToString(ans), err
|
||||
})
|
||||
}
|
||||
|
||||
func size_for_path(path string) (int64, error) {
|
||||
return size_cache.GetOrCreate(path, func(path string) (int64, error) {
|
||||
s, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return s.Size(), nil
|
||||
})
|
||||
}
|
||||
|
||||
func is_image(path string) bool {
|
||||
return strings.HasPrefix(mimetype_for_path(path), "image/")
|
||||
}
|
||||
|
||||
func is_path_text(path string) bool {
|
||||
return is_text_cache.MustGetOrCreate(path, func(path string) bool {
|
||||
if is_image(path) {
|
||||
return false
|
||||
}
|
||||
s1, err := os.Stat(path)
|
||||
if err == nil {
|
||||
s2, err := os.Stat("/dev/null")
|
||||
if err == nil && os.SameFile(s1, s2) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
d, err := data_for_path(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return utf8.ValidString(d)
|
||||
})
|
||||
}
|
||||
|
||||
func hash_for_path(path string) (string, error) {
|
||||
return hash_cache.GetOrCreate(path, func(path string) (string, error) {
|
||||
ans, err := data_for_path(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := md5.Sum(utils.UnsafeStringToBytes(ans))
|
||||
return utils.UnsafeBytesToString(hash[:]), err
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func text_to_lines(text string) []string {
|
||||
lines := make([]string, 0, 512)
|
||||
splitlines_like_git(text, false, func(line string) { lines = append(lines, line) })
|
||||
return lines
|
||||
}
|
||||
|
||||
func sanitize(text string) string { return utils.ReplaceControlCodes(text, conf.Replace_tab_by, "\n") }
|
||||
|
||||
func lines_for_path(path string) ([]string, error) {
|
||||
return lines_cache.GetOrCreate(path, func(path string) ([]string, error) {
|
||||
ans, err := data_for_path(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return text_to_lines(sanitize(ans)), nil
|
||||
})
|
||||
}
|
||||
|
||||
func highlighted_lines_for_path(path string) ([]string, error) {
|
||||
plain_lines, err := lines_for_path(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ans []string
|
||||
var found bool
|
||||
if use_light_colors {
|
||||
ans, found = light_highlighted_lines_cache.Get(path)
|
||||
} else {
|
||||
ans, found = dark_highlighted_lines_cache.Get(path)
|
||||
}
|
||||
if found && len(ans) == len(plain_lines) {
|
||||
return ans, nil
|
||||
}
|
||||
return plain_lines, nil
|
||||
}
|
||||
|
||||
type Collection struct {
|
||||
changes, renames, type_map map[string]string
|
||||
adds, removes *utils.Set[string]
|
||||
all_paths []string
|
||||
paths_to_highlight *utils.Set[string]
|
||||
added_count, removed_count int
|
||||
}
|
||||
|
||||
func (self *Collection) add_change(left, right string) {
|
||||
self.changes[left] = right
|
||||
self.all_paths = append(self.all_paths, left)
|
||||
self.paths_to_highlight.Add(left)
|
||||
self.paths_to_highlight.Add(right)
|
||||
self.type_map[left] = `diff`
|
||||
}
|
||||
|
||||
func (self *Collection) add_rename(left, right string) {
|
||||
self.renames[left] = right
|
||||
self.all_paths = append(self.all_paths, left)
|
||||
self.type_map[left] = `rename`
|
||||
}
|
||||
|
||||
func (self *Collection) add_add(right string) {
|
||||
self.adds.Add(right)
|
||||
self.all_paths = append(self.all_paths, right)
|
||||
self.paths_to_highlight.Add(right)
|
||||
self.type_map[right] = `add`
|
||||
if is_path_text(right) {
|
||||
num, _ := lines_for_path(right)
|
||||
self.added_count += len(num)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Collection) add_removal(left string) {
|
||||
self.removes.Add(left)
|
||||
self.all_paths = append(self.all_paths, left)
|
||||
self.paths_to_highlight.Add(left)
|
||||
self.type_map[left] = `removal`
|
||||
if is_path_text(left) {
|
||||
num, _ := lines_for_path(left)
|
||||
self.removed_count += len(num)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Collection) finalize() {
|
||||
utils.StableSortWithKey(self.all_paths, func(path string) string {
|
||||
return path_name_map[path]
|
||||
})
|
||||
}
|
||||
|
||||
func (self *Collection) Len() int { return len(self.all_paths) }
|
||||
|
||||
func (self *Collection) Items() int { return len(self.all_paths) }
|
||||
|
||||
func (self *Collection) Apply(f func(path, typ, changed_path string) error) error {
|
||||
for _, path := range self.all_paths {
|
||||
typ := self.type_map[path]
|
||||
changed_path := ""
|
||||
switch typ {
|
||||
case "diff":
|
||||
changed_path = self.changes[path]
|
||||
case "rename":
|
||||
changed_path = self.renames[path]
|
||||
}
|
||||
if err := f(path, typ, changed_path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func allowed(path string, patterns ...string) bool {
|
||||
name := filepath.Base(path)
|
||||
for _, pat := range patterns {
|
||||
if matched, err := filepath.Match(pat, name); err == nil && matched {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func remote_hostname(path string) (string, string) {
|
||||
for q, val := range remote_dirs {
|
||||
if strings.HasPrefix(path, q) {
|
||||
return q, val
|
||||
}
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func resolve_remote_name(path, defval string) string {
|
||||
remote_dir, rh := remote_hostname(path)
|
||||
if remote_dir != "" && rh != "" {
|
||||
r, err := filepath.Rel(remote_dir, path)
|
||||
if err == nil {
|
||||
return rh + ":" + r
|
||||
}
|
||||
}
|
||||
return defval
|
||||
}
|
||||
|
||||
func walk(base string, patterns []string, names *utils.Set[string], pmap, path_name_map map[string]string) error {
|
||||
base, err := filepath.Abs(base)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return filepath.WalkDir(base, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
is_allowed := allowed(path, patterns...)
|
||||
if !is_allowed {
|
||||
if d.IsDir() {
|
||||
return fs.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
path, err = filepath.Abs(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name, err := filepath.Rel(base, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if name != "." {
|
||||
path_name_map[path] = name
|
||||
names.Add(name)
|
||||
pmap[name] = path
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (self *Collection) collect_files(left, right string) error {
|
||||
left_names, right_names := utils.NewSet[string](16), utils.NewSet[string](16)
|
||||
left_path_map, right_path_map := make(map[string]string, 16), make(map[string]string, 16)
|
||||
err := walk(left, conf.Ignore_name, left_names, left_path_map, path_name_map)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = walk(right, conf.Ignore_name, right_names, right_path_map, path_name_map); err != nil {
|
||||
return err
|
||||
}
|
||||
common_names := left_names.Intersect(right_names)
|
||||
changed_names := utils.NewSet[string](common_names.Len())
|
||||
for n := range common_names.Iterable() {
|
||||
ld, err := data_for_path(left_path_map[n])
|
||||
var rd string
|
||||
if err == nil {
|
||||
rd, err = data_for_path(right_path_map[n])
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ld != rd {
|
||||
changed_names.Add(n)
|
||||
self.add_change(left_path_map[n], right_path_map[n])
|
||||
} else {
|
||||
if lstat, err := os.Stat(left_path_map[n]); err == nil {
|
||||
if rstat, err := os.Stat(right_path_map[n]); err == nil {
|
||||
if lstat.Mode() != rstat.Mode() {
|
||||
// identical files with only a mode change
|
||||
changed_names.Add(n)
|
||||
self.add_change(left_path_map[n], right_path_map[n])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
removed := left_names.Subtract(common_names)
|
||||
added := right_names.Subtract(common_names)
|
||||
ahash, rhash := make(map[string]string, added.Len()), make(map[string]string, removed.Len())
|
||||
for a := range added.Iterable() {
|
||||
ahash[a], err = hash_for_path(right_path_map[a])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for r := range removed.Iterable() {
|
||||
rhash[r], err = hash_for_path(left_path_map[r])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for name, rh := range rhash {
|
||||
found := false
|
||||
for n, ah := range ahash {
|
||||
if ah == rh {
|
||||
ld, _ := data_for_path(left_path_map[name])
|
||||
rd, _ := data_for_path(right_path_map[n])
|
||||
if ld == rd {
|
||||
self.add_rename(left_path_map[name], right_path_map[n])
|
||||
added.Discard(n)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
self.add_removal(left_path_map[name])
|
||||
}
|
||||
}
|
||||
for name := range added.Iterable() {
|
||||
self.add_add(right_path_map[name])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func create_collection(left, right string) (ans *Collection, err error) {
|
||||
ans = &Collection{
|
||||
changes: make(map[string]string),
|
||||
renames: make(map[string]string),
|
||||
type_map: make(map[string]string),
|
||||
adds: utils.NewSet[string](32),
|
||||
removes: utils.NewSet[string](32),
|
||||
paths_to_highlight: utils.NewSet[string](32),
|
||||
all_paths: make([]string, 0, 32),
|
||||
}
|
||||
left_stat, err := os.Stat(left)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if left_stat.IsDir() {
|
||||
err = ans.collect_files(left, right)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
pl, err := filepath.Abs(left)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pr, err := filepath.Abs(right)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path_name_map[pl] = resolve_remote_name(pl, left)
|
||||
path_name_map[pr] = resolve_remote_name(pr, right)
|
||||
ans.add_change(pl, pr)
|
||||
}
|
||||
ans.finalize()
|
||||
return ans, err
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestDiffCollectWalk(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
j := func(x ...string) string { return filepath.Join(append([]string{tdir}, x...)...) }
|
||||
_ = os.MkdirAll(j("a", "b"), 0o700)
|
||||
_ = os.WriteFile(j("a/b/c"), nil, 0o600)
|
||||
_ = os.WriteFile(j("b"), nil, 0o600)
|
||||
_ = os.WriteFile(j("d"), nil, 0o600)
|
||||
_ = os.WriteFile(j("e"), nil, 0o600)
|
||||
_ = os.WriteFile(j("#d#"), nil, 0o600)
|
||||
_ = os.WriteFile(j("e~"), nil, 0o600)
|
||||
_ = os.MkdirAll(j("f"), 0o700)
|
||||
_ = os.WriteFile(j("f/g"), nil, 0o600)
|
||||
_ = os.WriteFile(j("h space"), nil, 0o600)
|
||||
|
||||
expected_names := utils.NewSetWithItems("d", "e", "f/g", "h space")
|
||||
expected_pmap := map[string]string{
|
||||
"d": j("d"),
|
||||
"e": j("e"),
|
||||
"f/g": j("f/g"),
|
||||
"h space": j("h space"),
|
||||
}
|
||||
names := utils.NewSet[string](16)
|
||||
pmap := make(map[string]string, 16)
|
||||
if err := walk(tdir, []string{"*~", "#*#", "b"}, names, pmap, map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if diff := cmp.Diff(
|
||||
utils.Sort(expected_names.AsSlice(), strings.Compare),
|
||||
utils.Sort(names.AsSlice(), strings.Compare),
|
||||
); diff != "" {
|
||||
t.Fatal(diff)
|
||||
}
|
||||
if diff := cmp.Diff(expected_pmap, pmap); diff != "" {
|
||||
t.Fatal(diff)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
// Copied from the Go stdlib, with modifications.
|
||||
//https://github.com/golang/go/raw/master/src/internal/diff/diff.go
|
||||
|
||||
// Copyright 2022 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A pair is a pair of values tracked for both the x and y side of a diff.
|
||||
// It is typically a pair of line indexes.
|
||||
type pair struct{ x, y int }
|
||||
|
||||
// Diff returns an anchored diff of the two texts old and new
|
||||
// in the “unified diff” format. If old and new are identical,
|
||||
// Diff returns a nil slice (no output).
|
||||
//
|
||||
// Unix diff implementations typically look for a diff with
|
||||
// the smallest number of lines inserted and removed,
|
||||
// which can in the worst case take time quadratic in the
|
||||
// number of lines in the texts. As a result, many implementations
|
||||
// either can be made to run for a long time or cut off the search
|
||||
// after a predetermined amount of work.
|
||||
//
|
||||
// In contrast, this implementation looks for a diff with the
|
||||
// smallest number of “unique” lines inserted and removed,
|
||||
// where unique means a line that appears just once in both old and new.
|
||||
// We call this an “anchored diff” because the unique lines anchor
|
||||
// the chosen matching regions. An anchored diff is usually clearer
|
||||
// than a standard diff, because the algorithm does not try to
|
||||
// reuse unrelated blank lines or closing braces.
|
||||
// The algorithm also guarantees to run in O(n log n) time
|
||||
// instead of the standard O(n²) time.
|
||||
//
|
||||
// Some systems call this approach a “patience diff,” named for
|
||||
// the “patience sorting” algorithm, itself named for a solitaire card game.
|
||||
// We avoid that name for two reasons. First, the name has been used
|
||||
// for a few different variants of the algorithm, so it is imprecise.
|
||||
// Second, the name is frequently interpreted as meaning that you have
|
||||
// to wait longer (to be patient) for the diff, meaning that it is a slower algorithm,
|
||||
// when in fact the algorithm is faster than the standard one.
|
||||
func Diff(oldName, old, newName, new string, num_of_context_lines int) []byte {
|
||||
if old == new {
|
||||
return nil
|
||||
}
|
||||
x := lines(old)
|
||||
y := lines(new)
|
||||
|
||||
// Print diff header.
|
||||
var out bytes.Buffer
|
||||
fmt.Fprintf(&out, "diff %s %s\n", oldName, newName)
|
||||
fmt.Fprintf(&out, "--- %s\n", oldName)
|
||||
fmt.Fprintf(&out, "+++ %s\n", newName)
|
||||
|
||||
// Loop over matches to consider,
|
||||
// expanding each match to include surrounding lines,
|
||||
// and then printing diff chunks.
|
||||
// To avoid setup/teardown cases outside the loop,
|
||||
// tgs returns a leading {0,0} and trailing {len(x), len(y)} pair
|
||||
// in the sequence of matches.
|
||||
var (
|
||||
done pair // printed up to x[:done.x] and y[:done.y]
|
||||
chunk pair // start lines of current chunk
|
||||
count pair // number of lines from each side in current chunk
|
||||
ctext []string // lines for current chunk
|
||||
)
|
||||
for _, m := range tgs(x, y) {
|
||||
if m.x < done.x {
|
||||
// Already handled scanning forward from earlier match.
|
||||
continue
|
||||
}
|
||||
|
||||
// Expand matching lines as far possible,
|
||||
// establishing that x[start.x:end.x] == y[start.y:end.y].
|
||||
// Note that on the first (or last) iteration we may (or definitey do)
|
||||
// have an empty match: start.x==end.x and start.y==end.y.
|
||||
start := m
|
||||
for start.x > done.x && start.y > done.y && x[start.x-1] == y[start.y-1] {
|
||||
start.x--
|
||||
start.y--
|
||||
}
|
||||
end := m
|
||||
for end.x < len(x) && end.y < len(y) && x[end.x] == y[end.y] {
|
||||
end.x++
|
||||
end.y++
|
||||
}
|
||||
|
||||
// Emit the mismatched lines before start into this chunk.
|
||||
// (No effect on first sentinel iteration, when start = {0,0}.)
|
||||
for _, s := range x[done.x:start.x] {
|
||||
ctext = append(ctext, "-"+s)
|
||||
count.x++
|
||||
}
|
||||
for _, s := range y[done.y:start.y] {
|
||||
ctext = append(ctext, "+"+s)
|
||||
count.y++
|
||||
}
|
||||
|
||||
// If we're not at EOF and have too few common lines,
|
||||
// the chunk includes all the common lines and continues.
|
||||
C := num_of_context_lines // number of context lines
|
||||
if (end.x < len(x) || end.y < len(y)) &&
|
||||
(end.x-start.x < C || (len(ctext) > 0 && end.x-start.x < 2*C)) {
|
||||
for _, s := range x[start.x:end.x] {
|
||||
ctext = append(ctext, " "+s)
|
||||
count.x++
|
||||
count.y++
|
||||
}
|
||||
done = end
|
||||
continue
|
||||
}
|
||||
|
||||
// End chunk with common lines for context.
|
||||
if len(ctext) > 0 {
|
||||
n := min(end.x-start.x, C)
|
||||
for _, s := range x[start.x : start.x+n] {
|
||||
ctext = append(ctext, " "+s)
|
||||
count.x++
|
||||
count.y++
|
||||
}
|
||||
done = pair{start.x + n, start.y + n}
|
||||
|
||||
// Format and emit chunk.
|
||||
// Convert line numbers to 1-indexed.
|
||||
// Special case: empty file shows up as 0,0 not 1,0.
|
||||
if count.x > 0 {
|
||||
chunk.x++
|
||||
}
|
||||
if count.y > 0 {
|
||||
chunk.y++
|
||||
}
|
||||
fmt.Fprintf(&out, "@@ -%d,%d +%d,%d @@\n", chunk.x, count.x, chunk.y, count.y)
|
||||
for _, s := range ctext {
|
||||
out.WriteString(s)
|
||||
}
|
||||
count.x = 0
|
||||
count.y = 0
|
||||
ctext = ctext[:0]
|
||||
}
|
||||
|
||||
// If we reached EOF, we're done.
|
||||
if end.x >= len(x) && end.y >= len(y) {
|
||||
break
|
||||
}
|
||||
|
||||
// Otherwise start a new chunk.
|
||||
chunk = pair{end.x - C, end.y - C}
|
||||
for _, s := range x[chunk.x:end.x] {
|
||||
ctext = append(ctext, " "+s)
|
||||
count.x++
|
||||
count.y++
|
||||
}
|
||||
done = end
|
||||
}
|
||||
|
||||
return out.Bytes()
|
||||
}
|
||||
|
||||
// lines returns the lines in the file x, including newlines.
|
||||
// If the file does not end in a newline, one is supplied
|
||||
// along with a warning about the missing newline.
|
||||
func lines(x string) []string {
|
||||
l := strings.SplitAfter(x, "\n")
|
||||
if l[len(l)-1] == "" {
|
||||
l = l[:len(l)-1]
|
||||
} else {
|
||||
// Treat last line as having a message about the missing newline attached,
|
||||
// using the same text as BSD/GNU diff (including the leading backslash).
|
||||
l[len(l)-1] += "\n\\ No newline at end of file\n"
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// tgs returns the pairs of indexes of the longest common subsequence
|
||||
// of unique lines in x and y, where a unique line is one that appears
|
||||
// once in x and once in y.
|
||||
//
|
||||
// The longest common subsequence algorithm is as described in
|
||||
// Thomas G. Szymanski, “A Special Case of the Maximal Common
|
||||
// Subsequence Problem,” Princeton TR #170 (January 1975),
|
||||
// available at https://research.swtch.com/tgs170.pdf.
|
||||
func tgs(x, y []string) []pair {
|
||||
// Count the number of times each string appears in a and b.
|
||||
// We only care about 0, 1, many, counted as 0, -1, -2
|
||||
// for the x side and 0, -4, -8 for the y side.
|
||||
// Using negative numbers now lets us distinguish positive line numbers later.
|
||||
m := make(map[string]int)
|
||||
for _, s := range x {
|
||||
if c := m[s]; c > -2 {
|
||||
m[s] = c - 1
|
||||
}
|
||||
}
|
||||
for _, s := range y {
|
||||
if c := m[s]; c > -8 {
|
||||
m[s] = c - 4
|
||||
}
|
||||
}
|
||||
|
||||
// Now unique strings can be identified by m[s] = -1+-4.
|
||||
//
|
||||
// Gather the indexes of those strings in x and y, building:
|
||||
// xi[i] = increasing indexes of unique strings in x.
|
||||
// yi[i] = increasing indexes of unique strings in y.
|
||||
// inv[i] = index j such that x[xi[i]] = y[yi[j]].
|
||||
var xi, yi, inv []int
|
||||
for i, s := range y {
|
||||
if m[s] == -1+-4 {
|
||||
m[s] = len(yi)
|
||||
yi = append(yi, i)
|
||||
}
|
||||
}
|
||||
for i, s := range x {
|
||||
if j, ok := m[s]; ok && j >= 0 {
|
||||
xi = append(xi, i)
|
||||
inv = append(inv, j)
|
||||
}
|
||||
}
|
||||
|
||||
// Apply Algorithm A from Szymanski's paper.
|
||||
// In those terms, A = J = inv and B = [0, n).
|
||||
// We add sentinel pairs {0,0}, and {len(x),len(y)}
|
||||
// to the returned sequence, to help the processing loop.
|
||||
J := inv
|
||||
n := len(xi)
|
||||
T := make([]int, n)
|
||||
L := make([]int, n)
|
||||
for i := range T {
|
||||
T[i] = n + 1
|
||||
}
|
||||
for i := range n {
|
||||
k := sort.Search(n, func(k int) bool {
|
||||
return T[k] >= J[i]
|
||||
})
|
||||
T[k] = J[i]
|
||||
L[i] = k + 1
|
||||
}
|
||||
k := 0
|
||||
for _, v := range L {
|
||||
if k < v {
|
||||
k = v
|
||||
}
|
||||
}
|
||||
seq := make([]pair, 2+k)
|
||||
seq[1+k] = pair{len(x), len(y)} // sentinel at end
|
||||
lastj := n
|
||||
for i := n - 1; i >= 0; i-- {
|
||||
if L[i] == k && J[i] < lastj {
|
||||
seq[k] = pair{xi[i], yi[J[i]]}
|
||||
k--
|
||||
}
|
||||
}
|
||||
seq[0] = pair{0, 0} // sentinel at start
|
||||
return seq
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/highlight"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/images"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
var _ = os.WriteFile
|
||||
|
||||
type prefer_light_colors bool
|
||||
|
||||
func (s prefer_light_colors) StyleName() string {
|
||||
return utils.IfElse(bool(s), conf.Pygments_style, conf.Dark_pygments_style)
|
||||
}
|
||||
|
||||
func (s prefer_light_colors) UseLightColors() bool { return bool(s) }
|
||||
func (s prefer_light_colors) SyntaxAliases() map[string]string { return conf.Syntax_aliases }
|
||||
func (s prefer_light_colors) TextForPath(path string) (string, error) { return data_for_path(path) }
|
||||
|
||||
var highlighter = sync.OnceValue(func() highlight.Highlighter {
|
||||
return highlight.NewHighlighter(sanitize)
|
||||
})
|
||||
|
||||
func highlight_all(paths []string, light bool) {
|
||||
ctx := images.Context{}
|
||||
srd := prefer_light_colors(light)
|
||||
if err := ctx.SafeParallel(0, len(paths), func(nums <-chan int) {
|
||||
for i := range nums {
|
||||
path := paths[i]
|
||||
raw, err := highlighter().HighlightFile(path, &srd)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if light {
|
||||
light_highlighted_lines_cache.Set(path, text_to_lines(raw))
|
||||
} else {
|
||||
dark_highlighted_lines_cache.Set(path, text_to_lines(raw))
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/kittens/ssh"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func load_config(opts *Options) (ans *Config, err error) {
|
||||
ans = NewConfig()
|
||||
p := config.ConfigParser{LineHandler: ans.Parse}
|
||||
err = p.LoadConfig("diff.conf", opts.Config, opts.Override)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ans.KeyboardShortcuts = config.ResolveShortcuts(ans.KeyboardShortcuts)
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
var conf *Config
|
||||
var opts *Options
|
||||
var lp *loop.Loop
|
||||
|
||||
var temp_files []string
|
||||
|
||||
func resolve_path(path string) (ans string, is_dir bool, err error) {
|
||||
var s fs.FileInfo
|
||||
if s, err = os.Stat(path); err != nil {
|
||||
return
|
||||
} else {
|
||||
if s.Mode()&fs.ModeNamedPipe != 0 {
|
||||
var src, dest *os.File
|
||||
if src, err = os.Open(path); err != nil {
|
||||
return
|
||||
}
|
||||
defer src.Close()
|
||||
if dest, err = os.CreateTemp("", fmt.Sprintf("*-pipe-%s", filepath.Base(path))); err != nil {
|
||||
return
|
||||
}
|
||||
defer dest.Close()
|
||||
temp_files = append(temp_files, dest.Name())
|
||||
if _, err = io.Copy(dest, src); err != nil {
|
||||
return
|
||||
}
|
||||
return dest.Name(), false, nil
|
||||
|
||||
} else {
|
||||
return path, s.IsDir(), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func get_ssh_file(hostname, rpath string) (string, error) {
|
||||
tdir, err := os.MkdirTemp("", "*-"+hostname)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
add_remote_dir(tdir)
|
||||
is_abs := strings.HasPrefix(rpath, "/")
|
||||
for strings.HasPrefix(rpath, "/") {
|
||||
rpath = rpath[1:]
|
||||
}
|
||||
cmd := []string{ssh.SSHExe(), hostname, "tar", "--dereference", "--create", "--file", "-"}
|
||||
if is_abs {
|
||||
cmd = append(cmd, "-C", "/")
|
||||
}
|
||||
cmd = append(cmd, rpath)
|
||||
c := exec.Command(cmd[0], cmd[1:]...)
|
||||
c.Stdin, c.Stderr = os.Stdin, os.Stderr
|
||||
stdout, err := c.Output()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Failed to ssh into remote host %s to get file %s with error: %w", hostname, rpath, err)
|
||||
}
|
||||
tf := tar.NewReader(bytes.NewReader(stdout))
|
||||
count, err := utils.ExtractAllFromTar(tf, tdir, utils.TarExtractOptions{DontPreserveSuidAndSgid: true})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Failed to untar data from remote host %s to get file %s with error: %w", hostname, rpath, err)
|
||||
}
|
||||
ans := filepath.Join(tdir, rpath)
|
||||
if _, err = os.Lstat(ans); err == nil {
|
||||
// The archive contains rpath itself, which is either the requested
|
||||
// file or directory
|
||||
return ans, nil
|
||||
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||
return "", err
|
||||
}
|
||||
// rpath was expanded by the remote shell, for example, ~/file, so
|
||||
// look for the single file in the archive
|
||||
if count == 1 {
|
||||
if err = filepath.WalkDir(tdir, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !d.IsDir() {
|
||||
ans = path
|
||||
return fs.SkipAll
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func get_remote_file(path string) (string, error) {
|
||||
if strings.HasPrefix(path, "ssh:") {
|
||||
parts := strings.SplitN(path, ":", 3)
|
||||
if len(parts) == 3 {
|
||||
return get_ssh_file(parts[1], parts[2])
|
||||
}
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func main(_ *cli.Command, opts_ *Options, args []string) (rc int, err error) {
|
||||
opts = opts_
|
||||
conf, err = load_config(opts)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if len(args) != 2 {
|
||||
return 1, fmt.Errorf("You must specify exactly two files/directories to compare")
|
||||
}
|
||||
if err = set_diff_command(conf.Diff_cmd); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
switch conf.Color_scheme {
|
||||
case Color_scheme_light:
|
||||
use_light_colors = true
|
||||
case Color_scheme_dark:
|
||||
use_light_colors = false
|
||||
case Color_scheme_auto:
|
||||
use_light_colors = false
|
||||
}
|
||||
init_caches()
|
||||
defer func() {
|
||||
for tdir := range remote_dirs {
|
||||
// Directories extracted from the remote host can be read-only.
|
||||
// This is best effort cleanup of a temp dir, so errors are ignored.
|
||||
_ = filepath.WalkDir(tdir, func(path string, d fs.DirEntry, err error) error {
|
||||
if err == nil && d.IsDir() {
|
||||
_ = os.Chmod(path, 0o700)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
os.RemoveAll(tdir)
|
||||
}
|
||||
}()
|
||||
left, err := get_remote_file(args[0])
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
right, err := get_remote_file(args[1])
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
defer func() {
|
||||
for _, path := range temp_files {
|
||||
os.Remove(path)
|
||||
}
|
||||
}()
|
||||
var left_is_dir, right_is_dir bool
|
||||
if left, left_is_dir, err = resolve_path(left); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if right, right_is_dir, err = resolve_path(right); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if left_is_dir != right_is_dir {
|
||||
return 1, fmt.Errorf("The items to be diffed should both be either directories or files. Comparing a directory to a file is not valid.'")
|
||||
}
|
||||
|
||||
lp, err = loop.New()
|
||||
loop.MouseTrackingMode(lp, loop.BUTTONS_AND_DRAG_MOUSE_TRACKING)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
lp.ColorSchemeChangeNotifications()
|
||||
h := Handler{left: left, right: right, lp: lp}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
lp.SetCursorShape(loop.BAR_CURSOR, true)
|
||||
lp.AllowLineWrapping(false)
|
||||
lp.SetWindowTitle(fmt.Sprintf("%s vs. %s", left, right))
|
||||
lp.QueryCapabilities()
|
||||
h.initialize()
|
||||
return "", nil
|
||||
}
|
||||
lp.OnCapabilitiesReceived = func(tc loop.TerminalCapabilities) error {
|
||||
if !tc.KeyboardProtocol {
|
||||
return fmt.Errorf("This terminal does not support the kitty keyboard protocol, or you are running inside a terminal multiplexer that is blocking querying for kitty keyboard protocol support. The diff kitten cannot function without it.")
|
||||
}
|
||||
h.on_capabilities_received(tc)
|
||||
return nil
|
||||
}
|
||||
lp.OnWakeup = h.on_wakeup
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
lp.SetCursorShape(loop.BLOCK_CURSOR, true)
|
||||
h.finalize()
|
||||
return ""
|
||||
}
|
||||
lp.OnResize = h.on_resize
|
||||
lp.OnKeyEvent = h.on_key_event
|
||||
lp.OnText = h.on_text
|
||||
lp.OnMouseEvent = h.on_mouse_event
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
from functools import partial
|
||||
|
||||
from kitty.conf.types import Definition
|
||||
from kitty.constants import appname
|
||||
from kitty.simple_cli_definitions import CONFIG_HELP, CompletionSpec
|
||||
|
||||
|
||||
def main(args: list[str]) -> None:
|
||||
raise SystemExit('Must be run as kitten diff')
|
||||
|
||||
|
||||
definition = Definition(
|
||||
'!kittens.diff',
|
||||
)
|
||||
|
||||
agr = definition.add_group
|
||||
egr = definition.end_group
|
||||
opt = definition.add_option
|
||||
map = definition.add_map
|
||||
mma = definition.add_mouse_map
|
||||
|
||||
# diff {{{
|
||||
agr('diff', 'Diffing')
|
||||
|
||||
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('num_context_lines', '3', option_type='positive_int', long_text='The number of lines of context to show around each change.')
|
||||
|
||||
opt(
|
||||
'diff_cmd',
|
||||
'auto',
|
||||
long_text="""
|
||||
The diff command to use. Must contain the placeholder :code:`_CONTEXT_` which
|
||||
will be replaced by the number of lines of context. A few special values are allowed:
|
||||
:code:`auto` will automatically pick an available diff implementation. :code:`builtin`
|
||||
will use the anchored diff algorithm from the Go standard library. :code:`git` will
|
||||
use the git command to do the diffing. :code:`diff` will use the diff command to
|
||||
do the diffing.
|
||||
""",
|
||||
)
|
||||
|
||||
opt('replace_tab_by', '\\x20\\x20\\x20\\x20', option_type='python_string', long_text='The string to replace tabs with. Default is to use four spaces.')
|
||||
|
||||
opt(
|
||||
'+ignore_name',
|
||||
'',
|
||||
ctype='string',
|
||||
add_to_default=False,
|
||||
long_text="""
|
||||
A glob pattern that is matched against only the filename of files and directories. Matching
|
||||
files and directories are ignored when scanning the filesystem to look for files to diff.
|
||||
Can be specified multiple times to use multiple patterns. For example::
|
||||
|
||||
ignore_name .git
|
||||
ignore_name *~
|
||||
ignore_name *.pyc
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'mark_moved_lines',
|
||||
'yes',
|
||||
option_type='to_bool',
|
||||
long_text="""
|
||||
Highlight lines that are moved, that is removed from the left and added to the right
|
||||
differently, using the :opt:`moved_bg` color.""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'word_diff_mode',
|
||||
'words',
|
||||
choices=('words', 'central'),
|
||||
long_text="""
|
||||
The algorithm to use for highlighting which parts of changed lines differ.
|
||||
When set to :code:`words`, changed words in each changed line are highlighted.
|
||||
When set to :code:`central`, the central changed region of each changed line is
|
||||
highlighted at the byte level. The :code:`words` mode is generally more useful
|
||||
as it shows exactly which words changed. Note that the :code:`words` mode
|
||||
only applies when a changed chunk has equal numbers of added and removed lines.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'word_regex',
|
||||
r'[^\s\p{P}]+',
|
||||
long_text="""
|
||||
The regular expression used to define a word when :opt:`word_diff_mode` is
|
||||
:code:`words`. The default value matches any run of non-whitespace and
|
||||
non-punctuation characters. The expression must be a valid Go regular expression.
|
||||
If an invalid expression is provided, diff will fail with an error.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'sticky_header',
|
||||
'yes',
|
||||
option_type='to_bool',
|
||||
long_text="""
|
||||
When scrolled past the header of a file, keep the file's name and separator
|
||||
pinned to the top of the screen.
|
||||
""",
|
||||
)
|
||||
|
||||
egr() # }}}
|
||||
|
||||
# colors {{{
|
||||
agr('colors', 'Colors')
|
||||
|
||||
opt(
|
||||
'color_scheme',
|
||||
'auto',
|
||||
choices=('auto', 'light', 'dark'),
|
||||
long_text="""
|
||||
Whether to use the light or dark colors. The default of :code:`auto` means
|
||||
to follow the parent terminal color scheme. Note that the actual colors used
|
||||
for dark schemes are set by the :code:`dark_*` settings below and the non-prefixed
|
||||
settings are used for light colors.
|
||||
""",
|
||||
)
|
||||
|
||||
opt(
|
||||
'pygments_style',
|
||||
'default',
|
||||
long_text="""
|
||||
The pygments color scheme to use for syntax highlighting. See :link:`pygments
|
||||
builtin styles <https://pygments.org/styles/>` for a list of schemes. Note that
|
||||
this **does not** change the colors used for diffing,
|
||||
only the colors used for syntax highlighting. To change the general colors use the settings below.
|
||||
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. Note that
|
||||
this **does not** change the colors used for diffing,
|
||||
only the colors used for syntax highlighting. To change the general colors use the settings below.
|
||||
This sets the colors used for dark color schemes, use :opt:`pygments_style` to change the
|
||||
colors for light color schemes.""",
|
||||
)
|
||||
|
||||
opt('foreground', 'black', option_type='to_color', long_text='Basic colors')
|
||||
opt('dark_foreground', '#f8f8f2', option_type='to_color')
|
||||
|
||||
dark_bg = '#212830'
|
||||
opt(
|
||||
'background',
|
||||
'white',
|
||||
option_type='to_color',
|
||||
)
|
||||
opt(
|
||||
'dark_background',
|
||||
dark_bg,
|
||||
option_type='to_color',
|
||||
)
|
||||
|
||||
opt('title_fg', 'black', option_type='to_color', long_text='Title colors')
|
||||
opt('dark_title_fg', 'white', option_type='to_color')
|
||||
|
||||
opt(
|
||||
'title_bg',
|
||||
'white',
|
||||
option_type='to_color',
|
||||
)
|
||||
opt(
|
||||
'dark_title_bg',
|
||||
dark_bg,
|
||||
option_type='to_color',
|
||||
)
|
||||
|
||||
opt('margin_bg', '#fafbfc', option_type='to_color', long_text='Margin colors')
|
||||
opt('dark_margin_bg', dark_bg, option_type='to_color')
|
||||
|
||||
opt('margin_fg', '#aaaaaa', option_type='to_color')
|
||||
opt('dark_margin_fg', '#aaaaaa', option_type='to_color')
|
||||
|
||||
opt('removed_bg', '#ffeef0', option_type='to_color', long_text='Removed text backgrounds')
|
||||
opt('dark_removed_bg', '#352c33', option_type='to_color')
|
||||
|
||||
opt('highlight_removed_bg', '#fdb8c0', option_type='to_color')
|
||||
opt('dark_highlight_removed_bg', '#5c3539', option_type='to_color')
|
||||
|
||||
opt('removed_margin_bg', '#ffdce0', option_type='to_color')
|
||||
opt('dark_removed_margin_bg', '#5c3539', option_type='to_color')
|
||||
|
||||
opt('added_bg', '#e6ffed', option_type='to_color', long_text='Added text backgrounds')
|
||||
opt('dark_added_bg', '#263834', option_type='to_color')
|
||||
|
||||
opt('highlight_added_bg', '#acf2bd', option_type='to_color')
|
||||
opt('dark_highlight_added_bg', '#31503d', option_type='to_color')
|
||||
|
||||
opt('added_margin_bg', '#cdffd8', option_type='to_color')
|
||||
opt('dark_added_margin_bg', '#31503d', option_type='to_color')
|
||||
|
||||
opt('moved_bg', '#fffde7', option_type='to_color', long_text='Moved text backgrounds (same text that was removed in one place and added in another)')
|
||||
opt('dark_moved_bg', '#003333', option_type='to_color')
|
||||
|
||||
opt('moved_margin_bg', '#fff3b0', option_type='to_color')
|
||||
opt('dark_moved_margin_bg', '#00495b', option_type='to_color')
|
||||
|
||||
opt('filler_bg', '#fafbfc', option_type='to_color', long_text='Filler (empty) line background')
|
||||
opt('dark_filler_bg', '#262c36', option_type='to_color')
|
||||
|
||||
opt('margin_filler_bg', 'none', option_type='to_color_or_none', long_text='Filler (empty) line background in margins, defaults to the filler background')
|
||||
opt('dark_margin_filler_bg', 'none', option_type='to_color_or_none')
|
||||
|
||||
|
||||
opt('hunk_margin_bg', '#dbedff', option_type='to_color', long_text='Hunk header colors')
|
||||
opt('dark_hunk_margin_bg', '#0c2d6b', option_type='to_color')
|
||||
|
||||
opt('hunk_bg', '#f1f8ff', option_type='to_color')
|
||||
opt('dark_hunk_bg', '#253142', option_type='to_color')
|
||||
|
||||
opt('search_bg', '#444', option_type='to_color', long_text='Highlighting')
|
||||
opt('dark_search_bg', '#2c599c', option_type='to_color')
|
||||
|
||||
opt('search_fg', 'white', option_type='to_color')
|
||||
opt('dark_search_fg', 'white', option_type='to_color')
|
||||
|
||||
opt('select_bg', '#b4d5fe', option_type='to_color')
|
||||
opt('dark_select_bg', '#2c599c', option_type='to_color')
|
||||
|
||||
opt('select_fg', 'black', option_type='to_color_or_none')
|
||||
opt('dark_select_fg', 'white', option_type='to_color_or_none')
|
||||
egr() # }}}
|
||||
|
||||
# shortcuts {{{
|
||||
agr('shortcuts', 'Keyboard shortcuts')
|
||||
|
||||
map(
|
||||
'Quit',
|
||||
'quit --allow-fallback=shifted,ascii q quit',
|
||||
)
|
||||
map(
|
||||
'Quit',
|
||||
'quit esc quit',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll down',
|
||||
'scroll_down --allow-fallback=shifted,ascii j scroll_by 1',
|
||||
)
|
||||
map(
|
||||
'Scroll down',
|
||||
'scroll_down down scroll_by 1',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll up',
|
||||
'scroll_up --allow-fallback=shifted,ascii k scroll_by -1',
|
||||
)
|
||||
map(
|
||||
'Scroll up',
|
||||
'scroll_up up scroll_by -1',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to top',
|
||||
'scroll_top home scroll_to start',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to bottom',
|
||||
'scroll_bottom end scroll_to end',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to next page',
|
||||
'scroll_page_down page_down scroll_to next-page',
|
||||
)
|
||||
map(
|
||||
'Scroll to next page',
|
||||
'scroll_page_down space scroll_to next-page',
|
||||
)
|
||||
map(
|
||||
'Scroll to next page',
|
||||
'scroll_page_down --allow-fallback=shifted,ascii ctrl+f scroll_to next-page',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to previous page',
|
||||
'scroll_page_up page_up scroll_to prev-page',
|
||||
)
|
||||
map(
|
||||
'Scroll to previous page',
|
||||
'scroll_page_up --allow-fallback=shifted,ascii ctrl+b scroll_to prev-page',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll down half page',
|
||||
'scroll_half_page_down --allow-fallback=shifted,ascii ctrl+d scroll_to next-half-page',
|
||||
)
|
||||
map(
|
||||
'Scroll up half page',
|
||||
'scroll_half_page_up --allow-fallback=shifted,ascii ctrl+u scroll_to prev-half-page',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to next change',
|
||||
'next_change --allow-fallback=shifted,ascii n scroll_to next-change',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to previous change',
|
||||
'prev_change --allow-fallback=shifted,ascii p scroll_to prev-change',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to next file',
|
||||
'next_file --allow-fallback=shifted,ascii shift+j scroll_to next-file',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to previous file',
|
||||
'prev_file --allow-fallback=shifted,ascii shift+k scroll_to prev-file',
|
||||
)
|
||||
|
||||
map(
|
||||
'Show all context',
|
||||
'all_context --allow-fallback=shifted,ascii a change_context all',
|
||||
)
|
||||
|
||||
map(
|
||||
'Show default context',
|
||||
'default_context = change_context default',
|
||||
)
|
||||
|
||||
map(
|
||||
'Increase context',
|
||||
'increase_context + change_context 5',
|
||||
)
|
||||
|
||||
map(
|
||||
'Decrease context',
|
||||
'decrease_context - change_context -5',
|
||||
)
|
||||
|
||||
map(
|
||||
'Search forward',
|
||||
'search_forward / start_search regex forward',
|
||||
)
|
||||
|
||||
map(
|
||||
'Search backward',
|
||||
'search_backward ? start_search regex backward',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to next search match',
|
||||
'next_match . scroll_to next-match',
|
||||
)
|
||||
map(
|
||||
'Scroll to next search match',
|
||||
'next_match > scroll_to next-match',
|
||||
)
|
||||
|
||||
map(
|
||||
'Scroll to previous search match',
|
||||
'prev_match , scroll_to prev-match',
|
||||
)
|
||||
map(
|
||||
'Scroll to previous search match',
|
||||
'prev_match < scroll_to prev-match',
|
||||
)
|
||||
|
||||
map(
|
||||
'Search forward (no regex)',
|
||||
'search_forward_simple --allow-fallback=shifted,ascii f start_search substring forward',
|
||||
)
|
||||
|
||||
map(
|
||||
'Search backward (no regex)',
|
||||
'search_backward_simple --allow-fallback=shifted,ascii b start_search substring backward',
|
||||
)
|
||||
|
||||
map('Copy selection to clipboard', 'copy_to_clipboard --allow-fallback=shifted,ascii y copy_to_clipboard')
|
||||
map(
|
||||
'Copy selection to clipboard or exit if no selection is present',
|
||||
'copy_to_clipboard_or_exit --allow-fallback=shifted,ascii ctrl+c copy_to_clipboard_or_exit',
|
||||
)
|
||||
|
||||
egr() # }}}
|
||||
|
||||
OPTIONS = partial(
|
||||
"""\
|
||||
--context
|
||||
type=int
|
||||
default=-1
|
||||
Number of lines of context to show between changes. Negative values use the
|
||||
number set in :file:`diff.conf`.
|
||||
|
||||
|
||||
--config
|
||||
type=list
|
||||
completion=type:file ext:conf group:"Config files" kwds:none,NONE
|
||||
{config_help}
|
||||
|
||||
|
||||
--override -o
|
||||
type=list
|
||||
Override individual configuration options, can be specified multiple times.
|
||||
Syntax: :italic:`name=value`. For example: :italic:`-o background=gray`
|
||||
|
||||
""".format,
|
||||
config_help=CONFIG_HELP.format(conf_name='diff', appname=appname),
|
||||
)
|
||||
help_text = 'Show a side-by-side diff of the specified files/directories. You can also use :italic:`ssh:hostname:remote-file-path` to diff remote files.'
|
||||
usage = 'file_or_directory_left file_or_directory_right'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
elif __name__ == '__doc__':
|
||||
from kitty.guess_mime_type import text_mimes
|
||||
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = usage
|
||||
cd['options'] = OPTIONS
|
||||
cd['help_text'] = help_text
|
||||
cd['short_desc'] = 'Pretty, side-by-side diffing of files and images'
|
||||
mimes = ' '.join(f'mime:{x}' for x in ('text/*', 'image/*') + tuple(text_mimes))
|
||||
cd['args_completion'] = CompletionSpec.from_string(f'type:file {mimes} group:"Text and image files"')
|
||||
elif __name__ == '__conf__':
|
||||
sys.options_definition = definition # type: ignore
|
||||
@@ -0,0 +1,227 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type KittyOpts struct {
|
||||
Wheel_scroll_multiplier float64
|
||||
Copy_on_select bool
|
||||
}
|
||||
|
||||
func read_relevant_kitty_opts() KittyOpts {
|
||||
ans := KittyOpts{Wheel_scroll_multiplier: kitty.KittyConfigDefaults.Wheel_scroll_multiplier}
|
||||
handle_line := func(key, val string) error {
|
||||
switch key {
|
||||
case "wheel_scroll_multiplier":
|
||||
v, err := strconv.ParseFloat(val, 64)
|
||||
if err == nil {
|
||||
ans.Wheel_scroll_multiplier = v
|
||||
}
|
||||
case "copy_on_select":
|
||||
ans.Copy_on_select = strings.ToLower(val) == "clipboard"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config.ReadKittyConfig(handle_line)
|
||||
return ans
|
||||
}
|
||||
|
||||
var RelevantKittyOpts = sync.OnceValue(func() KittyOpts {
|
||||
return read_relevant_kitty_opts()
|
||||
})
|
||||
|
||||
func (self *Handler) handle_wheel_event(up bool) {
|
||||
amt := int(math.Round(RelevantKittyOpts().Wheel_scroll_multiplier))
|
||||
if amt == 0 {
|
||||
amt = 1
|
||||
}
|
||||
if up {
|
||||
amt *= -1
|
||||
}
|
||||
_ = self.dispatch_action(`scroll_by`, strconv.Itoa(amt))
|
||||
}
|
||||
|
||||
type line_pos struct {
|
||||
min_x, max_x int
|
||||
y ScrollPos
|
||||
}
|
||||
|
||||
func (self *line_pos) MinX() int { return self.min_x }
|
||||
func (self *line_pos) MaxX() int { return self.max_x }
|
||||
func (self *line_pos) Equal(other tui.LinePos) bool {
|
||||
if o, ok := other.(*line_pos); ok {
|
||||
return self.y == o.y
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *line_pos) LessThan(other tui.LinePos) bool {
|
||||
if o, ok := other.(*line_pos); ok {
|
||||
return self.y.Less(o.y)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Handler) line_pos_from_pos(x int, pos ScrollPos) *line_pos {
|
||||
ans := line_pos{min_x: self.logical_lines.margin_size, y: pos}
|
||||
available_cols := self.logical_lines.columns / 2
|
||||
if x >= available_cols {
|
||||
ans.min_x += available_cols
|
||||
ans.max_x = utils.Max(ans.min_x, ans.min_x+self.logical_lines.ScreenLineAt(pos).right.wcswidth()-1)
|
||||
} else {
|
||||
ans.max_x = utils.Max(ans.min_x, ans.min_x+self.logical_lines.ScreenLineAt(pos).left.wcswidth()-1)
|
||||
}
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *Handler) start_mouse_selection(ev *loop.MouseEvent) {
|
||||
available_cols := self.logical_lines.columns / 2
|
||||
if ev.Cell.Y >= self.screen_size.num_lines || ev.Cell.X < self.logical_lines.margin_size || (ev.Cell.X >= available_cols && ev.Cell.X < available_cols+self.logical_lines.margin_size) {
|
||||
return
|
||||
}
|
||||
pos := self.scroll_pos
|
||||
self.logical_lines.IncrementScrollPosBy(&pos, ev.Cell.Y)
|
||||
ll := self.logical_lines.At(pos.logical_line)
|
||||
if ll.line_type == EMPTY_LINE || ll.line_type == IMAGE_LINE {
|
||||
return
|
||||
}
|
||||
self.mouse_selection.StartNewSelection(ev, self.line_pos_from_pos(ev.Cell.X, pos), 0, self.screen_size.num_lines-1, self.screen_size.cell_width, self.screen_size.cell_height)
|
||||
}
|
||||
|
||||
func (self *Handler) drag_scroll_tick(timer_id loop.IdType) error {
|
||||
return self.mouse_selection.DragScrollTick(timer_id, self.lp, self.drag_scroll_tick, func(amt int, ev *loop.MouseEvent) error {
|
||||
if self.scroll_lines(amt) != 0 {
|
||||
self.do_update_mouse_selection(ev)
|
||||
self.draw_screen()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
|
||||
func (self *Handler) update_mouse_selection(ev *loop.MouseEvent) {
|
||||
if !self.mouse_selection.IsActive() {
|
||||
return
|
||||
}
|
||||
if self.mouse_selection.OutOfVerticalBounds(ev) {
|
||||
self.mouse_selection.DragScroll(ev, self.lp, self.drag_scroll_tick)
|
||||
return
|
||||
}
|
||||
if self.do_update_mouse_selection(ev) {
|
||||
self.draw_screen()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) do_update_mouse_selection(ev *loop.MouseEvent) (changed bool) {
|
||||
pos := self.scroll_pos
|
||||
y := ev.Cell.Y
|
||||
y = utils.Max(0, utils.Min(y, self.screen_size.num_lines-1))
|
||||
self.logical_lines.IncrementScrollPosBy(&pos, y)
|
||||
x := self.mouse_selection.StartLine().MinX()
|
||||
return self.mouse_selection.Update(ev, self.line_pos_from_pos(x, pos))
|
||||
}
|
||||
|
||||
func (self *Handler) clear_mouse_selection() {
|
||||
self.mouse_selection.Clear()
|
||||
}
|
||||
|
||||
func (self *Handler) text_for_current_mouse_selection() string {
|
||||
if self.mouse_selection.IsEmpty() {
|
||||
return ""
|
||||
}
|
||||
text := make([]byte, 0, 2048)
|
||||
start_pos, end_pos := *self.mouse_selection.StartLine().(*line_pos), *self.mouse_selection.EndLine().(*line_pos)
|
||||
|
||||
// if start is after end, swap them
|
||||
if end_pos.y.Less(start_pos.y) {
|
||||
start_pos, end_pos = end_pos, start_pos
|
||||
}
|
||||
|
||||
start, end := start_pos.y, end_pos.y
|
||||
is_left := start_pos.min_x == self.logical_lines.margin_size
|
||||
|
||||
line_for_pos := func(pos ScrollPos) string {
|
||||
if is_left {
|
||||
return self.logical_lines.ScreenLineAt(pos).left.marked_up_text
|
||||
}
|
||||
return self.logical_lines.ScreenLineAt(pos).right.marked_up_text
|
||||
}
|
||||
|
||||
for pos, prev_ll_idx := start, start.logical_line; pos.Less(end) || pos == end; {
|
||||
ll := self.logical_lines.At(pos.logical_line)
|
||||
var line string
|
||||
switch ll.line_type {
|
||||
case EMPTY_LINE:
|
||||
case IMAGE_LINE:
|
||||
if pos.screen_line < ll.image_lines_offset {
|
||||
line = line_for_pos(pos)
|
||||
}
|
||||
default:
|
||||
line = line_for_pos(pos)
|
||||
}
|
||||
line = wcswidth.StripEscapeCodes(line)
|
||||
s, e := self.mouse_selection.LineBounds(self.line_pos_from_pos(start_pos.min_x, pos))
|
||||
s -= start_pos.min_x
|
||||
e -= start_pos.min_x
|
||||
line = wcswidth.TruncateToVisualLength(line, e+1)
|
||||
if s > 0 {
|
||||
prefix := wcswidth.TruncateToVisualLength(line, s)
|
||||
line = line[len(prefix):]
|
||||
}
|
||||
// TODO: look at the original line from the source and handle leading tabs as per it
|
||||
if pos.logical_line > prev_ll_idx {
|
||||
line = "\n" + line
|
||||
}
|
||||
prev_ll_idx = pos.logical_line
|
||||
if line != "" {
|
||||
text = append(text, line...)
|
||||
}
|
||||
if self.logical_lines.IncrementScrollPosBy(&pos, 1) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return utils.UnsafeBytesToString(text)
|
||||
}
|
||||
|
||||
func (self *Handler) finish_mouse_selection(ev *loop.MouseEvent) {
|
||||
if !self.mouse_selection.IsActive() {
|
||||
return
|
||||
}
|
||||
self.update_mouse_selection(ev)
|
||||
self.mouse_selection.Finish()
|
||||
text := self.text_for_current_mouse_selection()
|
||||
if text != "" {
|
||||
if RelevantKittyOpts().Copy_on_select {
|
||||
self.lp.CopyTextToClipboard(text)
|
||||
} else {
|
||||
self.lp.CopyTextToPrimarySelection(text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) add_mouse_selection_to_line(line_pos ScrollPos, y int) string {
|
||||
if self.mouse_selection.IsEmpty() {
|
||||
return ""
|
||||
}
|
||||
selection_sgr := format_as_sgr.selection
|
||||
x := self.mouse_selection.StartLine().MinX()
|
||||
return self.mouse_selection.LineFormatSuffix(self.line_pos_from_pos(x, line_pos), selection_sgr[2:len(selection_sgr)-1], y)
|
||||
}
|
||||
@@ -0,0 +1,655 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
parallel "github.com/kovidgoyal/go-parallel"
|
||||
"github.com/kovidgoyal/kitty/tools/simdstring"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/images"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
const GIT_DIFF = `git diff --no-color --no-ext-diff --exit-code -U_CONTEXT_ --no-index --`
|
||||
const DIFF_DIFF = `diff -p -U _CONTEXT_ --`
|
||||
|
||||
var diff_cmd []string
|
||||
|
||||
var GitExe = sync.OnceValue(func() string {
|
||||
return utils.FindExe("git")
|
||||
})
|
||||
|
||||
var DiffExe = sync.OnceValue(func() string {
|
||||
return utils.FindExe("diff")
|
||||
})
|
||||
|
||||
func find_differ() {
|
||||
if GitExe() != "git" && exec.Command(GitExe(), "--help").Run() == nil {
|
||||
diff_cmd, _ = shlex.Split(GIT_DIFF)
|
||||
} else if DiffExe() != "diff" && exec.Command(DiffExe(), "--help").Run() == nil {
|
||||
diff_cmd, _ = shlex.Split(DIFF_DIFF)
|
||||
} else {
|
||||
diff_cmd = []string{}
|
||||
}
|
||||
}
|
||||
|
||||
func set_diff_command(q string) error {
|
||||
switch q {
|
||||
case "auto":
|
||||
find_differ()
|
||||
case "builtin", "":
|
||||
diff_cmd = []string{}
|
||||
case "diff":
|
||||
diff_cmd, _ = shlex.Split(DIFF_DIFF)
|
||||
case "git":
|
||||
diff_cmd, _ = shlex.Split(GIT_DIFF)
|
||||
default:
|
||||
c, err := shlex.Split(q)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
diff_cmd = c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Region represents a highlighted byte range within a line.
|
||||
type Region struct{ offset, size int }
|
||||
|
||||
// Center holds the highlighted regions for the left (removed) and right (added) sides of a changed line pair.
|
||||
type Center struct {
|
||||
left_regions []Region
|
||||
right_regions []Region
|
||||
}
|
||||
|
||||
type Chunk struct {
|
||||
is_context bool
|
||||
left_start, right_start int
|
||||
left_count, right_count int
|
||||
centers []Center
|
||||
}
|
||||
|
||||
func (self *Chunk) add_line() {
|
||||
self.right_count++
|
||||
}
|
||||
|
||||
func (self *Chunk) remove_line() {
|
||||
self.left_count++
|
||||
}
|
||||
|
||||
func (self *Chunk) context_line() {
|
||||
self.left_count++
|
||||
self.right_count++
|
||||
}
|
||||
|
||||
// changed_center computes the central changed region of left/right at the byte level.
|
||||
func changed_center(left, right string) (ans Center) {
|
||||
if len(left) > 0 && len(right) > 0 {
|
||||
ll, rl := len(left), len(right)
|
||||
ml := utils.Min(ll, rl)
|
||||
offset := 0
|
||||
for ; offset < ml && left[offset] == right[offset]; offset++ {
|
||||
}
|
||||
suffix_count := 0
|
||||
for ; suffix_count < ml && left[ll-1-suffix_count] == right[rl-1-suffix_count]; suffix_count++ {
|
||||
}
|
||||
left_size := ll - suffix_count - offset
|
||||
right_size := rl - suffix_count - offset
|
||||
if left_size > 0 {
|
||||
ans.left_regions = []Region{{offset: offset, size: left_size}}
|
||||
}
|
||||
if right_size > 0 {
|
||||
ans.right_regions = []Region{{offset: offset, size: right_size}}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var word_regexp = sync.OnceValues(func() (*regexp.Regexp, error) {
|
||||
pattern := `\S+`
|
||||
if conf != nil && conf.Word_regex != "" {
|
||||
pattern = conf.Word_regex
|
||||
}
|
||||
return regexp.Compile(pattern)
|
||||
})
|
||||
|
||||
// The LCS table in word_diff_center needs one cell per pair of words between
|
||||
// the first and last changed word, so lines where that span is longer than
|
||||
// this fall back to changed_center.
|
||||
const max_word_diff_words = 2048
|
||||
|
||||
// word_diff_center computes highlighted regions for changed words between left and right.
|
||||
func word_diff_center(left, right string, re *regexp.Regexp) Center {
|
||||
left_matches := re.FindAllStringIndex(left, -1)
|
||||
right_matches := re.FindAllStringIndex(right, -1)
|
||||
// Changed words are only highlighted when they pair up by position, which
|
||||
// is impossible when the word counts differ, so skip the LCS in that case.
|
||||
if len(left_matches) != len(right_matches) {
|
||||
return changed_center(left, right)
|
||||
}
|
||||
|
||||
type word struct {
|
||||
text string
|
||||
offset int
|
||||
size int
|
||||
}
|
||||
left_words := make([]word, len(left_matches))
|
||||
right_words := make([]word, len(right_matches))
|
||||
for i, m := range left_matches {
|
||||
left_words[i] = word{text: left[m[0]:m[1]], offset: m[0], size: m[1] - m[0]}
|
||||
}
|
||||
for i, m := range right_matches {
|
||||
right_words[i] = word{text: right[m[0]:m[1]], offset: m[0], size: m[1] - m[0]}
|
||||
}
|
||||
|
||||
// Strip common prefix and suffix words so LCS only runs on the differing middle.
|
||||
prefix := 0
|
||||
for prefix < len(left_words) && prefix < len(right_words) && left_words[prefix].text == right_words[prefix].text {
|
||||
prefix++
|
||||
}
|
||||
suffix := 0
|
||||
for suffix < len(left_words)-prefix && suffix < len(right_words)-prefix &&
|
||||
left_words[len(left_words)-1-suffix].text == right_words[len(right_words)-1-suffix].text {
|
||||
suffix++
|
||||
}
|
||||
lw := left_words[prefix : len(left_words)-suffix]
|
||||
rw := right_words[prefix : len(right_words)-suffix]
|
||||
|
||||
m, n := len(lw), len(rw)
|
||||
if max(m, n) > max_word_diff_words {
|
||||
return changed_center(left, right)
|
||||
}
|
||||
// LCS dynamic programming table
|
||||
dp := make([][]int32, m+1)
|
||||
for i := range dp {
|
||||
dp[i] = make([]int32, n+1)
|
||||
}
|
||||
for i := 1; i <= m; i++ {
|
||||
for j := 1; j <= n; j++ {
|
||||
if lw[i-1].text == rw[j-1].text {
|
||||
dp[i][j] = dp[i-1][j-1] + 1
|
||||
} else if dp[i-1][j] > dp[i][j-1] {
|
||||
dp[i][j] = dp[i-1][j]
|
||||
} else {
|
||||
dp[i][j] = dp[i][j-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Backtrack to find changed words within the middle slice.
|
||||
left_changed := make([]bool, m)
|
||||
right_changed := make([]bool, n)
|
||||
i, j := m, n
|
||||
for i > 0 && j > 0 {
|
||||
if lw[i-1].text == rw[j-1].text {
|
||||
i--
|
||||
j--
|
||||
} else if dp[i-1][j] > dp[i][j-1] {
|
||||
left_changed[i-1] = true
|
||||
i--
|
||||
} else {
|
||||
right_changed[j-1] = true
|
||||
j--
|
||||
}
|
||||
}
|
||||
for i > 0 {
|
||||
left_changed[i-1] = true
|
||||
i--
|
||||
}
|
||||
for j > 0 {
|
||||
right_changed[j-1] = true
|
||||
j--
|
||||
}
|
||||
|
||||
// Remap changed flags to absolute indices within the full words arrays.
|
||||
left_changed_abs := make([]bool, len(left_words))
|
||||
right_changed_abs := make([]bool, len(right_words))
|
||||
for k, c := range left_changed {
|
||||
left_changed_abs[prefix+k] = c
|
||||
}
|
||||
for k, c := range right_changed {
|
||||
right_changed_abs[prefix+k] = c
|
||||
}
|
||||
|
||||
// Verify that every changed word at index i has a corresponding changed
|
||||
// word at the same index i on the other side. If any position is changed
|
||||
// on exactly one side, the lines differ in word count and it makes more
|
||||
// sense to highlight the single changed central region of the whole line.
|
||||
max_idx := max(len(left_words), len(right_words))
|
||||
for idx := range max_idx {
|
||||
lc := idx < len(left_words) && left_changed_abs[idx]
|
||||
rc := idx < len(right_words) && right_changed_abs[idx]
|
||||
if lc != rc {
|
||||
return changed_center(left, right)
|
||||
}
|
||||
}
|
||||
|
||||
// All changed words are positionally paired. Apply character-level
|
||||
// prefix/suffix trimming to each pair so only the differing central bytes
|
||||
// are highlighted.
|
||||
var ans Center
|
||||
for idx := range left_words {
|
||||
if !left_changed_abs[idx] {
|
||||
continue
|
||||
}
|
||||
lword := left_words[idx]
|
||||
rword := right_words[idx]
|
||||
lt := left[lword.offset : lword.offset+lword.size]
|
||||
rt := right[rword.offset : rword.offset+rword.size]
|
||||
ll, rl := len(lt), len(rt)
|
||||
ml := min(ll, rl)
|
||||
cpfx := 0
|
||||
for cpfx < ml && lt[cpfx] == rt[cpfx] {
|
||||
cpfx++
|
||||
}
|
||||
csfx := 0
|
||||
for csfx < ml-cpfx && lt[ll-1-csfx] == rt[rl-1-csfx] {
|
||||
csfx++
|
||||
}
|
||||
lsize := ll - cpfx - csfx
|
||||
rsize := rl - cpfx - csfx
|
||||
if lsize > 0 {
|
||||
ans.left_regions = append(ans.left_regions, Region{offset: lword.offset + cpfx, size: lsize})
|
||||
}
|
||||
if rsize > 0 {
|
||||
ans.right_regions = append(ans.right_regions, Region{offset: rword.offset + cpfx, size: rsize})
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Chunk) finalize(_ []string, _ []string) {
|
||||
// Center computation is performed in parallel by Patch.compute_centers
|
||||
}
|
||||
|
||||
type Hunk struct {
|
||||
left_start, left_count int
|
||||
right_start, right_count int
|
||||
title string
|
||||
added_count, removed_count int
|
||||
chunks []*Chunk
|
||||
current_chunk *Chunk
|
||||
largest_line_number int
|
||||
}
|
||||
|
||||
func (self *Hunk) new_chunk(is_context bool) *Chunk {
|
||||
left_start, right_start := self.left_start, self.right_start
|
||||
if len(self.chunks) > 0 {
|
||||
c := self.chunks[len(self.chunks)-1]
|
||||
left_start = c.left_start + c.left_count
|
||||
right_start = c.right_start + c.right_count
|
||||
}
|
||||
return &Chunk{is_context: is_context, left_start: left_start, right_start: right_start}
|
||||
}
|
||||
|
||||
func (self *Hunk) ensure_diff_chunk() {
|
||||
if self.current_chunk == nil || self.current_chunk.is_context {
|
||||
if self.current_chunk != nil {
|
||||
self.chunks = append(self.chunks, self.current_chunk)
|
||||
}
|
||||
self.current_chunk = self.new_chunk(false)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Hunk) ensure_context_chunk() {
|
||||
if self.current_chunk == nil || !self.current_chunk.is_context {
|
||||
if self.current_chunk != nil {
|
||||
self.chunks = append(self.chunks, self.current_chunk)
|
||||
}
|
||||
self.current_chunk = self.new_chunk(true)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Hunk) add_line() {
|
||||
self.ensure_diff_chunk()
|
||||
self.current_chunk.add_line()
|
||||
self.added_count++
|
||||
}
|
||||
|
||||
func (self *Hunk) remove_line() {
|
||||
self.ensure_diff_chunk()
|
||||
self.current_chunk.remove_line()
|
||||
self.removed_count++
|
||||
}
|
||||
|
||||
func (self *Hunk) context_line() {
|
||||
self.ensure_context_chunk()
|
||||
self.current_chunk.context_line()
|
||||
}
|
||||
|
||||
func (self *Hunk) finalize(left_lines, right_lines []string) error {
|
||||
if self.current_chunk != nil {
|
||||
self.chunks = append(self.chunks, self.current_chunk)
|
||||
}
|
||||
// Sanity check
|
||||
c := self.chunks[len(self.chunks)-1]
|
||||
if c.left_start+c.left_count != self.left_start+self.left_count {
|
||||
return fmt.Errorf("Left side line mismatch %d != %d", c.left_start+c.left_count, self.left_start+self.left_count)
|
||||
}
|
||||
if c.right_start+c.right_count != self.right_start+self.right_count {
|
||||
return fmt.Errorf("Right side line mismatch %d != %d", c.right_start+c.right_count, self.right_start+self.right_count)
|
||||
}
|
||||
for _, c := range self.chunks {
|
||||
c.finalize(left_lines, right_lines)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Patch struct {
|
||||
all_hunks []*Hunk
|
||||
largest_line_number, added_count, removed_count int
|
||||
left_moved_lines, right_moved_lines *utils.Set[int]
|
||||
}
|
||||
|
||||
func (self *Patch) Len() int { return len(self.all_hunks) }
|
||||
|
||||
func splitlines_like_git(raw string, strip_trailing_lines bool, process_line func(string)) {
|
||||
sz := len(raw)
|
||||
if strip_trailing_lines {
|
||||
for sz > 0 && (raw[sz-1] == '\n' || raw[sz-1] == '\r') {
|
||||
sz--
|
||||
}
|
||||
}
|
||||
start := 0
|
||||
for i := 0; i < sz; i++ {
|
||||
switch raw[i] {
|
||||
case '\n':
|
||||
process_line(raw[start:i])
|
||||
start = i + 1
|
||||
case '\r':
|
||||
process_line(raw[start:i])
|
||||
start = i + 1
|
||||
if start < sz && raw[start] == '\n' {
|
||||
i++
|
||||
start++
|
||||
}
|
||||
}
|
||||
}
|
||||
if start < sz {
|
||||
process_line(raw[start:sz])
|
||||
}
|
||||
}
|
||||
|
||||
func parse_range(x string) (start, count int) {
|
||||
s, c, found := strings.Cut(x, ",")
|
||||
start, _ = strconv.Atoi(s)
|
||||
if start < 0 {
|
||||
start = -start
|
||||
}
|
||||
count = 1
|
||||
if found {
|
||||
count, _ = strconv.Atoi(c)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func parse_hunk_header(line string) *Hunk {
|
||||
parts := strings.SplitN(line, "@@", 3)
|
||||
linespec := strings.TrimSpace(parts[1])
|
||||
title := ""
|
||||
if len(parts) == 3 {
|
||||
title = strings.TrimSpace(parts[2])
|
||||
}
|
||||
left, right, _ := strings.Cut(linespec, " ")
|
||||
ls, lc := parse_range(left)
|
||||
rs, rc := parse_range(right)
|
||||
return &Hunk{
|
||||
title: title, left_start: ls - 1, left_count: lc, right_start: rs - 1, right_count: rc,
|
||||
largest_line_number: utils.Max(ls-1+lc, rs-1+rc),
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Patch) compute_centers(left_lines, right_lines []string) error {
|
||||
word_mode := conf != nil && conf.Word_diff_mode == Word_diff_mode_words
|
||||
var re *regexp.Regexp
|
||||
if word_mode {
|
||||
var err error
|
||||
re, err = word_regexp()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to compile word_regex %q: %w", conf.Word_regex, err)
|
||||
}
|
||||
}
|
||||
|
||||
type pair struct {
|
||||
chunk *Chunk
|
||||
idx int
|
||||
}
|
||||
var pairs []pair
|
||||
for _, hunk := range self.all_hunks {
|
||||
for _, chunk := range hunk.chunks {
|
||||
if !chunk.is_context && chunk.left_count == chunk.right_count {
|
||||
for i := 0; i < chunk.left_count; i++ {
|
||||
pairs = append(pairs, pair{chunk, i})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(pairs) == 0 {
|
||||
return nil
|
||||
}
|
||||
centers := make([]Center, len(pairs))
|
||||
if err := parallel.Run_in_parallel_over_range(0, func(start, end int) {
|
||||
for i := start; i < end; i++ {
|
||||
p := pairs[i]
|
||||
left := left_lines[p.chunk.left_start+p.idx]
|
||||
right := right_lines[p.chunk.right_start+p.idx]
|
||||
if word_mode {
|
||||
centers[i] = word_diff_center(left, right, re)
|
||||
} else {
|
||||
centers[i] = changed_center(left, right)
|
||||
}
|
||||
}
|
||||
}, 0, len(pairs)); err != nil {
|
||||
return err
|
||||
}
|
||||
ci := 0
|
||||
for _, hunk := range self.all_hunks {
|
||||
for _, chunk := range hunk.chunks {
|
||||
if !chunk.is_context && chunk.left_count == chunk.right_count {
|
||||
chunk.centers = centers[ci : ci+chunk.left_count]
|
||||
ci += chunk.left_count
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Use SIMD to efficiently find non-blank lines: a line is non-blank if it
|
||||
// contains at least one character that is not a space or tab.
|
||||
func is_non_blank(text string) bool {
|
||||
return simdstring.NotIndexByte2String(text, ' ', '\t') >= 0
|
||||
}
|
||||
|
||||
func (self *Patch) detect_moved_lines(left_lines, right_lines []string) {
|
||||
// Build maps from line text to lists of line numbers for removed and added lines.
|
||||
removed := make(map[string][]int, len(left_lines)) // text -> left line numbers
|
||||
added := make(map[string][]int, len(right_lines)) // text -> right line numbers
|
||||
for _, hunk := range self.all_hunks {
|
||||
for _, chunk := range hunk.chunks {
|
||||
if !chunk.is_context {
|
||||
for i := 0; i < chunk.left_count; i++ {
|
||||
lnum := chunk.left_start + i
|
||||
text := left_lines[lnum]
|
||||
if is_non_blank(text) {
|
||||
removed[text] = append(removed[text], lnum)
|
||||
}
|
||||
}
|
||||
for i := 0; i < chunk.right_count; i++ {
|
||||
rnum := chunk.right_start + i
|
||||
text := right_lines[rnum]
|
||||
if is_non_blank(text) {
|
||||
added[text] = append(added[text], rnum)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Lines that appear in both removed and added sets are moved lines. When a
|
||||
// line appears multiple times on each side, only min(left_count,
|
||||
// right_count) occurrences are marked as moved.
|
||||
self.left_moved_lines = utils.NewSet[int]()
|
||||
self.right_moved_lines = utils.NewSet[int]()
|
||||
for text, lnums := range removed {
|
||||
if rnums, ok := added[text]; ok {
|
||||
count := min(len(lnums), len(rnums))
|
||||
for _, lnum := range lnums[:count] {
|
||||
self.left_moved_lines.Add(lnum)
|
||||
}
|
||||
for _, rnum := range rnums[:count] {
|
||||
self.right_moved_lines.Add(rnum)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parse_patch(raw string, left_lines, right_lines []string) (ans *Patch, err error) {
|
||||
ans = &Patch{all_hunks: make([]*Hunk, 0, 32)}
|
||||
var current_hunk *Hunk
|
||||
splitlines_like_git(raw, true, func(line string) {
|
||||
if strings.HasPrefix(line, "@@ ") {
|
||||
current_hunk = parse_hunk_header(line)
|
||||
ans.all_hunks = append(ans.all_hunks, current_hunk)
|
||||
} else if current_hunk != nil {
|
||||
var ch byte
|
||||
if len(line) > 0 {
|
||||
ch = line[0]
|
||||
}
|
||||
switch ch {
|
||||
case '+':
|
||||
current_hunk.add_line()
|
||||
case '-':
|
||||
current_hunk.remove_line()
|
||||
case '\\':
|
||||
default:
|
||||
current_hunk.context_line()
|
||||
}
|
||||
}
|
||||
})
|
||||
for _, h := range ans.all_hunks {
|
||||
err = h.finalize(left_lines, right_lines)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ans.added_count += h.added_count
|
||||
ans.removed_count += h.removed_count
|
||||
}
|
||||
if len(ans.all_hunks) > 0 {
|
||||
ans.largest_line_number = ans.all_hunks[len(ans.all_hunks)-1].largest_line_number
|
||||
}
|
||||
err = ans.compute_centers(left_lines, right_lines)
|
||||
if err == nil && conf.Mark_moved_lines {
|
||||
ans.detect_moved_lines(left_lines, right_lines)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func run_diff(file1, file2 string, num_of_context_lines int) (ok, is_different bool, patch string, err error) {
|
||||
// we resolve symlinks because git diff does not follow symlinks, while diff
|
||||
// does. We want consistent behavior, also for integration with git difftool
|
||||
// we always want symlinks to be followed.
|
||||
path1, err := filepath.EvalSymlinks(file1)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
path2, err := filepath.EvalSymlinks(file2)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if len(diff_cmd) == 0 {
|
||||
data1, err := data_for_path(path1)
|
||||
if err != nil {
|
||||
return false, false, "", err
|
||||
}
|
||||
data2, err := data_for_path(path2)
|
||||
if err != nil {
|
||||
return false, false, "", err
|
||||
}
|
||||
patchb := Diff(path1, data1, path2, data2, num_of_context_lines)
|
||||
if patchb == nil {
|
||||
return true, false, "", nil
|
||||
}
|
||||
return true, len(patchb) > 0, utils.UnsafeBytesToString(patchb), nil
|
||||
} else {
|
||||
context := strconv.Itoa(num_of_context_lines)
|
||||
cmd := utils.Map(func(x string) string {
|
||||
return strings.ReplaceAll(x, "_CONTEXT_", context)
|
||||
}, diff_cmd)
|
||||
|
||||
cmd = append(cmd, path1, path2)
|
||||
c := exec.Command(cmd[0], cmd[1:]...)
|
||||
stdout, stderr := bytes.Buffer{}, bytes.Buffer{}
|
||||
c.Stdout, c.Stderr = &stdout, &stderr
|
||||
err = c.Run()
|
||||
if err != nil {
|
||||
var e *exec.ExitError
|
||||
if errors.As(err, &e) && e.ExitCode() == 1 {
|
||||
return true, true, stdout.String(), nil
|
||||
}
|
||||
return false, false, stderr.String(), err
|
||||
}
|
||||
return true, false, stdout.String(), nil
|
||||
}
|
||||
}
|
||||
|
||||
func do_diff(file1, file2 string, context_count int) (ans *Patch, err error) {
|
||||
ok, _, raw, err := run_diff(file1, file2, context_count)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("Failed to diff %s vs. %s with errors:\n%s", file1, file2, raw)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
left_lines, err := lines_for_path(file1)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
right_lines, err := lines_for_path(file2)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ans, err = parse_patch(raw, left_lines, right_lines)
|
||||
return
|
||||
}
|
||||
|
||||
type diff_job struct{ file1, file2 string }
|
||||
|
||||
func diff(jobs []diff_job, context_count int) (ans map[string]*Patch, err error) {
|
||||
ans = make(map[string]*Patch)
|
||||
ctx := images.Context{}
|
||||
type result struct {
|
||||
file1, file2 string
|
||||
err error
|
||||
patch *Patch
|
||||
}
|
||||
results := make(chan result, len(jobs))
|
||||
if err := ctx.SafeParallel(0, len(jobs), func(nums <-chan int) {
|
||||
for i := range nums {
|
||||
job := jobs[i]
|
||||
r := result{file1: job.file1, file2: job.file2}
|
||||
r.patch, r.err = do_diff(job.file1, job.file2, context_count)
|
||||
results <- r
|
||||
}
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
close(results)
|
||||
for r := range results {
|
||||
if r.err != nil {
|
||||
return nil, r.err
|
||||
}
|
||||
ans[r.file1] = r.patch
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
)
|
||||
|
||||
var region_eq = cmpopts.EquateComparable(Region{})
|
||||
|
||||
func TestWordDiffCenter(t *testing.T) {
|
||||
re := regexp.MustCompile(`\S+`)
|
||||
many_words := strings.Repeat("a ", 100000)
|
||||
too_many_words := strings.Repeat("a ", max_word_diff_words)
|
||||
type tc struct {
|
||||
left, right string
|
||||
left_regions []Region
|
||||
right_regions []Region
|
||||
}
|
||||
tests := []tc{
|
||||
{
|
||||
// word count equal, single substitution at index 1 → positional pair
|
||||
// "quick" vs "slow": no common chars → full words
|
||||
left: "the quick brown fox", right: "the slow brown fox",
|
||||
left_regions: []Region{{4, 5}},
|
||||
right_regions: []Region{{4, 4}},
|
||||
},
|
||||
{
|
||||
left: "hello world", right: "hello world",
|
||||
left_regions: nil,
|
||||
right_regions: nil,
|
||||
},
|
||||
{
|
||||
// word count equal, single substitution at index 1 → positional pair
|
||||
// "bar" vs "qux": no common chars → full words
|
||||
left: "foo bar baz", right: "foo qux baz",
|
||||
left_regions: []Region{{4, 3}},
|
||||
right_regions: []Region{{4, 3}},
|
||||
},
|
||||
{
|
||||
// left has 3 words, right has 4 → word counts differ with unmatched
|
||||
// changed words → fall back to changed_center
|
||||
// changed_center gives: offset=4 (common "aaa "), suffix="ccc"(4)
|
||||
// left_size=3 ("bbb"), right_size=7 ("xxx yyy")
|
||||
left: "aaa bbb ccc", right: "aaa xxx yyy ccc",
|
||||
left_regions: []Region{{4, 3}},
|
||||
right_regions: []Region{{4, 7}},
|
||||
},
|
||||
{
|
||||
// word on left deleted: unmatched changed word → fall back to changed_center
|
||||
// changed_center: prefix="aaa "(4), suffix=" ccc ddd"(8)
|
||||
// left_size=3 ("bbb"), right_size=-1 → nil
|
||||
left: "aaa bbb ccc ddd", right: "aaa ccc ddd",
|
||||
left_regions: []Region{{4, 3}},
|
||||
right_regions: nil,
|
||||
},
|
||||
{
|
||||
// word counts equal, single substitution at index 3 → positional pair
|
||||
// "fox" vs "cat": no common chars → full words
|
||||
left: "the quick brown fox over the lazy dog", right: "the quick brown cat over the lazy dog",
|
||||
left_regions: []Region{{16, 3}},
|
||||
right_regions: []Region{{16, 3}},
|
||||
},
|
||||
{
|
||||
// single word, positional pair with common char prefix "version" (7)
|
||||
left: "version1",
|
||||
right: "version2",
|
||||
left_regions: []Region{{7, 1}},
|
||||
right_regions: []Region{{7, 1}},
|
||||
},
|
||||
{
|
||||
// positional pair at index 1, char prefix="prefix"(6), suffix="suffix"(6)
|
||||
// word at offset 7 → highlight offset 13, size 2
|
||||
left: "update prefixABsuffix done",
|
||||
right: "update prefixCDsuffix done",
|
||||
left_regions: []Region{{13, 2}},
|
||||
right_regions: []Region{{13, 2}},
|
||||
},
|
||||
{
|
||||
// equal word count, multiple positional pairs (all words changed)
|
||||
// each pair has no common chars → full-word regions
|
||||
left: "aaa bbb ccc", right: "xxx yyy zzz",
|
||||
left_regions: []Region{{0, 3}, {4, 3}, {8, 3}},
|
||||
right_regions: []Region{{0, 3}, {4, 3}, {8, 3}},
|
||||
},
|
||||
{
|
||||
// pure insertion on right side → unmatched changed word → fall back to changed_center
|
||||
// changed_center finds common prefix "aaa bbb ccc" (11 bytes) and suffix "";
|
||||
// left_size=0 (nil), right_size=4 (" ddd" inserted at the end)
|
||||
left: "aaa bbb ccc", right: "aaa bbb ccc ddd",
|
||||
left_regions: nil,
|
||||
right_regions: []Region{{11, 4}},
|
||||
},
|
||||
{
|
||||
// very long line, word counts differ → changed_center without
|
||||
// running the LCS over 100000 words
|
||||
left: many_words, right: "x " + many_words + "y",
|
||||
left_regions: []Region{{0, len(many_words)}},
|
||||
right_regions: []Region{{0, len(many_words) + 3}},
|
||||
},
|
||||
{
|
||||
// word counts equal, but more than max_word_diff_words words
|
||||
// between the first and last changed word → changed_center
|
||||
left: "x " + too_many_words + "y", right: "X " + too_many_words + "Y",
|
||||
left_regions: []Region{{0, len(too_many_words) + 3}},
|
||||
right_regions: []Region{{0, len(too_many_words) + 3}},
|
||||
},
|
||||
{
|
||||
// more than max_word_diff_words words, but the changed ones are
|
||||
// close together → still diffed by word
|
||||
left: too_many_words + "x a y", right: too_many_words + "X a Y",
|
||||
left_regions: []Region{{len(too_many_words), 1}, {len(too_many_words) + 4, 1}},
|
||||
right_regions: []Region{{len(too_many_words), 1}, {len(too_many_words) + 4, 1}},
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
c := word_diff_center(tc.left, tc.right, re)
|
||||
if diff := cmp.Diff(tc.left_regions, c.left_regions, region_eq); diff != "" {
|
||||
t.Errorf("word_diff_center(%q, %q) left_regions mismatch: %s", tc.left, tc.right, diff)
|
||||
}
|
||||
if diff := cmp.Diff(tc.right_regions, c.right_regions, region_eq); diff != "" {
|
||||
t.Errorf("word_diff_center(%q, %q) right_regions mismatch: %s", tc.left, tc.right, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangedCenter(t *testing.T) {
|
||||
type tc struct {
|
||||
left, right string
|
||||
left_regions []Region
|
||||
right_regions []Region
|
||||
}
|
||||
tests := []tc{
|
||||
{
|
||||
left: "the quick brown fox", right: "the slow brown fox",
|
||||
left_regions: []Region{{4, 5}},
|
||||
right_regions: []Region{{4, 4}},
|
||||
},
|
||||
{
|
||||
left: "hello world", right: "hello world",
|
||||
left_regions: nil,
|
||||
right_regions: nil,
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
c := changed_center(tc.left, tc.right)
|
||||
if diff := cmp.Diff(tc.left_regions, c.left_regions, region_eq); diff != "" {
|
||||
t.Errorf("changed_center(%q, %q) left_regions mismatch: %s", tc.left, tc.right, diff)
|
||||
}
|
||||
if diff := cmp.Diff(tc.right_regions, c.right_regions, region_eq); diff != "" {
|
||||
t.Errorf("changed_center(%q, %q) right_regions mismatch: %s", tc.left, tc.right, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,886 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/graphics"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/sgr"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/style"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type LineType int
|
||||
|
||||
const (
|
||||
TITLE_LINE LineType = iota
|
||||
CHANGE_LINE
|
||||
CONTEXT_LINE
|
||||
HUNK_TITLE_LINE
|
||||
IMAGE_LINE
|
||||
EMPTY_LINE
|
||||
)
|
||||
|
||||
type Reference struct {
|
||||
path string
|
||||
linenum int // 1 based
|
||||
}
|
||||
|
||||
type HalfScreenLine struct {
|
||||
marked_up_margin_text string
|
||||
marked_up_text string
|
||||
is_filler bool
|
||||
is_moved bool
|
||||
cached_wcswidth int
|
||||
}
|
||||
|
||||
func (self *HalfScreenLine) wcswidth() int {
|
||||
if self.cached_wcswidth == 0 && self.marked_up_text != "" {
|
||||
self.cached_wcswidth = wcswidth.Stringwidth(self.marked_up_text)
|
||||
}
|
||||
return self.cached_wcswidth
|
||||
}
|
||||
|
||||
type ScreenLine struct {
|
||||
left, right HalfScreenLine
|
||||
}
|
||||
|
||||
type LogicalLine struct {
|
||||
line_type LineType
|
||||
screen_lines []*ScreenLine
|
||||
is_full_width bool
|
||||
is_change_start bool
|
||||
left_reference, right_reference Reference
|
||||
left_image, right_image struct {
|
||||
key string
|
||||
count int
|
||||
}
|
||||
image_lines_offset int
|
||||
}
|
||||
|
||||
func (self *LogicalLine) render_screen_line(n int, lp *loop.Loop, margin_size, columns int) {
|
||||
if n >= len(self.screen_lines) || n < 0 {
|
||||
return
|
||||
}
|
||||
sl := self.screen_lines[n]
|
||||
available_cols := columns/2 - margin_size
|
||||
if self.is_full_width {
|
||||
available_cols = columns - margin_size
|
||||
}
|
||||
left_margin := place_in(sl.left.marked_up_margin_text, margin_size)
|
||||
left_text := place_in(sl.left.marked_up_text, available_cols)
|
||||
if sl.left.is_filler {
|
||||
left_margin = format_as_sgr.margin_filler + left_margin
|
||||
left_text = format_as_sgr.filler + left_text
|
||||
} else if sl.left.is_moved {
|
||||
left_margin = format_as_sgr.moved_margin + left_margin
|
||||
left_text = format_as_sgr.moved + left_text
|
||||
} else {
|
||||
switch self.line_type {
|
||||
case CHANGE_LINE, IMAGE_LINE:
|
||||
left_margin = format_as_sgr.removed_margin + left_margin
|
||||
left_text = format_as_sgr.removed + left_text
|
||||
case HUNK_TITLE_LINE:
|
||||
left_margin = format_as_sgr.hunk_margin + left_margin
|
||||
left_text = format_as_sgr.hunk + left_text
|
||||
case TITLE_LINE:
|
||||
default:
|
||||
left_margin = format_as_sgr.margin + left_margin
|
||||
}
|
||||
}
|
||||
lp.QueueWriteString(left_margin + "\x1b[m")
|
||||
lp.QueueWriteString(left_text)
|
||||
if self.is_full_width {
|
||||
return
|
||||
}
|
||||
right_margin := place_in(sl.right.marked_up_margin_text, margin_size)
|
||||
right_text := place_in(sl.right.marked_up_text, available_cols)
|
||||
if sl.right.is_filler {
|
||||
right_margin = format_as_sgr.margin_filler + right_margin
|
||||
right_text = format_as_sgr.filler + right_text
|
||||
} else if sl.right.is_moved {
|
||||
right_margin = format_as_sgr.moved_margin + right_margin
|
||||
right_text = format_as_sgr.moved + right_text
|
||||
} else {
|
||||
switch self.line_type {
|
||||
case CHANGE_LINE, IMAGE_LINE:
|
||||
right_margin = format_as_sgr.added_margin + right_margin
|
||||
right_text = format_as_sgr.added + right_text
|
||||
case HUNK_TITLE_LINE:
|
||||
right_margin = format_as_sgr.hunk_margin + right_margin
|
||||
right_text = format_as_sgr.hunk + right_text
|
||||
case TITLE_LINE:
|
||||
default:
|
||||
right_margin = format_as_sgr.margin + right_margin
|
||||
}
|
||||
}
|
||||
lp.QueueWriteString("\x1b[m\r")
|
||||
lp.MoveCursorHorizontally(available_cols + margin_size)
|
||||
lp.QueueWriteString(right_margin + "\x1b[m")
|
||||
lp.QueueWriteString(right_text)
|
||||
}
|
||||
|
||||
func (self *LogicalLine) IncrementScrollPosBy(pos *ScrollPos, amt int) (delta int) {
|
||||
if len(self.screen_lines) > 0 {
|
||||
npos := utils.Max(0, utils.Min(pos.screen_line+amt, len(self.screen_lines)-1))
|
||||
delta = npos - pos.screen_line
|
||||
pos.screen_line = npos
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func fit_in(text string, count int) string {
|
||||
truncated := wcswidth.TruncateToVisualLength(text, count)
|
||||
if len(truncated) >= len(text) {
|
||||
return text
|
||||
}
|
||||
if count > 1 {
|
||||
truncated = wcswidth.TruncateToVisualLength(text, count-1)
|
||||
}
|
||||
return truncated + `…`
|
||||
}
|
||||
|
||||
func fill_in(text string, sz int) string {
|
||||
w := wcswidth.Stringwidth(text)
|
||||
if w < sz {
|
||||
text += strings.Repeat(` `, (sz - w))
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
func place_in(text string, sz int) string {
|
||||
return fill_in(fit_in(text, sz), sz)
|
||||
}
|
||||
|
||||
var format_as_sgr struct {
|
||||
title, margin, added, removed, added_margin, removed_margin, filler, margin_filler, hunk_margin, hunk, selection, search, moved, moved_margin string
|
||||
}
|
||||
|
||||
var statusline_format, added_count_format, removed_count_format, message_format func(...any) string
|
||||
var use_light_colors bool = false
|
||||
|
||||
type ResolvedColors struct {
|
||||
Added_bg style.RGBA
|
||||
Added_margin_bg style.RGBA
|
||||
Background style.RGBA
|
||||
Filler_bg style.RGBA
|
||||
Foreground style.RGBA
|
||||
Highlight_added_bg style.RGBA
|
||||
Highlight_removed_bg style.RGBA
|
||||
Hunk_bg style.RGBA
|
||||
Hunk_margin_bg style.RGBA
|
||||
Margin_bg style.RGBA
|
||||
Margin_fg style.RGBA
|
||||
Margin_filler_bg style.NullableColor
|
||||
Moved_bg style.RGBA
|
||||
Moved_margin_bg style.RGBA
|
||||
Removed_bg style.RGBA
|
||||
Removed_margin_bg style.RGBA
|
||||
Search_bg style.RGBA
|
||||
Search_fg style.RGBA
|
||||
Select_bg style.RGBA
|
||||
Select_fg style.NullableColor
|
||||
Title_bg style.RGBA
|
||||
Title_fg style.RGBA
|
||||
}
|
||||
|
||||
var resolved_colors ResolvedColors
|
||||
|
||||
func create_formatters() {
|
||||
rc := &resolved_colors
|
||||
if !use_light_colors {
|
||||
rc.Added_bg = conf.Dark_added_bg
|
||||
rc.Added_margin_bg = conf.Dark_added_margin_bg
|
||||
rc.Background = conf.Dark_background
|
||||
rc.Filler_bg = conf.Dark_filler_bg
|
||||
rc.Foreground = conf.Dark_foreground
|
||||
rc.Highlight_added_bg = conf.Dark_highlight_added_bg
|
||||
rc.Highlight_removed_bg = conf.Dark_highlight_removed_bg
|
||||
rc.Hunk_bg = conf.Dark_hunk_bg
|
||||
rc.Hunk_margin_bg = conf.Dark_hunk_margin_bg
|
||||
rc.Margin_bg = conf.Dark_margin_bg
|
||||
rc.Margin_fg = conf.Dark_margin_fg
|
||||
rc.Margin_filler_bg = conf.Dark_margin_filler_bg
|
||||
rc.Moved_bg = conf.Dark_moved_bg
|
||||
rc.Moved_margin_bg = conf.Dark_moved_margin_bg
|
||||
rc.Removed_bg = conf.Dark_removed_bg
|
||||
rc.Removed_margin_bg = conf.Dark_removed_margin_bg
|
||||
rc.Search_bg = conf.Dark_search_bg
|
||||
rc.Search_fg = conf.Dark_search_fg
|
||||
rc.Select_bg = conf.Dark_select_bg
|
||||
rc.Select_fg = conf.Dark_select_fg
|
||||
rc.Title_bg = conf.Dark_title_bg
|
||||
rc.Title_fg = conf.Dark_title_fg
|
||||
} else {
|
||||
rc.Added_bg = conf.Added_bg
|
||||
rc.Added_margin_bg = conf.Added_margin_bg
|
||||
rc.Background = conf.Background
|
||||
rc.Filler_bg = conf.Filler_bg
|
||||
rc.Foreground = conf.Foreground
|
||||
rc.Highlight_added_bg = conf.Highlight_added_bg
|
||||
rc.Highlight_removed_bg = conf.Highlight_removed_bg
|
||||
rc.Hunk_bg = conf.Hunk_bg
|
||||
rc.Hunk_margin_bg = conf.Hunk_margin_bg
|
||||
rc.Margin_bg = conf.Margin_bg
|
||||
rc.Margin_fg = conf.Margin_fg
|
||||
rc.Margin_filler_bg = conf.Margin_filler_bg
|
||||
rc.Moved_bg = conf.Moved_bg
|
||||
rc.Moved_margin_bg = conf.Moved_margin_bg
|
||||
rc.Removed_bg = conf.Removed_bg
|
||||
rc.Removed_margin_bg = conf.Removed_margin_bg
|
||||
rc.Search_bg = conf.Search_bg
|
||||
rc.Search_fg = conf.Search_fg
|
||||
rc.Select_bg = conf.Select_bg
|
||||
rc.Select_fg = conf.Select_fg
|
||||
rc.Title_bg = conf.Title_bg
|
||||
rc.Title_fg = conf.Title_fg
|
||||
}
|
||||
ctx := style.Context{AllowEscapeCodes: true}
|
||||
only_open := func(x string) string {
|
||||
ans := ctx.SprintFunc(x)("|")
|
||||
ans, _, _ = strings.Cut(ans, "|")
|
||||
return ans
|
||||
}
|
||||
format_as_sgr.filler = only_open("bg=" + rc.Filler_bg.AsRGBSharp())
|
||||
if rc.Margin_filler_bg.IsSet {
|
||||
format_as_sgr.margin_filler = only_open("bg=" + rc.Margin_filler_bg.Color.AsRGBSharp())
|
||||
} else {
|
||||
format_as_sgr.margin_filler = only_open("bg=" + rc.Filler_bg.AsRGBSharp())
|
||||
}
|
||||
format_as_sgr.added = only_open("bg=" + rc.Added_bg.AsRGBSharp())
|
||||
format_as_sgr.added_margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Added_margin_bg.AsRGBSharp()))
|
||||
format_as_sgr.removed = only_open("bg=" + rc.Removed_bg.AsRGBSharp())
|
||||
format_as_sgr.removed_margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Removed_margin_bg.AsRGBSharp()))
|
||||
format_as_sgr.moved = only_open("bg=" + rc.Moved_bg.AsRGBSharp())
|
||||
format_as_sgr.moved_margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Moved_margin_bg.AsRGBSharp()))
|
||||
format_as_sgr.title = only_open(fmt.Sprintf("fg=%s bg=%s bold", rc.Title_fg.AsRGBSharp(), rc.Title_bg.AsRGBSharp()))
|
||||
format_as_sgr.margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Margin_bg.AsRGBSharp()))
|
||||
format_as_sgr.hunk = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Hunk_bg.AsRGBSharp()))
|
||||
format_as_sgr.hunk_margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Hunk_margin_bg.AsRGBSharp()))
|
||||
format_as_sgr.search = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Search_fg.AsRGBSharp(), rc.Search_bg.AsRGBSharp()))
|
||||
statusline_format = ctx.SprintFunc(fmt.Sprintf("fg=%s", rc.Margin_fg.AsRGBSharp()))
|
||||
added_count_format = ctx.SprintFunc(fmt.Sprintf("fg=%s", rc.Highlight_added_bg.AsRGBSharp()))
|
||||
removed_count_format = ctx.SprintFunc(fmt.Sprintf("fg=%s", rc.Highlight_removed_bg.AsRGBSharp()))
|
||||
message_format = ctx.SprintFunc("bold")
|
||||
if rc.Select_fg.IsSet {
|
||||
format_as_sgr.selection = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Select_fg.Color.AsRGBSharp(), rc.Select_bg.AsRGBSharp()))
|
||||
} else {
|
||||
format_as_sgr.selection = only_open("bg=" + rc.Select_bg.AsRGBSharp())
|
||||
}
|
||||
}
|
||||
|
||||
func center_span(ltype string, offset, size int) *sgr.Span {
|
||||
ans := sgr.NewSpan(offset, size)
|
||||
switch ltype {
|
||||
case "add":
|
||||
ans.SetBackground(resolved_colors.Highlight_added_bg).SetClosingBackground(resolved_colors.Added_bg)
|
||||
case "remove":
|
||||
ans.SetBackground(resolved_colors.Highlight_removed_bg).SetClosingBackground(resolved_colors.Removed_bg)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func title_lines(left_path, right_path string, columns, margin_size int, ans []*LogicalLine) []*LogicalLine {
|
||||
left_name, right_name := path_name_map[left_path], path_name_map[right_path]
|
||||
available_cols := columns/2 - margin_size
|
||||
ll := LogicalLine{
|
||||
line_type: TITLE_LINE,
|
||||
left_reference: Reference{path: left_path}, right_reference: Reference{path: right_path},
|
||||
}
|
||||
sl := ScreenLine{}
|
||||
if right_name != "" && right_name != left_name {
|
||||
sl.left.marked_up_text = format_as_sgr.title + fit_in(sanitize(left_name), available_cols)
|
||||
sl.right.marked_up_text = format_as_sgr.title + fit_in(sanitize(right_name), available_cols)
|
||||
} else {
|
||||
sl.left.marked_up_text = format_as_sgr.title + fit_in(sanitize(left_name), columns-margin_size)
|
||||
ll.is_full_width = true
|
||||
}
|
||||
l2 := ll
|
||||
l2.line_type = EMPTY_LINE
|
||||
ll.screen_lines = append(ll.screen_lines, &sl)
|
||||
sl2 := ScreenLine{}
|
||||
sl2.left.marked_up_margin_text = "\x1b[m" + strings.Repeat("━", margin_size)
|
||||
sl2.left.marked_up_text = strings.Repeat("━", columns-margin_size)
|
||||
l2.is_full_width = true
|
||||
l2.screen_lines = append(l2.screen_lines, &sl2)
|
||||
return append(ans, &ll, &l2)
|
||||
}
|
||||
|
||||
type LogicalLines struct {
|
||||
lines []*LogicalLine
|
||||
title_line_indices []int // sorted indices of TITLE_LINEs in lines -- used for sticky_header
|
||||
margin_size, columns int
|
||||
}
|
||||
|
||||
func (self *LogicalLines) At(i int) *LogicalLine { return self.lines[i] }
|
||||
|
||||
func (self *LogicalLines) TitleLineIdxFor(line_idx int) int {
|
||||
if len(self.title_line_indices) == 0 || line_idx < 0 {
|
||||
return -1
|
||||
}
|
||||
// first title index > line_idx, so the one before it is our answer
|
||||
i := sort.SearchInts(self.title_line_indices, line_idx+1)
|
||||
if i == 0 {
|
||||
return -1
|
||||
}
|
||||
return self.title_line_indices[i-1]
|
||||
}
|
||||
|
||||
func (self *LogicalLines) ScreenLineAt(pos ScrollPos) *ScreenLine {
|
||||
if pos.logical_line < len(self.lines) && pos.logical_line >= 0 {
|
||||
line := self.lines[pos.logical_line]
|
||||
if pos.screen_line < len(line.screen_lines) && pos.screen_line >= 0 {
|
||||
return self.lines[pos.logical_line].screen_lines[pos.screen_line]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (self *LogicalLines) Len() int { return len(self.lines) }
|
||||
|
||||
func (self *LogicalLines) NumScreenLinesTo(a ScrollPos) (ans int) {
|
||||
return self.Minus(a, ScrollPos{})
|
||||
}
|
||||
|
||||
// a - b in terms of number of screen lines between the positions
|
||||
func (self *LogicalLines) Minus(a, b ScrollPos) (delta int) {
|
||||
if a.logical_line == b.logical_line {
|
||||
return a.screen_line - b.screen_line
|
||||
}
|
||||
amt := 1
|
||||
if a.Less(b) {
|
||||
amt = -1
|
||||
} else {
|
||||
a, b = b, a
|
||||
}
|
||||
for i := a.logical_line; i < utils.Min(len(self.lines), b.logical_line+1); i++ {
|
||||
line := self.lines[i]
|
||||
switch i {
|
||||
case a.logical_line:
|
||||
delta += utils.Max(0, len(line.screen_lines)-a.screen_line)
|
||||
case b.logical_line:
|
||||
delta += b.screen_line
|
||||
default:
|
||||
delta += len(line.screen_lines)
|
||||
}
|
||||
}
|
||||
return delta * amt
|
||||
}
|
||||
|
||||
func (self *LogicalLines) IncrementScrollPosBy(pos *ScrollPos, amt int) (delta int) {
|
||||
if pos.logical_line < 0 || pos.logical_line >= len(self.lines) || amt == 0 {
|
||||
return
|
||||
}
|
||||
one := 1
|
||||
if amt < 0 {
|
||||
one = -1
|
||||
}
|
||||
for amt != 0 {
|
||||
line := self.lines[pos.logical_line]
|
||||
d := line.IncrementScrollPosBy(pos, amt)
|
||||
if d == 0 {
|
||||
nlp := pos.logical_line + one
|
||||
if nlp < 0 || nlp >= len(self.lines) {
|
||||
break
|
||||
}
|
||||
pos.logical_line = nlp
|
||||
if one > 0 {
|
||||
pos.screen_line = 0
|
||||
} else {
|
||||
pos.screen_line = len(self.lines[nlp].screen_lines) - 1
|
||||
}
|
||||
delta += one
|
||||
amt -= one
|
||||
} else {
|
||||
amt -= d
|
||||
delta += d
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func human_readable(size int64) string {
|
||||
divisor, suffix := 1, "B"
|
||||
for i, candidate := range []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"} {
|
||||
if size < (1 << ((i + 1) * 10)) {
|
||||
divisor, suffix = (1 << (i * 10)), candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
fs := float64(size) / float64(divisor)
|
||||
s := strconv.FormatFloat(fs, 'f', 2, 64)
|
||||
if idx := strings.Index(s, "."); idx > -1 {
|
||||
s = s[:idx+2]
|
||||
}
|
||||
if strings.HasSuffix(s, ".0") || strings.HasSuffix(s, ".00") {
|
||||
idx := strings.IndexByte(s, '.')
|
||||
s = s[:idx]
|
||||
}
|
||||
return s + " " + suffix
|
||||
}
|
||||
|
||||
func image_lines(left_path, right_path string, screen_size screen_size, margin_size int, image_size graphics.Size, ans []*LogicalLine) ([]*LogicalLine, error) {
|
||||
columns := screen_size.columns
|
||||
available_cols := columns/2 - margin_size
|
||||
ll, err := first_binary_line(left_path, right_path, columns, margin_size, func(path string) (string, error) {
|
||||
sz, err := size_for_path(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
text := fmt.Sprintf("Size: %s", human_readable(sz))
|
||||
res := image_collection.ResolutionOf(path)
|
||||
if res.Width > -1 {
|
||||
text = fmt.Sprintf("Dimensions: %dx%d %s", res.Width, res.Height, text)
|
||||
}
|
||||
return text, nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ll.image_lines_offset = len(ll.screen_lines)
|
||||
|
||||
do_side := func(path string) []string {
|
||||
if path == "" {
|
||||
return nil
|
||||
}
|
||||
sz, err := image_collection.GetSizeIfAvailable(path, image_size)
|
||||
if err == nil {
|
||||
count := int(math.Ceil(float64(sz.Height) / float64(screen_size.cell_height)))
|
||||
return utils.Repeat("", count)
|
||||
}
|
||||
if errors.Is(err, graphics.ErrNotFound) {
|
||||
return splitlines("Loading image...", available_cols)
|
||||
}
|
||||
return splitlines(fmt.Sprintf("%s", err), available_cols)
|
||||
}
|
||||
left_lines := do_side(left_path)
|
||||
if ll.left_image.count = len(left_lines); ll.left_image.count > 0 {
|
||||
ll.left_image.key = left_path
|
||||
}
|
||||
right_lines := do_side(right_path)
|
||||
if ll.right_image.count = len(right_lines); ll.right_image.count > 0 {
|
||||
ll.right_image.key = right_path
|
||||
}
|
||||
for i := 0; i < utils.Max(len(left_lines), len(right_lines)); i++ {
|
||||
sl := ScreenLine{}
|
||||
if i < len(left_lines) {
|
||||
sl.left.marked_up_text = left_lines[i]
|
||||
} else {
|
||||
sl.left.is_filler = true
|
||||
}
|
||||
if i < len(right_lines) {
|
||||
sl.right.marked_up_text = right_lines[i]
|
||||
} else {
|
||||
sl.right.is_filler = true
|
||||
}
|
||||
ll.screen_lines = append(ll.screen_lines, &sl)
|
||||
}
|
||||
ll.line_type = IMAGE_LINE
|
||||
return append(ans, ll), nil
|
||||
}
|
||||
|
||||
func first_binary_line(left_path, right_path string, columns, margin_size int, renderer func(path string) (string, error)) (*LogicalLine, error) {
|
||||
available_cols := columns/2 - margin_size
|
||||
ll := LogicalLine{
|
||||
is_change_start: true, line_type: CHANGE_LINE,
|
||||
left_reference: Reference{path: left_path}, right_reference: Reference{path: right_path},
|
||||
}
|
||||
if left_path == "" {
|
||||
line, err := renderer(right_path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, x := range splitlines(line, available_cols) {
|
||||
sl := ScreenLine{}
|
||||
sl.right.marked_up_text = x
|
||||
sl.left.is_filler = true
|
||||
ll.screen_lines = append(ll.screen_lines, &sl)
|
||||
}
|
||||
} else if right_path == "" {
|
||||
line, err := renderer(left_path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, x := range splitlines(line, available_cols) {
|
||||
sl := ScreenLine{}
|
||||
sl.right.is_filler = true
|
||||
sl.left.marked_up_text = x
|
||||
ll.screen_lines = append(ll.screen_lines, &sl)
|
||||
}
|
||||
} else {
|
||||
l, err := renderer(left_path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := renderer(right_path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
left_lines, right_lines := splitlines(l, available_cols), splitlines(r, available_cols)
|
||||
for i := 0; i < utils.Max(len(left_lines), len(right_lines)); i++ {
|
||||
sl := ScreenLine{}
|
||||
if i < len(left_lines) {
|
||||
sl.left.marked_up_text = left_lines[i]
|
||||
}
|
||||
if i < len(right_lines) {
|
||||
sl.right.marked_up_text = right_lines[i]
|
||||
}
|
||||
ll.screen_lines = append(ll.screen_lines, &sl)
|
||||
}
|
||||
}
|
||||
return &ll, nil
|
||||
}
|
||||
|
||||
func binary_lines(left_path, right_path string, columns, margin_size int, ans []*LogicalLine) (ans2 []*LogicalLine, err error) {
|
||||
ll, err := first_binary_line(left_path, right_path, columns, margin_size, func(path string) (string, error) {
|
||||
sz, err := size_for_path(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("Binary file: %s", human_readable(sz)), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(ans, ll), nil
|
||||
}
|
||||
|
||||
type DiffData struct {
|
||||
left_path, right_path string
|
||||
available_cols, margin_size int
|
||||
|
||||
left_lines, right_lines []string
|
||||
left_moved_lines *utils.Set[int]
|
||||
right_moved_lines *utils.Set[int]
|
||||
}
|
||||
|
||||
func hunk_title(hunk *Hunk) string {
|
||||
return fmt.Sprintf("@@ -%d,%d +%d,%d @@ %s", hunk.left_start+1, hunk.left_count, hunk.right_start+1, hunk.right_count, hunk.title)
|
||||
}
|
||||
|
||||
func lines_for_context_chunk(data *DiffData, _ int, chunk *Chunk, _ int, ans []*LogicalLine) []*LogicalLine {
|
||||
for i := 0; i < chunk.left_count; i++ {
|
||||
left_line_number := chunk.left_start + i
|
||||
right_line_number := chunk.right_start + i
|
||||
ll := LogicalLine{line_type: CONTEXT_LINE,
|
||||
left_reference: Reference{path: data.left_path, linenum: left_line_number + 1},
|
||||
right_reference: Reference{path: data.right_path, linenum: right_line_number + 1},
|
||||
}
|
||||
left_line_number_s := strconv.Itoa(left_line_number + 1)
|
||||
right_line_number_s := strconv.Itoa(right_line_number + 1)
|
||||
for _, text := range splitlines(data.left_lines[left_line_number], data.available_cols) {
|
||||
left_line := HalfScreenLine{marked_up_margin_text: left_line_number_s, marked_up_text: text}
|
||||
right_line := left_line
|
||||
if right_line_number_s != left_line_number_s {
|
||||
right_line = HalfScreenLine{marked_up_margin_text: right_line_number_s, marked_up_text: text}
|
||||
}
|
||||
ll.screen_lines = append(ll.screen_lines, &ScreenLine{left_line, right_line})
|
||||
left_line_number_s, right_line_number_s = "", ""
|
||||
}
|
||||
ans = append(ans, &ll)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func splitlines(text string, width int) []string {
|
||||
return style.WrapTextAsLines(text, width, style.WrapOptions{})
|
||||
}
|
||||
|
||||
func render_half_line(line_number int, line, ltype string, available_cols int, center Center, is_moved bool, ans []HalfScreenLine) []HalfScreenLine {
|
||||
var regions []Region
|
||||
if ltype == "remove" {
|
||||
regions = center.left_regions
|
||||
} else {
|
||||
regions = center.right_regions
|
||||
}
|
||||
if len(regions) > 0 {
|
||||
spans := make([]*sgr.Span, len(regions))
|
||||
for i, r := range regions {
|
||||
spans[i] = center_span(ltype, r.offset, r.size)
|
||||
}
|
||||
line = sgr.InsertFormatting(line, spans...)
|
||||
}
|
||||
lnum := strconv.Itoa(line_number + 1)
|
||||
for _, sc := range splitlines(line, available_cols) {
|
||||
ans = append(ans, HalfScreenLine{marked_up_margin_text: lnum, marked_up_text: sc, is_moved: is_moved})
|
||||
lnum = ""
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func lines_for_diff_chunk(data *DiffData, _ int, chunk *Chunk, _ int, ans []*LogicalLine) []*LogicalLine {
|
||||
common := utils.Min(chunk.left_count, chunk.right_count)
|
||||
ll, rl := make([]HalfScreenLine, 0, 32), make([]HalfScreenLine, 0, 32)
|
||||
for i := 0; i < utils.Max(chunk.left_count, chunk.right_count); i++ {
|
||||
ll, rl = ll[:0], rl[:0]
|
||||
var center Center
|
||||
left_lnum, right_lnum := 0, 0
|
||||
if i < len(chunk.centers) {
|
||||
center = chunk.centers[i]
|
||||
}
|
||||
if i < chunk.left_count {
|
||||
left_lnum = chunk.left_start + i
|
||||
left_is_moved := data.left_moved_lines != nil && data.left_moved_lines.Has(left_lnum)
|
||||
ll = render_half_line(left_lnum, data.left_lines[left_lnum], "remove", data.available_cols, center, left_is_moved, ll)
|
||||
left_lnum++
|
||||
}
|
||||
|
||||
if i < chunk.right_count {
|
||||
right_lnum = chunk.right_start + i
|
||||
right_is_moved := data.right_moved_lines != nil && data.right_moved_lines.Has(right_lnum)
|
||||
rl = render_half_line(right_lnum, data.right_lines[right_lnum], "add", data.available_cols, center, right_is_moved, rl)
|
||||
right_lnum++
|
||||
}
|
||||
|
||||
if i < common {
|
||||
extra := len(ll) - len(rl)
|
||||
if extra < 0 {
|
||||
ll = append(ll, utils.Repeat(HalfScreenLine{}, -extra)...)
|
||||
} else if extra > 0 {
|
||||
rl = append(rl, utils.Repeat(HalfScreenLine{}, extra)...)
|
||||
}
|
||||
} else {
|
||||
if len(ll) > 0 {
|
||||
rl = append(rl, utils.Repeat(HalfScreenLine{is_filler: true}, len(ll))...)
|
||||
} else if len(rl) > 0 {
|
||||
ll = append(ll, utils.Repeat(HalfScreenLine{is_filler: true}, len(rl))...)
|
||||
}
|
||||
}
|
||||
logline := LogicalLine{
|
||||
line_type: CHANGE_LINE, is_change_start: i == 0,
|
||||
left_reference: Reference{path: data.left_path, linenum: left_lnum},
|
||||
right_reference: Reference{path: data.left_path, linenum: right_lnum},
|
||||
}
|
||||
for l := 0; l < len(ll); l++ {
|
||||
logline.screen_lines = append(logline.screen_lines, &ScreenLine{left: ll[l], right: rl[l]})
|
||||
}
|
||||
ans = append(ans, &logline)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func lines_for_diff(left_path string, right_path string, patch *Patch, columns, margin_size int, ans []*LogicalLine) (result []*LogicalLine, err error) {
|
||||
ht := LogicalLine{
|
||||
line_type: HUNK_TITLE_LINE,
|
||||
left_reference: Reference{path: left_path}, right_reference: Reference{path: right_path},
|
||||
is_full_width: true,
|
||||
}
|
||||
if patch.Len() == 0 {
|
||||
txt := "The files are identical"
|
||||
if lstat, err := os.Stat(left_path); err == nil {
|
||||
if rstat, err := os.Stat(right_path); err == nil {
|
||||
if lstat.Mode() != rstat.Mode() {
|
||||
txt = fmt.Sprintf("Mode changed: %s to %s", lstat.Mode(), rstat.Mode())
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, line := range splitlines(txt, columns-margin_size) {
|
||||
sl := ScreenLine{}
|
||||
sl.left.marked_up_text = line
|
||||
ht.screen_lines = append(ht.screen_lines, &sl)
|
||||
}
|
||||
ht.line_type = EMPTY_LINE
|
||||
ht.is_full_width = true
|
||||
return append(ans, &ht), nil
|
||||
}
|
||||
available_cols := columns/2 - margin_size
|
||||
data := DiffData{
|
||||
left_path: left_path, right_path: right_path, available_cols: available_cols, margin_size: margin_size,
|
||||
left_moved_lines: patch.left_moved_lines, right_moved_lines: patch.right_moved_lines,
|
||||
}
|
||||
if left_path != "" {
|
||||
data.left_lines, err = highlighted_lines_for_path(left_path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if right_path != "" {
|
||||
data.right_lines, err = highlighted_lines_for_path(right_path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for hunk_num, hunk := range patch.all_hunks {
|
||||
htl := ht
|
||||
htl.left_reference.linenum = hunk.left_start + 1
|
||||
htl.right_reference.linenum = hunk.right_start + 1
|
||||
for _, line := range splitlines(hunk_title(hunk), columns-margin_size) {
|
||||
sl := ScreenLine{}
|
||||
sl.left.marked_up_text = line
|
||||
htl.screen_lines = append(htl.screen_lines, &sl)
|
||||
}
|
||||
ans = append(ans, &htl)
|
||||
for cnum, chunk := range hunk.chunks {
|
||||
if chunk.is_context {
|
||||
ans = lines_for_context_chunk(&data, hunk_num, chunk, cnum, ans)
|
||||
} else {
|
||||
ans = lines_for_diff_chunk(&data, hunk_num, chunk, cnum, ans)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func all_lines(path string, columns, margin_size int, is_add bool, ans []*LogicalLine) ([]*LogicalLine, error) {
|
||||
available_cols := columns/2 - margin_size
|
||||
ltype := `add`
|
||||
ll := LogicalLine{line_type: CHANGE_LINE}
|
||||
if !is_add {
|
||||
ltype = `remove`
|
||||
ll.left_reference.path = path
|
||||
} else {
|
||||
ll.right_reference.path = path
|
||||
}
|
||||
lines, err := highlighted_lines_for_path(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var msg_lines []string
|
||||
if is_add {
|
||||
msg_lines = splitlines(`This file was added`, available_cols)
|
||||
} else {
|
||||
msg_lines = splitlines(`This file was removed`, available_cols)
|
||||
}
|
||||
for line_number, line := range lines {
|
||||
hlines := make([]HalfScreenLine, 0, 8)
|
||||
hlines = render_half_line(line_number, line, ltype, available_cols, Center{}, false, hlines)
|
||||
l := ll
|
||||
if is_add {
|
||||
l.right_reference.linenum = line_number + 1
|
||||
} else {
|
||||
l.left_reference.linenum = line_number + 1
|
||||
}
|
||||
l.is_change_start = line_number == 0
|
||||
for i, hl := range hlines {
|
||||
sl := ScreenLine{}
|
||||
if is_add {
|
||||
sl.right = hl
|
||||
if len(msg_lines) > 0 {
|
||||
sl.left.marked_up_text = msg_lines[i]
|
||||
sl.left.is_filler = true
|
||||
msg_lines = msg_lines[1:]
|
||||
} else {
|
||||
sl.left.is_filler = true
|
||||
}
|
||||
} else {
|
||||
sl.left = hl
|
||||
if len(msg_lines) > 0 {
|
||||
sl.right.marked_up_text = msg_lines[i]
|
||||
sl.right.is_filler = true
|
||||
msg_lines = msg_lines[1:]
|
||||
} else {
|
||||
sl.right.is_filler = true
|
||||
}
|
||||
}
|
||||
l.screen_lines = append(l.screen_lines, &sl)
|
||||
}
|
||||
ans = append(ans, &l)
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
|
||||
func rename_lines(path, other_path string, columns, margin_size int, ans []*LogicalLine) ([]*LogicalLine, error) {
|
||||
ll := LogicalLine{
|
||||
left_reference: Reference{path: path}, right_reference: Reference{path: other_path},
|
||||
line_type: CHANGE_LINE, is_change_start: true, is_full_width: true}
|
||||
for _, line := range splitlines(fmt.Sprintf(`The file %s was renamed to %s`, sanitize(path_name_map[path]), sanitize(path_name_map[other_path])), columns-margin_size) {
|
||||
sl := ScreenLine{}
|
||||
sl.right.marked_up_text = line
|
||||
ll.screen_lines = append(ll.screen_lines, &sl)
|
||||
}
|
||||
return append(ans, &ll), nil
|
||||
}
|
||||
|
||||
func render(collection *Collection, diff_map map[string]*Patch, screen_size screen_size, largest_line_number int, image_size graphics.Size) (result *LogicalLines, err error) {
|
||||
margin_size := utils.Max(3, len(strconv.Itoa(largest_line_number))+1)
|
||||
ans := make([]*LogicalLine, 0, 1024)
|
||||
var title_line_indices []int
|
||||
track_titles := conf != nil && conf.Sticky_header
|
||||
columns := screen_size.columns
|
||||
err = collection.Apply(func(path, item_type, changed_path string) error {
|
||||
if track_titles {
|
||||
title_line_indices = append(title_line_indices, len(ans))
|
||||
}
|
||||
ans = title_lines(path, changed_path, columns, margin_size, ans)
|
||||
defer func() {
|
||||
ans = append(ans, &LogicalLine{line_type: EMPTY_LINE, screen_lines: []*ScreenLine{{}}})
|
||||
}()
|
||||
|
||||
is_binary := !is_path_text(path)
|
||||
if !is_binary && item_type == `diff` && !is_path_text(changed_path) {
|
||||
is_binary = true
|
||||
}
|
||||
is_img := is_binary && is_image(path) || (item_type == `diff` && is_image(changed_path))
|
||||
_ = is_img
|
||||
switch item_type {
|
||||
case "diff":
|
||||
if is_binary {
|
||||
if is_img {
|
||||
ans, err = image_lines(path, changed_path, screen_size, margin_size, image_size, ans)
|
||||
} else {
|
||||
ans, err = binary_lines(path, changed_path, columns, margin_size, ans)
|
||||
}
|
||||
} else {
|
||||
ans, err = lines_for_diff(path, changed_path, diff_map[path], columns, margin_size, ans)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case "add":
|
||||
if is_binary {
|
||||
if is_img {
|
||||
ans, err = image_lines("", path, screen_size, margin_size, image_size, ans)
|
||||
} else {
|
||||
ans, err = binary_lines("", path, columns, margin_size, ans)
|
||||
}
|
||||
} else {
|
||||
ans, err = all_lines(path, columns, margin_size, true, ans)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case "removal":
|
||||
if is_binary {
|
||||
if is_img {
|
||||
ans, err = image_lines(path, "", screen_size, margin_size, image_size, ans)
|
||||
} else {
|
||||
ans, err = binary_lines(path, "", columns, margin_size, ans)
|
||||
}
|
||||
} else {
|
||||
ans, err = all_lines(path, columns, margin_size, false, ans)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case "rename":
|
||||
ans, err = rename_lines(path, changed_path, columns, margin_size, ans)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("Unknown change type: %#v", item_type)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
var ll []*LogicalLine
|
||||
if len(ans) > 1 {
|
||||
ll = ans[:len(ans)-1]
|
||||
} else {
|
||||
// Having am empty list of lines causes panics later on
|
||||
ll = []*LogicalLine{{line_type: EMPTY_LINE, screen_lines: []*ScreenLine{{}}}}
|
||||
}
|
||||
return &LogicalLines{lines: ll, title_line_indices: title_line_indices, margin_size: margin_size, columns: columns}, err
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/images"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Search struct {
|
||||
pat *regexp.Regexp
|
||||
matches map[ScrollPos][]Span
|
||||
}
|
||||
|
||||
func (self *Search) Len() int { return len(self.matches) }
|
||||
|
||||
func (self *Search) find_matches_in_lines(clean_lines []string, origin int, send_result func(screen_line, offset, size int)) {
|
||||
lengths := utils.Map(func(x string) int { return len(x) }, clean_lines)
|
||||
offsets := make([]int, len(clean_lines))
|
||||
cell_lengths := utils.Map(wcswidth.Stringwidth, clean_lines)
|
||||
cell_offsets := make([]int, len(clean_lines))
|
||||
for i := range clean_lines {
|
||||
if i > 0 {
|
||||
offsets[i] = offsets[i-1] + lengths[i-1]
|
||||
cell_offsets[i] = cell_offsets[i-1] + cell_lengths[i-1]
|
||||
}
|
||||
}
|
||||
joined_text := strings.Join(clean_lines, "")
|
||||
matches := self.pat.FindAllStringIndex(joined_text, -1)
|
||||
pos := 0
|
||||
|
||||
find_pos := func(start int) int {
|
||||
for i := pos; i < len(clean_lines); i++ {
|
||||
if start < offsets[i]+lengths[i] {
|
||||
pos = i
|
||||
return pos
|
||||
}
|
||||
|
||||
}
|
||||
return -1
|
||||
}
|
||||
for _, m := range matches {
|
||||
start, end := m[0], m[1]
|
||||
total_size := end - start
|
||||
if total_size < 1 {
|
||||
continue
|
||||
}
|
||||
start_line := find_pos(start)
|
||||
if start_line > -1 {
|
||||
end_line := find_pos(end - 1)
|
||||
if end_line > -1 {
|
||||
for i := start_line; i <= end_line; i++ {
|
||||
cell_start := 0
|
||||
if i == start_line {
|
||||
byte_offset := start - offsets[i]
|
||||
cell_start = wcswidth.Stringwidth(clean_lines[i][:byte_offset])
|
||||
}
|
||||
cell_end := cell_lengths[i]
|
||||
if i == end_line {
|
||||
byte_offset := end - offsets[i]
|
||||
cell_end = wcswidth.Stringwidth(clean_lines[i][:byte_offset])
|
||||
}
|
||||
send_result(i, origin+cell_start, cell_end-cell_start)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (self *Search) find_matches_in_line(line *LogicalLine, margin_size, cols int, send_result func(screen_line, offset, size int)) {
|
||||
half_width := cols / 2
|
||||
right_offset := half_width + margin_size
|
||||
left_clean_lines, right_clean_lines := make([]string, len(line.screen_lines)), make([]string, len(line.screen_lines))
|
||||
for i, sl := range line.screen_lines {
|
||||
if line.is_full_width {
|
||||
left_clean_lines[i] = wcswidth.StripEscapeCodes(sl.left.marked_up_text)
|
||||
} else {
|
||||
left_clean_lines[i] = wcswidth.StripEscapeCodes(sl.left.marked_up_text)
|
||||
right_clean_lines[i] = wcswidth.StripEscapeCodes(sl.right.marked_up_text)
|
||||
}
|
||||
}
|
||||
self.find_matches_in_lines(left_clean_lines, margin_size, send_result)
|
||||
self.find_matches_in_lines(right_clean_lines, right_offset, send_result)
|
||||
}
|
||||
|
||||
func (self *Search) Has(pos ScrollPos) bool {
|
||||
return len(self.matches[pos]) > 0
|
||||
}
|
||||
|
||||
type Span struct{ start, end int }
|
||||
|
||||
func (self *Search) search(logical_lines *LogicalLines) {
|
||||
margin_size := logical_lines.margin_size
|
||||
cols := logical_lines.columns
|
||||
self.matches = make(map[ScrollPos][]Span)
|
||||
ctx := images.Context{}
|
||||
mutex := sync.Mutex{}
|
||||
if err := ctx.SafeParallel(0, logical_lines.Len(), func(nums <-chan int) {
|
||||
for i := range nums {
|
||||
line := logical_lines.At(i)
|
||||
if line.line_type == EMPTY_LINE || line.line_type == IMAGE_LINE {
|
||||
continue
|
||||
}
|
||||
self.find_matches_in_line(line, margin_size, cols, func(screen_line, offset, size int) {
|
||||
if size > 0 {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
pos := ScrollPos{i, screen_line}
|
||||
self.matches[pos] = append(self.matches[pos], Span{offset, offset + size - 1})
|
||||
}
|
||||
})
|
||||
}
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
for _, spans := range self.matches {
|
||||
slices.SortFunc(spans, func(a, b Span) int { return a.start - b.start })
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Search) markup_line(pos ScrollPos, y int) string {
|
||||
spans := self.matches[pos]
|
||||
if spans == nil {
|
||||
return ""
|
||||
}
|
||||
sgr := format_as_sgr.search[2:]
|
||||
sgr = sgr[:len(sgr)-1]
|
||||
ans := make([]byte, 0, 32)
|
||||
for _, span := range spans {
|
||||
ans = append(ans, tui.FormatPartOfLine(sgr, span.start, span.end, y)...)
|
||||
}
|
||||
return utils.UnsafeBytesToString(ans)
|
||||
}
|
||||
|
||||
func do_search(pat *regexp.Regexp, logical_lines *LogicalLines) *Search {
|
||||
ans := &Search{pat: pat, matches: make(map[ScrollPos][]Span)}
|
||||
ans.search(logical_lines)
|
||||
return ans
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
func TestDiffSearchFindMatches(t *testing.T) {
|
||||
wrapped := []string{"abc def ", "ghi rows"}
|
||||
for _, tc := range []struct {
|
||||
pat string
|
||||
lines []string
|
||||
origin int
|
||||
expected [][3]int
|
||||
}{
|
||||
{"foo", []string{"x := foo"}, 0, [][3]int{{0, 5, 3}}},
|
||||
{"o", []string{"foo"}, 0, [][3]int{{0, 1, 1}, {0, 2, 1}}},
|
||||
{"rows", wrapped, 0, [][3]int{{1, 4, 4}}},
|
||||
{"def ghi", wrapped, 0, [][3]int{{0, 4, 4}, {1, 0, 3}}},
|
||||
{"def ", wrapped, 0, [][3]int{{0, 4, 4}}},
|
||||
{"foo", []string{"日本 foo"}, 0, [][3]int{{0, 5, 3}}},
|
||||
{"foo", []string{"x := foo"}, 7, [][3]int{{0, 12, 3}}},
|
||||
} {
|
||||
s := &Search{pat: regexp.MustCompile(tc.pat)}
|
||||
var actual [][3]int
|
||||
s.find_matches_in_lines(tc.lines, tc.origin, func(screen_line, offset, size int) {
|
||||
if size > 0 {
|
||||
actual = append(actual, [3]int{screen_line, offset, size})
|
||||
}
|
||||
})
|
||||
if diff := cmp.Diff(tc.expected, actual); diff != "" {
|
||||
t.Errorf("Unexpected matches for %#v in %#v:\n%s", tc.pat, tc.lines, diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package diff
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"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/tui/readline"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type ResultType int
|
||||
|
||||
const (
|
||||
COLLECTION ResultType = iota
|
||||
DIFF
|
||||
HIGHLIGHT
|
||||
IMAGE_LOAD
|
||||
IMAGE_RESIZE
|
||||
)
|
||||
|
||||
type ScrollPos struct {
|
||||
logical_line, screen_line int
|
||||
}
|
||||
|
||||
func (self ScrollPos) Less(other ScrollPos) bool {
|
||||
return self.logical_line < other.logical_line || (self.logical_line == other.logical_line && self.screen_line < other.screen_line)
|
||||
}
|
||||
|
||||
func (self ScrollPos) Add(other ScrollPos) ScrollPos {
|
||||
return ScrollPos{self.logical_line + other.logical_line, self.screen_line + other.screen_line}
|
||||
}
|
||||
|
||||
type AsyncResult struct {
|
||||
err error
|
||||
rtype ResultType
|
||||
collection *Collection
|
||||
diff_map map[string]*Patch
|
||||
page_size graphics.Size
|
||||
}
|
||||
|
||||
var image_collection *graphics.ImageCollection
|
||||
|
||||
type screen_size struct{ rows, columns, num_lines, cell_width, cell_height int }
|
||||
type Handler struct {
|
||||
async_results chan AsyncResult
|
||||
mouse_selection tui.MouseSelection
|
||||
image_count int
|
||||
shortcut_tracker config.ShortcutTracker
|
||||
left, right string
|
||||
collection *Collection
|
||||
diff_map map[string]*Patch
|
||||
logical_lines *LogicalLines
|
||||
terminal_capabilities_received bool
|
||||
lp *loop.Loop
|
||||
current_context_count, original_context_count int
|
||||
added_count, removed_count int
|
||||
screen_size screen_size
|
||||
scroll_pos, max_scroll_pos ScrollPos
|
||||
restore_position *ScrollPos
|
||||
inputting_command bool
|
||||
statusline_message string
|
||||
rl *readline.Readline
|
||||
current_search *Search
|
||||
current_search_is_regex, current_search_is_backward bool
|
||||
largest_line_number int
|
||||
images_resized_to graphics.Size
|
||||
}
|
||||
|
||||
func (self *Handler) calculate_statistics() {
|
||||
self.added_count, self.removed_count = self.collection.added_count, self.collection.removed_count
|
||||
self.largest_line_number = 0
|
||||
for _, patch := range self.diff_map {
|
||||
self.added_count += patch.added_count
|
||||
self.removed_count += patch.removed_count
|
||||
self.largest_line_number = utils.Max(patch.largest_line_number, self.largest_line_number)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) update_screen_size(sz loop.ScreenSize) {
|
||||
self.screen_size.rows = int(sz.HeightCells)
|
||||
self.screen_size.columns = int(sz.WidthCells)
|
||||
self.screen_size.num_lines = self.screen_size.rows - 1
|
||||
self.screen_size.cell_height = int(sz.CellHeight)
|
||||
self.screen_size.cell_width = int(sz.CellWidth)
|
||||
}
|
||||
|
||||
func (self *Handler) on_escape_code(etype loop.EscapeCodeType, payload []byte) error {
|
||||
switch etype {
|
||||
case loop.APC:
|
||||
gc := graphics.GraphicsCommandFromAPC(payload)
|
||||
if gc != nil {
|
||||
if !image_collection.HandleGraphicsCommand(gc) {
|
||||
self.draw_screen()
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) finalize() {
|
||||
image_collection.Finalize(self.lp)
|
||||
}
|
||||
|
||||
func set_terminal_colors(lp *loop.Loop) {
|
||||
create_formatters()
|
||||
lp.SetDefaultColor(loop.FOREGROUND, resolved_colors.Foreground)
|
||||
lp.SetDefaultColor(loop.CURSOR, resolved_colors.Foreground)
|
||||
lp.SetDefaultColor(loop.BACKGROUND, resolved_colors.Background)
|
||||
lp.SetDefaultColor(loop.SELECTION_BG, resolved_colors.Select_bg)
|
||||
if resolved_colors.Select_fg.IsSet {
|
||||
lp.SetDefaultColor(loop.SELECTION_FG, resolved_colors.Select_fg.Color)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) on_capabilities_received(tc loop.TerminalCapabilities) {
|
||||
var use_dark_colors bool
|
||||
prev := use_light_colors
|
||||
switch conf.Color_scheme {
|
||||
case Color_scheme_auto:
|
||||
use_dark_colors = tc.ColorPreference != loop.LIGHT_COLOR_PREFERENCE
|
||||
case Color_scheme_light:
|
||||
use_dark_colors = false
|
||||
case Color_scheme_dark:
|
||||
use_dark_colors = true
|
||||
}
|
||||
use_light_colors = !use_dark_colors
|
||||
if use_light_colors != prev && (light_highlight_started || dark_highlight_started) {
|
||||
self.highlight_all()
|
||||
}
|
||||
set_terminal_colors(self.lp)
|
||||
self.terminal_capabilities_received = true
|
||||
self.draw_screen()
|
||||
}
|
||||
|
||||
func (self *Handler) on_color_scheme_change(cp loop.ColorPreference) error {
|
||||
if conf.Color_scheme != Color_scheme_auto {
|
||||
return nil
|
||||
}
|
||||
light := cp == loop.LIGHT_COLOR_PREFERENCE
|
||||
if use_light_colors != light {
|
||||
use_light_colors = light
|
||||
set_terminal_colors(self.lp)
|
||||
self.highlight_all()
|
||||
self.draw_screen()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) initialize() {
|
||||
self.rl = readline.New(self.lp, readline.RlInit{DontMarkPrompts: true, Prompt: "/"})
|
||||
self.lp.OnEscapeCode = self.on_escape_code
|
||||
self.lp.OnColorSchemeChange = self.on_color_scheme_change
|
||||
image_collection = graphics.NewImageCollection()
|
||||
self.current_context_count = opts.Context
|
||||
if self.current_context_count < 0 {
|
||||
self.current_context_count = int(conf.Num_context_lines)
|
||||
}
|
||||
sz, _ := self.lp.ScreenSize()
|
||||
self.update_screen_size(sz)
|
||||
self.original_context_count = self.current_context_count
|
||||
self.async_results = make(chan AsyncResult, 32)
|
||||
go func() {
|
||||
self.lp.RecoverFromPanicInGoRoutine()
|
||||
r := AsyncResult{}
|
||||
r.collection, r.err = create_collection(self.left, self.right)
|
||||
self.async_results <- r
|
||||
self.lp.WakeupMainThread()
|
||||
}()
|
||||
self.draw_screen()
|
||||
}
|
||||
|
||||
func (self *Handler) generate_diff() {
|
||||
self.diff_map = nil
|
||||
jobs := make([]diff_job, 0, 32)
|
||||
_ = self.collection.Apply(func(path, typ, changed_path string) error {
|
||||
if typ == "diff" {
|
||||
if is_path_text(path) && is_path_text(changed_path) {
|
||||
jobs = append(jobs, diff_job{path, changed_path})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
go func() {
|
||||
self.lp.RecoverFromPanicInGoRoutine()
|
||||
r := AsyncResult{rtype: DIFF}
|
||||
r.diff_map, r.err = diff(jobs, self.current_context_count)
|
||||
self.async_results <- r
|
||||
self.lp.WakeupMainThread()
|
||||
}()
|
||||
}
|
||||
|
||||
func (self *Handler) on_wakeup() error {
|
||||
var r AsyncResult
|
||||
for {
|
||||
select {
|
||||
case r = <-self.async_results:
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
r.err = self.handle_async_result(r)
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var dark_highlight_started bool
|
||||
var light_highlight_started bool
|
||||
|
||||
func (self *Handler) highlight_all() {
|
||||
if (use_light_colors && light_highlight_started) || (!use_light_colors && dark_highlight_started) {
|
||||
return
|
||||
}
|
||||
if use_light_colors {
|
||||
light_highlight_started = true
|
||||
} else {
|
||||
dark_highlight_started = true
|
||||
}
|
||||
text_files := utils.Filter(self.collection.paths_to_highlight.AsSlice(), is_path_text)
|
||||
go func() {
|
||||
self.lp.RecoverFromPanicInGoRoutine()
|
||||
r := AsyncResult{rtype: HIGHLIGHT}
|
||||
highlight_all(text_files, use_light_colors)
|
||||
self.async_results <- r
|
||||
self.lp.WakeupMainThread()
|
||||
}()
|
||||
}
|
||||
|
||||
func (self *Handler) load_all_images() {
|
||||
_ = self.collection.Apply(func(path, item_type, changed_path string) error {
|
||||
if path != "" && is_image(path) {
|
||||
image_collection.AddPaths(path)
|
||||
self.image_count++
|
||||
}
|
||||
if changed_path != "" && is_image(changed_path) {
|
||||
image_collection.AddPaths(changed_path)
|
||||
self.image_count++
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if self.image_count > 0 {
|
||||
image_collection.Initialize(self.lp)
|
||||
go func() {
|
||||
self.lp.RecoverFromPanicInGoRoutine()
|
||||
r := AsyncResult{rtype: IMAGE_LOAD}
|
||||
image_collection.LoadAll()
|
||||
self.async_results <- r
|
||||
self.lp.WakeupMainThread()
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) resize_all_images_if_needed() {
|
||||
if self.logical_lines == nil {
|
||||
return
|
||||
}
|
||||
margin_size := self.logical_lines.margin_size
|
||||
columns := self.logical_lines.columns
|
||||
available_cols := columns/2 - margin_size
|
||||
sz := graphics.Size{
|
||||
Width: available_cols * self.screen_size.cell_width,
|
||||
Height: self.screen_size.num_lines * 2 * self.screen_size.cell_height,
|
||||
}
|
||||
if sz != self.images_resized_to && self.image_count > 0 {
|
||||
go func() {
|
||||
self.lp.RecoverFromPanicInGoRoutine()
|
||||
image_collection.ResizeForPageSize(sz.Width, sz.Height)
|
||||
r := AsyncResult{rtype: IMAGE_RESIZE, page_size: sz}
|
||||
self.async_results <- r
|
||||
self.lp.WakeupMainThread()
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) rerender_diff() error {
|
||||
if self.diff_map != nil && self.collection != nil && self.terminal_capabilities_received {
|
||||
err := self.render_diff()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.draw_screen()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) handle_async_result(r AsyncResult) error {
|
||||
switch r.rtype {
|
||||
case COLLECTION:
|
||||
self.collection = r.collection
|
||||
self.generate_diff()
|
||||
self.highlight_all()
|
||||
self.load_all_images()
|
||||
case DIFF:
|
||||
if !self.terminal_capabilities_received {
|
||||
go func() {
|
||||
self.async_results <- r
|
||||
self.lp.WakeupMainThread()
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
self.diff_map = r.diff_map
|
||||
self.calculate_statistics()
|
||||
self.clear_mouse_selection()
|
||||
err := self.render_diff()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.scroll_pos = ScrollPos{}
|
||||
if self.restore_position != nil {
|
||||
self.scroll_pos = *self.restore_position
|
||||
if self.max_scroll_pos.Less(self.scroll_pos) {
|
||||
self.scroll_pos = self.max_scroll_pos
|
||||
}
|
||||
self.restore_position = nil
|
||||
}
|
||||
self.draw_screen()
|
||||
case IMAGE_RESIZE:
|
||||
self.images_resized_to = r.page_size
|
||||
return self.rerender_diff()
|
||||
case IMAGE_LOAD, HIGHLIGHT:
|
||||
return self.rerender_diff()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) on_resize(old_size, new_size loop.ScreenSize) error {
|
||||
self.clear_mouse_selection()
|
||||
self.update_screen_size(new_size)
|
||||
if self.diff_map != nil && self.collection != nil && self.terminal_capabilities_received {
|
||||
err := self.render_diff()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if self.max_scroll_pos.Less(self.scroll_pos) {
|
||||
self.scroll_pos = self.max_scroll_pos
|
||||
}
|
||||
}
|
||||
self.draw_screen()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) render_diff() (err error) {
|
||||
if self.screen_size.columns < 8 {
|
||||
return fmt.Errorf("Screen too narrow, need at least 8 columns")
|
||||
}
|
||||
if self.screen_size.rows < 2 {
|
||||
return fmt.Errorf("Screen too short, need at least 2 rows")
|
||||
}
|
||||
self.logical_lines, err = render(self.collection, self.diff_map, self.screen_size, self.largest_line_number, self.images_resized_to)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
last := self.logical_lines.Len() - 1
|
||||
self.max_scroll_pos.logical_line = last
|
||||
if last > -1 {
|
||||
self.max_scroll_pos.screen_line = len(self.logical_lines.At(last).screen_lines) - 1
|
||||
} else {
|
||||
self.max_scroll_pos.screen_line = 0
|
||||
}
|
||||
self.logical_lines.IncrementScrollPosBy(&self.max_scroll_pos, -self.screen_size.num_lines+1)
|
||||
if self.current_search != nil {
|
||||
self.current_search.search(self.logical_lines)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) draw_image(key string, _, starting_row int) {
|
||||
image_collection.PlaceImageSubRect(self.lp, key, self.images_resized_to, 0, self.screen_size.cell_height*starting_row, -1, -1)
|
||||
}
|
||||
|
||||
func (self *Handler) draw_image_pair(ll *LogicalLine, starting_row int) {
|
||||
if ll.left_image.key == "" && ll.right_image.key == "" {
|
||||
return
|
||||
}
|
||||
defer self.lp.QueueWriteString("\r")
|
||||
if ll.left_image.key != "" {
|
||||
self.lp.QueueWriteString("\r")
|
||||
self.lp.MoveCursorHorizontally(self.logical_lines.margin_size)
|
||||
self.draw_image(ll.left_image.key, ll.left_image.count, starting_row)
|
||||
}
|
||||
if ll.right_image.key != "" {
|
||||
self.lp.QueueWriteString("\r")
|
||||
self.lp.MoveCursorHorizontally(self.logical_lines.margin_size + self.logical_lines.columns/2)
|
||||
self.draw_image(ll.right_image.key, ll.right_image.count, starting_row)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) draw_screen() {
|
||||
self.lp.StartAtomicUpdate()
|
||||
defer self.lp.EndAtomicUpdate()
|
||||
if self.image_count > 0 {
|
||||
self.resize_all_images_if_needed()
|
||||
image_collection.DeleteAllVisiblePlacements(self.lp)
|
||||
}
|
||||
lp.MoveCursorTo(1, 1)
|
||||
lp.ClearToEndOfScreen()
|
||||
if self.logical_lines == nil || self.diff_map == nil || self.collection == nil || !self.terminal_capabilities_received {
|
||||
lp.Println(`Calculating diff, please wait...`)
|
||||
return
|
||||
}
|
||||
pos := self.scroll_pos
|
||||
seen_images := utils.NewSet[int]()
|
||||
num_written := 0
|
||||
if conf != nil && conf.Sticky_header {
|
||||
num_written = self.draw_sticky_header(&pos)
|
||||
}
|
||||
for ; num_written < self.screen_size.num_lines; num_written++ {
|
||||
ll := self.logical_lines.At(pos.logical_line)
|
||||
if ll == nil || self.logical_lines.ScreenLineAt(pos) == nil {
|
||||
num_written--
|
||||
} else {
|
||||
is_image := ll.line_type == IMAGE_LINE
|
||||
ll.render_screen_line(pos.screen_line, lp, self.logical_lines.margin_size, self.logical_lines.columns)
|
||||
if is_image && !seen_images.Has(pos.logical_line) && pos.screen_line >= ll.image_lines_offset {
|
||||
seen_images.Add(pos.logical_line)
|
||||
self.draw_image_pair(ll, pos.screen_line-ll.image_lines_offset)
|
||||
}
|
||||
if self.current_search != nil {
|
||||
if mkp := self.current_search.markup_line(pos, num_written); mkp != "" {
|
||||
lp.QueueWriteString(mkp)
|
||||
}
|
||||
}
|
||||
if mkp := self.add_mouse_selection_to_line(pos, num_written); mkp != "" {
|
||||
lp.QueueWriteString(mkp)
|
||||
}
|
||||
lp.MoveCursorVertically(1)
|
||||
lp.QueueWriteString("\x1b[m\r")
|
||||
}
|
||||
if self.logical_lines.IncrementScrollPosBy(&pos, 1) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
self.draw_status_line()
|
||||
}
|
||||
|
||||
func (self *Handler) draw_sticky_header(pos *ScrollPos) int {
|
||||
title_idx := self.logical_lines.TitleLineIdxFor(pos.logical_line)
|
||||
if title_idx < 0 {
|
||||
return 0
|
||||
}
|
||||
// If the next line is a different file's TITLE_LINE, skip sticky so the
|
||||
// real title flows into view naturally instead of being consumed.
|
||||
next := pos.logical_line + 1
|
||||
if next < self.logical_lines.Len() && self.logical_lines.At(next).line_type == TITLE_LINE && next != title_idx {
|
||||
return 0
|
||||
}
|
||||
// file title
|
||||
self.logical_lines.At(title_idx).render_screen_line(0, self.lp, self.logical_lines.margin_size, self.logical_lines.columns)
|
||||
self.lp.MoveCursorVertically(1)
|
||||
self.lp.QueueWriteString("\x1b[m\r")
|
||||
self.logical_lines.IncrementScrollPosBy(pos, 1)
|
||||
|
||||
// separator
|
||||
self.logical_lines.At(title_idx+1).render_screen_line(0, self.lp, self.logical_lines.margin_size, self.logical_lines.columns)
|
||||
self.lp.MoveCursorVertically(1)
|
||||
self.lp.QueueWriteString("\x1b[m\r")
|
||||
self.logical_lines.IncrementScrollPosBy(pos, 1)
|
||||
|
||||
return 2
|
||||
}
|
||||
|
||||
func (self *Handler) draw_status_line() {
|
||||
if self.logical_lines == nil || self.diff_map == nil {
|
||||
return
|
||||
}
|
||||
self.lp.MoveCursorTo(1, self.screen_size.rows)
|
||||
self.lp.ClearToEndOfLine()
|
||||
self.lp.SetCursorVisible(self.inputting_command)
|
||||
if self.inputting_command {
|
||||
self.rl.RedrawNonAtomic()
|
||||
} else if self.statusline_message != "" {
|
||||
self.lp.QueueWriteString(message_format(wcswidth.TruncateToVisualLength(sanitize(self.statusline_message), self.screen_size.columns)))
|
||||
} else {
|
||||
num := self.logical_lines.NumScreenLinesTo(self.scroll_pos)
|
||||
den := self.logical_lines.NumScreenLinesTo(self.max_scroll_pos)
|
||||
var frac int
|
||||
if den > 0 {
|
||||
frac = int((float64(num) * 100.0) / float64(den))
|
||||
}
|
||||
sp := statusline_format(fmt.Sprintf("%d%%", frac))
|
||||
var counts string
|
||||
if self.current_search == nil {
|
||||
counts = added_count_format(strconv.Itoa(self.added_count)) + statusline_format(`,`) + removed_count_format(strconv.Itoa(self.removed_count))
|
||||
} else {
|
||||
counts = statusline_format(fmt.Sprintf("%d matches", self.current_search.Len()))
|
||||
}
|
||||
suffix := counts + " " + sp
|
||||
prefix := statusline_format(":")
|
||||
filler := strings.Repeat(" ", utils.Max(0, self.screen_size.columns-wcswidth.Stringwidth(prefix)-wcswidth.Stringwidth(suffix)))
|
||||
self.lp.QueueWriteString(prefix + filler + suffix)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) on_text(text string, a, b bool) error {
|
||||
if self.inputting_command {
|
||||
defer self.draw_status_line()
|
||||
return self.rl.OnText(text, a, b)
|
||||
}
|
||||
if self.statusline_message != "" {
|
||||
self.statusline_message = ""
|
||||
self.draw_status_line()
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) do_search(query string) {
|
||||
self.current_search = nil
|
||||
if len(query) < 2 {
|
||||
return
|
||||
}
|
||||
if !self.current_search_is_regex {
|
||||
query = regexp.QuoteMeta(query)
|
||||
}
|
||||
pat, err := regexp.Compile(`(?i)` + query)
|
||||
if err != nil {
|
||||
self.statusline_message = fmt.Sprintf("Bad regex: %s", err)
|
||||
self.lp.Beep()
|
||||
return
|
||||
}
|
||||
self.current_search = do_search(pat, self.logical_lines)
|
||||
if self.current_search.Len() == 0 {
|
||||
self.current_search = nil
|
||||
self.statusline_message = fmt.Sprintf("No matches for: %#v", query)
|
||||
self.lp.Beep()
|
||||
} else {
|
||||
if self.scroll_to_next_match(false, true) {
|
||||
self.draw_screen()
|
||||
} else {
|
||||
self.lp.Beep()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Handler) on_key_event(ev *loop.KeyEvent) error {
|
||||
if self.inputting_command {
|
||||
defer self.draw_status_line()
|
||||
if ev.MatchesPressOrRepeat("esc") {
|
||||
self.inputting_command = false
|
||||
ev.Handled = true
|
||||
return nil
|
||||
}
|
||||
if ev.MatchesPressOrRepeat("enter") {
|
||||
self.inputting_command = false
|
||||
ev.Handled = true
|
||||
self.do_search(self.rl.AllText())
|
||||
self.draw_screen()
|
||||
return nil
|
||||
}
|
||||
return self.rl.OnKeyEvent(ev)
|
||||
}
|
||||
if self.statusline_message != "" {
|
||||
if ev.Type != loop.RELEASE {
|
||||
ev.Handled = true
|
||||
self.statusline_message = ""
|
||||
self.draw_status_line()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if self.current_search != nil && ev.MatchesPressOrRepeat("esc") {
|
||||
self.current_search = nil
|
||||
self.draw_screen()
|
||||
return nil
|
||||
}
|
||||
ac := self.shortcut_tracker.Match(ev, conf.KeyboardShortcuts)
|
||||
if ac != nil {
|
||||
ev.Handled = true
|
||||
return self.dispatch_action(ac.Name, ac.Args)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) scroll_lines(amt int) (delta int) {
|
||||
before := self.scroll_pos
|
||||
delta = self.logical_lines.IncrementScrollPosBy(&self.scroll_pos, amt)
|
||||
if delta > 0 && self.max_scroll_pos.Less(self.scroll_pos) {
|
||||
self.scroll_pos = self.max_scroll_pos
|
||||
delta = self.logical_lines.Minus(self.scroll_pos, before)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Handler) scroll_to_next_change(backwards bool) bool {
|
||||
if backwards {
|
||||
for i := self.scroll_pos.logical_line - 1; i >= 0; i-- {
|
||||
line := self.logical_lines.At(i)
|
||||
if line.is_change_start {
|
||||
self.scroll_pos = ScrollPos{i, 0}
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i := self.scroll_pos.logical_line + 1; i < self.logical_lines.Len(); i++ {
|
||||
line := self.logical_lines.At(i)
|
||||
if line.is_change_start {
|
||||
self.scroll_pos = ScrollPos{i, 0}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Handler) scroll_to_next_file(backwards bool) bool {
|
||||
if backwards {
|
||||
for i := self.scroll_pos.logical_line - 1; i >= 0; i-- {
|
||||
line := self.logical_lines.At(i)
|
||||
if line.line_type == TITLE_LINE {
|
||||
self.scroll_pos = ScrollPos{i, 0}
|
||||
return true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i := self.scroll_pos.logical_line + 1; i < self.logical_lines.Len(); i++ {
|
||||
line := self.logical_lines.At(i)
|
||||
if line.line_type == TITLE_LINE {
|
||||
self.scroll_pos = ScrollPos{i, 0}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Handler) scroll_to_next_match(backwards, include_current_match bool) bool {
|
||||
if self.current_search == nil {
|
||||
return false
|
||||
}
|
||||
if self.current_search_is_backward {
|
||||
backwards = !backwards
|
||||
}
|
||||
offset, delta := 1, 1
|
||||
if include_current_match {
|
||||
offset = 0
|
||||
}
|
||||
if backwards {
|
||||
offset *= -1
|
||||
delta *= -1
|
||||
}
|
||||
pos := self.scroll_pos
|
||||
if offset != 0 && self.logical_lines.IncrementScrollPosBy(&pos, offset) == 0 {
|
||||
return false
|
||||
}
|
||||
for {
|
||||
if self.current_search.Has(pos) {
|
||||
self.scroll_pos = pos
|
||||
self.draw_screen()
|
||||
return true
|
||||
}
|
||||
if self.logical_lines.IncrementScrollPosBy(&pos, delta) == 0 || self.max_scroll_pos.Less(pos) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Handler) change_context_count(val int) bool {
|
||||
val = utils.Max(0, val)
|
||||
if val == self.current_context_count {
|
||||
return false
|
||||
}
|
||||
self.current_context_count = val
|
||||
p := self.scroll_pos
|
||||
self.restore_position = &p
|
||||
self.clear_mouse_selection()
|
||||
self.generate_diff()
|
||||
self.draw_screen()
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Handler) start_search(is_regex, is_backward bool) {
|
||||
if self.inputting_command {
|
||||
self.lp.Beep()
|
||||
return
|
||||
}
|
||||
self.inputting_command = true
|
||||
self.current_search_is_regex = is_regex
|
||||
self.current_search_is_backward = is_backward
|
||||
self.rl.SetText(``)
|
||||
self.draw_status_line()
|
||||
}
|
||||
|
||||
func (self *Handler) dispatch_action(name, args string) error {
|
||||
switch name {
|
||||
case `quit`:
|
||||
self.lp.Quit(0)
|
||||
case `copy_to_clipboard`:
|
||||
text := self.text_for_current_mouse_selection()
|
||||
if text == "" {
|
||||
self.lp.Beep()
|
||||
} else {
|
||||
self.lp.CopyTextToClipboard(text)
|
||||
}
|
||||
case `copy_to_clipboard_or_exit`:
|
||||
text := self.text_for_current_mouse_selection()
|
||||
if text == "" {
|
||||
self.lp.Quit(0)
|
||||
} else {
|
||||
self.lp.CopyTextToClipboard(text)
|
||||
}
|
||||
case `scroll_by`:
|
||||
if args == "" {
|
||||
args = "1"
|
||||
}
|
||||
amt, err := strconv.Atoi(args)
|
||||
if err == nil {
|
||||
if self.scroll_lines(amt) == 0 {
|
||||
self.lp.Beep()
|
||||
} else {
|
||||
self.draw_screen()
|
||||
}
|
||||
} else {
|
||||
self.lp.Beep()
|
||||
}
|
||||
case `scroll_to`:
|
||||
done := false
|
||||
switch {
|
||||
case strings.Contains(args, "file"):
|
||||
done = self.scroll_to_next_file(strings.Contains(args, `prev`))
|
||||
case strings.Contains(args, `change`):
|
||||
done = self.scroll_to_next_change(strings.Contains(args, `prev`))
|
||||
case strings.Contains(args, `match`):
|
||||
done = self.scroll_to_next_match(strings.Contains(args, `prev`), false)
|
||||
case strings.Contains(args, `page`):
|
||||
amt := self.screen_size.num_lines
|
||||
if strings.Contains(args, `half`) {
|
||||
amt = amt / 2
|
||||
}
|
||||
if strings.Contains(args, `prev`) {
|
||||
amt *= -1
|
||||
}
|
||||
done = self.scroll_lines(amt) != 0
|
||||
default:
|
||||
npos := ScrollPos{}
|
||||
if strings.Contains(args, `end`) {
|
||||
npos = self.max_scroll_pos
|
||||
}
|
||||
done = npos != self.scroll_pos
|
||||
self.scroll_pos = npos
|
||||
}
|
||||
if done {
|
||||
self.draw_screen()
|
||||
} else {
|
||||
self.lp.Beep()
|
||||
}
|
||||
case `change_context`:
|
||||
new_ctx := self.current_context_count
|
||||
switch args {
|
||||
case `all`:
|
||||
new_ctx = 100000
|
||||
case `default`:
|
||||
new_ctx = self.original_context_count
|
||||
default:
|
||||
delta, _ := strconv.Atoi(args)
|
||||
new_ctx += delta
|
||||
}
|
||||
if !self.change_context_count(new_ctx) {
|
||||
self.lp.Beep()
|
||||
}
|
||||
case `start_search`:
|
||||
if self.diff_map != nil && self.logical_lines != nil {
|
||||
a, b, _ := strings.Cut(args, " ")
|
||||
self.start_search(config.StringToBool(a), config.StringToBool(b))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Handler) on_mouse_event(ev *loop.MouseEvent) error {
|
||||
if self.logical_lines == nil {
|
||||
return nil
|
||||
}
|
||||
if ev.Event_type == loop.MOUSE_PRESS && ev.Buttons&(loop.MOUSE_WHEEL_UP|loop.MOUSE_WHEEL_DOWN) != 0 {
|
||||
self.handle_wheel_event(ev.Buttons&(loop.MOUSE_WHEEL_UP) != 0)
|
||||
return nil
|
||||
}
|
||||
if ev.Event_type == loop.MOUSE_PRESS && ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
|
||||
self.start_mouse_selection(ev)
|
||||
return nil
|
||||
}
|
||||
if ev.Event_type == loop.MOUSE_MOVE {
|
||||
self.update_mouse_selection(ev)
|
||||
return nil
|
||||
}
|
||||
if ev.Event_type == loop.MOUSE_RELEASE && ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
|
||||
self.finish_mouse_selection(ev)
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,18 @@
|
||||
//go:build darwin || freebsd || netbsd
|
||||
|
||||
package dnd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Return the birth time of the file at path, which must be the file
|
||||
// described by info, or the zero time if it is unknown.
|
||||
func birth_time(path string, info os.FileInfo) time.Time {
|
||||
if st, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
return time.Unix(st.Birthtimespec.Unix())
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package dnd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// Return the birth time of the file at path, which must be the file
|
||||
// described by info, or the zero time if it is unknown.
|
||||
func birth_time(path string, info os.FileInfo) time.Time {
|
||||
var sx unix.Statx_t
|
||||
for {
|
||||
err := unix.Statx(unix.AT_FDCWD, path, unix.AT_SYMLINK_NOFOLLOW, unix.STATX_INO|unix.STATX_BTIME, &sx)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if err != unix.EINTR {
|
||||
return time.Time{}
|
||||
}
|
||||
}
|
||||
if sx.Mask&unix.STATX_BTIME == 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
// The path may have been replaced since info was obtained
|
||||
dev, ino, err := file_identity(info)
|
||||
if err != nil || ino != sx.Ino || dev != unix.Mkdev(sx.Dev_major, sx.Dev_minor) {
|
||||
return time.Time{}
|
||||
}
|
||||
return time.Unix(sx.Btime.Sec, int64(sx.Btime.Nsec))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !linux && !darwin && !freebsd && !netbsd
|
||||
|
||||
package dnd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Return the birth time of the file at path, which must be the file
|
||||
// described by info, or the zero time if it is unknown.
|
||||
func birth_time(path string, info os.FileInfo) time.Time {
|
||||
return time.Time{}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
package dnd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
"github.com/kovidgoyal/imaging"
|
||||
"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/streaming_base64"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type data_request struct {
|
||||
drag_source *drag_source
|
||||
index int
|
||||
write_id loop.IdType
|
||||
base64 streaming_base64.StreamingBase64Encoder
|
||||
}
|
||||
|
||||
type remote_data_item struct {
|
||||
path string
|
||||
metadata os.FileInfo
|
||||
file *os.File
|
||||
write_id loop.IdType
|
||||
base64 streaming_base64.StreamingBase64Encoder
|
||||
parent_dir_handle, idx_in_parent int
|
||||
idx_in_uri_list int
|
||||
}
|
||||
|
||||
type drag_status struct {
|
||||
active bool
|
||||
terminal_accepted_drag bool
|
||||
offered_mimes []string
|
||||
accepted_mime int
|
||||
accepted_operation int
|
||||
dropped bool
|
||||
data_requests []*data_request
|
||||
remote_items []*remote_data_item
|
||||
current_remote_file *remote_data_item
|
||||
dir_handle_counter int
|
||||
remote_item_write_id loop.IdType
|
||||
remote_data_requests []int
|
||||
}
|
||||
|
||||
func find_drag_image(drag_sources map[string]*drag_source) image.Image {
|
||||
for mime, ds := range drag_sources {
|
||||
if ds.path != "" {
|
||||
if strings.HasPrefix(mime, "image/") {
|
||||
q, err := imaging.Open(ds.path)
|
||||
if err == nil {
|
||||
return q
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var uri_list []string
|
||||
if ds := drag_sources["text/uri-list"]; ds != nil {
|
||||
for _, e := range ds.uri_list {
|
||||
if e.path != "" {
|
||||
uri_list = append(uri_list, e.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, path := range uri_list {
|
||||
q, err := imaging.Open(path)
|
||||
if err == nil {
|
||||
return q
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dnd *dnd) set_drag_image_text() (err error) {
|
||||
icon := ""
|
||||
from_path := func(path string) bool {
|
||||
if st, err := os.Lstat(path); err == nil {
|
||||
ans := strings.TrimSpace(icons.IconForFileWithMode(path, st.Mode(), true))
|
||||
if ans != "" {
|
||||
icon = ans
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
for _, ds := range dnd.drag_sources {
|
||||
if ds.path != "" && from_path(ds.path) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if icon == "" {
|
||||
if ds := dnd.drag_sources["text/uri-list"]; ds != nil {
|
||||
for _, e := range ds.uri_list {
|
||||
if e.path != "" && from_path(e.path) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if icon == "" {
|
||||
icon = strings.TrimSpace(" ")
|
||||
}
|
||||
cmd := DC{Type: 'p', X: -1, Xp: 6, Yp: 1, Payload: []byte(icon)}
|
||||
dnd.lp.QueueDnDData(cmd)
|
||||
cmd.Payload = nil
|
||||
dnd.lp.QueueDnDData(cmd)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dnd *dnd) set_drag_image() (err error) {
|
||||
img := dnd.drag_thumbnail
|
||||
if img == nil {
|
||||
img = find_drag_image(dnd.drag_sources)
|
||||
}
|
||||
if img == nil {
|
||||
return dnd.set_drag_image_text()
|
||||
}
|
||||
num_channels := utils.IfElse(imaging.IsOpaque(img), 3, 4)
|
||||
sz := dnd.opts.DragThumbnailSize
|
||||
if max(img.Bounds().Dx(), img.Bounds().Dy()) > sz {
|
||||
w, h := 0, 0
|
||||
if img.Bounds().Dx() >= img.Bounds().Dy() {
|
||||
w = sz
|
||||
} else {
|
||||
h = sz
|
||||
}
|
||||
img = imaging.ResizeWithOpacity(img, w, h, imaging.Lanczos, num_channels == 3)
|
||||
if dnd.drag_thumbnail != nil {
|
||||
dnd.drag_thumbnail = img
|
||||
}
|
||||
}
|
||||
var pix []byte
|
||||
if imaging.IsOpaque(img) {
|
||||
_, pix = 3, imaging.AsRGBData8(img)
|
||||
} else {
|
||||
pix = imaging.AsRGBAData8(img)
|
||||
}
|
||||
cmd := DC{
|
||||
Type: 'p', X: -1, Y: utils.IfElse(num_channels == 3, 24, 32), Xp: img.Bounds().Dx(), Yp: img.Bounds().Dy(),
|
||||
Payload: pix}
|
||||
dnd.lp.QueueDnDData(cmd)
|
||||
cmd.Payload = nil
|
||||
dnd.lp.QueueDnDData(cmd)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dnd *dnd) on_potential_drag_start(cell_x, cell_y int) (err error) {
|
||||
if !dnd.allow_drags || dnd.drag_status.active {
|
||||
return
|
||||
}
|
||||
mimes := slices.Collect(maps.Keys(dnd.drag_sources))
|
||||
actions := 3
|
||||
if dnd.copy_button_region.has(cell_x, cell_y) {
|
||||
actions = 1
|
||||
} else if dnd.move_button_region.has(cell_x, cell_y) {
|
||||
actions = 2
|
||||
}
|
||||
dnd.lp.QueueDnDData(DC{Type: 'o', Operation: actions, Payload: utils.UnsafeStringToBytes(strings.Join(mimes, " "))})
|
||||
total_preloaded_data_sz := 0
|
||||
for i, mt := range mimes {
|
||||
s := dnd.drag_sources[mt]
|
||||
if len(s.data) > 0 && len(s.data)+total_preloaded_data_sz < 64*1024*1024 {
|
||||
total_preloaded_data_sz += len(s.data)
|
||||
dnd.lp.QueueDnDData(DC{Type: 'p', X: i, Operation: actions, Payload: s.data})
|
||||
dnd.lp.QueueDnDData(DC{Type: 'p', X: i, Operation: actions})
|
||||
}
|
||||
}
|
||||
dnd.drag_status.offered_mimes = mimes
|
||||
err = dnd.set_drag_image()
|
||||
if err != nil {
|
||||
dnd.finish_drag("EIO")
|
||||
return err
|
||||
}
|
||||
dnd.lp.QueueDnDData(DC{Type: 'P', X: -1}) // start drag
|
||||
dnd.drag_status.active = true
|
||||
|
||||
return dnd.render_screen()
|
||||
}
|
||||
|
||||
func (dnd *dnd) on_drag_error(cmd DC) (err error) {
|
||||
payload := string(cmd.Payload)
|
||||
switch payload {
|
||||
case "OK":
|
||||
if dnd.drag_status.active && !dnd.drag_status.terminal_accepted_drag {
|
||||
dnd.drag_status.terminal_accepted_drag = true
|
||||
err = dnd.render_screen()
|
||||
}
|
||||
default:
|
||||
err = fmt.Errorf("terminal responded with drag source error: %s", payload)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) reset_drag() {
|
||||
for _, dr := range dnd.drag_status.data_requests {
|
||||
if dr.drag_source.file != nil {
|
||||
dr.drag_source.file.Close()
|
||||
dr.drag_source.file = nil
|
||||
}
|
||||
}
|
||||
if dnd.drag_status.current_remote_file != nil && dnd.drag_status.current_remote_file.file != nil {
|
||||
dnd.drag_status.current_remote_file.file.Close()
|
||||
}
|
||||
dnd.drag_status = drag_status{}
|
||||
}
|
||||
|
||||
func (dnd *dnd) on_drag_event(x, y, operation int) (err error) {
|
||||
switch x {
|
||||
case 1:
|
||||
dnd.drag_status.accepted_mime = y
|
||||
case 2:
|
||||
dnd.drag_status.accepted_operation = operation
|
||||
case 3:
|
||||
dnd.drag_status.dropped = true
|
||||
case 4:
|
||||
was_dropped := dnd.drag_status.dropped
|
||||
was_move := dnd.drag_status.accepted_operation == 2
|
||||
dnd.reset_drag()
|
||||
if was_dropped && dnd.has_exit_on("drag-finish") {
|
||||
dnd.lp.Quit(0)
|
||||
}
|
||||
if was_dropped && was_move {
|
||||
if ds := dnd.drag_sources["text/uri-list"]; ds != nil {
|
||||
for _, item := range ds.uri_list {
|
||||
if item.was_sent {
|
||||
if item.metadata.IsDir() {
|
||||
err = os.RemoveAll(item.path)
|
||||
} else {
|
||||
err = os.Remove(item.path)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dnd.drag_sources = nil
|
||||
dnd.allow_drags = false
|
||||
dnd.lp.StopOfferingDrags()
|
||||
if !dnd.allow_drops {
|
||||
dnd.lp.Quit(0)
|
||||
}
|
||||
}
|
||||
case 5:
|
||||
if err = dnd.handle_data_request(y); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return dnd.render_screen()
|
||||
}
|
||||
|
||||
func (dnd *dnd) finish_drag(errname string) {
|
||||
if errname == "" { // cancel drag
|
||||
dnd.lp.QueueDnDData(DC{Type: 'E', Y: -1})
|
||||
} else {
|
||||
dnd.lp.QueueDnDData(DC{Type: 'E', Payload: []byte(errname)})
|
||||
}
|
||||
dnd.reset_drag()
|
||||
}
|
||||
|
||||
func (dnd *dnd) handle_data_request(idx int) (err error) {
|
||||
if idx < 0 || idx >= len(dnd.drag_status.offered_mimes) {
|
||||
dnd.finish_drag("EINVAL")
|
||||
return fmt.Errorf("terminal asked for drag data from MIME list with out of bounds index: %d", idx)
|
||||
}
|
||||
mime := dnd.drag_status.offered_mimes[idx]
|
||||
ds := dnd.drag_sources[mime]
|
||||
for _, dr := range dnd.drag_status.data_requests {
|
||||
if dr.index == idx {
|
||||
dnd.finish_drag("EINVAL")
|
||||
return fmt.Errorf("terminal sent a duplicate drag data request")
|
||||
}
|
||||
}
|
||||
dr := &data_request{drag_source: ds, index: idx}
|
||||
if ds.path == "" {
|
||||
dnd.lp.QueueDnDData(DC{Type: 'e', Y: idx, Payload: utils.UnsafeStringToBytes(base64.RawStdEncoding.EncodeToString(ds.data))})
|
||||
dnd.lp.QueueDnDData(DC{Type: 'e', Y: idx}) // EOF
|
||||
return
|
||||
} else {
|
||||
if ds.file != nil {
|
||||
ds.file.Close()
|
||||
}
|
||||
if ds.file, err = os.Open(ds.path); err != nil {
|
||||
dnd.finish_drag("EIO")
|
||||
return err
|
||||
}
|
||||
}
|
||||
dnd.drag_status.data_requests = append(dnd.drag_status.data_requests, dr)
|
||||
return dnd.send_data_for_data_request(len(dnd.drag_status.data_requests) - 1)
|
||||
}
|
||||
|
||||
var read_buf [64 * 1024]byte
|
||||
var encode_buf [128 * 1024]byte
|
||||
|
||||
func (dnd *dnd) send_data_for_data_request(i int) (err error) {
|
||||
dr := dnd.drag_status.data_requests[i]
|
||||
n, err := dr.drag_source.file.Read(read_buf[:])
|
||||
if n > 0 {
|
||||
for chunk := range dr.base64.Encode(read_buf[:n], encode_buf[:]) {
|
||||
dr.write_id = dnd.lp.QueueDnDData(DC{Type: 'e', Y: dr.index, Payload: chunk})
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
chunk := dr.base64.Finish()
|
||||
if len(chunk) > 0 {
|
||||
dr.write_id = dnd.lp.QueueDnDData(DC{Type: 'e', Y: dr.index, Payload: chunk})
|
||||
}
|
||||
dr.write_id = dnd.lp.QueueDnDData(DC{Type: 'e', Y: dr.index}) // EOF
|
||||
return dnd.on_data_request_finished(i)
|
||||
}
|
||||
dnd.finish_drag("EIO")
|
||||
return err
|
||||
}
|
||||
|
||||
func (dnd *dnd) on_send_done(id loop.IdType) (err error) {
|
||||
for i, dr := range dnd.drag_status.data_requests {
|
||||
if dr.write_id == id {
|
||||
return dnd.send_data_for_data_request(i)
|
||||
}
|
||||
}
|
||||
if id == dnd.drag_status.remote_item_write_id {
|
||||
dnd.drag_status.remote_item_write_id = 0
|
||||
err = dnd.send_next_file_chunk()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) on_data_request_finished(i int) (err error) {
|
||||
dr := dnd.drag_status.data_requests[i]
|
||||
if dr.drag_source.file != nil {
|
||||
dr.drag_source.file.Close()
|
||||
dr.drag_source.file = nil
|
||||
}
|
||||
dnd.drag_status.data_requests = slices.Delete(dnd.drag_status.data_requests, i, i+1)
|
||||
if len(dnd.drag_status.data_requests) > 0 {
|
||||
err = dnd.send_data_for_data_request(0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) send_remote_item_payload(parent_dir_handle, idx_in_parent, idx_in_uri_list, item_type int, payload []byte) loop.IdType {
|
||||
cmd := DC{Type: 'k', Xp: item_type, X: idx_in_uri_list + 1}
|
||||
if len(payload) > 0 {
|
||||
if item_type == 0 {
|
||||
cmd.Payload = payload
|
||||
} else {
|
||||
cmd.Payload = utils.UnsafeStringToBytes(base64.RawStdEncoding.EncodeToString(payload))
|
||||
}
|
||||
}
|
||||
if parent_dir_handle != 0 {
|
||||
cmd.Yp = parent_dir_handle
|
||||
cmd.Y = idx_in_parent + 1
|
||||
}
|
||||
return dnd.lp.QueueDnDData(cmd)
|
||||
}
|
||||
|
||||
func (dnd *dnd) send_remote_dir(path string, idx_in_uri_list, parent_dir_handle, idx int) (children []*remote_data_item, err error) {
|
||||
entries, err := os.ReadDir(path)
|
||||
if err != nil {
|
||||
dnd.finish_drag("EIO")
|
||||
return nil, err
|
||||
}
|
||||
for dnd.drag_status.dir_handle_counter < 2 {
|
||||
dnd.drag_status.dir_handle_counter++
|
||||
}
|
||||
handle := dnd.drag_status.dir_handle_counter
|
||||
dnd.drag_status.dir_handle_counter++
|
||||
names := make([]string, 0, len(entries))
|
||||
for i, entry := range entries {
|
||||
st, err := entry.Info()
|
||||
if err != nil {
|
||||
dnd.finish_drag("EIO")
|
||||
return nil, err
|
||||
}
|
||||
x := remote_data_item{
|
||||
parent_dir_handle: handle, idx_in_parent: i, metadata: st, idx_in_uri_list: idx_in_uri_list,
|
||||
path: filepath.Join(path, entry.Name())}
|
||||
children = append(children, &x)
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
payload := utils.UnsafeStringToBytes(strings.Join(names, "\x00"))
|
||||
if len(payload) > 0 {
|
||||
dnd.send_remote_item_payload(parent_dir_handle, idx, idx_in_uri_list, handle, payload)
|
||||
}
|
||||
dnd.drag_status.remote_item_write_id = dnd.send_remote_item_payload(parent_dir_handle, idx, idx_in_uri_list, handle, nil)
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) send_remote_symlink(path string, idx_in_uri_list, parent_dir_handle, idx int) (err error) {
|
||||
target, err := os.Readlink(path)
|
||||
if err != nil {
|
||||
dnd.finish_drag("EIO")
|
||||
return err
|
||||
}
|
||||
if len(target) > 0 {
|
||||
dnd.send_remote_item_payload(parent_dir_handle, idx, idx_in_uri_list, 1, utils.UnsafeStringToBytes(target))
|
||||
}
|
||||
dnd.drag_status.remote_item_write_id = dnd.send_remote_item_payload(parent_dir_handle, idx, idx_in_uri_list, 1, nil)
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) send_next_file_chunk() (err error) {
|
||||
cr := dnd.drag_status.current_remote_file
|
||||
if cr == nil {
|
||||
return dnd.next_remote_item()
|
||||
}
|
||||
n, err := cr.file.Read(read_buf[:])
|
||||
if n > 0 {
|
||||
encoded_chunk_sent := false
|
||||
for chunk := range cr.base64.Encode(read_buf[:n], encode_buf[:]) {
|
||||
dnd.drag_status.remote_item_write_id = dnd.send_remote_item_payload(cr.parent_dir_handle, cr.idx_in_parent, cr.idx_in_uri_list, 0, chunk)
|
||||
encoded_chunk_sent = true
|
||||
}
|
||||
if !encoded_chunk_sent {
|
||||
return dnd.send_next_file_chunk()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
cr.file.Close()
|
||||
dnd.drag_status.current_remote_file = nil
|
||||
if chunk := cr.base64.Finish(); len(chunk) > 0 {
|
||||
dnd.send_remote_item_payload(cr.parent_dir_handle, cr.idx_in_parent, cr.idx_in_uri_list, 0, chunk)
|
||||
}
|
||||
dnd.drag_status.remote_item_write_id = dnd.send_remote_item_payload(cr.parent_dir_handle, cr.idx_in_parent, cr.idx_in_uri_list, 0, nil)
|
||||
return nil
|
||||
}
|
||||
dnd.finish_drag("EIO")
|
||||
return err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) next_remote_item() (err error) {
|
||||
if len(dnd.drag_status.remote_items) < 1 {
|
||||
// current remote data request finished
|
||||
dnd.drag_status.remote_data_requests = dnd.drag_status.remote_data_requests[1:]
|
||||
if len(dnd.drag_status.remote_data_requests) > 0 {
|
||||
return dnd.send_next_remote_data_request()
|
||||
}
|
||||
if len(dnd.drag_status.data_requests) > 0 {
|
||||
err = dnd.send_data_for_data_request(0)
|
||||
}
|
||||
return
|
||||
}
|
||||
x := dnd.drag_status.remote_items[0]
|
||||
dnd.drag_status.remote_items = dnd.drag_status.remote_items[1:]
|
||||
if x.metadata.IsDir() {
|
||||
children, err := dnd.send_remote_dir(x.path, x.idx_in_uri_list, x.parent_dir_handle, x.idx_in_parent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dnd.drag_status.remote_items = append(dnd.drag_status.remote_items, children...)
|
||||
} else if x.metadata.Mode().Type()&os.ModeSymlink != 0 {
|
||||
if err = dnd.send_remote_symlink(x.path, x.idx_in_uri_list, x.parent_dir_handle, x.idx_in_parent); err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if x.file, err = os.Open(x.path); err != nil {
|
||||
dnd.finish_drag("EIO")
|
||||
return err
|
||||
}
|
||||
dnd.drag_status.current_remote_file = x
|
||||
if err = dnd.send_next_file_chunk(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) on_drag_remote_data_request(idx int) (err error) {
|
||||
ds := dnd.drag_sources["text/uri-list"]
|
||||
if ds == nil || len(ds.uri_list) < 1 {
|
||||
dnd.finish_drag("EINVAL")
|
||||
return fmt.Errorf("terminal asked for drag data from URI list but no list present")
|
||||
}
|
||||
if idx < 0 || idx >= len(ds.uri_list) {
|
||||
dnd.finish_drag("EINVAL")
|
||||
return fmt.Errorf("terminal asked for drag data from URI list with out of bounds index: %d", idx)
|
||||
}
|
||||
ds.uri_list[idx].was_sent = true
|
||||
dnd.drag_status.remote_data_requests = append(dnd.drag_status.remote_data_requests, idx)
|
||||
if len(dnd.drag_status.remote_data_requests) == 1 {
|
||||
err = dnd.send_next_remote_data_request()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) send_next_remote_data_request() (err error) {
|
||||
if len(dnd.drag_status.remote_data_requests) == 0 {
|
||||
return nil
|
||||
}
|
||||
i := dnd.drag_status.remote_data_requests[0]
|
||||
x := dnd.drag_sources["text/uri-list"].uri_list[i]
|
||||
items := []*remote_data_item{}
|
||||
if x.metadata.IsDir() {
|
||||
if children, err := dnd.send_remote_dir(x.path, i, 0, i); err != nil {
|
||||
return err
|
||||
} else {
|
||||
items = append(items, children...)
|
||||
}
|
||||
} else if x.metadata.Mode().Type()&os.ModeSymlink != 0 {
|
||||
if err = dnd.send_remote_symlink(x.path, i, 0, i); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
f := remote_data_item{idx_in_parent: i, idx_in_uri_list: i, metadata: x.metadata, path: x.path}
|
||||
dnd.drag_status.remote_items = append(dnd.drag_status.remote_items, &f)
|
||||
}
|
||||
dnd.drag_status.remote_items = append(dnd.drag_status.remote_items, items...)
|
||||
if dnd.drag_status.remote_item_write_id == 0 {
|
||||
return dnd.next_remote_item()
|
||||
}
|
||||
return
|
||||
}
|
||||
+1262
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,468 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package dnd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"io/fs"
|
||||
"maps"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/kovidgoyal/imaging"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Append
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
type uri_list_item struct {
|
||||
path, uri, human_name string
|
||||
file *os.File
|
||||
metadata os.FileInfo
|
||||
was_sent bool
|
||||
}
|
||||
|
||||
type drag_source struct {
|
||||
human_name, path string
|
||||
file *os.File
|
||||
mime_type string
|
||||
uri_list []uri_list_item
|
||||
data []byte
|
||||
}
|
||||
|
||||
type bufferWriteCloser struct {
|
||||
*bytes.Buffer
|
||||
}
|
||||
|
||||
// Close implements the io.Closer interface (as a no-op)
|
||||
func (bwc *bufferWriteCloser) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type DC = loop.DndCommand
|
||||
|
||||
type dir_handle struct {
|
||||
handle *os.File
|
||||
refcnt atomic.Int32
|
||||
}
|
||||
|
||||
func new_dir_handle(x *os.File) *dir_handle {
|
||||
ans := dir_handle{x, atomic.Int32{}}
|
||||
ans.refcnt.Store(1)
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (d *dir_handle) newref() *dir_handle {
|
||||
d.refcnt.Add(1)
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *dir_handle) unref() *dir_handle {
|
||||
if d.refcnt.Add(-1) <= 0 {
|
||||
d.handle.Close()
|
||||
d.handle = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type dnd struct {
|
||||
opts *Options
|
||||
drop_dests map[string]*drop_dest
|
||||
drag_sources map[string]*drag_source
|
||||
initial_drag_sources map[string]*drag_source
|
||||
drag_thumbnail image.Image
|
||||
allow_drops, allow_drags bool
|
||||
|
||||
lp *loop.Loop
|
||||
drop_status drop_status
|
||||
drop_output_dir *os.File
|
||||
base_tempdir *os.File
|
||||
tdir_counter int
|
||||
is_case_sensitive_filesystem bool // false if names differing in case or Unicode normalization are aliases
|
||||
num_dropped_files int
|
||||
drag_status drag_status
|
||||
in_test_mode bool
|
||||
copy_button_region, move_button_region button_region
|
||||
confirm_drop struct {
|
||||
overwrites []string
|
||||
staging_dir *os.File
|
||||
}
|
||||
}
|
||||
|
||||
func (dnd *dnd) send_test_response(payload string) {
|
||||
dnd.lp.DebugPrintln(payload)
|
||||
}
|
||||
|
||||
func (dnd *dnd) has_exit_on(event string) bool {
|
||||
for e := range strings.SplitSeq(dnd.opts.ExitOn, ",") {
|
||||
if strings.TrimSpace(e) == event {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (dnd *dnd) setup_base_dir(base_dir string) (err error) {
|
||||
if dnd.drop_output_dir != nil {
|
||||
dnd.drop_output_dir.Close()
|
||||
}
|
||||
if dnd.drop_output_dir, err = os.Open(base_dir); err != nil {
|
||||
return err
|
||||
}
|
||||
base_tdir, err := os.MkdirTemp(base_dir, ".dnd-kitten-drop-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
bf, err := os.Open(base_tdir)
|
||||
if err != nil {
|
||||
os.RemoveAll(base_tdir)
|
||||
return err
|
||||
}
|
||||
dnd.base_tempdir = bf
|
||||
dnd.is_case_sensitive_filesystem = names_are_distinct(base_tdir)
|
||||
return err
|
||||
}
|
||||
|
||||
// Return true if names that differ only in case or Unicode normalization
|
||||
// refer to different entries in the empty directory dir. Any failure to
|
||||
// determine this is treated as them being aliases, which is the safe choice.
|
||||
func names_are_distinct(dir string) bool {
|
||||
is_absent := func(path string) bool {
|
||||
_, err := os.Lstat(path)
|
||||
return errors.Is(err, fs.ErrNotExist)
|
||||
}
|
||||
if !is_absent(filepath.Join(filepath.Dir(dir), strings.ToUpper(filepath.Base(dir)))) {
|
||||
return false
|
||||
}
|
||||
probe := filepath.Join(dir, "\u00e9")
|
||||
if err := os.WriteFile(probe, nil, 0o600); err != nil {
|
||||
return false
|
||||
}
|
||||
defer os.Remove(probe)
|
||||
return is_absent(filepath.Join(dir, "e\u0301"))
|
||||
}
|
||||
|
||||
func (dnd *dnd) remove_tdir() error {
|
||||
path := dnd.base_tempdir.Name()
|
||||
dnd.base_tempdir.Close()
|
||||
dnd.base_tempdir = nil
|
||||
return os.RemoveAll(path)
|
||||
}
|
||||
|
||||
func (dnd *dnd) run_loop() (err error) {
|
||||
defer func() {
|
||||
if dnd.in_test_mode && err != nil {
|
||||
debugprintln("dnd kitten exiting with error: ", err)
|
||||
}
|
||||
}()
|
||||
base_dir := dnd.opts.DropDest
|
||||
if base_dir == "" {
|
||||
base_dir, err = os.Getwd()
|
||||
} else {
|
||||
base_dir, err = filepath.Abs(base_dir)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = dnd.setup_base_dir(base_dir); err != nil {
|
||||
return err
|
||||
}
|
||||
defer dnd.remove_tdir()
|
||||
|
||||
dnd.allow_drops, dnd.allow_drags = len(dnd.drop_dests) > 0, len(dnd.drag_sources) > 0
|
||||
dnd.initial_drag_sources = dnd.drag_sources
|
||||
if dnd.lp, err = loop.New(); err != nil {
|
||||
return err
|
||||
}
|
||||
dnd.lp.MouseTrackingMode(loop.BUTTONS_AND_DRAG_MOUSE_TRACKING)
|
||||
dnd.reset_drop()
|
||||
|
||||
dnd.lp.OnInitialize = func() (string, error) {
|
||||
dnd.lp.AllowLineWrapping(false)
|
||||
dnd.lp.SetCursorVisible(false)
|
||||
if dnd.allow_drops {
|
||||
dnd.lp.StartAcceptingDrops("", slices.Collect(maps.Keys(dnd.drop_dests))...)
|
||||
}
|
||||
if dnd.allow_drags {
|
||||
dnd.lp.StartOfferingDrags("")
|
||||
}
|
||||
dnd.lp.SetWindowTitle("Drag and drop")
|
||||
return "", dnd.render_screen()
|
||||
}
|
||||
|
||||
dnd.lp.OnFinalize = func() string {
|
||||
dnd.lp.AllowLineWrapping(true)
|
||||
dnd.lp.SetCursorVisible(true)
|
||||
if dnd.allow_drops {
|
||||
dnd.lp.StopAcceptingDrops()
|
||||
}
|
||||
if dnd.allow_drags {
|
||||
dnd.lp.StopOfferingDrags()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
dnd.lp.OnWakeup = func() error {
|
||||
if err := dnd.drop_on_wakeup(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
dnd.lp.OnDnDData = func(cmd loop.DndCommand) error {
|
||||
switch cmd.Type {
|
||||
case 'T':
|
||||
switch string(cmd.Payload) {
|
||||
case "PING":
|
||||
dnd.send_test_response("PONG")
|
||||
case "SETUP_LOCAL", "SETUP_REMOTE":
|
||||
dnd.in_test_mode = true
|
||||
dnd.lp.NoRoundtripToTerminalOnExit()
|
||||
dnd.drop_status.reset()
|
||||
dnd.lp.StopAcceptingDrops()
|
||||
dnd.lp.StopOfferingDrags()
|
||||
dnd.remove_tdir()
|
||||
dnd.setup_base_dir(base_dir)
|
||||
dnd.drag_sources = dnd.initial_drag_sources
|
||||
dnd.allow_drops, dnd.allow_drags = len(dnd.drop_dests) > 0, len(dnd.drag_sources) > 0
|
||||
machine_id := ""
|
||||
if string(cmd.Payload) == "SETUP_REMOTE" {
|
||||
machine_id = "remote-client-for-test"
|
||||
}
|
||||
if dnd.allow_drops {
|
||||
dnd.lp.StartAcceptingDrops(machine_id, slices.Collect(maps.Keys(dnd.drop_dests))...)
|
||||
}
|
||||
if dnd.allow_drags {
|
||||
dnd.lp.StartOfferingDrags(machine_id)
|
||||
}
|
||||
dnd.render_screen()
|
||||
dnd.send_test_response("SETUP_DONE")
|
||||
case "GEOMETRY":
|
||||
dnd.send_test_response(fmt.Sprintf("GEOMETRY:%d:%d:%d:%d:%d:%d:%d:%d", dnd.copy_button_region.left, dnd.copy_button_region.top, dnd.copy_button_region.width, dnd.copy_button_region.height, dnd.move_button_region.left, dnd.move_button_region.top, dnd.move_button_region.width, dnd.move_button_region.height))
|
||||
case "DROP_MIMES":
|
||||
if dnd.drop_status.offered_mimes != nil {
|
||||
dnd.send_test_response(strings.Join(dnd.drop_status.offered_mimes, " "))
|
||||
} else {
|
||||
dnd.send_test_response("")
|
||||
}
|
||||
case "DROP_IS_REMOTE":
|
||||
dnd.send_test_response(utils.IfElse(dnd.drop_status.is_remote_client, "True", "False"))
|
||||
case "DROP_URI_LIST":
|
||||
paths := make([]string, len(dnd.drop_status.uri_list))
|
||||
for i, u := range dnd.drop_status.uri_list {
|
||||
paths[i] = u.path
|
||||
}
|
||||
dnd.send_test_response(strings.Join(paths, "|"))
|
||||
case "DRAG_ACTIVE":
|
||||
dnd.send_test_response(utils.IfElse(dnd.drag_status.active, "DRAG_ACTIVE", "DRAG_INACTIVE"))
|
||||
case "DRAG_OK":
|
||||
dnd.send_test_response(utils.IfElse(dnd.drag_status.terminal_accepted_drag, "DRAG_OK", "DRAG_NOT_OK"))
|
||||
case "DRAG_STATUS":
|
||||
dnd.send_test_response(fmt.Sprintf("%s:%d:%v", dnd.drag_status.offered_mimes[dnd.drag_status.accepted_mime], dnd.drag_status.accepted_operation, dnd.drag_status.dropped))
|
||||
default:
|
||||
dnd.send_test_response("UNKNOWN TEST COMMAND: " + string(cmd.Payload))
|
||||
}
|
||||
// Drops
|
||||
case 'm':
|
||||
payload := ""
|
||||
if cmd.Payload != nil {
|
||||
payload = utils.UnsafeBytesToString(cmd.Payload)
|
||||
}
|
||||
if dnd.on_drop_move(cmd.X, cmd.Y, cmd.Has_more, payload, false, cmd.Operation) {
|
||||
dnd.render_screen()
|
||||
}
|
||||
case 'M':
|
||||
if dnd.on_drop_move(cmd.X, cmd.Y, cmd.Has_more, utils.UnsafeBytesToString(cmd.Payload), true, cmd.Operation) {
|
||||
dnd.render_screen()
|
||||
}
|
||||
case 'R':
|
||||
return fmt.Errorf("error from the terminal while reading dropped data: %s", string(cmd.Payload))
|
||||
case 'r':
|
||||
return dnd.on_drop_data(cmd)
|
||||
|
||||
// Drag source
|
||||
case 'o':
|
||||
return dnd.on_potential_drag_start(cmd.X, cmd.Y)
|
||||
case 'E':
|
||||
return dnd.on_drag_error(cmd)
|
||||
case 'e':
|
||||
return dnd.on_drag_event(cmd.X, cmd.Y, cmd.Operation)
|
||||
case 'k':
|
||||
return dnd.on_drag_remote_data_request(cmd.X - 1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
dnd.lp.OnWriteComplete = func(msg_id loop.IdType, has_pending_writes bool) (err error) {
|
||||
return dnd.on_send_done(msg_id)
|
||||
}
|
||||
|
||||
dnd.lp.OnKeyEvent = func(e *loop.KeyEvent) (err error) {
|
||||
e.Handled = true
|
||||
if len(dnd.confirm_drop.overwrites) > 0 {
|
||||
if e.MatchesPressOrRepeat("esc") {
|
||||
return dnd.drop_confirm(false)
|
||||
}
|
||||
if e.MatchesPressOrRepeat("enter") {
|
||||
return dnd.drop_confirm(true)
|
||||
}
|
||||
}
|
||||
if e.MatchesPressOrRepeat("ctrl+c") {
|
||||
dnd.lp.Quit(0)
|
||||
return
|
||||
}
|
||||
if e.MatchesPressOrRepeat("esc") && dnd.has_exit_on("esc-key") {
|
||||
dnd.lp.Quit(0)
|
||||
return
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
dnd.lp.OnResize = func(old_size loop.ScreenSize, new_size loop.ScreenSize) error {
|
||||
return dnd.render_screen()
|
||||
}
|
||||
|
||||
err = dnd.lp.Run()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := dnd.lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
dnd.lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func dnd_main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
drop_dests := make(map[string]*drop_dest)
|
||||
if os.Stdout != nil && !tty.IsTerminal(os.Stdout.Fd()) {
|
||||
drop_dests["text/plain"] = &drop_dest{human_name: "STDOUT", dest: os.Stdout, mime_type: "text/plain"}
|
||||
}
|
||||
drop_dests["text/uri-list"] = &drop_dest{
|
||||
human_name: "Files", mime_type: "text/uri-list", dest: &bufferWriteCloser{&bytes.Buffer{}}}
|
||||
for _, spec := range opts.Drop {
|
||||
mime, dest, _ := strings.Cut(spec, ":")
|
||||
if dest == "" {
|
||||
delete(drop_dests, mime)
|
||||
} else {
|
||||
path, err := filepath.Abs(utils.Expanduser(dest))
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
drop_dests[mime] = &drop_dest{human_name: dest, path: path, mime_type: mime}
|
||||
}
|
||||
}
|
||||
drag_sources := make(map[string]*drag_source)
|
||||
var stdin_data []byte
|
||||
stdin_read := false
|
||||
for _, spec := range opts.Drag {
|
||||
mime, src, found := strings.Cut(spec, ":")
|
||||
if !found {
|
||||
return 1, fmt.Errorf("invalid drag source %s, must be of the form mime-type:path", spec)
|
||||
}
|
||||
s := &drag_source{human_name: src, mime_type: mime}
|
||||
if src == "-" || src == "/dev/stdin" {
|
||||
if !stdin_read {
|
||||
stdin_data, err = io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
stdin_read = true
|
||||
}
|
||||
s.human_name, s.data = "STDIN", stdin_data
|
||||
} else {
|
||||
path, err := filepath.Abs(utils.Expanduser(src))
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
s.path = path
|
||||
}
|
||||
drag_sources[mime] = s
|
||||
}
|
||||
|
||||
if _, has_plain := drag_sources["text/plain"]; os.Stdin != nil && !stdin_read && !has_plain && !tty.IsTerminal(os.Stdin.Fd()) {
|
||||
data, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if len(data) > 0 {
|
||||
drag_sources["text/plain"] = &drag_source{human_name: "STDIN", mime_type: "text/plain", data: data}
|
||||
}
|
||||
}
|
||||
var uri_list []uri_list_item
|
||||
for _, arg := range args {
|
||||
arg = utils.Expanduser(arg)
|
||||
st, err := os.Lstat(arg)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if st.IsDir() || st.Mode().IsRegular() || st.Mode().Type()&os.ModeSymlink != 0 {
|
||||
path, err := filepath.Abs(arg)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
upath := filepath.ToSlash(path)
|
||||
if runtime.GOOS == "windows" && !strings.HasPrefix(upath, "/") {
|
||||
upath = "/" + upath
|
||||
}
|
||||
if st.IsDir() && !strings.HasSuffix(upath, "/") {
|
||||
upath += "/"
|
||||
}
|
||||
u := &url.URL{Scheme: "file", Path: upath}
|
||||
uri_list = append(uri_list, uri_list_item{path: path, uri: u.String(), human_name: arg, metadata: st})
|
||||
} else {
|
||||
return 1, fmt.Errorf("%s is not a directory or regular file", arg)
|
||||
}
|
||||
}
|
||||
if len(uri_list) > 0 {
|
||||
uris := make([]string, len(uri_list))
|
||||
for i, u := range uri_list {
|
||||
uris[i] = u.uri
|
||||
}
|
||||
payload := strings.Join(uris, "\r\n") + "\r\n"
|
||||
drag_sources["text/uri-list"] = &drag_source{
|
||||
human_name: "Files", mime_type: "text/uri-list", uri_list: uri_list, data: utils.UnsafeStringToBytes(payload),
|
||||
}
|
||||
}
|
||||
dnd := dnd{opts: opts, drop_dests: drop_dests, drag_sources: drag_sources}
|
||||
if opts.DragThumbnail != "" {
|
||||
if dnd.drag_thumbnail, err = imaging.Open(opts.DragThumbnail); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
}
|
||||
|
||||
defer func() {
|
||||
dnd.end_drop(false)
|
||||
if dnd.confirm_drop.staging_dir != nil {
|
||||
dnd.confirm_drop.staging_dir.Close()
|
||||
dnd.confirm_drop.staging_dir = nil
|
||||
}
|
||||
if dnd.drop_output_dir != nil {
|
||||
dnd.drop_output_dir.Close()
|
||||
}
|
||||
}()
|
||||
if err = dnd.run_loop(); err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, dnd_main)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
|
||||
OPTIONS = r"""
|
||||
--drag
|
||||
type=list
|
||||
When starting a drag, use the specified file as the data source for the specified
|
||||
MIME type. Syntax is: mime-type:path/to/file. For example image/jpeg:mypic.jpg
|
||||
Can be specified multiple times to drag multiple MIME types.
|
||||
Use :code:`-` or :file:`/dev/stdin` to read from STDIN. The same input can be used for multiple MIME types.
|
||||
|
||||
|
||||
--drop
|
||||
type=list
|
||||
When receiving a drop, use the specified file as the data destination for the specified
|
||||
MIME type. Syntax is: mime-type:path/to/file. For example image/jpeg:mypic.jpg
|
||||
Can be specified multiple times to enable receiving multiple MIME types. If no path is specified,
|
||||
it will prevent that MIME type being dropped, useful to disable accepting text/plain and
|
||||
text/uri-list.
|
||||
|
||||
|
||||
--drop-dest
|
||||
Path to the directory in which dropped data is saved. Defaults to the current working directory.
|
||||
|
||||
|
||||
--copy-mode
|
||||
type=choices
|
||||
choices=auto,independent
|
||||
default=auto
|
||||
Control how local files are handled for Copy drops. The default, :code:`auto`, uses hard links
|
||||
when possible for performance and falls back to copying file data. :code:`independent` always
|
||||
copies file data, so modifying a dropped file cannot modify its source. Move drops always use
|
||||
hard links when possible.
|
||||
|
||||
|
||||
--confirm-drop-overwrite
|
||||
type=bool-set
|
||||
Ask for confirmation when dropping text/uri-list data if the drop will cause any existing
|
||||
files to be overwritten. Note that confirmation is asked only for actual file conflicts, non
|
||||
conflicting files are automatically created.
|
||||
|
||||
|
||||
--drop-anywhere
|
||||
choices=disallowed,copy,move
|
||||
default=disallowed
|
||||
type=choices
|
||||
Allow dropping anywhere, not just on the Copy or Move drop regions. Dropping anywhere will perform
|
||||
the specified action.
|
||||
|
||||
|
||||
--drag-thumbnail
|
||||
Path to an image to use as the drag icon when starting a drag. Must be in PNG/JPEG/GIF/WEBP formats.
|
||||
Other formats will require the presence of ImageMagick on the system to load the image.
|
||||
If not specified, an image is derived based on the data being dragged.
|
||||
|
||||
|
||||
--drag-thumbnail-size
|
||||
default=512
|
||||
type=int
|
||||
The thumbnail size for the image used as the drag icon. Images larger than this size are downscaled.
|
||||
Note that the terminal may reject the drag if the image is too large.
|
||||
|
||||
|
||||
--exit-on
|
||||
default=esc-key
|
||||
A comma separated list of events to exit on. Possible events are :code:`drag-finish`,
|
||||
:code:`drop-finish` and :code:`esc-key`. The first two events refer to a successful
|
||||
completion of a drag or a drop respectively. :code:`esc-key` means press the :kbd:`Esc`
|
||||
key.
|
||||
""".format
|
||||
|
||||
|
||||
help_text = """\
|
||||
Perform drag and drop operations, even over SSH.
|
||||
|
||||
Any arguments on the command line are assumed to be files and directories to drag.
|
||||
They will be dragged as the text/uri-list MIME type which can then be dropped into any
|
||||
file manager or similar program to copy the files.
|
||||
|
||||
If the text/uri-list MIME type is dropped onto this window, the files and directories in it are
|
||||
copied into the current working directory. When dragging from this window, if a move operation is
|
||||
performed when dropping and the drop is to a remote machine, the files and directories to drag and deleted.
|
||||
|
||||
If data is present on STDIN it is set as text/plain when dragging, unless STDIN is used explicitly via --drag or text/plain is specified via --drag.
|
||||
Any text/plain data that is dropped onto this window is output to STDOUT, if STDOUT is connected to a file, otherwise it
|
||||
is discarded.
|
||||
|
||||
Press the Esc or Ctrl+C keys to quit the kitten at any time, cancelling any in progress drag.
|
||||
"""
|
||||
|
||||
usage = '[files to drag]'
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit('This should be run as kitten dnd')
|
||||
elif __name__ == '__doc__':
|
||||
from kitty.simple_cli_definitions import CompletionSpec
|
||||
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = usage
|
||||
cd['options'] = OPTIONS
|
||||
cd['help_text'] = help_text
|
||||
cd['short_desc'] = 'Perform drag and drop operations, even over SSH'
|
||||
cd['args_completion'] = CompletionSpec.from_string('type:file mime:* group:Files')
|
||||
@@ -0,0 +1,182 @@
|
||||
package dnd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type button_region struct {
|
||||
left, width, top, height int
|
||||
}
|
||||
|
||||
func (r button_region) has(x, y int) bool {
|
||||
return r.left <= x && x < r.left+r.width && r.top <= y && y < r.top+r.height
|
||||
}
|
||||
|
||||
func truncate_at_space(text string, width int) (string, string) {
|
||||
truncated := wcswidth.TruncateToVisualLength(text, width)
|
||||
if len(truncated) == len(text) {
|
||||
return text, ""
|
||||
}
|
||||
p := len(truncated)
|
||||
i := strings.LastIndexByte(truncated, ' ')
|
||||
if i > 0 && p-i < 12 {
|
||||
p = i + 1
|
||||
}
|
||||
return text[:p], text[p:]
|
||||
}
|
||||
|
||||
func paragraph_as_lines(text string, width int) (ans []string) {
|
||||
for text != "" {
|
||||
var line string
|
||||
if line, text = truncate_at_space(text, width); line == "" {
|
||||
// width too small to fit even a single character
|
||||
ans = append(ans, text)
|
||||
break
|
||||
}
|
||||
ans = append(ans, line)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (dnd *dnd) render_screen() error {
|
||||
lp := dnd.lp
|
||||
if !dnd.in_test_mode {
|
||||
lp.StartAtomicUpdate()
|
||||
defer lp.EndAtomicUpdate()
|
||||
}
|
||||
lp.ClearScreen()
|
||||
dnd.copy_button_region, dnd.move_button_region = button_region{}, button_region{}
|
||||
y := 0
|
||||
sz, _ := lp.ScreenSize()
|
||||
render_paragraph := func(text string) {
|
||||
for _, line := range paragraph_as_lines(text, int(sz.WidthCells)) {
|
||||
lp.Println(line)
|
||||
y++
|
||||
}
|
||||
}
|
||||
next_line := func() {
|
||||
lp.Println()
|
||||
y++
|
||||
}
|
||||
if dnd.drag_status.active {
|
||||
lp.Println("Dragging data...")
|
||||
if dnd.drag_status.dropped {
|
||||
render_paragraph("The dragged data has been dropped, waiting for data transfer requests...")
|
||||
} else if dnd.drag_status.accepted_operation > 0 {
|
||||
render_paragraph("Another window is willing to accept the dragged data")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(dnd.confirm_drop.overwrites) > 0 {
|
||||
render_paragraph("Some of the dropped files will overwrite existing files, listed below. Press \x1b[32mEnter\x1b[39m to drop anyway or \x1b[31mEsc\x1b[39m to cancel the drop.")
|
||||
sz, _ := lp.ScreenSize()
|
||||
next_line()
|
||||
next_line()
|
||||
overwrites := dnd.confirm_drop.overwrites[:max(0, min(int(sz.HeightCells)-y-1, len(dnd.confirm_drop.overwrites)))]
|
||||
for _, x := range overwrites {
|
||||
lp.Println(x)
|
||||
}
|
||||
if left := len(dnd.confirm_drop.overwrites) - len(overwrites); left > 0 {
|
||||
lp.Printf("... (%d more)", left)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if dnd.drop_status.reading_data {
|
||||
render_paragraph("Reading dropped data, please wait...")
|
||||
return nil
|
||||
}
|
||||
|
||||
if dnd.drop_status.in_window {
|
||||
if dnd.drop_status.action == 0 {
|
||||
render_paragraph("A drag is active. Drop it into one of the boxes below to perform that action on the dragged data. Available MIME types in the drag:")
|
||||
next_line()
|
||||
render_paragraph(strings.Join(dnd.drop_status.offered_mimes, " "))
|
||||
} else {
|
||||
render_paragraph("The drag can be dropped. Supported MIME types:")
|
||||
next_line()
|
||||
render_paragraph(strings.Join(dnd.drop_status.accepted_mimes, " "))
|
||||
}
|
||||
} else {
|
||||
// Neither active drag nor drop over window
|
||||
if dnd.allow_drags {
|
||||
render_paragraph(`Start dragging anywhere in this window to initiate a drag and drop. If you start the drag in one of the Copy or Move boxes below, only that action will be allowed when dropping, otherwise, the drop destination can pick either copy or move.`)
|
||||
next_line()
|
||||
}
|
||||
if dnd.allow_drops {
|
||||
if dnd.num_dropped_files > 0 {
|
||||
verb := "have"
|
||||
noun := "files"
|
||||
if dnd.num_dropped_files == 1 {
|
||||
verb = "has"
|
||||
noun = "file"
|
||||
}
|
||||
render_paragraph(fmt.Sprintf(`%d %s %s been dropped in the last drop event. You can drop more data or press Esc to quit.`, dnd.num_dropped_files, noun, verb))
|
||||
} else {
|
||||
render_paragraph(`Drag some data from another application into this window to transfer the files here.`)
|
||||
}
|
||||
}
|
||||
}
|
||||
frame_width, padding_width := 4, 8
|
||||
text_width := len("copymove")
|
||||
scale := 5
|
||||
for scale > 1 && frame_width+padding_width+text_width*scale > int(sz.WidthCells) {
|
||||
scale--
|
||||
}
|
||||
height := scale + 4
|
||||
boxy := 1 + max(0, int(sz.HeightCells)-height)
|
||||
lp.MoveCursorTo(1, boxy)
|
||||
lp.ClearToEndOfScreen()
|
||||
|
||||
render_box := func(x int, text string, r *button_region) {
|
||||
width := scale*wcswidth.Stringwidth(text) + 6
|
||||
r.left = x - 1
|
||||
r.top = boxy - 1
|
||||
r.width = width
|
||||
r.height = height
|
||||
lp.MoveCursorTo(x, boxy)
|
||||
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("│")
|
||||
if i == 2 {
|
||||
lp.MoveCursorHorizontally(2)
|
||||
lp.DrawSizedText(text, loop.SizedText{Scale: scale})
|
||||
}
|
||||
lp.MoveCursorTo(x+width-1, boxy+i)
|
||||
lp.QueueWriteString("│")
|
||||
}
|
||||
lp.RestoreCursorPosition()
|
||||
lp.MoveCursorVertically(1)
|
||||
}
|
||||
}
|
||||
const fg = 32
|
||||
if dnd.drop_status.action == copy_on_drop {
|
||||
lp.Printf("\x1b[%dm", fg)
|
||||
}
|
||||
render_box(1, "Copy", &dnd.copy_button_region)
|
||||
lp.QueueWriteString("\x1b[39m")
|
||||
box_width := 6 + len("move")*scale
|
||||
if dnd.drop_status.action == move_on_drop {
|
||||
lp.Printf("\x1b[%dm", fg)
|
||||
}
|
||||
render_box(1+int(sz.WidthCells)-box_width, "Move", &dnd.move_button_region)
|
||||
lp.QueueWriteString("\x1b[39m")
|
||||
return nil
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,90 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
// hints_to_skip calculates how many hints to skip based on the given n and
|
||||
// alphabet size so that the next n hints generated by expanding the prefix tree
|
||||
// of an alphabet of size alphabetSize will be prefix-free.
|
||||
//
|
||||
// The result is 1-based, meaning that the first hint to be skipped is the first
|
||||
// non-empty hint.
|
||||
//
|
||||
// For example, if alphabet was "abc" and n was 5, the first non-empty hints
|
||||
// from that alphabet would be: "a", "b", "c", "aa", "ab", "ac", ...
|
||||
// the result of hints_to_skip would be 1, and this would mean that if you skip
|
||||
// "a" from the list above, the next 5 hints are prefix-free:
|
||||
// "b", "c", "aa", "ab", "ac".
|
||||
//
|
||||
// See issue #10195 for an informal proof on why this function works.
|
||||
func hints_to_skip(n int, alphabetSize int) int {
|
||||
if n < 2 {
|
||||
n = 2
|
||||
}
|
||||
return (n - 2) / (alphabetSize - 1)
|
||||
}
|
||||
|
||||
// encode_hint generates the hint corresponding to the given index in the
|
||||
// breadth-first traversal of the prefix tree generated by the given alphabet.
|
||||
//
|
||||
// For example, given the alphabet "abc", the hints would be generated in
|
||||
// the following order:
|
||||
// 0. "a"
|
||||
// 1. "b"
|
||||
// 2. "c"
|
||||
// 3. "aa"
|
||||
// 4. "ab"
|
||||
// 5. "ac"
|
||||
// 6. "ba"
|
||||
// 7. "bb"
|
||||
// 8. "bc"
|
||||
// 9. "ca"
|
||||
// 10. "cb"
|
||||
// 11. "cc"
|
||||
// 12. "aaa"
|
||||
// ...
|
||||
//
|
||||
// Indices are 0-based on non-empty hints; index=0 the hint of length 1 with
|
||||
// the first character of the alphabet.
|
||||
func encode_hint(num int, alphabet string) (res string) {
|
||||
l := len(alphabet)
|
||||
|
||||
for num >= 0 {
|
||||
mod := num % l
|
||||
res = string(alphabet[mod]) + res
|
||||
num /= l
|
||||
num -= 1
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func rune_to_index_map(alphabet string) *map[rune]int {
|
||||
runeToIndexMap := make(map[rune]int)
|
||||
for index, char := range alphabet {
|
||||
runeToIndexMap[char] = index
|
||||
}
|
||||
return &runeToIndexMap
|
||||
}
|
||||
|
||||
// decode_hint converts a hint to its corresponding index as it would appear in
|
||||
// the breadth-first traversal of the prefix tree generated by the given
|
||||
// alphabet.
|
||||
//
|
||||
// For example, given the alphabet "abc", the hints would be generated in
|
||||
// the following order:
|
||||
// 0. "a"
|
||||
// 1. "b"
|
||||
// 2. "c"
|
||||
// 3. "aa"
|
||||
// 4. "ab"
|
||||
// ...
|
||||
//
|
||||
// hint is expected to be non-empty.
|
||||
func decode_hint(hint string, char_to_index *map[rune]int) (res int) {
|
||||
base := len(*char_to_index)
|
||||
|
||||
for _, c := range hint {
|
||||
res = res*base + ((*char_to_index)[c] + 1)
|
||||
}
|
||||
return res - 1
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
)
|
||||
|
||||
func TestPrefixFreeHints(t *testing.T) {
|
||||
// Test hints_to_skip
|
||||
testsToSkip := []struct {
|
||||
n, alphabetSize, expected int
|
||||
}{
|
||||
{5, 3, 1},
|
||||
{6, 3, 2},
|
||||
{4, 3, 1},
|
||||
{3, 3, 0},
|
||||
{2, 3, 0},
|
||||
{1, 3, 0},
|
||||
{0, 3, 0},
|
||||
}
|
||||
for _, tc := range testsToSkip {
|
||||
actual := hints_to_skip(tc.n, tc.alphabetSize)
|
||||
if actual != tc.expected {
|
||||
t.Errorf("hints_to_skip(%d, %d) = %d, expected %d", tc.n, tc.alphabetSize, actual, tc.expected)
|
||||
}
|
||||
}
|
||||
|
||||
// Test prefix-free property verification
|
||||
alphabets := []string{"abc", "0123456789"}
|
||||
for _, alph := range alphabets {
|
||||
l := len(alph)
|
||||
for n := 1; n <= 10; n++ {
|
||||
total_hints := int(math.Pow(float64(2), float64(n)))
|
||||
skip := hints_to_skip(total_hints, l)
|
||||
hints := make([]string, total_hints)
|
||||
for i := range total_hints {
|
||||
hints[i] = encode_hint(skip+1+i, alph)
|
||||
}
|
||||
// Verify that no hint is a prefix of another hint
|
||||
for i := range total_hints {
|
||||
for j := range total_hints {
|
||||
if i == j {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(hints[j], hints[i]) {
|
||||
t.Errorf("For alphabet %q and n=%d: %q is a prefix of %q (skip=%d)", alph, total_hints, hints[i], hints[j], skip)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HintsOffset + PrefixFree Test case 1: HintsOffset is smaller than dynamic
|
||||
// offset (dynamic offset wins)
|
||||
//
|
||||
// With 4 matches, and alphabet size 3:
|
||||
// hints_to_skip(4, 3) = 1.
|
||||
// HintsOffset = 0.
|
||||
// Effective offset = max(0, 1) = 1.
|
||||
// Ascending = true.
|
||||
// Match 0: 0 + 1 + 1 = 2 -> "b"
|
||||
// Match 1: 1 + 1 + 1 = 3 -> "c"
|
||||
// Match 2: 2 + 1 + 1 = 4 -> "aa"
|
||||
// Match 3: 3 + 1 + 1 = 5 -> "ab"
|
||||
opts1 := &Options{
|
||||
Type: "url",
|
||||
UrlPrefixes: "default",
|
||||
Regex: kitty.HintsDefaultRegex,
|
||||
PrefixFree: true,
|
||||
Alphabet: "abc",
|
||||
HintsOffset: 0,
|
||||
Ascending: false, // default
|
||||
}
|
||||
_, marks1, _, err := find_marks("http://a.com http://b.com http://c.com http://d.com", opts1)
|
||||
if err != nil {
|
||||
t.Fatalf("find_marks failed: %v", err)
|
||||
}
|
||||
expectedCodes1 := []string{"ab", "aa", "c", "b"}
|
||||
for i, m := range marks1 {
|
||||
hint := encode_hint(m.Index, opts1.Alphabet)
|
||||
if hint != expectedCodes1[i] {
|
||||
t.Errorf("Case 1 - Match %d (Index %d): got hint %q, expected %q", i, m.Index, hint, expectedCodes1[i])
|
||||
}
|
||||
}
|
||||
|
||||
// HintsOffset + PrefixFree Test case 2: HintsOffset is larger than dynamic
|
||||
// offset (HintsOffset wins)
|
||||
//
|
||||
// With 4 matches, and alphabet size 3:
|
||||
// hints_to_skip(4, 3) = 1.
|
||||
// HintsOffset = 3.
|
||||
// Effective offset = max(3, 1) = 3.
|
||||
// Ascending = true.
|
||||
// Match 0: 0 + 3 + 1 = 4 -> "aa"
|
||||
// Match 1: 1 + 3 + 1 = 5 -> "ab"
|
||||
// Match 2: 2 + 3 + 1 = 6 -> "ac"
|
||||
// Match 3: 3 + 3 + 1 = 7 -> "ba"
|
||||
opts2 := &Options{
|
||||
Type: "url",
|
||||
UrlPrefixes: "default",
|
||||
Regex: kitty.HintsDefaultRegex,
|
||||
PrefixFree: true,
|
||||
Alphabet: "abc",
|
||||
HintsOffset: 3,
|
||||
Ascending: true,
|
||||
}
|
||||
_, marks2, _, err := find_marks("http://a.com http://b.com http://c.com http://d.com", opts2)
|
||||
if err != nil {
|
||||
t.Fatalf("find_marks failed: %v", err)
|
||||
}
|
||||
expectedCodes2 := []string{"aa", "ab", "ac", "ba"}
|
||||
for i, m := range marks2 {
|
||||
hint := encode_hint(m.Index, opts2.Alphabet)
|
||||
if hint != expectedCodes2[i] {
|
||||
t.Errorf("Case 2 - Match %d (Index %d): got hint %q, expected %q", i, m.Index, hint, expectedCodes2[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeDecodeHint(t *testing.T) {
|
||||
// enchode_hint sample tests
|
||||
tests := []struct {
|
||||
num int
|
||||
alphabet string
|
||||
expected string
|
||||
}{
|
||||
{0, "abc", "a"},
|
||||
{1, "abc", "b"},
|
||||
{2, "abc", "c"},
|
||||
{3, "abc", "aa"},
|
||||
{11, "abc", "cc"},
|
||||
{12, "abc", "aaa"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
actual := encode_hint(tc.num, tc.alphabet)
|
||||
if actual != tc.expected {
|
||||
t.Errorf("encode_hint(%d, %q) = %q, expected %q", tc.num, tc.alphabet, actual, tc.expected)
|
||||
}
|
||||
}
|
||||
|
||||
// decode_hint should reverse encode_hint (round-trip test)
|
||||
for _, alph := range []string{"abc", "0123456789", DEFAULT_HINT_ALPHABET} {
|
||||
char_to_index := rune_to_index_map(alph)
|
||||
for num := range 200 {
|
||||
hint := encode_hint(num, alph)
|
||||
decoded := decode_hint(hint, char_to_index)
|
||||
if decoded != num {
|
||||
t.Errorf("decode_hint(encode_hint(%d, %q)) = %d, expected %d", num, alph, decoded, num)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"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 convert_text(text string, cols int) string {
|
||||
lines := make([]string, 0, 64)
|
||||
empty_line := strings.Repeat("\x00", cols) + "\n"
|
||||
s1 := utils.NewLineScanner(text)
|
||||
for s1.Scan() {
|
||||
full_line := s1.Text()
|
||||
if full_line == "" {
|
||||
lines = append(lines, empty_line)
|
||||
continue
|
||||
}
|
||||
if strings.TrimRight(full_line, "\r") == "" {
|
||||
for range len(full_line) {
|
||||
lines = append(lines, empty_line)
|
||||
}
|
||||
continue
|
||||
}
|
||||
appended := false
|
||||
s2 := utils.NewSeparatorScanner(full_line, "\r")
|
||||
for s2.Scan() {
|
||||
line := s2.Text()
|
||||
if line != "" {
|
||||
line_sz := wcswidth.Stringwidth(line)
|
||||
extra := cols - line_sz
|
||||
if extra > 0 {
|
||||
line += strings.Repeat("\x00", extra)
|
||||
}
|
||||
lines = append(lines, line)
|
||||
lines = append(lines, "\r")
|
||||
appended = true
|
||||
}
|
||||
}
|
||||
if appended {
|
||||
lines[len(lines)-1] = "\n"
|
||||
}
|
||||
}
|
||||
ans := strings.Join(lines, "")
|
||||
return strings.TrimRight(ans, "\r\n")
|
||||
}
|
||||
|
||||
func parse_input(text string) string {
|
||||
cols, err := strconv.Atoi(os.Getenv("OVERLAID_WINDOW_COLS"))
|
||||
if err == nil {
|
||||
return convert_text(text, cols)
|
||||
}
|
||||
term, err := tty.OpenControllingTerm()
|
||||
if err == nil {
|
||||
sz, err := term.GetSize()
|
||||
term.Close()
|
||||
if err == nil {
|
||||
return convert_text(text, int(sz.Col))
|
||||
}
|
||||
}
|
||||
return convert_text(text, 80)
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Match []string `json:"match"`
|
||||
Programs []string `json:"programs"`
|
||||
Multiple_joiner string `json:"multiple_joiner"`
|
||||
Customize_processing string `json:"customize_processing"`
|
||||
Type string `json:"type"`
|
||||
Groupdicts []map[string]any `json:"groupdicts"`
|
||||
Extra_cli_args []string `json:"extra_cli_args"`
|
||||
Linenum_action string `json:"linenum_action"`
|
||||
Cwd string `json:"cwd"`
|
||||
}
|
||||
|
||||
func as_rgb(c uint32) [3]float32 {
|
||||
return [3]float32{float32((c>>16)&255) / 255.0, float32((c>>8)&255) / 255.0, float32(c&255) / 255.0}
|
||||
}
|
||||
|
||||
func hints_text_color(confval string) (ans string) {
|
||||
ans = confval
|
||||
if ans == "auto" {
|
||||
ans = "bright-gray"
|
||||
if bc, err := tui.ReadBasicColors(); err == nil {
|
||||
bg := as_rgb(bc.Background)
|
||||
c15 := as_rgb(bc.Color15)
|
||||
c8 := as_rgb(bc.Color8)
|
||||
if utils.RGBContrast(bg[0], bg[1], bg[2], c8[0], c8[1], c8[2]) > utils.RGBContrast(bg[0], bg[1], bg[2], c15[0], c15[1], c15[2]) {
|
||||
ans = "bright-black"
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func main(_ *cli.Command, o *Options, args []string) (rc int, err error) {
|
||||
o.HintsTextColor = hints_text_color(o.HintsTextColor)
|
||||
output := tui.KittenOutputSerializer()
|
||||
if tty.IsTerminal(os.Stdin.Fd()) {
|
||||
return 1, fmt.Errorf("You must pass the text to be hinted on STDIN")
|
||||
}
|
||||
stdin, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
return 1, fmt.Errorf("Failed to read from STDIN with error: %w", err)
|
||||
}
|
||||
if len(args) > 0 && o.CustomizeProcessing == "" && o.Type != "linenum" {
|
||||
return 1, fmt.Errorf("Extra command line arguments present: %s", strings.Join(args, " "))
|
||||
}
|
||||
input_text := parse_input(utils.UnsafeBytesToString(stdin))
|
||||
text, all_marks, index_map, err := find_marks(input_text, o, os.Args[2:]...)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
|
||||
result := Result{
|
||||
Programs: o.Program, Multiple_joiner: o.MultipleJoiner, Customize_processing: o.CustomizeProcessing, Type: o.Type,
|
||||
Extra_cli_args: args, Linenum_action: o.LinenumAction,
|
||||
}
|
||||
result.Cwd, _ = os.Getwd()
|
||||
alphabet := o.Alphabet
|
||||
if alphabet == "" {
|
||||
alphabet = DEFAULT_HINT_ALPHABET
|
||||
}
|
||||
ignore_mark_indices := utils.NewSet[int](8)
|
||||
window_title := o.WindowTitle
|
||||
if window_title == "" {
|
||||
switch o.Type {
|
||||
case "url":
|
||||
window_title = "Choose URL"
|
||||
default:
|
||||
window_title = "Choose text"
|
||||
}
|
||||
}
|
||||
current_text := ""
|
||||
current_input := ""
|
||||
match_suffix := ""
|
||||
switch o.AddTrailingSpace {
|
||||
case "always":
|
||||
match_suffix = " "
|
||||
case "never":
|
||||
default:
|
||||
if o.Multiple {
|
||||
match_suffix = " "
|
||||
}
|
||||
}
|
||||
chosen := []*Mark{}
|
||||
lp, err := loop.New(loop.NoAlternateScreen) // no alternate screen reduces flicker on exit
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
fctx := style.Context{AllowEscapeCodes: true}
|
||||
faint := fctx.SprintFunc("dim")
|
||||
hint_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsForegroundColor, o.HintsBackgroundColor))
|
||||
text_style := fctx.SprintFunc(fmt.Sprintf("fg=%s bg=%s bold", o.HintsTextColor, o.HintsTextBackgroundColor))
|
||||
|
||||
highlight_mark := func(m *Mark, mark_text string) string {
|
||||
hint := encode_hint(m.Index, alphabet)
|
||||
if current_input != "" && !strings.HasPrefix(hint, current_input) {
|
||||
return faint(mark_text)
|
||||
}
|
||||
hint = hint[len(current_input):]
|
||||
if hint == "" {
|
||||
hint = " "
|
||||
}
|
||||
hint_runes := len(hint)
|
||||
runes := []rune(mark_text)
|
||||
if len(runes) <= hint_runes {
|
||||
mark_text = ""
|
||||
} else {
|
||||
replaced_text := string(runes[:hint_runes])
|
||||
replaced_text = strings.ReplaceAll(replaced_text, "\r", "\n")
|
||||
if strings.Contains(replaced_text, "\n") {
|
||||
buf := strings.Builder{}
|
||||
buf.Grow(2 * len(hint))
|
||||
h := hint
|
||||
parts := strings.Split(replaced_text, "\n")
|
||||
for i, x := range parts {
|
||||
if x != "" {
|
||||
buf.WriteString(h[:len(x)])
|
||||
h = h[len(x):]
|
||||
}
|
||||
if i != len(parts)-1 {
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
}
|
||||
if h != "" {
|
||||
buf.WriteString(h)
|
||||
}
|
||||
hint = buf.String()
|
||||
}
|
||||
mark_text = string(runes[hint_runes:])
|
||||
}
|
||||
ans := hint_style(hint) + text_style(mark_text)
|
||||
return fmt.Sprintf("\x1b]8;;mark:%d\a%s\x1b]8;;\a", m.Index, ans)
|
||||
}
|
||||
|
||||
render := func() string {
|
||||
ans := text
|
||||
for i := len(all_marks) - 1; i >= 0; i-- {
|
||||
mark := &all_marks[i]
|
||||
if ignore_mark_indices.Has(mark.Index) {
|
||||
continue
|
||||
}
|
||||
mtext := highlight_mark(mark, ans[mark.Start:mark.End])
|
||||
ans = ans[:mark.Start] + mtext + ans[mark.End:]
|
||||
}
|
||||
ans = strings.ReplaceAll(ans, "\x00", "")
|
||||
return strings.TrimRightFunc(strings.NewReplacer("\r", "\r\n", "\n", "\r\n").Replace(ans), unicode.IsSpace)
|
||||
}
|
||||
|
||||
draw_screen := func() {
|
||||
lp.StartAtomicUpdate()
|
||||
defer lp.EndAtomicUpdate()
|
||||
if current_text == "" {
|
||||
current_text = render()
|
||||
}
|
||||
lp.ClearScreen()
|
||||
lp.QueueWriteString(current_text)
|
||||
}
|
||||
reset := func() {
|
||||
current_input = ""
|
||||
current_text = ""
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
lp.SetWindowTitle(window_title)
|
||||
lp.AllowLineWrapping(false)
|
||||
draw_screen()
|
||||
lp.SendOverlayReady()
|
||||
return "", nil
|
||||
}
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
return ""
|
||||
}
|
||||
lp.OnResize = func(old_size, new_size loop.ScreenSize) error {
|
||||
draw_screen()
|
||||
return nil
|
||||
}
|
||||
lp.OnRCResponse = func(data []byte) error {
|
||||
var r struct {
|
||||
Type string
|
||||
Mark int
|
||||
}
|
||||
if err := json.Unmarshal(data, &r); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Type == "mark_activated" {
|
||||
if m, ok := index_map[r.Mark]; ok {
|
||||
chosen = append(chosen, m)
|
||||
if o.Multiple {
|
||||
ignore_mark_indices.Add(m.Index)
|
||||
reset()
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnText = func(text string, _, _ bool) error {
|
||||
changed := false
|
||||
for _, ch := range text {
|
||||
if strings.ContainsRune(alphabet, ch) {
|
||||
current_input += string(ch)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
matches := []*Mark{}
|
||||
for idx, m := range index_map {
|
||||
if eh := encode_hint(idx, alphabet); strings.HasPrefix(eh, current_input) {
|
||||
matches = append(matches, m)
|
||||
}
|
||||
}
|
||||
if len(matches) == 1 {
|
||||
chosen = append(chosen, matches[0])
|
||||
if o.Multiple {
|
||||
ignore_mark_indices.Add(matches[0].Index)
|
||||
reset()
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
current_text = ""
|
||||
draw_screen()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnKeyEvent = func(ev *loop.KeyEvent) error {
|
||||
if ev.MatchesPressOrRepeat("backspace") {
|
||||
ev.Handled = true
|
||||
r := []rune(current_input)
|
||||
if len(r) > 0 {
|
||||
r = r[:len(r)-1]
|
||||
current_input = string(r)
|
||||
current_text = ""
|
||||
}
|
||||
draw_screen()
|
||||
} else if ev.MatchesPressOrRepeat("enter") || ev.MatchesPressOrRepeat("space") {
|
||||
ev.Handled = true
|
||||
if current_input != "" {
|
||||
char_to_index := rune_to_index_map(alphabet)
|
||||
idx := decode_hint(current_input, char_to_index)
|
||||
if m := index_map[idx]; m != nil {
|
||||
chosen = append(chosen, m)
|
||||
ignore_mark_indices.Add(idx)
|
||||
if o.Multiple {
|
||||
reset()
|
||||
draw_screen()
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
}
|
||||
} else {
|
||||
current_input = ""
|
||||
current_text = ""
|
||||
draw_screen()
|
||||
}
|
||||
}
|
||||
} else if ev.MatchesPressOrRepeat("esc") {
|
||||
if o.Multiple {
|
||||
lp.Quit(0)
|
||||
} else {
|
||||
lp.Quit(1)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
fmt.Println("Killed by signal: ", ds)
|
||||
lp.KillIfSignalled()
|
||||
return 1, nil
|
||||
}
|
||||
if lp.ExitCode() != 0 {
|
||||
return lp.ExitCode(), nil
|
||||
}
|
||||
result.Match = make([]string, len(chosen))
|
||||
result.Groupdicts = make([]map[string]any, len(chosen))
|
||||
for i, m := range chosen {
|
||||
result.Match[i] = m.Text + match_suffix
|
||||
result.Groupdicts[i] = m.Groupdict
|
||||
}
|
||||
fmt.Println(output(result))
|
||||
return
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
from kitty.cli_stub import HintsCLIOptions
|
||||
from kitty.clipboard import set_clipboard_string, set_primary_selection
|
||||
from kitty.constants import website_url
|
||||
from kitty.fast_data_types import get_options
|
||||
from kitty.typing_compat import BossType, WindowType
|
||||
from kitty.utils import get_editor, resolve_custom_file
|
||||
|
||||
from ..tui.handler import result_handler
|
||||
|
||||
DEFAULT_REGEX = r'(?m)^\s*(.+?)\s*$'
|
||||
|
||||
|
||||
def load_custom_processor(customize_processing: str) -> Any:
|
||||
if customize_processing.startswith('::import::'):
|
||||
import importlib
|
||||
|
||||
m = importlib.import_module(customize_processing[len('::import::') :])
|
||||
return {k: getattr(m, k) for k in dir(m)}
|
||||
if customize_processing == '::linenum::':
|
||||
return {'handle_result': linenum_handle_result}
|
||||
custom_path = resolve_custom_file(customize_processing)
|
||||
import runpy
|
||||
|
||||
return runpy.run_path(custom_path, run_name='__main__')
|
||||
|
||||
|
||||
class Mark:
|
||||
__slots__ = ('index', 'start', 'end', 'text', 'is_hyperlink', 'group_id', 'groupdict')
|
||||
|
||||
def __init__(self, index: int, start: int, end: int, text: str, groupdict: Any, is_hyperlink: bool = False, group_id: str | None = None):
|
||||
self.index, self.start, self.end = index, start, end
|
||||
self.text = text
|
||||
self.groupdict = groupdict
|
||||
self.is_hyperlink = is_hyperlink
|
||||
self.group_id = group_id
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
'index': self.index,
|
||||
'start': self.start,
|
||||
'end': self.end,
|
||||
'text': self.text,
|
||||
'groupdict': {str(k): v for k, v in (self.groupdict or {}).items()},
|
||||
'group_id': self.group_id or '',
|
||||
'is_hyperlink': self.is_hyperlink,
|
||||
}
|
||||
|
||||
|
||||
def parse_hints_args(args: list[str]) -> tuple[HintsCLIOptions, list[str]]:
|
||||
from kitty.cli import parse_args
|
||||
|
||||
return parse_args(args, OPTIONS, usage, help_text, 'kitty +kitten hints', result_class=HintsCLIOptions)
|
||||
|
||||
|
||||
def custom_marking() -> None:
|
||||
import json
|
||||
|
||||
text = sys.stdin.read()
|
||||
sys.stdin.close()
|
||||
opts, extra_cli_args = parse_hints_args(sys.argv[1:])
|
||||
m = load_custom_processor(opts.customize_processing or '::impossible::')
|
||||
if 'mark' not in m:
|
||||
raise SystemExit(2)
|
||||
all_marks = tuple(x.as_dict() for x in m['mark'](text, opts, Mark, extra_cli_args))
|
||||
sys.stdout.write(json.dumps(all_marks))
|
||||
raise SystemExit(0)
|
||||
|
||||
|
||||
OPTIONS = r"""
|
||||
--program
|
||||
type=list
|
||||
What program to use to open matched text. Defaults to the default open program
|
||||
for the operating system. Various special values are supported:
|
||||
|
||||
:code:`-`
|
||||
paste the match into the terminal window.
|
||||
|
||||
:code:`@`
|
||||
copy the match to the clipboard
|
||||
|
||||
:code:`*`
|
||||
copy the match to the primary selection (on systems that support primary selections)
|
||||
|
||||
:code:`@NAME`
|
||||
copy the match to the specified buffer, e.g. :code:`@a`
|
||||
|
||||
:code:`default`
|
||||
run the default open program. Note that when using the hyperlink :code:`--type`
|
||||
the default is to use the kitty :doc:`hyperlink handling </open_actions>` facilities.
|
||||
|
||||
:code:`launch`
|
||||
run :doc:`/launch` to open the program in a new kitty tab, window, overlay, etc.
|
||||
For example::
|
||||
|
||||
--program "launch --type=tab vim"
|
||||
|
||||
Can be specified multiple times to run multiple programs.
|
||||
|
||||
|
||||
--type
|
||||
default=url
|
||||
choices=url,regex,path,line,hash,word,linenum,hyperlink,ip
|
||||
The type of text to search for. A value of :code:`linenum` is special, it looks
|
||||
for error messages using the pattern specified with :option:`--regex`, which
|
||||
must have the named groups: :code:`path` and :code:`line`. If not specified,
|
||||
will look for :code:`path:line`. The :option:`--linenum-action` option
|
||||
controls where to display the selected error message, other options are ignored.
|
||||
|
||||
|
||||
--regex
|
||||
default={default_regex}
|
||||
The regular expression to use when option :option:`--type` is set to
|
||||
:code:`regex`, in Perl 5 syntax. If you specify a numbered group in the regular
|
||||
expression, only the group will be matched. This allows you to match text
|
||||
ignoring a prefix/suffix, as needed. The default expression matches lines. To
|
||||
match text over multiple lines, things get a little tricky, as line endings
|
||||
are a sequence of zero or more null bytes followed by either a carriage return
|
||||
or a newline character. To have a pattern match over line endings you will need to
|
||||
match the character set ``[\0\r\n]``. The newlines and null bytes are automatically
|
||||
stripped from the returned text. If you specify named groups and a
|
||||
:option:`--program`, then the program will be passed arguments corresponding
|
||||
to each named group of the form :code:`key=value`.
|
||||
|
||||
|
||||
--linenum-action
|
||||
default=self
|
||||
type=choice
|
||||
choices=self,window,tab,os_window,background,remote-control
|
||||
Where to perform the action on matched errors. :code:`self` means the current
|
||||
window, :code:`window` a new kitty window, :code:`tab` a new tab,
|
||||
:code:`os_window` a new OS window and :code:`background` run in the background.
|
||||
:code:`remote-control` is like background but the program can use kitty remote control
|
||||
without needing to turn on remote control globally.
|
||||
The actual action is whatever arguments are provided to the kitten, for
|
||||
example:
|
||||
:code:`kitten hints --type=linenum --linenum-action=tab vim +{line} {path}`
|
||||
will open the matched path at the matched line number in vim in
|
||||
a new kitty tab. Note that in order to use :option:`--program` to copy or paste
|
||||
the provided arguments, you need to use the special value :code:`self`.
|
||||
|
||||
|
||||
--url-prefixes
|
||||
default=default
|
||||
Comma separated list of recognized URL prefixes. Defaults to the list of
|
||||
prefixes defined by the :opt:`url_prefixes` option in :file:`kitty.conf`.
|
||||
|
||||
|
||||
--url-excluded-characters
|
||||
default=default
|
||||
Characters to exclude when matching URLs. Defaults to the list of characters
|
||||
defined by the :opt:`url_excluded_characters` option in :file:`kitty.conf`.
|
||||
The syntax for this option is the same as for :opt:`url_excluded_characters`.
|
||||
|
||||
|
||||
--word-characters
|
||||
Characters to consider as part of a word. In addition, all characters marked as
|
||||
alphanumeric in the Unicode database will be considered as word characters.
|
||||
Defaults to the :opt:`select_by_word_characters` option from :file:`kitty.conf`.
|
||||
|
||||
|
||||
--minimum-match-length
|
||||
default=3
|
||||
type=int
|
||||
The minimum number of characters to consider a match.
|
||||
|
||||
|
||||
--multiple
|
||||
type=bool-set
|
||||
Select multiple matches and perform the action on all of them together at the
|
||||
end. In this mode, press :kbd:`Esc` to finish selecting.
|
||||
|
||||
|
||||
--multiple-joiner
|
||||
default=auto
|
||||
String for joining multiple selections when copying to the clipboard or
|
||||
inserting into the terminal. The special values are: :code:`space` - a space
|
||||
character, :code:`newline` - a newline, :code:`empty` - an empty joiner,
|
||||
:code:`json` - a JSON serialized list, :code:`auto` - an automatic choice, based
|
||||
on the type of text being selected. In addition, integers are interpreted as
|
||||
zero-based indices into the list of selections. You can use :code:`0` for the
|
||||
first selection and :code:`-1` for the last.
|
||||
|
||||
|
||||
--add-trailing-space
|
||||
default=auto
|
||||
choices=auto,always,never
|
||||
Add trailing space after matched text. Defaults to :code:`auto`, which adds the
|
||||
space when used together with :option:`--multiple`.
|
||||
|
||||
|
||||
--hints-offset
|
||||
default=1
|
||||
type=int
|
||||
The offset (from zero) at which to start hint numbering. Note that only numbers
|
||||
greater than or equal to zero are respected.
|
||||
|
||||
|
||||
--prefix-free
|
||||
type=bool-set
|
||||
Generate hints such that no hint is a prefix of another. For example, with
|
||||
alphabet "abc" and 4 matches, hints are "b", "c", "aa", "ab", instead of "a",
|
||||
"b", "c", "aa" (where "a" prefixes "aa"). This works by applying a dynamic
|
||||
offset large enough so that the hints are prefix-free. When combined with a
|
||||
:option:`--hints-offset` greater than 0, the effective offset is whichever is
|
||||
larger.
|
||||
|
||||
|
||||
--alphabet
|
||||
The list of characters to use for hints. The default is to use numbers and
|
||||
lowercase English alphabets. Specify your preference as a string of characters.
|
||||
Note that you need to specify the :option:`--hints-offset` as zero to use the
|
||||
first character to highlight the first match, otherwise it will start with the
|
||||
second character by default.
|
||||
|
||||
|
||||
--ascending
|
||||
type=bool-set
|
||||
Make the hints increase from top to bottom, instead of decreasing from top to
|
||||
bottom.
|
||||
|
||||
|
||||
--hints-foreground-color
|
||||
default=black
|
||||
type=str
|
||||
The foreground color for hints. You can use color names or hex values. For the eight basic
|
||||
named terminal colors you can also use the :code:`bright-` prefix to get the bright variant of the
|
||||
color.
|
||||
|
||||
|
||||
--hints-background-color
|
||||
default=green
|
||||
type=str
|
||||
The background color for hints. You can use color names or hex values. For the eight basic
|
||||
named terminal colors you can also use the :code:`bright-` prefix to get the bright variant of the
|
||||
color.
|
||||
|
||||
|
||||
--hints-text-color
|
||||
default=auto
|
||||
type=str
|
||||
The foreground color for text pointed to by the hints (excluding the hint label itself). You can use
|
||||
color names or hex values. For the eight basic named terminal colors you can also use the
|
||||
:code:`bright-` prefix to get the bright variant of the color. The default is to pick a suitable
|
||||
color automatically.
|
||||
|
||||
|
||||
--hints-text-background-color
|
||||
default=auto
|
||||
type=str
|
||||
The background color for text pointed to by the hints (excluding the hint label itself). You can use
|
||||
color names or hex values. For the eight basic named terminal colors you can also use the
|
||||
:code:`bright-` prefix to get the bright variant of the color. The default is to pick a suitable
|
||||
color automatically.
|
||||
|
||||
|
||||
--customize-processing
|
||||
Name of a python file in the kitty config directory which will be imported to
|
||||
provide custom implementations for pattern finding and performing actions
|
||||
on selected matches. You can also specify absolute paths to load the script from
|
||||
elsewhere. See {hints_url} for details.
|
||||
|
||||
|
||||
--window-title
|
||||
The title for the hints window, default title is based on the type of text being
|
||||
hinted.
|
||||
""".format(
|
||||
default_regex=DEFAULT_REGEX,
|
||||
line='{{line}}',
|
||||
path='{{path}}',
|
||||
hints_url=website_url('kittens/hints'),
|
||||
).format
|
||||
help_text = 'Select text from the screen using the keyboard. Defaults to searching for URLs.'
|
||||
usage = ''
|
||||
|
||||
|
||||
def main(args: list[str]) -> dict[str, Any] | None:
|
||||
raise SystemExit('Should be run as kitten hints')
|
||||
|
||||
|
||||
def linenum_process_result(data: dict[str, Any]) -> tuple[str, int]:
|
||||
for match, g in zip(data['match'], data['groupdicts']):
|
||||
path, line = g['path'], g['line']
|
||||
if path and line:
|
||||
return path, int(line)
|
||||
return '', -1
|
||||
|
||||
|
||||
def linenum_handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType, extra_cli_args: Sequence[str], *a: Any) -> None:
|
||||
path, line = linenum_process_result(data)
|
||||
if not path:
|
||||
return
|
||||
|
||||
if extra_cli_args:
|
||||
cmd = [x.format(path=path, line=line) for x in extra_cli_args]
|
||||
else:
|
||||
cmd = get_editor(path_to_edit=path, line_number=line)
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
action = data['linenum_action']
|
||||
|
||||
if action == 'self':
|
||||
if w is not None:
|
||||
|
||||
def is_copy_action(s: str) -> bool:
|
||||
return s in ('-', '@', '*') or s.startswith('@')
|
||||
|
||||
programs = list(filter(is_copy_action, data['programs'] or []))
|
||||
# keep for backward compatibility, previously option `--program` does not need to be specified to perform copy actions
|
||||
if is_copy_action(cmd[0]):
|
||||
programs.append(cmd.pop(0))
|
||||
if programs:
|
||||
text = ' '.join(cmd)
|
||||
for program in programs:
|
||||
if program == '-':
|
||||
w.paste_bytes(text)
|
||||
elif program == '@':
|
||||
set_clipboard_string(text)
|
||||
boss.handle_clipboard_loss('clipboard')
|
||||
elif program == '*':
|
||||
set_primary_selection(text)
|
||||
boss.handle_clipboard_loss('primary')
|
||||
elif program.startswith('@'):
|
||||
boss.set_clipboard_buffer(program[1:], text)
|
||||
else:
|
||||
import shlex
|
||||
|
||||
text = shlex.join(cmd)
|
||||
w.paste_bytes(f'{text}\r')
|
||||
elif action == 'background':
|
||||
boss.run_background_process(cmd, cwd=data['cwd'], allow_remote_control=False)
|
||||
elif action == 'remote-control':
|
||||
boss.run_background_process(cmd, cwd=data['cwd'], allow_remote_control=True)
|
||||
else:
|
||||
getattr(boss, {'window': 'new_window_with_cwd', 'tab': 'new_tab_with_cwd', 'os_window': 'new_os_window_with_cwd'}[action])(*cmd)
|
||||
|
||||
|
||||
def on_mark_clicked(boss: BossType, window: WindowType, url: str, hyperlink_id: int, cwd: str) -> bool:
|
||||
if url.startswith('mark:'):
|
||||
window.send_cmd_response({'Type': 'mark_activated', 'Mark': int(url[5:])})
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@result_handler(type_of_input='screen-ansi', has_ready_notification=True, open_url_handler=on_mark_clicked)
|
||||
def handle_result(args: list[str], data: dict[str, Any], target_window_id: int, boss: BossType) -> None:
|
||||
cp = data['customize_processing']
|
||||
if data['type'] == 'linenum':
|
||||
cp = '::linenum::'
|
||||
if cp:
|
||||
m = load_custom_processor(cp)
|
||||
if 'handle_result' in m:
|
||||
m['handle_result'](args, data, target_window_id, boss, data['extra_cli_args'])
|
||||
return None
|
||||
|
||||
programs = data['programs'] or ('default',)
|
||||
matches: list[str] = []
|
||||
groupdicts = []
|
||||
for m, g in zip(data['match'], data['groupdicts']):
|
||||
if m:
|
||||
matches.append(m)
|
||||
groupdicts.append(g)
|
||||
if not matches:
|
||||
return
|
||||
joiner = data['multiple_joiner']
|
||||
try:
|
||||
is_int: int | None = int(joiner)
|
||||
except Exception:
|
||||
is_int = None
|
||||
text_type = data['type']
|
||||
|
||||
@lru_cache
|
||||
def joined_text() -> str:
|
||||
if is_int is not None:
|
||||
try:
|
||||
return matches[is_int]
|
||||
except IndexError:
|
||||
return matches[-1]
|
||||
if joiner == 'json':
|
||||
import json
|
||||
|
||||
return json.dumps(matches, ensure_ascii=False, indent='\t')
|
||||
if joiner == 'auto':
|
||||
q = '\n\r' if text_type in ('line', 'url') else ' '
|
||||
else:
|
||||
q = {'newline': '\n\r', 'space': ' '}.get(joiner, '')
|
||||
return q.join(matches)
|
||||
|
||||
for program in programs:
|
||||
if program == '-':
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
if w is not None:
|
||||
w.paste_text(joined_text())
|
||||
elif program == '*':
|
||||
set_primary_selection(joined_text())
|
||||
elif program.startswith('@'):
|
||||
if program == '@':
|
||||
set_clipboard_string(joined_text())
|
||||
else:
|
||||
boss.set_clipboard_buffer(program[1:], joined_text())
|
||||
else:
|
||||
from kitty.conf.utils import to_cmdline
|
||||
|
||||
cwd = data['cwd']
|
||||
is_default_program = program == 'default'
|
||||
program = get_options().open_url_with if is_default_program else program
|
||||
if text_type == 'hyperlink' and is_default_program:
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
for m in matches:
|
||||
if w is not None:
|
||||
w.open_url(m, hyperlink_id=1, cwd=cwd)
|
||||
else:
|
||||
launch_args = []
|
||||
if isinstance(program, str) and program.startswith('launch '):
|
||||
launch_args = to_cmdline(program)
|
||||
launch_args.insert(1, '--cwd=' + cwd)
|
||||
for m, groupdict in zip(matches, groupdicts):
|
||||
if groupdict:
|
||||
m = []
|
||||
for k, v in groupdict.items():
|
||||
m.append('{}={}'.format(k, v or ''))
|
||||
if launch_args:
|
||||
w = boss.window_id_map.get(target_window_id)
|
||||
boss.call_remote_control(self_window=w, args=tuple(launch_args + ([m] if isinstance(m, str) else m)))
|
||||
else:
|
||||
boss.open_url(m, program, cwd=cwd)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Run with kitty +kitten hints
|
||||
main(sys.argv)
|
||||
elif __name__ == '__doc__':
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = usage
|
||||
cd['short_desc'] = 'Select text from screen with keyboard'
|
||||
cd['options'] = OPTIONS
|
||||
cd['help_text'] = help_text
|
||||
# }}}
|
||||
@@ -0,0 +1,796 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/dlclark/regexp2"
|
||||
"github.com/dlclark/regexp2/syntax"
|
||||
"github.com/seancfoley/ipaddress-go/ipaddr"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
const (
|
||||
DEFAULT_HINT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
FILE_EXTENSION = `\.(?:[a-zA-Z0-9]{2,7}|[ahcmo])(?:\b|[^.])`
|
||||
)
|
||||
|
||||
func path_regex() string {
|
||||
return fmt.Sprintf(`(?:\S*?/[\r\S]+)|(?:\S[\r\S]*%s)\b`, FILE_EXTENSION)
|
||||
}
|
||||
|
||||
func default_linenum_regex() string {
|
||||
return fmt.Sprintf(`(?P<path>%s):(?P<line>\d+)`, path_regex())
|
||||
}
|
||||
|
||||
type Mark struct {
|
||||
Index int `json:"index"`
|
||||
Start int `json:"start"`
|
||||
End int `json:"end"`
|
||||
Text string `json:"text"`
|
||||
Group_id string `json:"group_id"`
|
||||
Is_hyperlink bool `json:"is_hyperlink"`
|
||||
Groupdict map[string]any `json:"groupdict"`
|
||||
}
|
||||
|
||||
func process_escape_codes(text string) (ans string, hyperlinks []Mark) {
|
||||
removed_size, idx := 0, 0
|
||||
active_hyperlink_url := ""
|
||||
active_hyperlink_id := ""
|
||||
active_hyperlink_start_offset := 0
|
||||
|
||||
add_hyperlink := func(end int) {
|
||||
hyperlinks = append(hyperlinks, Mark{
|
||||
Index: idx, Start: active_hyperlink_start_offset, End: end, Text: active_hyperlink_url, Is_hyperlink: true, Group_id: active_hyperlink_id})
|
||||
active_hyperlink_url, active_hyperlink_id = "", ""
|
||||
active_hyperlink_start_offset = 0
|
||||
idx++
|
||||
}
|
||||
|
||||
ans = utils.ReplaceAll(utils.MustCompile("\x1b(?:\\[[0-9;:]*?m|\\].*?\x1b\\\\)"), text, func(raw string, groupdict map[string]utils.SubMatch) string {
|
||||
if !strings.HasPrefix(raw, "\x1b]8") {
|
||||
removed_size += len(raw)
|
||||
return ""
|
||||
}
|
||||
start := groupdict[""].Start - removed_size
|
||||
removed_size += len(raw)
|
||||
if active_hyperlink_url != "" {
|
||||
add_hyperlink(start)
|
||||
}
|
||||
raw = raw[4 : len(raw)-2]
|
||||
if metadata, url, found := strings.Cut(raw, ";"); found && url != "" {
|
||||
active_hyperlink_url = url
|
||||
active_hyperlink_start_offset = start
|
||||
if metadata != "" {
|
||||
for entry := range strings.SplitSeq(metadata, ":") {
|
||||
if strings.HasPrefix(entry, "id=") && len(entry) > 3 {
|
||||
active_hyperlink_id = entry[3:]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
})
|
||||
if active_hyperlink_url != "" {
|
||||
add_hyperlink(len(ans))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type PostProcessorFunc = func(string, int, int) (int, int)
|
||||
type GroupProcessorFunc = func(map[string]string)
|
||||
|
||||
func is_punctuation(b string) bool {
|
||||
switch b {
|
||||
case ",", ".", "?", "!":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func closing_bracket_for(ch string) string {
|
||||
switch ch {
|
||||
case "(":
|
||||
return ")"
|
||||
case "[":
|
||||
return "]"
|
||||
case "{":
|
||||
return "}"
|
||||
case "<":
|
||||
return ">"
|
||||
case "*":
|
||||
return "*"
|
||||
case `"`:
|
||||
return `"`
|
||||
case "'":
|
||||
return "'"
|
||||
case "“":
|
||||
return "”"
|
||||
case "‘":
|
||||
return "’"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func char_at(s string, i int) string {
|
||||
ans, _ := utf8.DecodeRuneInString(s[i:])
|
||||
if ans == utf8.RuneError {
|
||||
return ""
|
||||
}
|
||||
return string(ans)
|
||||
}
|
||||
|
||||
func char_before(s string, i int) string {
|
||||
ans, _ := utf8.DecodeLastRuneInString(s[:i])
|
||||
if ans == utf8.RuneError {
|
||||
return ""
|
||||
}
|
||||
return string(ans)
|
||||
}
|
||||
|
||||
func matching_remover(openers ...string) PostProcessorFunc {
|
||||
return func(text string, s, e int) (int, int) {
|
||||
if s < e && e <= len(text) {
|
||||
before := char_at(text, s)
|
||||
if slices.Index(openers, before) > -1 {
|
||||
q := closing_bracket_for(before)
|
||||
if s+len(before) <= e-len(q) && char_before(text, e) == q {
|
||||
s += len(before)
|
||||
e -= len(q)
|
||||
} else if char_at(text, e) == q {
|
||||
s += len(before)
|
||||
}
|
||||
}
|
||||
}
|
||||
return s, e
|
||||
}
|
||||
}
|
||||
|
||||
func linenum_group_processor(gd map[string]string) {
|
||||
pat := utils.MustCompile(`:\d+$`)
|
||||
gd[`path`] = pat.ReplaceAllStringFunc(gd["path"], func(m string) string {
|
||||
gd["line"] = m[1:]
|
||||
return ``
|
||||
})
|
||||
gd[`path`] = utils.Expanduser(gd[`path`])
|
||||
}
|
||||
|
||||
var PostProcessorMap = sync.OnceValue(func() map[string]PostProcessorFunc {
|
||||
return map[string]PostProcessorFunc{
|
||||
"url": func(text string, s, e int) (int, int) {
|
||||
if s > 4 && text[s-5:s] == "link:" { // asciidoc URLs
|
||||
url := text[s:e]
|
||||
idx := strings.LastIndex(url, "[")
|
||||
if idx > -1 {
|
||||
e -= len(url) - idx
|
||||
}
|
||||
}
|
||||
for e > 1 && is_punctuation(char_before(text, e)) { // remove trailing punctuation
|
||||
e--
|
||||
}
|
||||
// truncate url at closing bracket/quote
|
||||
if s > 0 && e <= len(text) {
|
||||
if q := closing_bracket_for(char_before(text, s)); q != "" {
|
||||
idx := strings.Index(text[s:], q)
|
||||
if idx > 0 {
|
||||
e = s + idx
|
||||
}
|
||||
}
|
||||
}
|
||||
// reStructuredText URLs
|
||||
if e > 3 && text[e-2:e] == "`_" {
|
||||
e -= 2
|
||||
}
|
||||
return s, e
|
||||
},
|
||||
|
||||
"brackets": matching_remover("(", "{", "[", "<"),
|
||||
"quotes": matching_remover("'", `"`, "“", "‘"),
|
||||
"ip": func(text string, s, e int) (int, int) {
|
||||
addr := ipaddr.NewHostName(text[s:e])
|
||||
if !addr.IsAddress() {
|
||||
return -1, -1
|
||||
}
|
||||
return s, e
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
type KittyOpts struct {
|
||||
Url_prefixes *utils.Set[string]
|
||||
Url_excluded_characters string
|
||||
Select_by_word_characters string
|
||||
}
|
||||
|
||||
func read_relevant_kitty_opts() KittyOpts {
|
||||
ans := KittyOpts{
|
||||
Select_by_word_characters: kitty.KittyConfigDefaults.Select_by_word_characters,
|
||||
Url_excluded_characters: kitty.KittyConfigDefaults.Url_excluded_characters}
|
||||
handle_line := func(key, val string) error {
|
||||
switch key {
|
||||
case "url_prefixes":
|
||||
ans.Url_prefixes = utils.NewSetWithItems(strings.Split(val, " ")...)
|
||||
case "select_by_word_characters":
|
||||
ans.Select_by_word_characters = strings.TrimSpace(val)
|
||||
case "url_excluded_characters":
|
||||
if s, err := config.StringLiteral(val); err == nil {
|
||||
ans.Url_excluded_characters = s
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config.ReadKittyConfig(handle_line)
|
||||
if ans.Url_prefixes == nil {
|
||||
ans.Url_prefixes = utils.NewSetWithItems(kitty.KittyConfigDefaults.Url_prefixes...)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
var RelevantKittyOpts = sync.OnceValue(func() KittyOpts {
|
||||
return read_relevant_kitty_opts()
|
||||
})
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func url_excluded_characters_as_ranges_for_regex(extra_excluded string) string {
|
||||
// See https://url.spec.whatwg.org/#url-code-points
|
||||
ans := strings.Builder{}
|
||||
ans.Grow(4096)
|
||||
type cr struct{ start, end rune }
|
||||
ranges := []cr{}
|
||||
r := func(start rune, end ...rune) {
|
||||
if len(end) == 0 {
|
||||
ranges = append(ranges, cr{start, start})
|
||||
} else {
|
||||
ranges = append(ranges, cr{start, end[0]})
|
||||
}
|
||||
}
|
||||
if !strings.Contains(extra_excluded, "\n") {
|
||||
r('\n')
|
||||
}
|
||||
if !strings.Contains(extra_excluded, "\r") {
|
||||
r('\r')
|
||||
}
|
||||
r('!')
|
||||
r('$')
|
||||
r('&')
|
||||
r('#')
|
||||
r('\'')
|
||||
r('/')
|
||||
r(':')
|
||||
r(';')
|
||||
r('@')
|
||||
r('_')
|
||||
r('~')
|
||||
r('(')
|
||||
r(')')
|
||||
r('*')
|
||||
r('+')
|
||||
r(',')
|
||||
r('-')
|
||||
r('.')
|
||||
r('=')
|
||||
r('?')
|
||||
r('%')
|
||||
r('a', 'z')
|
||||
r('A', 'Z')
|
||||
r('0', '9')
|
||||
slices.SortFunc(ranges, func(a, b cr) int { return int(a.start - b.start) })
|
||||
var prev rune = -1
|
||||
for _, cr := range ranges {
|
||||
if cr.start-1 > prev+1 {
|
||||
ans.WriteString(regexp.QuoteMeta(string(prev + 1)))
|
||||
ans.WriteRune('-')
|
||||
ans.WriteString(regexp.QuoteMeta(string(cr.start - 1)))
|
||||
}
|
||||
prev = cr.end
|
||||
}
|
||||
ans.WriteString(regexp.QuoteMeta(string(ranges[len(ranges)-1].end + 1)))
|
||||
ans.WriteRune('-')
|
||||
ans.WriteRune(0x9f)
|
||||
ans.WriteString(`\x{d800}-\x{dfff}`)
|
||||
ans.WriteString(`\x{fdd0}-\x{fdef}`)
|
||||
w := func(x rune) { ans.WriteRune(x) }
|
||||
|
||||
w(0xFFFE)
|
||||
w(0xFFFF)
|
||||
w(0x1FFFE)
|
||||
w(0x1FFFF)
|
||||
w(0x2FFFE)
|
||||
w(0x2FFFF)
|
||||
w(0x3FFFE)
|
||||
w(0x3FFFF)
|
||||
w(0x4FFFE)
|
||||
w(0x4FFFF)
|
||||
w(0x5FFFE)
|
||||
w(0x5FFFF)
|
||||
w(0x6FFFE)
|
||||
w(0x6FFFF)
|
||||
w(0x7FFFE)
|
||||
w(0x7FFFF)
|
||||
w(0x8FFFE)
|
||||
w(0x8FFFF)
|
||||
w(0x9FFFE)
|
||||
w(0x9FFFF)
|
||||
w(0xAFFFE)
|
||||
w(0xAFFFF)
|
||||
w(0xBFFFE)
|
||||
w(0xBFFFF)
|
||||
w(0xCFFFE)
|
||||
w(0xCFFFF)
|
||||
w(0xDFFFE)
|
||||
w(0xDFFFF)
|
||||
w(0xEFFFE)
|
||||
w(0xEFFFF)
|
||||
w(0xFFFFE)
|
||||
w(0xFFFFF)
|
||||
|
||||
if strings.Contains(extra_excluded, "-") {
|
||||
extra_excluded = strings.ReplaceAll(extra_excluded, "-", "")
|
||||
extra_excluded = regexp.QuoteMeta(extra_excluded) + "-"
|
||||
} else {
|
||||
extra_excluded = regexp.QuoteMeta(extra_excluded)
|
||||
}
|
||||
ans.WriteString(extra_excluded)
|
||||
return ans.String()
|
||||
|
||||
}
|
||||
|
||||
func functions_for(opts *Options) (pattern string, post_processors []PostProcessorFunc, group_processors []GroupProcessorFunc, err error) {
|
||||
switch opts.Type {
|
||||
case "url":
|
||||
var url_prefixes *utils.Set[string]
|
||||
if opts.UrlPrefixes == "default" {
|
||||
url_prefixes = RelevantKittyOpts().Url_prefixes
|
||||
} else {
|
||||
url_prefixes = utils.NewSetWithItems(strings.Split(opts.UrlPrefixes, ",")...)
|
||||
}
|
||||
url_excluded_characters := RelevantKittyOpts().Url_excluded_characters
|
||||
if opts.UrlExcludedCharacters != "default" {
|
||||
if url_excluded_characters, err = config.StringLiteral(opts.UrlExcludedCharacters); err != nil {
|
||||
err = fmt.Errorf("Failed to parse --url-excluded-characters value: %#v with error: %w", opts.UrlExcludedCharacters, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
pattern = fmt.Sprintf(`(?:%s)://[^%s]{3,}`, strings.Join(url_prefixes.AsSlice(), "|"), url_excluded_characters_as_ranges_for_regex(url_excluded_characters))
|
||||
post_processors = append(post_processors, PostProcessorMap()["url"])
|
||||
case "path":
|
||||
pattern = path_regex()
|
||||
post_processors = append(post_processors, PostProcessorMap()["brackets"], PostProcessorMap()["quotes"])
|
||||
case "line":
|
||||
pattern = "(?m)^\\s*(.+)[\\s\x00]*$"
|
||||
case "hash":
|
||||
pattern = "[0-9a-f][0-9a-f\r]{6,127}"
|
||||
case "ip":
|
||||
pattern = (
|
||||
// IPv4 with no validation
|
||||
`((?:\d{1,3}\.){3}\d{1,3}` + "|" +
|
||||
// IPv6 with no validation
|
||||
`(?:[a-fA-F0-9]{0,4}:){2,7}[a-fA-F0-9]{0,4})`)
|
||||
post_processors = append(post_processors, PostProcessorMap()["ip"])
|
||||
default:
|
||||
pattern = opts.Regex
|
||||
if opts.Type == "linenum" {
|
||||
if pattern == kitty.HintsDefaultRegex {
|
||||
pattern = default_linenum_regex()
|
||||
}
|
||||
post_processors = append(post_processors, PostProcessorMap()["brackets"], PostProcessorMap()["quotes"])
|
||||
group_processors = append(group_processors, linenum_group_processor)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type Capture struct {
|
||||
Text string
|
||||
Text_as_runes []rune
|
||||
Byte_Offsets struct {
|
||||
Start, End int
|
||||
}
|
||||
Rune_Offsets struct {
|
||||
Start, End int
|
||||
}
|
||||
}
|
||||
|
||||
func (self Capture) String() string {
|
||||
return fmt.Sprintf("Capture(start=%d, end=%d, %#v)", self.Byte_Offsets.Start, self.Byte_Offsets.End, self.Text)
|
||||
}
|
||||
|
||||
type Group struct {
|
||||
Name string
|
||||
IsNamed bool
|
||||
Captures []Capture
|
||||
}
|
||||
|
||||
func (self Group) LastCapture() Capture {
|
||||
if len(self.Captures) == 0 {
|
||||
return Capture{}
|
||||
}
|
||||
return self.Captures[len(self.Captures)-1]
|
||||
}
|
||||
|
||||
func (self Group) String() string {
|
||||
return fmt.Sprintf("Group(name=%#v, captures=%v)", self.Name, self.Captures)
|
||||
}
|
||||
|
||||
type Match struct {
|
||||
Groups []Group
|
||||
}
|
||||
|
||||
func (self Match) HasNamedGroups() bool {
|
||||
for _, g := range self.Groups {
|
||||
if g.IsNamed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func find_all_matches(re *regexp2.Regexp, text string) (ans []Match, err error) {
|
||||
m, err := re.FindStringMatch(text)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rune_to_bytes := utils.RuneOffsetsToByteOffsets(text)
|
||||
get_byte_offset_map := func(groups []regexp2.Group) (ans map[int]int, err error) {
|
||||
ans = make(map[int]int, len(groups)*2)
|
||||
rune_offsets := make([]int, 0, len(groups)*2)
|
||||
for _, g := range groups {
|
||||
for _, c := range g.Captures {
|
||||
if _, found := ans[c.Index]; !found {
|
||||
rune_offsets = append(rune_offsets, c.Index)
|
||||
ans[c.Index] = -1
|
||||
}
|
||||
end := c.Index + c.Length
|
||||
if _, found := ans[end]; !found {
|
||||
rune_offsets = append(rune_offsets, end)
|
||||
ans[end] = -1
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(rune_offsets)
|
||||
for _, pos := range rune_offsets {
|
||||
if ans[pos] = rune_to_bytes(pos); ans[pos] < 0 {
|
||||
return nil, fmt.Errorf("Matches are not monotonic cannot map rune offsets to byte offsets")
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
for m != nil {
|
||||
groups := m.Groups()
|
||||
bom, err := get_byte_offset_map(groups)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
match := Match{Groups: make([]Group, len(groups))}
|
||||
for i, g := range m.Groups() {
|
||||
match.Groups[i].Name = g.Name
|
||||
match.Groups[i].IsNamed = g.Name != "" && g.Name != strconv.Itoa(i)
|
||||
for _, c := range g.Captures {
|
||||
cn := Capture{Text: c.String(), Text_as_runes: c.Runes()}
|
||||
cn.Rune_Offsets.End = c.Index + c.Length
|
||||
cn.Rune_Offsets.Start = c.Index
|
||||
cn.Byte_Offsets.Start, cn.Byte_Offsets.End = bom[c.Index], bom[cn.Rune_Offsets.End]
|
||||
match.Groups[i].Captures = append(match.Groups[i].Captures, cn)
|
||||
}
|
||||
}
|
||||
ans = append(ans, match)
|
||||
m, _ = re.FindNextMatch(m)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Go's regexp only considers ASCII characters when matching \b whereas regexp2
|
||||
// uses Unicode word characters. So replace every non-ASCII rune with a single
|
||||
// ASCII byte that is a word character iff the rune is one, and return the byte
|
||||
// offsets of the runes in text, to map match offsets back.
|
||||
func ascii_word_proxy(text string) (proxy string, byte_offsets []int) {
|
||||
if !slices.ContainsFunc(utils.UnsafeStringToBytes(text), func(b byte) bool { return b >= utf8.RuneSelf }) {
|
||||
return text, nil
|
||||
}
|
||||
buf := make([]byte, 0, len(text))
|
||||
byte_offsets = make([]int, 0, len(text)+1)
|
||||
for i, r := range text {
|
||||
byte_offsets = append(byte_offsets, i)
|
||||
switch {
|
||||
case r < utf8.RuneSelf:
|
||||
buf = append(buf, byte(r))
|
||||
case syntax.IsWordChar(r):
|
||||
buf = append(buf, '_')
|
||||
default:
|
||||
buf = append(buf, 0x7f)
|
||||
}
|
||||
}
|
||||
return string(buf), append(byte_offsets, len(text))
|
||||
}
|
||||
|
||||
func find_all_matches_stdlib(re *regexp.Regexp, text string, unicode_word_boundaries bool) (ans []Match) {
|
||||
haystack, byte_offsets := text, []int(nil)
|
||||
if unicode_word_boundaries {
|
||||
haystack, byte_offsets = ascii_word_proxy(text)
|
||||
}
|
||||
names := re.SubexpNames()
|
||||
for _, loc := range re.FindAllStringSubmatchIndex(haystack, -1) {
|
||||
match := Match{Groups: make([]Group, len(names))}
|
||||
for i, name := range names {
|
||||
match.Groups[i] = Group{Name: name, IsNamed: name != ""}
|
||||
if s, e := loc[2*i], loc[2*i+1]; s > -1 {
|
||||
if byte_offsets != nil {
|
||||
s, e = byte_offsets[s], byte_offsets[e]
|
||||
}
|
||||
c := Capture{Text: text[s:e]}
|
||||
c.Byte_Offsets.Start, c.Byte_Offsets.End = s, e
|
||||
match.Groups[i].Captures = []Capture{c}
|
||||
}
|
||||
}
|
||||
ans = append(ans, match)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func mark(all_matches []Match, post_processors []PostProcessorFunc, group_processors []GroupProcessorFunc, text string, opts *Options) (ans []Mark) {
|
||||
sanitize_pat := regexp.MustCompile("[\r\n\x00]")
|
||||
for i, m := range all_matches {
|
||||
full_capture := m.Groups[0].LastCapture()
|
||||
match_start, match_end := full_capture.Byte_Offsets.Start, full_capture.Byte_Offsets.End
|
||||
for match_end > match_start+1 && text[match_end-1] == 0 {
|
||||
match_end--
|
||||
}
|
||||
full_match := text[match_start:match_end]
|
||||
if len([]rune(full_match)) < opts.MinimumMatchLength {
|
||||
continue
|
||||
}
|
||||
for _, f := range post_processors {
|
||||
match_start, match_end = f(text, match_start, match_end)
|
||||
if match_start < 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if match_start < 0 {
|
||||
continue
|
||||
}
|
||||
full_match = sanitize_pat.ReplaceAllLiteralString(text[match_start:match_end], "")
|
||||
gd := make(map[string]string, len(m.Groups))
|
||||
for idx, g := range m.Groups {
|
||||
if idx > 0 && g.IsNamed {
|
||||
c := g.LastCapture()
|
||||
if s, e := c.Byte_Offsets.Start, c.Byte_Offsets.End; s > -1 && e > -1 {
|
||||
s = max(s, match_start)
|
||||
e = min(e, match_end)
|
||||
gd[g.Name] = sanitize_pat.ReplaceAllLiteralString(text[s:e], "")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range group_processors {
|
||||
f(gd)
|
||||
}
|
||||
gd2 := make(map[string]any, len(gd))
|
||||
for k, v := range gd {
|
||||
gd2[k] = v
|
||||
}
|
||||
if opts.Type == "regex" && len(m.Groups) > 1 && !m.HasNamedGroups() {
|
||||
cp := m.Groups[1].LastCapture()
|
||||
ms, me := cp.Byte_Offsets.Start, cp.Byte_Offsets.End
|
||||
match_start = max(match_start, ms)
|
||||
match_end = min(match_end, me)
|
||||
full_match = sanitize_pat.ReplaceAllLiteralString(text[match_start:match_end], "")
|
||||
}
|
||||
if full_match != "" {
|
||||
ans = append(ans, Mark{
|
||||
Index: i, Start: match_start, End: match_end, Text: full_match, Groupdict: gd2,
|
||||
})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type ErrNoMatches struct{ Type, Pattern string }
|
||||
|
||||
func is_word_char(ch rune, current_chars []rune) bool {
|
||||
return unicode.IsLetter(ch) || unicode.IsNumber(ch) || (unicode.IsMark(ch) && len(current_chars) > 0 && unicode.IsLetter(current_chars[len(current_chars)-1]))
|
||||
}
|
||||
|
||||
func mark_words(text string, opts *Options) (ans []Mark) {
|
||||
left := text
|
||||
var current_run struct {
|
||||
chars []rune
|
||||
start, size int
|
||||
}
|
||||
chars := opts.WordCharacters
|
||||
if chars == "" {
|
||||
chars = RelevantKittyOpts().Select_by_word_characters
|
||||
}
|
||||
allowed_chars := make(map[rune]bool, len(chars))
|
||||
for _, ch := range chars {
|
||||
allowed_chars[ch] = true
|
||||
}
|
||||
pos := 0
|
||||
post_processors := []PostProcessorFunc{PostProcessorMap()["brackets"], PostProcessorMap()["quotes"]}
|
||||
|
||||
commit_run := func() {
|
||||
if len(current_run.chars) >= opts.MinimumMatchLength {
|
||||
match_start, match_end := current_run.start, current_run.start+current_run.size
|
||||
for _, f := range post_processors {
|
||||
match_start, match_end = f(text, match_start, match_end)
|
||||
if match_start < 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if match_start > -1 && match_end > match_start {
|
||||
full_match := text[match_start:match_end]
|
||||
if len([]rune(full_match)) >= opts.MinimumMatchLength {
|
||||
ans = append(ans, Mark{
|
||||
Index: len(ans), Start: match_start, End: match_end, Text: full_match,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
current_run.chars = nil
|
||||
current_run.start = 0
|
||||
current_run.size = 0
|
||||
}
|
||||
|
||||
for {
|
||||
ch, size := utf8.DecodeRuneInString(left)
|
||||
if ch == utf8.RuneError {
|
||||
break
|
||||
}
|
||||
if allowed_chars[ch] || is_word_char(ch, current_run.chars) {
|
||||
if len(current_run.chars) == 0 {
|
||||
current_run.start = pos
|
||||
}
|
||||
current_run.chars = append(current_run.chars, ch)
|
||||
current_run.size += size
|
||||
} else {
|
||||
commit_run()
|
||||
}
|
||||
left = left[size:]
|
||||
pos += size
|
||||
}
|
||||
commit_run()
|
||||
return
|
||||
}
|
||||
|
||||
func adjust_python_offsets(text string, marks []Mark) error {
|
||||
// python returns rune based offsets (unicode chars not utf-8 bytes)
|
||||
adjust := utils.RuneOffsetsToByteOffsets(text)
|
||||
for i := range marks {
|
||||
mark := &marks[i]
|
||||
if mark.End < mark.Start {
|
||||
return fmt.Errorf("The end of a mark must not be before its start")
|
||||
}
|
||||
s, e := adjust(mark.Start), adjust(mark.End)
|
||||
if s < 0 || e < 0 {
|
||||
return fmt.Errorf("Overlapping marks are not supported")
|
||||
}
|
||||
mark.Start, mark.End = s, e
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *ErrNoMatches) Error() string {
|
||||
none_of := "matches"
|
||||
switch self.Type {
|
||||
case "urls":
|
||||
none_of = "URLs"
|
||||
case "hyperlinks":
|
||||
none_of = "hyperlinks"
|
||||
}
|
||||
if self.Pattern != "" {
|
||||
return fmt.Sprintf("No %s found with pattern: %s", none_of, self.Pattern)
|
||||
}
|
||||
return fmt.Sprintf("No %s found", none_of)
|
||||
}
|
||||
|
||||
func find_marks(text string, opts *Options, cli_args ...string) (sanitized_text string, ans []Mark, index_map map[int]*Mark, err error) {
|
||||
sanitized_text, hyperlinks := process_escape_codes(text)
|
||||
used_pattern := ""
|
||||
|
||||
run_basic_matching := func() error {
|
||||
pattern, post_processors, group_processors, err := functions_for(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var matches []Match
|
||||
// the builtin patterns dont need lookarounds, so use the linear time stdlib engine for them
|
||||
if pattern != opts.Regex {
|
||||
r, err := regexp.Compile(pattern)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to compile the regex pattern: %#v with error: %w", pattern, err)
|
||||
}
|
||||
// the proxy text is only valid for patterns that dont reference specific non-ASCII characters
|
||||
matches = find_all_matches_stdlib(r, sanitized_text, opts.Type == "path" || opts.Type == "linenum")
|
||||
} else {
|
||||
r, err := regexp2.Compile(pattern, regexp2.RE2)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to compile the regex pattern: %#v with error: %w", pattern, err)
|
||||
}
|
||||
matches, _ = find_all_matches(r, sanitized_text)
|
||||
}
|
||||
ans = mark(matches, post_processors, group_processors, sanitized_text, opts)
|
||||
used_pattern = pattern
|
||||
return nil
|
||||
}
|
||||
|
||||
if opts.CustomizeProcessing != "" {
|
||||
cmd := exec.Command(utils.KittyExe(), append([]string{"+runpy", "from kittens.hints.main import custom_marking; custom_marking()"}, cli_args...)...)
|
||||
cmd.Stdin = strings.NewReader(sanitized_text)
|
||||
stdout, stderr := bytes.Buffer{}, bytes.Buffer{}
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
err = cmd.Run()
|
||||
if err != nil {
|
||||
var e *exec.ExitError
|
||||
if errors.As(err, &e) && e.ExitCode() == 2 {
|
||||
err = run_basic_matching()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
goto process_answer
|
||||
} else {
|
||||
return "", nil, nil, fmt.Errorf("Failed to run custom processor %#v with error: %w\n%s", opts.CustomizeProcessing, err, stderr.String())
|
||||
}
|
||||
}
|
||||
ans = make([]Mark, 0, 32)
|
||||
err = json.Unmarshal(stdout.Bytes(), &ans)
|
||||
if err != nil {
|
||||
return "", nil, nil, fmt.Errorf("Failed to load output from custom processor %#v with error: %w", opts.CustomizeProcessing, err)
|
||||
}
|
||||
err = adjust_python_offsets(sanitized_text, ans)
|
||||
if err != nil {
|
||||
return "", nil, nil, fmt.Errorf("Custom processor %#v produced invalid mark output with error: %w", opts.CustomizeProcessing, err)
|
||||
}
|
||||
} else if opts.Type == "hyperlink" {
|
||||
ans = hyperlinks
|
||||
} else if opts.Type == "word" {
|
||||
ans = mark_words(sanitized_text, opts)
|
||||
} else {
|
||||
err = run_basic_matching()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
process_answer:
|
||||
if len(ans) == 0 {
|
||||
return "", nil, nil, &ErrNoMatches{Type: opts.Type, Pattern: used_pattern}
|
||||
}
|
||||
largest_index := ans[len(ans)-1].Index
|
||||
offset := max(0, opts.HintsOffset)
|
||||
if opts.PrefixFree {
|
||||
alphabetLength := len(opts.Alphabet)
|
||||
if alphabetLength == 0 {
|
||||
alphabetLength = len(DEFAULT_HINT_ALPHABET)
|
||||
}
|
||||
offset = max(offset, hints_to_skip(len(ans), alphabetLength))
|
||||
}
|
||||
index_map = make(map[int]*Mark, len(ans))
|
||||
for i := range ans {
|
||||
m := &ans[i]
|
||||
if opts.Ascending {
|
||||
m.Index += offset
|
||||
} else {
|
||||
m.Index = largest_index - m.Index + offset
|
||||
}
|
||||
index_map[m.Index] = m
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hints
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestHintMarking(t *testing.T) {
|
||||
|
||||
var opts *Options
|
||||
cols := 20
|
||||
cli_args := []string{}
|
||||
|
||||
reset := func() {
|
||||
opts = &Options{Type: "url", UrlPrefixes: "default", Regex: kitty.HintsDefaultRegex}
|
||||
cols = 20
|
||||
cli_args = []string{}
|
||||
}
|
||||
|
||||
r := func(text string, url ...string) (marks []Mark) {
|
||||
ptext := convert_text(text, cols)
|
||||
ptext, marks, _, err := find_marks(ptext, opts, cli_args...)
|
||||
if err != nil {
|
||||
var e *ErrNoMatches
|
||||
if len(url) != 0 || !errors.As(err, &e) {
|
||||
t.Fatalf("%#v failed with error: %s", text, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
actual := utils.Map(func(m Mark) string { return m.Text }, marks)
|
||||
if diff := cmp.Diff(url, actual); diff != "" {
|
||||
t.Fatalf("%#v failed:\n%s", text, diff)
|
||||
}
|
||||
for _, m := range marks {
|
||||
q := strings.NewReplacer("\n", "", "\r", "", "\x00", "").Replace(ptext[m.Start:m.End])
|
||||
if diff := cmp.Diff(m.Text, q); diff != "" {
|
||||
t.Fatalf("Mark start (%d) and end (%d) dont point to correct offset in text for %#v\n%s", m.Start, m.End, text, diff)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
reset()
|
||||
u := `http://test.me/`
|
||||
r(u, u)
|
||||
r(u+"#fragme", u+"#fragme")
|
||||
r(`"`+u+`"`, u)
|
||||
r("("+u+")", u)
|
||||
cols = len(u)
|
||||
r(u+"\nxxx", u+"xxx")
|
||||
cols = 20
|
||||
r("link:"+u+"[xxx]", u)
|
||||
r("`xyz <"+u+">`_.", u)
|
||||
r(`<a href="`+u+`">moo`, u)
|
||||
r("\x1b[mhttp://test.me/1234\n\x1b[mx", "http://test.me/1234")
|
||||
r("\x1b[mhttp://test.me/12345\r\x1b[m6\n\x1b[mx", "http://test.me/123456")
|
||||
r("http://example.com,", "http://example.com")
|
||||
r("http://example.com.", "http://example.com")
|
||||
r("http://example.com!", "http://example.com")
|
||||
r("http://example.com?", "http://example.com")
|
||||
r("“"+u+"”", u)
|
||||
r("‘"+u+"’", u)
|
||||
|
||||
opts.Type = "linenum"
|
||||
m := func(text, path string, line int) {
|
||||
ptext := convert_text(text, cols)
|
||||
_, marks, _, err := find_marks(ptext, opts, cli_args...)
|
||||
if err != nil {
|
||||
t.Fatalf("%#v failed with error: %s", text, err)
|
||||
}
|
||||
gd := map[string]any{"path": path, "line": strconv.Itoa(line)}
|
||||
if diff := cmp.Diff(marks[0].Groupdict, gd); diff != "" {
|
||||
t.Fatalf("%#v failed:\n%s", text, diff)
|
||||
}
|
||||
}
|
||||
m("file.c:23", "file.c", 23)
|
||||
m("file.c:23:32", "file.c", 23)
|
||||
m("file.cpp:23:1", "file.cpp", 23)
|
||||
m("a/file.c:23", "a/file.c", 23)
|
||||
m("a/file.c:23:32", "a/file.c", 23)
|
||||
m("~/file.c:23:32", utils.Expanduser("~/file.c"), 23)
|
||||
|
||||
reset()
|
||||
opts.Type = "path"
|
||||
r("file.c", "file.c")
|
||||
r("file.c.", "file.c")
|
||||
r("file.epub.", "file.epub")
|
||||
r("(file.epub)", "file.epub")
|
||||
r("some/path", "some/path")
|
||||
r("“some/path”", "some/path")
|
||||
r("Saving to: ‘index.html’", "index.html")
|
||||
// a match consisting of only a quote must not result in start > end
|
||||
for _, text := range []string{`"`, `'`, `""`, "“”", "“"} {
|
||||
for _, name := range []string{"quotes", "brackets"} {
|
||||
if s, e := PostProcessorMap()[name](text, 0, len(text)); s > e {
|
||||
t.Fatalf("%s post processor returned start (%d) > end (%d) for %#v", name, s, e, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
// long lines without spaces must not cause quadratic backtracking
|
||||
long_line := strings.Repeat("1,", 20000)
|
||||
r(long_line)
|
||||
r("漢字 "+long_line+" some/path", "some/path")
|
||||
r("漢字"+long_line+"a.txt", "漢字"+long_line+"a.txt")
|
||||
// \b must use Unicode word characters, like regexp2
|
||||
r("config.yaml文件")
|
||||
r("a.txt文 é/b.c", "a.txt文", "é/b.c")
|
||||
opts.Type = "linenum"
|
||||
r(long_line)
|
||||
m(long_line+" a/file.c:23", "a/file.c", 23)
|
||||
|
||||
reset()
|
||||
cols = 60
|
||||
opts.Type = "ip"
|
||||
r(`100.64.0.0`, `100.64.0.0`)
|
||||
r(`2001:0db8:0000:0000:0000:ff00:0042:8329`, `2001:0db8:0000:0000:0000:ff00:0042:8329`)
|
||||
r(`2001:db8:0:0:0:ff00:42:8329`, `2001:db8:0:0:0:ff00:42:8329`)
|
||||
r(`2001:db8::ff00:42:8329`, `2001:db8::ff00:42:8329`)
|
||||
r(`2001:DB8::FF00:42:8329`, `2001:DB8::FF00:42:8329`)
|
||||
r(`0000:0000:0000:0000:0000:0000:0000:0001`, `0000:0000:0000:0000:0000:0000:0000:0001`)
|
||||
r(`2600:1901:0:b2bd::`, `2600:1901:0:b2bd::`) // ifconfig.me
|
||||
r(`::1`, `::1`)
|
||||
r(`255.255.255.256`)
|
||||
r(`:1`)
|
||||
|
||||
reset()
|
||||
opts.Type = "regex"
|
||||
opts.Regex = `(?ms)^[*]?\s(\S+)`
|
||||
r(`* 2b687c2 - test1`, `2b687c2`)
|
||||
opts.Regex = `(?<=got: )sha256.{4}`
|
||||
r(`got: sha256-L8=`, `sha256-L8=`)
|
||||
|
||||
reset()
|
||||
opts.Type = "word"
|
||||
r(`#one (two) 😍 a-1b `, `#one`, `two`, `a-1b`)
|
||||
r("fōtiz час a\u0310b ", `fōtiz`, `час`, "a\u0310b")
|
||||
|
||||
reset()
|
||||
tdir := t.TempDir()
|
||||
simple := filepath.Join(tdir, "simple.py")
|
||||
cli_args = []string{"--customize-processing", simple, "extra1"}
|
||||
os.WriteFile(simple, []byte(`
|
||||
def mark(text, args, Mark, extra_cli_args, *a):
|
||||
import re
|
||||
for idx, m in enumerate(re.finditer(r'\w+', text)):
|
||||
start, end = m.span()
|
||||
mark_text = text[start:end].replace('\n', '').replace('\0', '')
|
||||
yield Mark(idx, start, end, mark_text, {"idx": idx, "args": extra_cli_args})
|
||||
`), 0o600)
|
||||
opts.Type = "regex"
|
||||
opts.CustomizeProcessing = simple
|
||||
marks := r("漢字 b", `漢字`, `b`)
|
||||
if diff := cmp.Diff(marks[0].Groupdict, map[string]any{"idx": float64(0), "args": []any{"extra1"}}); diff != "" {
|
||||
t.Fatalf("Did not get expected groupdict from custom processor:\n%s", diff)
|
||||
}
|
||||
opts.Regex = "b"
|
||||
os.WriteFile(simple, []byte(""), 0o600)
|
||||
r("a b", `b`)
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,467 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package hyperlinked_grep
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var RgExe = sync.OnceValue(func() string {
|
||||
return utils.FindExe("rg")
|
||||
})
|
||||
|
||||
func get_options_for_rg() (expecting_args map[string]bool, alias_map map[string]string, err error) {
|
||||
var raw []byte
|
||||
raw, err = exec.Command(RgExe(), "--help").Output()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Failed to execute rg: %w", err)
|
||||
return
|
||||
}
|
||||
scanner := utils.NewLineScanner(utils.UnsafeBytesToString(raw))
|
||||
options_started := false
|
||||
expecting_args = make(map[string]bool, 64)
|
||||
alias_map = make(map[string]string, 52)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if options_started {
|
||||
s := strings.TrimLeft(line, " ")
|
||||
indent := len(line) - len(s)
|
||||
if indent < 8 && indent > 0 {
|
||||
expecting_arg := strings.Contains(s, "=")
|
||||
single_letter_aliases := make([]string, 0, 1)
|
||||
long_option_names := make([]string, 0, 1)
|
||||
for x := range strings.SplitSeq(s, ",") {
|
||||
x = strings.TrimSpace(x)
|
||||
if strings.HasPrefix(x, "--") {
|
||||
lon, _, _ := strings.Cut(x[2:], "=")
|
||||
long_option_names = append(long_option_names, lon)
|
||||
} else if strings.HasPrefix(x, "-") {
|
||||
son, _, _ := strings.Cut(x[1:], " ")
|
||||
single_letter_aliases = append(single_letter_aliases, son)
|
||||
}
|
||||
}
|
||||
if len(long_option_names) == 0 {
|
||||
err = fmt.Errorf("Failed to parse rg help output line: %s", line)
|
||||
return
|
||||
}
|
||||
for _, x := range single_letter_aliases {
|
||||
alias_map[x] = long_option_names[0]
|
||||
}
|
||||
for _, x := range long_option_names[1:] {
|
||||
alias_map[x] = long_option_names[0]
|
||||
}
|
||||
expecting_args[long_option_names[0]] = expecting_arg
|
||||
}
|
||||
} else {
|
||||
if strings.HasSuffix(line, "OPTIONS:") {
|
||||
options_started = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(expecting_args) == 0 || len(alias_map) == 0 {
|
||||
err = fmt.Errorf("Failed to parse rg help output, could not find any options")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type kitten_options struct {
|
||||
matching_lines, context_lines, file_headers bool
|
||||
with_filename, heading, line_number bool
|
||||
stats, count, count_matches bool
|
||||
files, files_with_matches, files_without_match bool
|
||||
vimgrep bool
|
||||
}
|
||||
|
||||
func default_kitten_opts() *kitten_options {
|
||||
return &kitten_options{
|
||||
matching_lines: true, context_lines: true, file_headers: true,
|
||||
with_filename: true, heading: true, line_number: true,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func parse_args(args ...string) (delegate_to_rg bool, sanitized_args []string, kitten_opts *kitten_options, err error) {
|
||||
options_that_expect_args, alias_map, err := get_options_for_rg()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
options_that_expect_args["kitten"] = true
|
||||
kitten_opts = default_kitten_opts()
|
||||
sanitized_args = make([]string, 0, len(args))
|
||||
expecting_option_arg := ""
|
||||
|
||||
context_separator := "--"
|
||||
field_context_separator := "-"
|
||||
field_match_separator := "-"
|
||||
|
||||
handle_option_arg := func(key, val string, with_equals bool) error {
|
||||
if key != "kitten" {
|
||||
if with_equals {
|
||||
sanitized_args = append(sanitized_args, "--"+key+"="+val)
|
||||
} else {
|
||||
sanitized_args = append(sanitized_args, "--"+key, val)
|
||||
}
|
||||
}
|
||||
switch key {
|
||||
case "path-separator":
|
||||
if val != string(os.PathSeparator) {
|
||||
delegate_to_rg = true
|
||||
}
|
||||
case "context-separator":
|
||||
context_separator = val
|
||||
case "field-context-separator":
|
||||
field_context_separator = val
|
||||
case "field-match-separator":
|
||||
field_match_separator = val
|
||||
case "kitten":
|
||||
k, v, found := strings.Cut(val, "=")
|
||||
if !found || k != "hyperlink" {
|
||||
return fmt.Errorf("Unknown --kitten option: %s", val)
|
||||
}
|
||||
for x := range strings.SplitSeq(v, ",") {
|
||||
switch x {
|
||||
case "none":
|
||||
kitten_opts.context_lines = false
|
||||
kitten_opts.file_headers = false
|
||||
kitten_opts.matching_lines = false
|
||||
case "all":
|
||||
kitten_opts.context_lines = true
|
||||
kitten_opts.file_headers = true
|
||||
kitten_opts.matching_lines = true
|
||||
case "matching_lines":
|
||||
kitten_opts.matching_lines = true
|
||||
case "file_headers":
|
||||
kitten_opts.file_headers = true
|
||||
case "context_lines":
|
||||
kitten_opts.context_lines = true
|
||||
default:
|
||||
return fmt.Errorf("hyperlink option invalid: %s", x)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
handle_bool_option := func(key string) {
|
||||
switch key {
|
||||
case "no-context-separator":
|
||||
context_separator = ""
|
||||
case "no-filename":
|
||||
kitten_opts.with_filename = false
|
||||
case "with-filename":
|
||||
kitten_opts.with_filename = true
|
||||
case "heading":
|
||||
kitten_opts.heading = true
|
||||
case "no-heading":
|
||||
kitten_opts.heading = false
|
||||
case "line-number":
|
||||
kitten_opts.line_number = true
|
||||
case "no-line-number":
|
||||
kitten_opts.line_number = false
|
||||
case "pretty":
|
||||
kitten_opts.line_number = true
|
||||
kitten_opts.heading = true
|
||||
case "stats":
|
||||
kitten_opts.stats = true
|
||||
case "count":
|
||||
kitten_opts.count = true
|
||||
case "count-matches":
|
||||
kitten_opts.count_matches = true
|
||||
case "files":
|
||||
kitten_opts.files = true
|
||||
case "files-with-matches":
|
||||
kitten_opts.files_with_matches = true
|
||||
case "files-without-match":
|
||||
kitten_opts.files_without_match = true
|
||||
case "vimgrep":
|
||||
kitten_opts.vimgrep = true
|
||||
case "null", "null-data", "type-list", "version", "help":
|
||||
delegate_to_rg = true
|
||||
}
|
||||
}
|
||||
|
||||
for i, x := range args {
|
||||
if expecting_option_arg != "" {
|
||||
if err = handle_option_arg(expecting_option_arg, x, false); err != nil {
|
||||
return
|
||||
}
|
||||
expecting_option_arg = ""
|
||||
} else {
|
||||
if x == "--" {
|
||||
sanitized_args = append(sanitized_args, args[i:]...)
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(x, "--") {
|
||||
a, b, found := strings.Cut(x, "=")
|
||||
a = a[2:]
|
||||
q := alias_map[a]
|
||||
if q != "" {
|
||||
a = q
|
||||
}
|
||||
if found {
|
||||
if _, is_known_option := options_that_expect_args[a]; is_known_option {
|
||||
if err = handle_option_arg(a, b, true); err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
sanitized_args = append(sanitized_args, x)
|
||||
}
|
||||
} else {
|
||||
if options_that_expect_args[a] {
|
||||
expecting_option_arg = a
|
||||
} else {
|
||||
handle_bool_option(a)
|
||||
sanitized_args = append(sanitized_args, x)
|
||||
}
|
||||
}
|
||||
} else if x != "-" && strings.HasPrefix(x, "-") {
|
||||
// rg semantics: everything after the first short option that
|
||||
// takes a value is that value, with an optional leading = stripped
|
||||
ok := true
|
||||
chars := make([]string, 0, len(x)-1)
|
||||
option_arg, has_option_arg := "", false
|
||||
for j, ch := range x[1:] {
|
||||
chars = append(chars, string(ch))
|
||||
var target string
|
||||
if target, ok = alias_map[string(ch)]; !ok {
|
||||
sanitized_args = append(sanitized_args, x)
|
||||
break
|
||||
}
|
||||
if options_that_expect_args[target] {
|
||||
if rest := x[j+2:]; rest != "" {
|
||||
option_arg, has_option_arg = strings.TrimPrefix(rest, "="), true
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if ok {
|
||||
for _, ch := range chars {
|
||||
target := alias_map[ch]
|
||||
if options_that_expect_args[target] {
|
||||
if !has_option_arg {
|
||||
expecting_option_arg = target
|
||||
} else if err = handle_option_arg(target, option_arg, false); err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
handle_bool_option(target)
|
||||
sanitized_args = append(sanitized_args, "-"+ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sanitized_args = append(sanitized_args, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !kitten_opts.with_filename || context_separator != "--" || field_context_separator != "-" || field_match_separator != "-" {
|
||||
delegate_to_rg = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type stdout_filter struct {
|
||||
prefix []byte
|
||||
process_line func(string)
|
||||
}
|
||||
|
||||
func (self *stdout_filter) Write(p []byte) (n int, err error) {
|
||||
n = len(p)
|
||||
for len(p) > 0 {
|
||||
idx := bytes.IndexByte(p, '\n')
|
||||
if idx < 0 {
|
||||
self.prefix = append(self.prefix, p...)
|
||||
break
|
||||
}
|
||||
line := p[:idx]
|
||||
if len(self.prefix) > 0 {
|
||||
self.prefix = append(self.prefix, line...)
|
||||
line = self.prefix
|
||||
}
|
||||
p = p[idx+1:]
|
||||
self.process_line(utils.UnsafeBytesToString(line))
|
||||
self.prefix = self.prefix[:0]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func main(_ *cli.Command, _ *Options, args []string) (rc int, err error) {
|
||||
delegate_to_rg, sanitized_args, kitten_opts, err := parse_args(args...)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
if delegate_to_rg {
|
||||
sanitized_args = append([]string{"rg"}, sanitized_args...)
|
||||
err = unix.Exec(RgExe(), sanitized_args, os.Environ())
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Failed to execute rg: %w", err)
|
||||
rc = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
cmdline := append([]string{"--pretty", "--with-filename"}, sanitized_args...)
|
||||
cmd := exec.Command(RgExe(), cmdline...)
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stderr = os.Stderr
|
||||
buf := stdout_filter{prefix: make([]byte, 0, 8*1024)}
|
||||
cmd.Stdout = &buf
|
||||
sgr_pat := regexp.MustCompile("\x1b\\[.*?m")
|
||||
osc_pat := regexp.MustCompile("\x1b\\].*?\x1b\\\\")
|
||||
num_pat := regexp.MustCompile(`^(\d+)([:-])`)
|
||||
path_with_count_pat := regexp.MustCompile(`^(.*?)(:\d+)`)
|
||||
path_with_linenum_pat := regexp.MustCompile(`^(.*?):(\d+):`)
|
||||
stats_pat := regexp.MustCompile(`^\d+ matches$`)
|
||||
vimgrep_pat := regexp.MustCompile(`^(.*?):(\d+):(\d+):`)
|
||||
|
||||
in_stats := false
|
||||
in_result := ""
|
||||
hostname := utils.Hostname()
|
||||
|
||||
get_quoted_url := func(file_path string) string {
|
||||
q, err := filepath.Abs(file_path)
|
||||
if err == nil {
|
||||
file_path = q
|
||||
}
|
||||
file_path = filepath.ToSlash(file_path)
|
||||
file_path = strings.Join(utils.Map(url.PathEscape, strings.Split(file_path, "/")), "/")
|
||||
return "file://" + hostname + file_path
|
||||
}
|
||||
|
||||
write := func(items ...string) {
|
||||
for _, x := range items {
|
||||
os.Stdout.WriteString(x)
|
||||
}
|
||||
}
|
||||
|
||||
write_hyperlink := func(url, line, frag string) {
|
||||
write("\033]8;;", url)
|
||||
if frag != "" {
|
||||
write("#", frag)
|
||||
}
|
||||
write("\033\\", line, "\n\033]8;;\033\\")
|
||||
}
|
||||
|
||||
buf.process_line = func(line string) {
|
||||
line = osc_pat.ReplaceAllLiteralString(line, "") // remove existing hyperlinks
|
||||
clean_line := strings.TrimRightFunc(line, unicode.IsSpace)
|
||||
clean_line = sgr_pat.ReplaceAllLiteralString(clean_line, "") // remove SGR formatting
|
||||
if clean_line == "" {
|
||||
in_result = ""
|
||||
write("\n")
|
||||
} else if in_stats {
|
||||
write(line, "\n")
|
||||
} else if in_result != "" {
|
||||
if kitten_opts.line_number {
|
||||
m := num_pat.FindStringSubmatch(clean_line)
|
||||
if len(m) > 0 {
|
||||
is_match_line := len(m) > 1 && m[2] == ":"
|
||||
if (is_match_line && kitten_opts.matching_lines) || (!is_match_line && kitten_opts.context_lines) {
|
||||
write_hyperlink(in_result, line, m[1])
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
write(line, "\n")
|
||||
} else {
|
||||
if strings.TrimSpace(line) != "" {
|
||||
// The option priority should be consistent with ripgrep here.
|
||||
if kitten_opts.stats && !in_stats && stats_pat.MatchString(clean_line) {
|
||||
in_stats = true
|
||||
} else if kitten_opts.count || kitten_opts.count_matches {
|
||||
if m := path_with_count_pat.FindStringSubmatch(clean_line); len(m) > 0 && kitten_opts.file_headers {
|
||||
write_hyperlink(get_quoted_url(m[1]), line, "")
|
||||
return
|
||||
}
|
||||
} else if kitten_opts.files || kitten_opts.files_with_matches || kitten_opts.files_without_match {
|
||||
if kitten_opts.file_headers {
|
||||
write_hyperlink(get_quoted_url(clean_line), line, "")
|
||||
return
|
||||
}
|
||||
} else if kitten_opts.vimgrep || !kitten_opts.heading {
|
||||
var m []string
|
||||
// When the vimgrep option is present, it will take precedence.
|
||||
if kitten_opts.vimgrep {
|
||||
m = vimgrep_pat.FindStringSubmatch(clean_line)
|
||||
} else {
|
||||
m = path_with_linenum_pat.FindStringSubmatch(clean_line)
|
||||
}
|
||||
if len(m) > 0 && (kitten_opts.file_headers || kitten_opts.matching_lines) {
|
||||
write_hyperlink(get_quoted_url(m[1]), line, m[2])
|
||||
return
|
||||
}
|
||||
} else {
|
||||
in_result = get_quoted_url(clean_line)
|
||||
if kitten_opts.file_headers {
|
||||
write_hyperlink(in_result, line, "")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
write(line, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
err = cmd.Run()
|
||||
var ee *exec.ExitError
|
||||
if err != nil {
|
||||
if errors.As(err, &ee) {
|
||||
return ee.ExitCode(), nil
|
||||
}
|
||||
return 1, fmt.Errorf("Failed to execute rg: %w", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func specialize_command(hg *cli.Command) {
|
||||
hg.Usage = "arguments for the rg command"
|
||||
hg.ShortDescription = "Add hyperlinks to the output of ripgrep"
|
||||
hg.HelpText = "The hyperlinked_grep kitten is a thin wrapper around the rg command. It automatically adds hyperlinks to the output of rg allowing the user to click on search results to have them open directly in their editor. For details on its usage, see :doc:`/kittens/hyperlinked_grep`."
|
||||
hg.IgnoreAllArgs = true
|
||||
hg.OnlyArgsAllowed = true
|
||||
hg.ArgCompleter = cli.CompletionForWrapper("rg")
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
}
|
||||
|
||||
func create_cmd(root *cli.Command, run_func func(*cli.Command, *Options, []string) (int, error)) {
|
||||
ans := root.AddSubCommand(&cli.Command{
|
||||
Name: "hyperlinked_grep",
|
||||
Run: func(cmd *cli.Command, args []string) (int, error) {
|
||||
opts := Options{}
|
||||
err := cmd.GetOptionValues(&opts)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
return run_func(cmd, &opts, args)
|
||||
},
|
||||
Hidden: true,
|
||||
})
|
||||
specialize_command(ans)
|
||||
clone := root.AddClone(ans.Group, ans)
|
||||
clone.Hidden = false
|
||||
clone.Name = "hyperlinked-grep"
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
Loaded 100 of 1134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user