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
@@ -0,0 +1,29 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func DCSToKitty(msgtype, payload string) (string, error) {
|
||||
data := base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(payload))
|
||||
ans := "\x1bP@kitty-" + msgtype + "|" + data
|
||||
tmux := TmuxSocketAddress()
|
||||
if tmux != "" {
|
||||
err := TmuxAllowPassthrough()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
ans = "\033Ptmux;\033" + ans + "\033\033\\\033\\"
|
||||
} else {
|
||||
ans += "\033\\"
|
||||
}
|
||||
return ans, nil
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/humanize"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type dl_data struct {
|
||||
mutex sync.Mutex
|
||||
canceled_by_user bool
|
||||
error_from_download error
|
||||
done, total uint64
|
||||
download_started bool
|
||||
download_finished bool
|
||||
temp_file_path string
|
||||
}
|
||||
|
||||
type render_data struct {
|
||||
done, total uint64
|
||||
screen_width int
|
||||
spinner *Spinner
|
||||
started_at time.Time
|
||||
}
|
||||
|
||||
func render_without_total(rd *render_data) string {
|
||||
return fmt.Sprint(rd.spinner.Tick(), humanize.Bytes(rd.done), " downloaded so far. Started %s", humanize.Time(rd.started_at))
|
||||
}
|
||||
|
||||
func format_time(d time.Duration) string {
|
||||
d = d.Round(time.Second)
|
||||
ans := ""
|
||||
if d.Hours() > 1 {
|
||||
h := d / time.Hour
|
||||
d -= h * time.Hour
|
||||
ans += fmt.Sprintf("%02d:", h)
|
||||
}
|
||||
m := d / time.Minute
|
||||
d -= m * time.Minute
|
||||
s := d / time.Second
|
||||
return fmt.Sprintf("%s%02d:%02d", ans, m, s)
|
||||
}
|
||||
|
||||
func render_progress(rd *render_data) string {
|
||||
if rd.total == 0 {
|
||||
return render_without_total(rd)
|
||||
}
|
||||
now := time.Now()
|
||||
duration := now.Sub(rd.started_at)
|
||||
rate := float64(rd.done) / float64(duration)
|
||||
frac := float64(rd.done) / float64(rd.total)
|
||||
bytes_left := rd.total - rd.done
|
||||
time_left := time.Duration(float64(bytes_left) / rate)
|
||||
speed := rate * float64(time.Second)
|
||||
before := rd.spinner.Tick()
|
||||
after := fmt.Sprintf(" %d%% %s/s %s", int(frac*100), strings.ReplaceAll(humanize.Bytes(uint64(speed)), " ", ""), format_time(time_left))
|
||||
available_width := rd.screen_width - len("T 100% 1000 MB/s 11:11:11")
|
||||
// fmt.Println("\r\n", frac, available_width)
|
||||
progress_bar := ""
|
||||
if available_width > 10 {
|
||||
progress_bar = " " + RenderProgressBar(frac, available_width)
|
||||
}
|
||||
return before + progress_bar + after
|
||||
}
|
||||
|
||||
func DownloadFileWithProgress(destpath, url string, kill_if_signaled bool) (err error) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.NoMouseTracking)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
dl_data := dl_data{}
|
||||
rd := render_data{spinner: NewSpinner("dots"), started_at: time.Now()}
|
||||
|
||||
register_temp_file_path := func(path string) {
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.temp_file_path = path
|
||||
dl_data.mutex.Unlock()
|
||||
}
|
||||
|
||||
report_progress := func(done, total uint64) error {
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.done = done
|
||||
dl_data.total = total
|
||||
canceled := dl_data.canceled_by_user
|
||||
dl_data.mutex.Unlock()
|
||||
if canceled {
|
||||
return Canceled
|
||||
}
|
||||
lp.WakeupMainThread()
|
||||
return nil
|
||||
}
|
||||
|
||||
do_download := func() {
|
||||
lp.RecoverFromPanicInGoRoutine()
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.download_started = true
|
||||
dl_data.mutex.Unlock()
|
||||
err := utils.DownloadToFile(destpath, url, report_progress, register_temp_file_path)
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.download_finished = true
|
||||
if err != Canceled && err != nil {
|
||||
dl_data.error_from_download = err
|
||||
}
|
||||
dl_data.mutex.Unlock()
|
||||
lp.WakeupMainThread()
|
||||
}
|
||||
|
||||
redraw := func() {
|
||||
lp.StartAtomicUpdate()
|
||||
lp.AllowLineWrapping(false)
|
||||
defer func() {
|
||||
lp.AllowLineWrapping(true)
|
||||
lp.EndAtomicUpdate()
|
||||
}()
|
||||
lp.QueueWriteString("\r")
|
||||
lp.ClearToEndOfLine()
|
||||
dl_data.mutex.Lock()
|
||||
rd.done, rd.total = dl_data.done, dl_data.total
|
||||
dl_data.mutex.Unlock()
|
||||
if rd.done+rd.total == 0 {
|
||||
lp.QueueWriteString("Waiting for download to start...")
|
||||
} else {
|
||||
sz, err := lp.ScreenSize()
|
||||
w := sz.WidthCells
|
||||
if err != nil {
|
||||
w = 80
|
||||
}
|
||||
rd.screen_width = int(w)
|
||||
lp.QueueWriteString(render_progress(&rd))
|
||||
}
|
||||
}
|
||||
|
||||
on_timer_tick := func(timer_id loop.IdType) error {
|
||||
return lp.OnWakeup()
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
if _, err = lp.AddTimer(rd.spinner.interval, true, on_timer_tick); err != nil {
|
||||
return "", err
|
||||
}
|
||||
go do_download()
|
||||
lp.QueueWriteString("Downloading: " + url + "\r\n")
|
||||
return "\r\n", nil
|
||||
}
|
||||
|
||||
lp.OnResumeFromStop = func() error {
|
||||
redraw()
|
||||
return nil
|
||||
}
|
||||
lp.OnResize = func(old_size, new_size loop.ScreenSize) error {
|
||||
redraw()
|
||||
return nil
|
||||
}
|
||||
lp.OnWakeup = func() error {
|
||||
dl_data.mutex.Lock()
|
||||
err := dl_data.error_from_download
|
||||
finished := dl_data.download_finished
|
||||
dl_data.mutex.Unlock()
|
||||
if err != nil {
|
||||
return dl_data.error_from_download
|
||||
}
|
||||
if finished {
|
||||
lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
redraw()
|
||||
return nil
|
||||
}
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
dl_data.mutex.Lock()
|
||||
dl_data.canceled_by_user = true
|
||||
dl_data.mutex.Unlock()
|
||||
return Canceled
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
dl_data.mutex.Lock()
|
||||
if dl_data.temp_file_path != "" && !dl_data.download_finished {
|
||||
os.Remove(dl_data.temp_file_path)
|
||||
}
|
||||
dl_data.mutex.Unlock()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
if kill_if_signaled {
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
return &KilledBySignal{Msg: fmt.Sprint("Killed by signal: ", ds), SignalName: ds}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package graphics
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
shm "github.com/kovidgoyal/go-shm/v2"
|
||||
"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/images"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Size struct{ Width, Height int }
|
||||
|
||||
type rendering struct {
|
||||
img *images.ImageData
|
||||
image_id uint32
|
||||
}
|
||||
|
||||
type temp_resource struct {
|
||||
path string
|
||||
mmap shm.MMap
|
||||
}
|
||||
|
||||
func (self *temp_resource) remove() {
|
||||
if self.path != "" {
|
||||
os.Remove(self.path)
|
||||
self.path = ""
|
||||
}
|
||||
if self.mmap != nil {
|
||||
_ = self.mmap.Unlink()
|
||||
self.mmap = nil
|
||||
}
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
src struct {
|
||||
path string
|
||||
data *images.ImageData
|
||||
size Size
|
||||
loaded bool
|
||||
}
|
||||
renderings map[Size]*rendering
|
||||
err error
|
||||
}
|
||||
|
||||
func NewImage() *Image {
|
||||
return &Image{
|
||||
renderings: make(map[Size]*rendering),
|
||||
}
|
||||
}
|
||||
|
||||
type ImageCollection struct {
|
||||
Shm_supported, Files_supported atomic.Bool
|
||||
detection_file_id, detection_shm_id uint32
|
||||
temp_file_map map[uint32]*temp_resource
|
||||
running_in_tmux bool
|
||||
|
||||
mutex sync.Mutex
|
||||
image_id_counter uint32
|
||||
|
||||
images map[string]*Image
|
||||
}
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
func (self *ImageCollection) GetSizeIfAvailable(key string, page_size Size) (Size, error) {
|
||||
if !self.mutex.TryLock() {
|
||||
return Size{}, ErrNotFound
|
||||
}
|
||||
defer self.mutex.Unlock()
|
||||
img := self.images[key]
|
||||
if img == nil {
|
||||
return Size{}, ErrNotFound
|
||||
}
|
||||
ans := img.renderings[page_size]
|
||||
if ans == nil {
|
||||
if img.err != nil {
|
||||
return Size{}, img.err
|
||||
}
|
||||
return Size{}, ErrNotFound
|
||||
}
|
||||
return Size{ans.img.Width, ans.img.Height}, img.err
|
||||
}
|
||||
|
||||
func (self *ImageCollection) ResolutionOf(key string) Size {
|
||||
if !self.mutex.TryLock() {
|
||||
return Size{-1, -1}
|
||||
}
|
||||
defer self.mutex.Unlock()
|
||||
i := self.images[key]
|
||||
if i == nil {
|
||||
return Size{-2, -2}
|
||||
}
|
||||
return i.src.size
|
||||
}
|
||||
|
||||
func (self *ImageCollection) AddPaths(paths ...string) {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
for _, path := range paths {
|
||||
if self.images[path] == nil {
|
||||
i := NewImage()
|
||||
i.src.path = path
|
||||
self.images[path] = i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Image) ResizeForPageSize(width, height int) {
|
||||
sz := Size{width, height}
|
||||
if self.renderings[sz] != nil {
|
||||
return
|
||||
}
|
||||
final_width, final_height := images.FitImage(self.src.size.Width, self.src.size.Height, width, height)
|
||||
if final_width == self.src.size.Width && final_height == self.src.data.Height {
|
||||
self.renderings[sz] = &rendering{img: self.src.data}
|
||||
return
|
||||
}
|
||||
x_frac, y_frac := float64(final_width)/float64(self.src.size.Width), float64(final_height)/float64(self.src.size.Height)
|
||||
self.renderings[sz] = &rendering{img: self.src.data.Resize(x_frac, y_frac)}
|
||||
}
|
||||
|
||||
func (self *ImageCollection) ResizeForPageSize(width, height int) {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
|
||||
ctx := images.Context{}
|
||||
keys := utils.Keys(self.images)
|
||||
if err := ctx.SafeParallel(0, len(keys), func(nums <-chan int) {
|
||||
for i := range nums {
|
||||
img := self.images[keys[i]]
|
||||
if img.src.loaded && img.err == nil {
|
||||
img.ResizeForPageSize(width, height)
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *ImageCollection) DeleteAllVisiblePlacements(lp *loop.Loop) {
|
||||
g := self.new_graphics_command()
|
||||
g.SetAction(GRT_action_delete).SetDelete(GRT_delete_visible)
|
||||
_ = g.WriteWithPayloadToLoop(lp, nil)
|
||||
}
|
||||
|
||||
func (self *ImageCollection) PlaceImageSubRect(lp *loop.Loop, key string, page_size Size, left, top, width, height int) {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
img := self.images[key]
|
||||
if img == nil {
|
||||
return
|
||||
}
|
||||
r := img.renderings[page_size]
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
if r.image_id == 0 {
|
||||
self.transmit_rendering(lp, r)
|
||||
}
|
||||
if width < 0 {
|
||||
width = r.img.Width
|
||||
}
|
||||
if height < 0 {
|
||||
height = r.img.Height
|
||||
}
|
||||
width = utils.Max(0, utils.Min(r.img.Width-left, width))
|
||||
height = utils.Max(0, utils.Min(r.img.Height-top, height))
|
||||
gc := self.new_graphics_command()
|
||||
gc.SetAction(GRT_action_display).SetLeftEdge(uint64(left)).SetTopEdge(uint64(top)).SetWidth(uint64(width)).SetHeight(uint64(height))
|
||||
gc.SetImageId(r.image_id).SetPlacementId(1).SetCursorMovement(GRT_cursor_static)
|
||||
_ = gc.WriteWithPayloadToLoop(lp, nil)
|
||||
}
|
||||
|
||||
func (self *ImageCollection) Initialize(lp *loop.Loop) {
|
||||
tmux := tui.TmuxSocketAddress()
|
||||
if tmux != "" && tui.TmuxAllowPassthrough() == nil {
|
||||
self.running_in_tmux = true
|
||||
}
|
||||
if !self.running_in_tmux {
|
||||
g := func(t GRT_t, payload string) uint32 {
|
||||
self.image_id_counter++
|
||||
g1 := self.new_graphics_command()
|
||||
g1.SetTransmission(t).SetAction(GRT_action_query).SetImageId(self.image_id_counter).SetDataWidth(1).SetDataHeight(1).SetFormat(
|
||||
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(GRT_transmission_tempfile, tf.Name())
|
||||
self.temp_file_map[self.detection_file_id] = &temp_resource{path: tf.Name()}
|
||||
}
|
||||
tf.Close()
|
||||
}
|
||||
sf, err := shm.CreateTemp("icat-", 3)
|
||||
if err == nil {
|
||||
copy(sf.Slice(), []byte{1, 2, 3})
|
||||
sf.Close()
|
||||
self.detection_shm_id = g(GRT_transmission_sharedmem, sf.Name())
|
||||
self.temp_file_map[self.detection_shm_id] = &temp_resource{mmap: sf}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *ImageCollection) Finalize(lp *loop.Loop) {
|
||||
for _, tr := range self.temp_file_map {
|
||||
tr.remove()
|
||||
}
|
||||
for _, img := range self.images {
|
||||
for _, r := range img.renderings {
|
||||
if r.image_id > 0 {
|
||||
g := self.new_graphics_command()
|
||||
g.SetAction(GRT_action_delete).SetDelete(GRT_free_by_id).SetImageId(r.image_id)
|
||||
_ = g.WriteWithPayloadToLoop(lp, nil)
|
||||
}
|
||||
}
|
||||
img.renderings = nil
|
||||
}
|
||||
self.images = nil
|
||||
}
|
||||
|
||||
func (self *ImageCollection) mark_img_as_needing_transmission(id uint32) bool {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
|
||||
for _, img := range self.images {
|
||||
for _, r := range img.renderings {
|
||||
if r.image_id == id {
|
||||
r.image_id = 0
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Handle graphics response. Returns false if an image needs re-transmission because
|
||||
// the terminal replied with ENOENT for a placement
|
||||
func (self *ImageCollection) HandleGraphicsCommand(gc *GraphicsCommand) bool {
|
||||
switch gc.ImageId() {
|
||||
case self.detection_file_id:
|
||||
if gc.ResponseMessage() == "OK" {
|
||||
self.Files_supported.Store(true)
|
||||
} else {
|
||||
if tr := self.temp_file_map[gc.ImageId()]; tr != nil {
|
||||
tr.remove()
|
||||
}
|
||||
}
|
||||
delete(self.temp_file_map, gc.ImageId())
|
||||
self.detection_file_id = 0
|
||||
return true
|
||||
case self.detection_shm_id:
|
||||
if gc.ResponseMessage() == "OK" {
|
||||
self.Shm_supported.Store(true)
|
||||
} else {
|
||||
if tr := self.temp_file_map[gc.ImageId()]; tr != nil {
|
||||
tr.remove()
|
||||
}
|
||||
}
|
||||
delete(self.temp_file_map, gc.ImageId())
|
||||
self.detection_shm_id = 0
|
||||
return true
|
||||
}
|
||||
if is_transmission_response := gc.PlacementId() == 0; is_transmission_response {
|
||||
if gc.ResponseMessage() != "OK" {
|
||||
// this should never happen but lets cleanup anyway
|
||||
if tr := self.temp_file_map[gc.ImageId()]; tr != nil {
|
||||
tr.remove()
|
||||
delete(self.temp_file_map, gc.ImageId())
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if gc.ResponseMessage() != "OK" && gc.PlacementId() != 0 {
|
||||
if self.mark_img_as_needing_transmission(gc.ImageId()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *ImageCollection) LoadAll() {
|
||||
self.mutex.Lock()
|
||||
defer self.mutex.Unlock()
|
||||
ctx := images.Context{}
|
||||
all := utils.Values(self.images)
|
||||
if err := ctx.SafeParallel(0, len(self.images), func(nums <-chan int) {
|
||||
for i := range nums {
|
||||
img := all[i]
|
||||
if !img.src.loaded {
|
||||
img.src.data, img.err = images.OpenImageFromPath(img.src.path)
|
||||
if img.err == nil {
|
||||
img.src.size.Width, img.src.size.Height = img.src.data.Width, img.src.data.Height
|
||||
}
|
||||
img.src.loaded = true
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func NewImageCollection(paths ...string) *ImageCollection {
|
||||
items := make(map[string]*Image, len(paths))
|
||||
for _, path := range paths {
|
||||
i := NewImage()
|
||||
i.src.path = path
|
||||
items[path] = i
|
||||
}
|
||||
return &ImageCollection{images: items, temp_file_map: make(map[uint32]*temp_resource)}
|
||||
}
|
||||
|
||||
func (self *ImageCollection) new_graphics_command() *GraphicsCommand {
|
||||
gc := 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 transmit_by_escape_code(lp *loop.Loop, image_id uint32, temp_file_map map[uint32]*temp_resource, frame *images.ImageFrame, gc *GraphicsCommand) {
|
||||
atomic := lp.IsAtomicUpdateActive()
|
||||
lp.EndAtomicUpdate()
|
||||
gc.SetTransmission(GRT_transmission_direct)
|
||||
_, _, _, data := frame.Data()
|
||||
_ = gc.WriteWithPayloadToLoop(lp, data)
|
||||
if atomic {
|
||||
lp.StartAtomicUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
func transmit_by_shm(lp *loop.Loop, image_id uint32, temp_file_map map[uint32]*temp_resource, frame *images.ImageFrame, gc *GraphicsCommand) {
|
||||
mmap, err := frame.DataAsSHM("kdiff-img-*")
|
||||
if err != nil {
|
||||
transmit_by_escape_code(lp, image_id, temp_file_map, frame, gc)
|
||||
return
|
||||
}
|
||||
mmap.Close()
|
||||
temp_file_map[image_id] = &temp_resource{mmap: mmap}
|
||||
gc.SetTransmission(GRT_transmission_sharedmem)
|
||||
_ = gc.WriteWithPayloadToLoop(lp, utils.UnsafeStringToBytes(mmap.Name()))
|
||||
}
|
||||
|
||||
func transmit_by_file(lp *loop.Loop, image_id uint32, temp_file_map map[uint32]*temp_resource, frame *images.ImageFrame, gc *GraphicsCommand) {
|
||||
f, err := images.CreateTempInRAM()
|
||||
if err != nil {
|
||||
transmit_by_escape_code(lp, image_id, temp_file_map, frame, gc)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
temp_file_map[image_id] = &temp_resource{path: f.Name()}
|
||||
_, _, _, data := frame.Data()
|
||||
_, err = f.Write(data)
|
||||
if err != nil {
|
||||
transmit_by_escape_code(lp, image_id, temp_file_map, frame, gc)
|
||||
return
|
||||
}
|
||||
gc.SetTransmission(GRT_transmission_tempfile)
|
||||
_ = gc.WriteWithPayloadToLoop(lp, utils.UnsafeStringToBytes(f.Name()))
|
||||
}
|
||||
|
||||
func (self *ImageCollection) transmit_rendering(lp *loop.Loop, r *rendering) {
|
||||
if r.image_id == 0 {
|
||||
self.image_id_counter++
|
||||
r.image_id = self.image_id_counter
|
||||
}
|
||||
is_animated := len(r.img.Frames) > 0
|
||||
transmit := transmit_by_escape_code
|
||||
if self.Shm_supported.Load() {
|
||||
transmit = transmit_by_shm
|
||||
} else if self.Files_supported.Load() {
|
||||
transmit = transmit_by_file
|
||||
}
|
||||
|
||||
frame_control_cmd := self.new_graphics_command()
|
||||
frame_control_cmd.SetAction(GRT_action_animate).SetImageId(r.image_id)
|
||||
for frame_num, frame := range r.img.Frames {
|
||||
gc := self.new_graphics_command()
|
||||
gc.SetImageId(r.image_id)
|
||||
gc.SetDataWidth(uint64(frame.Width)).SetDataHeight(uint64(frame.Height))
|
||||
if frame.Is_opaque {
|
||||
gc.SetFormat(GRT_format_rgb)
|
||||
}
|
||||
switch frame_num {
|
||||
case 0:
|
||||
gc.SetAction(GRT_action_transmit)
|
||||
gc.SetCursorMovement(GRT_cursor_static)
|
||||
default:
|
||||
gc.SetAction(GRT_action_frame)
|
||||
gc.SetGap(frame.Delay_ms)
|
||||
if frame.Compose_onto > 0 {
|
||||
gc.SetOverlaidFrame(uint64(frame.Compose_onto))
|
||||
}
|
||||
if frame.Replace {
|
||||
gc.SetCompositionMode(Overwrite)
|
||||
}
|
||||
gc.SetLeftEdge(uint64(frame.Left)).SetTopEdge(uint64(frame.Top))
|
||||
}
|
||||
transmit(lp, r.image_id, self.temp_file_map, frame, 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,847 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package graphics
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"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
|
||||
|
||||
// Enums {{{
|
||||
type GRT_a int // enum
|
||||
|
||||
const (
|
||||
GRT_action_transmit GRT_a = iota // t
|
||||
GRT_action_transmit_and_display // T
|
||||
GRT_action_query // q
|
||||
GRT_action_display // p
|
||||
GRT_action_delete // d
|
||||
GRT_action_frame // f
|
||||
GRT_action_animate // a
|
||||
GRT_action_compose // c
|
||||
)
|
||||
|
||||
type GRT_q int // enum
|
||||
|
||||
const (
|
||||
GRT_quiet_noisy GRT_q = iota // 0
|
||||
GRT_quiet_only_errors // 1
|
||||
GRT_quiet_silent // 2
|
||||
)
|
||||
|
||||
type GRT_f int // enum
|
||||
|
||||
const (
|
||||
GRT_format_rgba GRT_f = iota // 32
|
||||
GRT_format_rgb // 24
|
||||
GRT_format_png // 100
|
||||
GRT_format_indexed // 8
|
||||
GRT_format_indexed_alpha // 16
|
||||
)
|
||||
|
||||
type GRT_t int // enum
|
||||
|
||||
const (
|
||||
GRT_transmission_direct GRT_t = iota // d
|
||||
GRT_transmission_file // f
|
||||
GRT_transmission_tempfile // t
|
||||
GRT_transmission_sharedmem // s
|
||||
)
|
||||
|
||||
type GRT_o int // enum
|
||||
|
||||
const (
|
||||
GRT_compression_none GRT_o = iota //
|
||||
GRT_compression_zlib // z
|
||||
)
|
||||
|
||||
type GRT_m int // enum
|
||||
|
||||
const (
|
||||
GRT_more_nomore GRT_m = iota // 0
|
||||
GRT_more_more // 1
|
||||
)
|
||||
|
||||
type GRT_C int // enum
|
||||
|
||||
const (
|
||||
GRT_cursor_move GRT_C = iota // 0
|
||||
GRT_cursor_static // 1
|
||||
)
|
||||
|
||||
type GRT_U int // enum
|
||||
|
||||
const (
|
||||
GRT_no_unicode_placeholder GRT_U = iota // 0
|
||||
GRT_create_unicode_placeholder // 1
|
||||
)
|
||||
|
||||
type CompositionMode int // enum
|
||||
|
||||
const (
|
||||
AlphaBlend CompositionMode = iota // 0
|
||||
Overwrite // 1
|
||||
)
|
||||
|
||||
type GRT_d int // enum
|
||||
|
||||
const (
|
||||
GRT_delete_visible GRT_d = iota // a
|
||||
GRT_free_visible // A
|
||||
|
||||
GRT_delete_by_id // i
|
||||
GRT_free_by_id // I
|
||||
|
||||
GRT_delete_by_number // n
|
||||
GRT_free_by_number // N
|
||||
|
||||
GRT_delete_by_cursor // c
|
||||
GRT_free_by_cursor // C
|
||||
|
||||
GRT_delete_by_frame // f
|
||||
GRT_free_by_frame // F
|
||||
|
||||
GRT_delete_by_cell // p
|
||||
GRT_free_by_cell // P
|
||||
|
||||
GRT_delete_by_cell_zindex // q
|
||||
GRT_free_by_cell_zindex // Q
|
||||
|
||||
GRT_delete_by_range // r
|
||||
GRT_free_by_range // R
|
||||
|
||||
GRT_delete_by_column // x
|
||||
GRT_free_by_column // X
|
||||
|
||||
GRT_delete_by_row // y
|
||||
GRT_free_by_row // Y
|
||||
|
||||
GRT_delete_by_zindex // z
|
||||
GRT_free_by_zindex // Z
|
||||
)
|
||||
|
||||
// }}}
|
||||
|
||||
type GraphicsCommand struct {
|
||||
a GRT_a
|
||||
q GRT_q
|
||||
f GRT_f
|
||||
t GRT_t
|
||||
o GRT_o
|
||||
m GRT_m
|
||||
C GRT_C
|
||||
d GRT_d
|
||||
U GRT_U
|
||||
|
||||
s, v, S, O, x, y, w, h, X, Y, c, r, N uint64
|
||||
|
||||
i, I, p uint32
|
||||
|
||||
z int32
|
||||
|
||||
DisableCompression bool
|
||||
WrapPrefix, WrapSuffix string
|
||||
EncodeSerializedDataFunc func(string) string
|
||||
|
||||
response_message string
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) serialize_non_default_fields() (ans []string) {
|
||||
var null GraphicsCommand
|
||||
ans = make([]string, 0, 16)
|
||||
|
||||
write_key := func(k byte, val, defval any) {
|
||||
if val != defval {
|
||||
ans = append(ans, fmt.Sprintf("%c=%v", k, val))
|
||||
}
|
||||
}
|
||||
|
||||
write_key('a', self.a, null.a)
|
||||
write_key('q', self.q, null.q)
|
||||
write_key('f', self.f, null.f)
|
||||
write_key('t', self.t, null.t)
|
||||
write_key('o', self.o, null.o)
|
||||
write_key('m', self.m, null.m)
|
||||
write_key('C', self.C, null.C)
|
||||
write_key('U', self.U, null.U)
|
||||
write_key('d', self.d, null.d)
|
||||
|
||||
write_key('N', self.N, null.N)
|
||||
write_key('s', self.s, null.s)
|
||||
write_key('v', self.v, null.v)
|
||||
write_key('S', self.S, null.S)
|
||||
write_key('O', self.O, null.O)
|
||||
write_key('x', self.x, null.x)
|
||||
write_key('y', self.y, null.y)
|
||||
write_key('w', self.w, null.w)
|
||||
write_key('h', self.h, null.h)
|
||||
write_key('X', self.X, null.X)
|
||||
write_key('Y', self.Y, null.Y)
|
||||
write_key('c', self.c, null.c)
|
||||
write_key('r', self.r, null.r)
|
||||
|
||||
write_key('i', self.i, null.i)
|
||||
write_key('I', self.I, null.I)
|
||||
write_key('p', self.p, null.p)
|
||||
|
||||
write_key('z', self.z, null.z)
|
||||
return
|
||||
}
|
||||
|
||||
func (self GraphicsCommand) String() string {
|
||||
ans := "GraphicsCommand(" + strings.Join(self.serialize_non_default_fields(), ", ")
|
||||
if self.response_message != "" {
|
||||
ans += fmt.Sprintf(", response=%#v", self.response_message)
|
||||
}
|
||||
return ans + ")"
|
||||
}
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func (self *GraphicsCommand) serialize_to(buf io.StringWriter, chunk string) (err error) {
|
||||
var ws func(string)
|
||||
if self.EncodeSerializedDataFunc == nil {
|
||||
ws = func(s string) {
|
||||
_, err = buf.WriteString(s)
|
||||
}
|
||||
} else {
|
||||
ws = func(s string) {
|
||||
_, err = buf.WriteString(self.EncodeSerializedDataFunc(s))
|
||||
}
|
||||
}
|
||||
if self.WrapPrefix != "" {
|
||||
_, err = buf.WriteString(self.WrapPrefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if self.WrapSuffix != "" {
|
||||
defer func() {
|
||||
if err == nil {
|
||||
_, err = buf.WriteString(self.WrapSuffix)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
ws("\033_G")
|
||||
if err == nil {
|
||||
items := self.serialize_non_default_fields()
|
||||
ws(strings.Join(items, ","))
|
||||
if err == nil {
|
||||
if len(chunk) > 0 {
|
||||
ws(";")
|
||||
if err == nil {
|
||||
ws(chunk)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
ws("\033\\")
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func compress_with_zlib(data []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
b.Grow(len(data) + 128)
|
||||
w := zlib.NewWriter(&b)
|
||||
_, _ = w.Write(data)
|
||||
w.Close()
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) AsAPC(payload []byte) string {
|
||||
buf := strings.Builder{}
|
||||
buf.Grow(1024)
|
||||
_ = self.WriteWithPayloadTo(&buf, payload)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) WriteWithPayloadTo(o io.StringWriter, payload []byte) (err error) {
|
||||
const compression_threshold = 2048
|
||||
if len(payload) == 0 {
|
||||
return self.serialize_to(o, "")
|
||||
}
|
||||
if len(payload) <= compression_threshold {
|
||||
return self.serialize_to(o, base64.RawStdEncoding.EncodeToString(payload))
|
||||
}
|
||||
gc := *self
|
||||
if !self.DisableCompression && self.Format() != GRT_format_png {
|
||||
compressed := compress_with_zlib(payload)
|
||||
if len(compressed) < len(payload) {
|
||||
gc.SetCompression(GRT_compression_zlib)
|
||||
payload = compressed
|
||||
}
|
||||
}
|
||||
const chunk_size = 128 * 1024
|
||||
data := base64.RawStdEncoding.EncodeToString(payload)
|
||||
for len(data) > 0 && err == nil {
|
||||
chunk := data
|
||||
if len(data) > chunk_size {
|
||||
chunk = data[:chunk_size]
|
||||
data = data[chunk_size:]
|
||||
} else {
|
||||
data = ""
|
||||
}
|
||||
if len(data) > 0 {
|
||||
gc.m = GRT_more_more
|
||||
} else {
|
||||
gc.m = GRT_more_nomore
|
||||
}
|
||||
err = gc.serialize_to(o, chunk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gc = GraphicsCommand{
|
||||
q: self.q, a: self.a, WrapPrefix: self.WrapPrefix, WrapSuffix: self.WrapSuffix,
|
||||
EncodeSerializedDataFunc: self.EncodeSerializedDataFunc}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type loop_io_writer struct {
|
||||
lp *loop.Loop
|
||||
}
|
||||
|
||||
func (self *loop_io_writer) WriteString(data string) (n int, err error) {
|
||||
self.lp.QueueWriteString(data)
|
||||
return
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) WriteWithPayloadToLoop(lp *loop.Loop, payload []byte) (err error) {
|
||||
w := loop_io_writer{lp}
|
||||
return self.WriteWithPayloadTo(&w, payload)
|
||||
}
|
||||
|
||||
func set_val[T any](loc *T, parser func(string) (T, error), value string) (err error) {
|
||||
var temp T
|
||||
temp, err = parser(value)
|
||||
if err == nil {
|
||||
*loc = temp
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func set_uval(loc *uint64, value string) (err error) {
|
||||
temp, err := strconv.ParseUint(value, 10, 64)
|
||||
if err == nil {
|
||||
*loc = temp
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func set_u32val(loc *uint32, value string) (err error) {
|
||||
temp, err := strconv.ParseUint(value, 10, 32)
|
||||
if err == nil {
|
||||
*loc = uint32(temp)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func set_i32val(loc *int32, value string) (err error) {
|
||||
temp, err := strconv.ParseInt(value, 10, 32)
|
||||
if err == nil {
|
||||
*loc = int32(temp)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetString(key byte, value string) (err error) {
|
||||
switch key {
|
||||
case 'a':
|
||||
err = set_val(&self.a, GRT_a_from_string, value)
|
||||
case 'q':
|
||||
err = set_val(&self.q, GRT_q_from_string, value)
|
||||
case 'f':
|
||||
err = set_val(&self.f, GRT_f_from_string, value)
|
||||
case 't':
|
||||
err = set_val(&self.t, GRT_t_from_string, value)
|
||||
case 'o':
|
||||
err = set_val(&self.o, GRT_o_from_string, value)
|
||||
case 'm':
|
||||
err = set_val(&self.m, GRT_m_from_string, value)
|
||||
case 'C':
|
||||
err = set_val(&self.C, GRT_C_from_string, value)
|
||||
case 'U':
|
||||
err = set_val(&self.U, GRT_U_from_string, value)
|
||||
case 'd':
|
||||
err = set_val(&self.d, GRT_d_from_string, value)
|
||||
case 'N':
|
||||
err = set_uval(&self.N, value)
|
||||
case 's':
|
||||
err = set_uval(&self.s, value)
|
||||
case 'v':
|
||||
err = set_uval(&self.v, value)
|
||||
case 'S':
|
||||
err = set_uval(&self.S, value)
|
||||
case 'O':
|
||||
err = set_uval(&self.O, value)
|
||||
case 'x':
|
||||
err = set_uval(&self.x, value)
|
||||
case 'y':
|
||||
err = set_uval(&self.y, value)
|
||||
case 'w':
|
||||
err = set_uval(&self.w, value)
|
||||
case 'h':
|
||||
err = set_uval(&self.h, value)
|
||||
case 'X':
|
||||
err = set_uval(&self.X, value)
|
||||
case 'Y':
|
||||
err = set_uval(&self.Y, value)
|
||||
case 'c':
|
||||
err = set_uval(&self.c, value)
|
||||
case 'r':
|
||||
err = set_uval(&self.r, value)
|
||||
case 'i':
|
||||
err = set_u32val(&self.i, value)
|
||||
case 'I':
|
||||
err = set_u32val(&self.I, value)
|
||||
case 'p':
|
||||
err = set_u32val(&self.p, value)
|
||||
case 'z':
|
||||
err = set_i32val(&self.z, value)
|
||||
default:
|
||||
return fmt.Errorf("Unknown key: %c", key)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func GraphicsCommandFromAPCPayload(raw []byte) *GraphicsCommand {
|
||||
const (
|
||||
expecting_key int = iota
|
||||
expecting_equals
|
||||
expecting_value
|
||||
)
|
||||
state := expecting_key
|
||||
var current_key byte
|
||||
var value_start_at int
|
||||
var payload_start_at int = -1
|
||||
var gc GraphicsCommand
|
||||
|
||||
add_key := func(pos int) {
|
||||
_ = gc.SetString(current_key, utils.UnsafeBytesToString(raw[value_start_at:pos]))
|
||||
}
|
||||
|
||||
for pos, ch := range raw {
|
||||
if ch == ';' {
|
||||
if state == expecting_value {
|
||||
add_key(pos)
|
||||
}
|
||||
state = expecting_key
|
||||
payload_start_at = pos + 1
|
||||
break
|
||||
}
|
||||
switch state {
|
||||
case expecting_key:
|
||||
current_key = ch
|
||||
state = expecting_equals
|
||||
case expecting_equals:
|
||||
if ch == '=' {
|
||||
state = expecting_value
|
||||
value_start_at = pos + 1
|
||||
} else {
|
||||
state = expecting_key
|
||||
}
|
||||
case expecting_value:
|
||||
if ch == ',' {
|
||||
add_key(pos)
|
||||
state = expecting_key
|
||||
}
|
||||
}
|
||||
}
|
||||
if state == expecting_value {
|
||||
add_key(len(raw))
|
||||
}
|
||||
if payload_start_at > -1 {
|
||||
payload := raw[payload_start_at:]
|
||||
if len(payload) > 0 {
|
||||
gc.response_message = string(payload)
|
||||
}
|
||||
}
|
||||
return &gc
|
||||
}
|
||||
|
||||
func GraphicsCommandFromAPC(raw []byte) *GraphicsCommand {
|
||||
if len(raw) < 1 || raw[0] != 'G' {
|
||||
return nil
|
||||
}
|
||||
return GraphicsCommandFromAPCPayload(raw[1:])
|
||||
}
|
||||
|
||||
// Getters and Setters {{{
|
||||
func (self *GraphicsCommand) Action() GRT_a {
|
||||
return self.a
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetAction(a GRT_a) *GraphicsCommand {
|
||||
self.a = a
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Delete() GRT_d {
|
||||
return self.d
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDelete(d GRT_d) *GraphicsCommand {
|
||||
self.d = d
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Quiet() GRT_q {
|
||||
return self.q
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetQuiet(q GRT_q) *GraphicsCommand {
|
||||
self.q = q
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) CursorMovement() GRT_C {
|
||||
return self.C
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetCursorMovement(c GRT_C) *GraphicsCommand {
|
||||
self.C = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) UnicodePlaceholder() GRT_U {
|
||||
return self.U
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetUnicodePlaceholder(U GRT_U) *GraphicsCommand {
|
||||
self.U = U
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Format() GRT_f {
|
||||
return self.f
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetFormat(f GRT_f) *GraphicsCommand {
|
||||
self.f = f
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Transmission() GRT_t {
|
||||
return self.t
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetTransmission(t GRT_t) *GraphicsCommand {
|
||||
self.t = t
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Compression() GRT_o {
|
||||
return self.o
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetCompression(o GRT_o) *GraphicsCommand {
|
||||
self.o = o
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Width() uint64 {
|
||||
return self.w
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetWidth(w uint64) *GraphicsCommand {
|
||||
self.w = w
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Height() uint64 {
|
||||
return self.h
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetHeight(h uint64) *GraphicsCommand {
|
||||
self.h = h
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) DataWidth() uint64 {
|
||||
return self.s
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDataWidth(w uint64) *GraphicsCommand {
|
||||
self.s = w
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) DataHeight() uint64 {
|
||||
return self.v
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDataHeight(h uint64) *GraphicsCommand {
|
||||
self.v = h
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) NumberOfLoops() uint64 {
|
||||
return self.v
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetNumberOfLoops(n uint64) *GraphicsCommand {
|
||||
self.v = n
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) DataSize() uint64 {
|
||||
return self.S
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDataSize(s uint64) *GraphicsCommand {
|
||||
self.S = s
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) DataOffset() uint64 {
|
||||
return self.O
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetDataOffset(o uint64) *GraphicsCommand {
|
||||
self.O = o
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) LeftEdge() uint64 {
|
||||
return self.x
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetLeftEdge(x uint64) *GraphicsCommand {
|
||||
self.x = x
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) TopEdge() uint64 {
|
||||
return self.y
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetTopEdge(y uint64) *GraphicsCommand {
|
||||
self.y = y
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) XOffset() uint64 {
|
||||
return self.X
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetXOffset(x uint64) *GraphicsCommand {
|
||||
self.X = x
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) BlendMode() CompositionMode {
|
||||
switch self.X {
|
||||
case 1:
|
||||
return Overwrite
|
||||
default:
|
||||
return AlphaBlend
|
||||
}
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetBlendMode(x CompositionMode) *GraphicsCommand {
|
||||
self.X = uint64(x)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) CompositionMode() CompositionMode {
|
||||
switch self.C {
|
||||
case 1:
|
||||
return Overwrite
|
||||
default:
|
||||
return AlphaBlend
|
||||
}
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetCompositionMode(x CompositionMode) *GraphicsCommand {
|
||||
switch x {
|
||||
case Overwrite:
|
||||
self.C = 1
|
||||
case AlphaBlend:
|
||||
self.C = 0
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) YOffset() uint64 {
|
||||
return self.Y
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetYOffset(y uint64) *GraphicsCommand {
|
||||
self.Y = y
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SourceTopEdge() uint64 {
|
||||
return self.Y
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetSourceTopEdge(y uint64) *GraphicsCommand {
|
||||
self.Y = y
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) BackgroundColor() uint32 {
|
||||
return uint32(self.Y)
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetBackgroundColor(y uint32) *GraphicsCommand {
|
||||
self.Y = uint64(y)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Rows() uint64 {
|
||||
return self.r
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetRows(r uint64) *GraphicsCommand {
|
||||
self.r = r
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Columns() uint64 {
|
||||
return self.c
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetColumns(c uint64) *GraphicsCommand {
|
||||
self.c = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) TargetFrame() uint64 {
|
||||
return self.r
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetTargetFrame(r uint64) *GraphicsCommand {
|
||||
self.r = r
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) BaseFrame() uint64 {
|
||||
return self.c
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetBaseFrame(c uint64) *GraphicsCommand {
|
||||
self.c = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) OverlaidFrame() uint64 {
|
||||
return self.c
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetOverlaidFrame(c uint64) *GraphicsCommand {
|
||||
self.c = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) FrameToMakeCurrent() uint64 {
|
||||
return self.c
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetFrameToMakeCurrent(c uint64) *GraphicsCommand {
|
||||
self.c = c
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) UsageHints() uint64 {
|
||||
return self.N
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetUsageHints(hints uint64) *GraphicsCommand {
|
||||
self.N = hints
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) ImageId() uint32 {
|
||||
return self.i
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetImageId(i uint32) *GraphicsCommand {
|
||||
self.i = i
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) ImageNumber() uint32 {
|
||||
return self.I
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetImageNumber(n uint32) *GraphicsCommand {
|
||||
self.I = n
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) PlacementId() uint32 {
|
||||
return self.p
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetPlacementId(p uint32) *GraphicsCommand {
|
||||
self.p = p
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) ZIndex() int32 {
|
||||
return self.z
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetZIndex(z int32) *GraphicsCommand {
|
||||
self.z = z
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) Gap() int32 {
|
||||
return self.z
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetGap(z int32) *GraphicsCommand {
|
||||
self.z = z
|
||||
return self
|
||||
}
|
||||
|
||||
type AnimationControl uint
|
||||
|
||||
const (
|
||||
NoAnimationAction AnimationControl = iota
|
||||
StopAnimation
|
||||
RunAnimationButWaitForNewFrames
|
||||
RunAnimation
|
||||
)
|
||||
|
||||
func (self *GraphicsCommand) AnimationControl() AnimationControl {
|
||||
switch AnimationControl(self.s) {
|
||||
default:
|
||||
return NoAnimationAction
|
||||
case StopAnimation:
|
||||
return StopAnimation
|
||||
case RunAnimationButWaitForNewFrames:
|
||||
return RunAnimationButWaitForNewFrames
|
||||
case RunAnimation:
|
||||
return RunAnimation
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) SetAnimationControl(z uint) *GraphicsCommand {
|
||||
self.s = uint64(z)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *GraphicsCommand) ResponseMessage() string {
|
||||
return self.response_message
|
||||
}
|
||||
|
||||
// }}}
|
||||
@@ -0,0 +1,115 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package graphics
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"golang.org/x/exp/rand"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func from_full_apc_escape_code(raw string) *GraphicsCommand {
|
||||
return GraphicsCommandFromAPC([]byte(raw[2 : len(raw)-2]))
|
||||
}
|
||||
|
||||
func TestGraphicsCommandSerialization(t *testing.T) {
|
||||
gc := &GraphicsCommand{}
|
||||
|
||||
test_serialize := func(payload string, vals ...string) {
|
||||
expected := "\033_G" + strings.Join(vals, ",")
|
||||
if payload != "" {
|
||||
expected += ";" + base64.RawStdEncoding.EncodeToString([]byte(payload))
|
||||
}
|
||||
expected += "\033\\"
|
||||
if diff := cmp.Diff(expected, gc.AsAPC([]byte(payload))); diff != "" {
|
||||
t.Fatalf("Failed to write vals: %#v with payload: %#v\n%s", vals, payload, diff)
|
||||
}
|
||||
}
|
||||
|
||||
test_chunked_payload := func(payload []byte) {
|
||||
c := &GraphicsCommand{}
|
||||
data := c.AsAPC([]byte(payload))
|
||||
encoded := strings.Builder{}
|
||||
compressed := false
|
||||
is_first := true
|
||||
for {
|
||||
idx := strings.Index(data, "\033_")
|
||||
if idx < 0 {
|
||||
break
|
||||
}
|
||||
l := strings.Index(data, "\033\\")
|
||||
apc := data[idx+2 : l]
|
||||
data = data[l+2:]
|
||||
g := GraphicsCommandFromAPC([]byte(apc))
|
||||
if is_first {
|
||||
compressed = g.Compression() != 0
|
||||
is_first = false
|
||||
}
|
||||
encoded.WriteString(g.ResponseMessage())
|
||||
if g.m == GRT_more_nomore {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(data) > 0 {
|
||||
t.Fatalf("Unparsed remnant: %#v", string(data))
|
||||
}
|
||||
decoded, err := base64.RawStdEncoding.DecodeString(encoded.String())
|
||||
if err != nil {
|
||||
t.Fatalf("Encoded data not valid base-64 with error: %v", err)
|
||||
}
|
||||
if compressed {
|
||||
b := bytes.Buffer{}
|
||||
b.Write(decoded)
|
||||
r, _ := zlib.NewReader(&b)
|
||||
o := bytes.Buffer{}
|
||||
if _, err = io.Copy(&o, r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Close()
|
||||
decoded = o.Bytes()
|
||||
}
|
||||
if diff := cmp.Diff(payload, decoded); diff != "" {
|
||||
t.Fatalf("Decoded payload does not match original\nlen decoded=%d len payload=%d", len(decoded), len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
test_serialize("")
|
||||
gc.SetTransmission(GRT_transmission_sharedmem).SetAction(GRT_action_query).SetZIndex(-3).SetWidth(33).SetImageId(11)
|
||||
test_serialize("abcd", "a=q", "t=s", "w=33", "i=11", "z=-3")
|
||||
q := from_full_apc_escape_code(gc.AsAPC([]byte("abcd")))
|
||||
if diff := cmp.Diff(gc.AsAPC(nil), q.AsAPC(nil)); diff != "" {
|
||||
t.Fatalf("Parsing failed:\n%s", diff)
|
||||
}
|
||||
if diff := cmp.Diff(q.response_message, base64.RawStdEncoding.EncodeToString([]byte("abcd"))); diff != "" {
|
||||
t.Fatalf("Failed to parse payload:\n%s", diff)
|
||||
}
|
||||
|
||||
for _, x := range []struct {
|
||||
f GRT_f
|
||||
s string
|
||||
}{{GRT_format_indexed, "f=8"}, {GRT_format_indexed_alpha, "f=16"}} {
|
||||
gc = &GraphicsCommand{}
|
||||
gc.SetFormat(x.f).SetDataWidth(2).SetDataHeight(1)
|
||||
test_serialize("ab", x.s, "s=2", "v=1")
|
||||
if q = from_full_apc_escape_code(gc.AsAPC(nil)); q.Format() != x.f {
|
||||
t.Fatalf("Failed to parse format %s, got: %s", x.s, q.Format())
|
||||
}
|
||||
}
|
||||
|
||||
test_chunked_payload([]byte("abcd"))
|
||||
data := make([]byte, 8111)
|
||||
_, _ = rand.Read(data)
|
||||
test_chunked_payload(data)
|
||||
test_chunked_payload([]byte(strings.Repeat("a", 8007)))
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
// Tells kitty that a program it cannot see exit has exited, so that it can drop
|
||||
// the program status (OSC 7501) records that do not outlive the program
|
||||
const PROGRAM_STATUS_PROCESS_EXITED = "\x1b]7501;process-exited\x1b\\"
|
||||
|
||||
func HoldTillEnter(start_with_newline bool) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.NoMouseTracking)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
if start_with_newline {
|
||||
lp.QueueWriteString("\r\n")
|
||||
}
|
||||
lp.QueueWriteString("\x1b[1;32mPress Enter or Esc to exit\x1b[m")
|
||||
return "", nil
|
||||
}
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
return ""
|
||||
}
|
||||
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
if event.MatchesPressOrRepeat("enter") || event.MatchesPressOrRepeat("kp_enter") || event.MatchesPressOrRepeat("esc") || event.MatchesPressOrRepeat("ctrl+c") || event.MatchesPressOrRepeat("ctrl+d") {
|
||||
event.Handled = true
|
||||
lp.Quit(0)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
lp.Run()
|
||||
}
|
||||
|
||||
func ExecAndHoldTillEnter(cmdline []string) (int, error) {
|
||||
if len(cmdline) == 0 {
|
||||
HoldTillEnter(false)
|
||||
return 0, nil
|
||||
}
|
||||
var cmd *exec.Cmd
|
||||
if len(cmdline) == 1 {
|
||||
cmd = exec.Command(cmdline[0])
|
||||
} else {
|
||||
cmd = exec.Command(cmdline[0], cmdline[1:]...)
|
||||
}
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
var ee *exec.ExitError
|
||||
err := cmd.Run()
|
||||
_, _ = os.Stdout.WriteString(PROGRAM_STATUS_PROCESS_EXITED)
|
||||
is_exit_error := err != nil && errors.As(err, &ee)
|
||||
if err != nil && !is_exit_error {
|
||||
return 1, err
|
||||
}
|
||||
HoldTillEnter(true)
|
||||
if err == nil {
|
||||
return 0, nil
|
||||
}
|
||||
if is_exit_error {
|
||||
return ee.ExitCode(), nil
|
||||
}
|
||||
return 1, err
|
||||
}
|
||||
@@ -0,0 +1,758 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/go-parallel"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/machine_id"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/style"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
type ScreenSize struct {
|
||||
WidthCells, HeightCells, WidthPx, HeightPx, CellWidth, CellHeight uint
|
||||
updated bool
|
||||
}
|
||||
|
||||
type IdType uint64
|
||||
type TimerCallback func(timer_id IdType) error
|
||||
type EscapeCodeType int
|
||||
|
||||
const (
|
||||
CSI EscapeCodeType = iota
|
||||
DCS
|
||||
OSC
|
||||
APC
|
||||
SOS
|
||||
PM
|
||||
)
|
||||
|
||||
type DndCommand struct {
|
||||
Type byte
|
||||
Has_more bool
|
||||
Operation int
|
||||
X, Y, Xp, Yp int
|
||||
Payload []byte
|
||||
}
|
||||
|
||||
type Loop struct {
|
||||
controlling_term *tty.Term
|
||||
terminal_options TerminalStateOptions
|
||||
screen_size ScreenSize
|
||||
seen_inband_resize bool
|
||||
escape_code_parser wcswidth.EscapeCodeParser
|
||||
keep_going bool
|
||||
death_signal unix.Signal
|
||||
exit_code int
|
||||
timers, timers_temp []*timer
|
||||
timer_id_counter, write_msg_id_counter IdType
|
||||
wakeup_channel chan byte
|
||||
panic_channel chan error
|
||||
pending_writes []write_msg
|
||||
tty_write_channel chan write_msg
|
||||
pending_mouse_events *utils.RingBuffer[MouseEvent]
|
||||
on_SIGTSTP func() error
|
||||
style_cache map[string]func(...any) string
|
||||
style_ctx style.Context
|
||||
atomic_update_active bool
|
||||
pointer_shapes []PointerShape
|
||||
dnd_chunking struct {
|
||||
active bool
|
||||
metadata DndCommand
|
||||
}
|
||||
|
||||
// Queried capabilities from terminal
|
||||
TerminalCapabilities TerminalCapabilities
|
||||
|
||||
// Suspend the loop restoring terminal state, and run the provided function. When it returns terminal state is
|
||||
// put back to what it was before suspending unless the function returns an error or an error occurs saving/restoring state.
|
||||
SuspendAndRun func(func() error) error
|
||||
|
||||
// Callbacks
|
||||
|
||||
// Called when the terminal has been fully setup. Any string returned is sent to
|
||||
// the terminal on shutdown
|
||||
OnInitialize func() (string, error)
|
||||
|
||||
// Called just before the loop shuts down. Any returned string is written to the terminal before
|
||||
// shutdown
|
||||
OnFinalize func() string
|
||||
|
||||
// Called when a key event happens
|
||||
OnKeyEvent func(event *KeyEvent) error
|
||||
|
||||
// Called when a mouse event happens
|
||||
OnMouseEvent func(event *MouseEvent) error
|
||||
|
||||
// Called when text is received either from a key event or directly from the terminal
|
||||
// Called with an empty string when bracketed paste ends
|
||||
OnText func(text string, from_key_event bool, in_bracketed_paste bool) error
|
||||
|
||||
// Called when the terminal is resized
|
||||
OnResize func(old_size ScreenSize, new_size ScreenSize) error
|
||||
|
||||
// Called when writing is done
|
||||
OnWriteComplete func(msg_id IdType, has_pending_writes bool) error
|
||||
|
||||
// Called when a response to an rc command is received
|
||||
OnRCResponse func(data []byte) error
|
||||
|
||||
// Called when a response to a query command is received
|
||||
OnQueryResponse func(key, val string, valid bool) error
|
||||
|
||||
// Called when a drag and drop protocol escape code is received
|
||||
OnDnDData func(cmd DndCommand) error
|
||||
|
||||
// Called when any input from tty is received
|
||||
OnReceivedData func(data []byte) error
|
||||
|
||||
// Called when an escape code is received that is not handled by any other handler
|
||||
OnEscapeCode func(EscapeCodeType, []byte) error
|
||||
|
||||
// Called when resuming from a SIGTSTP or Ctrl-z
|
||||
OnResumeFromStop func() error
|
||||
|
||||
// Called when main loop is woken up
|
||||
OnWakeup func() error
|
||||
|
||||
// Called on SIGINT return true if you wish to handle it yourself
|
||||
OnSIGINT func() (bool, error)
|
||||
|
||||
// Called on SIGTERM return true if you wish to handle it yourself
|
||||
OnSIGTERM func() (bool, error)
|
||||
|
||||
// Called when capabilities response is received
|
||||
OnCapabilitiesReceived func(TerminalCapabilities) error
|
||||
|
||||
// Called when the terminal's color scheme changes
|
||||
OnColorSchemeChange func(ColorPreference) error
|
||||
|
||||
// Called on focus in/out events
|
||||
OnFocusChange func(bool) error
|
||||
}
|
||||
|
||||
func New(options ...func(self *Loop)) (*Loop, error) {
|
||||
l := new_loop()
|
||||
for _, f := range options {
|
||||
f(l)
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// Create a loop that does not change terminal state such as keyboard mode,
|
||||
// resize/focus notifications, mouse tracking, alternate screen etc. Useful
|
||||
// for special purpose kittens such as icat/clipboard/@ etc.
|
||||
func NewForSimpleInteraction() (*Loop, error) {
|
||||
lp, err := New(
|
||||
NoAlternateScreen, NoRestoreColors, NoMouseTracking, NoInBandResizeNotifications,
|
||||
NoFocusTracking, NoKeyboardStateChange, NoRoundtripToTerminalOnExit,
|
||||
)
|
||||
if err == nil {
|
||||
lp.terminal_options.color_scheme_change_notification = false
|
||||
}
|
||||
return lp, err
|
||||
}
|
||||
|
||||
func (self *Loop) AddTimer(interval time.Duration, repeats bool, callback TimerCallback) (IdType, error) {
|
||||
return self.add_timer(interval, repeats, callback)
|
||||
}
|
||||
|
||||
func (self *Loop) CallSoon(callback TimerCallback) (IdType, error) {
|
||||
return self.add_timer(0, false, callback)
|
||||
}
|
||||
|
||||
func (self *Loop) RemoveTimer(id IdType) bool {
|
||||
return self.remove_timer(id)
|
||||
}
|
||||
|
||||
func (self *Loop) NoAlternateScreen() *Loop {
|
||||
self.terminal_options.Alternate_screen = false
|
||||
return self
|
||||
}
|
||||
|
||||
func NoAlternateScreen(self *Loop) {
|
||||
self.terminal_options.Alternate_screen = false
|
||||
}
|
||||
|
||||
func (self *Loop) NoRoundtripToTerminalOnExit() *Loop {
|
||||
self.terminal_options.roundtrip_on_exit = false
|
||||
return self
|
||||
}
|
||||
|
||||
func NoRoundtripToTerminalOnExit(self *Loop) {
|
||||
self.terminal_options.roundtrip_on_exit = false
|
||||
}
|
||||
|
||||
func (self *Loop) OnlyDisambiguateKeys() *Loop {
|
||||
self.terminal_options.kitty_keyboard_mode = DISAMBIGUATE_KEYS
|
||||
return self
|
||||
}
|
||||
|
||||
func OnlyDisambiguateKeys(self *Loop) {
|
||||
self.terminal_options.kitty_keyboard_mode = DISAMBIGUATE_KEYS
|
||||
}
|
||||
|
||||
func (self *Loop) NoKeyboardStateChange() *Loop {
|
||||
self.terminal_options.kitty_keyboard_mode = NO_KEYBOARD_STATE_CHANGE
|
||||
return self
|
||||
}
|
||||
|
||||
func NoKeyboardStateChange(self *Loop) {
|
||||
self.terminal_options.kitty_keyboard_mode = NO_KEYBOARD_STATE_CHANGE
|
||||
}
|
||||
|
||||
func (self *Loop) FullKeyboardProtocol() *Loop {
|
||||
self.terminal_options.kitty_keyboard_mode = FULL_KEYBOARD_PROTOCOL
|
||||
return self
|
||||
}
|
||||
|
||||
func FullKeyboardProtocol(self *Loop) {
|
||||
self.terminal_options.kitty_keyboard_mode = FULL_KEYBOARD_PROTOCOL
|
||||
}
|
||||
|
||||
func (self *Loop) MouseTrackingMode(mt MouseTracking) *Loop {
|
||||
self.terminal_options.mouse_tracking = mt
|
||||
return self
|
||||
}
|
||||
|
||||
func MouseTrackingMode(self *Loop, mt MouseTracking) {
|
||||
self.terminal_options.mouse_tracking = mt
|
||||
}
|
||||
|
||||
func NoMouseTracking(self *Loop) {
|
||||
self.terminal_options.mouse_tracking = NO_MOUSE_TRACKING
|
||||
}
|
||||
|
||||
func (self *Loop) NoMouseTracking() *Loop {
|
||||
self.terminal_options.mouse_tracking = NO_MOUSE_TRACKING
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Loop) NoRestoreColors() *Loop {
|
||||
self.terminal_options.restore_colors = false
|
||||
return self
|
||||
}
|
||||
|
||||
func NoRestoreColors(self *Loop) {
|
||||
self.terminal_options.restore_colors = false
|
||||
}
|
||||
|
||||
func (self *Loop) NoFocusTracking() *Loop {
|
||||
self.terminal_options.focus_tracking = false
|
||||
return self
|
||||
}
|
||||
|
||||
func NoFocusTracking(self *Loop) {
|
||||
self.terminal_options.focus_tracking = false
|
||||
}
|
||||
|
||||
func (self *Loop) RequestCurrentColorScheme() {
|
||||
self.QueueWriteString("\x1b[?996n")
|
||||
}
|
||||
|
||||
func (self *Loop) ColorSchemeChangeNotifications() *Loop {
|
||||
self.terminal_options.color_scheme_change_notification = true
|
||||
return self
|
||||
}
|
||||
|
||||
func ColorSchemeChangeNotifications(self *Loop) {
|
||||
self.terminal_options.color_scheme_change_notification = true
|
||||
}
|
||||
|
||||
func NoInBandResizeNotifications(self *Loop) {
|
||||
self.terminal_options.in_band_resize_notification = false
|
||||
}
|
||||
|
||||
func (self *Loop) DeathSignalName() string {
|
||||
if self.death_signal != SIGNULL {
|
||||
return self.death_signal.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (self *Loop) ScreenSize() (ScreenSize, error) {
|
||||
if self.screen_size.updated {
|
||||
return self.screen_size, nil
|
||||
}
|
||||
err := self.update_screen_size()
|
||||
return self.screen_size, err
|
||||
}
|
||||
|
||||
func (self *Loop) KillIfSignalled() {
|
||||
if self.death_signal != SIGNULL {
|
||||
kill_self(self.death_signal)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) Println(args ...any) {
|
||||
self.QueueWriteString(fmt.Sprintln(args...))
|
||||
self.QueueWriteString("\r")
|
||||
}
|
||||
|
||||
func (self *Loop) style_region(style string, start_x, start_y, end_x, end_y int) string {
|
||||
sgr := self.SprintStyled(style, "|")
|
||||
if len(sgr) > 2 {
|
||||
sgr = sgr[2:strings.IndexByte(sgr, 'm')]
|
||||
return fmt.Sprintf("\x1b[%d;%d;%d;%d;%s$r", start_y+1, start_x+1, end_y+1, end_x+1, sgr)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Apply the specified style to the specified region of the screen (0-based
|
||||
// indexing). The region is all cells from the start cell to the end cell. See
|
||||
// StyleRectangle to apply style to a rectangular area.
|
||||
func (self *Loop) StyleRegion(style string, start_x, start_y, end_x, end_y int) IdType {
|
||||
return self.QueueWriteString(self.style_region(style, start_x, start_y, end_x, end_y))
|
||||
}
|
||||
|
||||
// Apply the specified style to the specified rectangle of the screen (0-based indexing).
|
||||
func (self *Loop) StyleRectangle(style string, start_x, start_y, end_x, end_y int) IdType {
|
||||
return self.QueueWriteString("\x1b[2*x" + self.style_region(style, start_x, start_y, end_x, end_y) + "\x1b[*x")
|
||||
}
|
||||
|
||||
func (self *Loop) SprintStyled(style string, args ...any) string {
|
||||
f := self.style_cache[style]
|
||||
if f == nil {
|
||||
f = self.style_ctx.SprintFunc(style)
|
||||
self.style_cache[style] = f
|
||||
}
|
||||
return f(args...)
|
||||
}
|
||||
|
||||
func (self *Loop) PrintStyled(style string, args ...any) {
|
||||
self.QueueWriteString(self.SprintStyled(style, args...))
|
||||
}
|
||||
|
||||
func (self *Loop) SaveCursorPosition() {
|
||||
self.QueueWriteString("\x1b7")
|
||||
}
|
||||
|
||||
func (self *Loop) RestoreCursorPosition() {
|
||||
self.QueueWriteString("\x1b8")
|
||||
}
|
||||
|
||||
func (self *Loop) Printf(format string, args ...any) {
|
||||
format = strings.ReplaceAll(format, "\n", "\r\n")
|
||||
self.QueueWriteString(fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
func (self *Loop) DebugPrintln(args ...any) {
|
||||
if self.controlling_term != nil {
|
||||
const limit = 2048
|
||||
msg := fmt.Sprintln(args...)
|
||||
for i := 0; i < len(msg); i += limit {
|
||||
end := min(i+limit, len(msg))
|
||||
self.QueueWriteString("\x1bP@kitty-print|")
|
||||
self.QueueWriteString(base64.StdEncoding.EncodeToString([]byte(msg[i:end])))
|
||||
self.QueueWriteString("\x1b\\")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) Run() (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err = parallel.Format_stacktrace_on_panic(r, 1)
|
||||
is_terminal := tty.IsTerminal(os.Stderr.Fd())
|
||||
if is_terminal {
|
||||
os.Stderr.WriteString("\x1b]\x1b\\\x1bc\x1b[H\x1b[2J") // reset terminal
|
||||
}
|
||||
os.Stderr.WriteString(err.Error())
|
||||
os.Stderr.WriteString("\n")
|
||||
if is_terminal {
|
||||
if term, err := tty.OpenControllingTerm(tty.SetRaw); err != nil {
|
||||
defer term.RestoreAndClose()
|
||||
term.DebugPrintln(err.Error())
|
||||
fmt.Println("Press any key to exit.\r")
|
||||
buf := make([]byte, 16)
|
||||
_, _ = term.Read(buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return self.run()
|
||||
}
|
||||
|
||||
func (self *Loop) WakeupMainThread() bool {
|
||||
select {
|
||||
case self.wakeup_channel <- 1:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) QueueWriteString(data string) IdType {
|
||||
self.write_msg_id_counter++
|
||||
msg := write_msg{str: data, bytes: nil, id: self.write_msg_id_counter}
|
||||
self.add_write_to_pending_queue(msg)
|
||||
return msg.id
|
||||
}
|
||||
|
||||
// This is dangerous as it is upto the calling code
|
||||
// to ensure the data in the underlying array does not change
|
||||
func (self *Loop) UnsafeQueueWriteBytes(data []byte) IdType {
|
||||
self.write_msg_id_counter++
|
||||
msg := write_msg{bytes: data, id: self.write_msg_id_counter}
|
||||
self.add_write_to_pending_queue(msg)
|
||||
return msg.id
|
||||
}
|
||||
|
||||
func (self *Loop) QueueWriteBytesCopy(data []byte) IdType {
|
||||
d := make([]byte, len(data))
|
||||
copy(d, data)
|
||||
return self.UnsafeQueueWriteBytes(d)
|
||||
}
|
||||
|
||||
func (self *Loop) ExitCode() int {
|
||||
return self.exit_code
|
||||
}
|
||||
|
||||
func (self *Loop) Beep() {
|
||||
self.QueueWriteString("\a")
|
||||
}
|
||||
|
||||
func (self *Loop) StartAtomicUpdate() {
|
||||
if self.atomic_update_active {
|
||||
self.EndAtomicUpdate()
|
||||
}
|
||||
self.QueueWriteString(PENDING_UPDATE.EscapeCodeToSet())
|
||||
self.atomic_update_active = true
|
||||
}
|
||||
|
||||
func (self *Loop) IsAtomicUpdateActive() bool { return self.atomic_update_active }
|
||||
|
||||
func (self *Loop) EndAtomicUpdate() {
|
||||
if self.atomic_update_active {
|
||||
self.QueueWriteString(PENDING_UPDATE.EscapeCodeToReset())
|
||||
self.atomic_update_active = false
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) SetCursorShape(shape CursorShapes, blink bool) {
|
||||
self.QueueWriteString(CursorShape(shape, blink))
|
||||
}
|
||||
|
||||
func (self *Loop) SetCursorVisible(visible bool) {
|
||||
if visible {
|
||||
self.QueueWriteString(DECTCEM.EscapeCodeToSet())
|
||||
} else {
|
||||
self.QueueWriteString(DECTCEM.EscapeCodeToReset())
|
||||
}
|
||||
}
|
||||
|
||||
const MoveCursorToTemplate = "\x1b[%d;%dH"
|
||||
|
||||
func (self *Loop) MoveCursorTo(x, y int) { // 1, 1 is top left
|
||||
if x > 0 && y > 0 {
|
||||
self.QueueWriteString(fmt.Sprintf(MoveCursorToTemplate, y, x))
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) MoveCursorHorizontally(amt int) {
|
||||
if amt != 0 {
|
||||
suffix := "C"
|
||||
if amt < 0 {
|
||||
suffix = "D"
|
||||
amt *= -1
|
||||
}
|
||||
self.QueueWriteString(fmt.Sprintf("\x1b[%d%s", amt, suffix))
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) MoveCursorVertically(amt int) {
|
||||
if amt != 0 {
|
||||
suffix := "B"
|
||||
if amt < 0 {
|
||||
suffix = "A"
|
||||
amt *= -1
|
||||
}
|
||||
self.QueueWriteString(fmt.Sprintf("\x1b[%d%s", amt, suffix))
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) ClearToEndOfScreen() {
|
||||
self.QueueWriteString("\x1b[J")
|
||||
}
|
||||
|
||||
func (self *Loop) ClearToEndOfLine() {
|
||||
self.QueueWriteString("\x1b[K")
|
||||
}
|
||||
|
||||
func (self *Loop) StartBracketedPaste() {
|
||||
self.QueueWriteString(BRACKETED_PASTE.EscapeCodeToSet())
|
||||
}
|
||||
|
||||
func (self *Loop) EndBracketedPaste() {
|
||||
self.QueueWriteString(BRACKETED_PASTE.EscapeCodeToReset())
|
||||
}
|
||||
|
||||
func (self *Loop) AllowLineWrapping(allow bool) {
|
||||
if allow {
|
||||
self.QueueWriteString(DECAWM.EscapeCodeToSet())
|
||||
} else {
|
||||
self.QueueWriteString(DECAWM.EscapeCodeToReset())
|
||||
}
|
||||
}
|
||||
|
||||
func EscapeCodeToSetWindowTitle(title string) string {
|
||||
title = wcswidth.StripEscapeCodes(title)
|
||||
return "\033]2;" + title + "\033\\"
|
||||
}
|
||||
|
||||
func (self *Loop) SetWindowTitle(title string) {
|
||||
self.QueueWriteString(EscapeCodeToSetWindowTitle(title))
|
||||
}
|
||||
|
||||
func (self *Loop) ClearScreen() {
|
||||
self.QueueWriteString("\x1b[H\x1b[2J")
|
||||
}
|
||||
|
||||
func (self *Loop) ClearScreenButNotGraphics() {
|
||||
self.QueueWriteString("\x1b[H\x1b[J")
|
||||
}
|
||||
|
||||
func (self *Loop) SendOverlayReady() {
|
||||
self.QueueWriteString("\x1bP@kitty-overlay-ready|\x1b\\")
|
||||
}
|
||||
|
||||
func (self *Loop) Quit(exit_code int) {
|
||||
self.exit_code = exit_code
|
||||
self.keep_going = false
|
||||
}
|
||||
|
||||
type DefaultColor int
|
||||
|
||||
const (
|
||||
BACKGROUND DefaultColor = 11
|
||||
FOREGROUND DefaultColor = 10
|
||||
CURSOR DefaultColor = 12
|
||||
SELECTION_BG DefaultColor = 17
|
||||
SELECTION_FG DefaultColor = 19
|
||||
)
|
||||
|
||||
func (self *Loop) SetDefaultColor(which DefaultColor, val style.RGBA) {
|
||||
self.QueueWriteString(fmt.Sprintf("\033]%d;%s\033\\", int(which), val.AsRGBSharp()))
|
||||
}
|
||||
|
||||
func (self *Loop) copy_text_to(text, dest string) {
|
||||
self.QueueWriteString("\x1b]52;" + dest + ";")
|
||||
self.QueueWriteString(base64.StdEncoding.EncodeToString(utils.UnsafeStringToBytes(text)))
|
||||
self.QueueWriteString("\x1b\\")
|
||||
}
|
||||
|
||||
func (self *Loop) CopyTextToPrimarySelection(text string) {
|
||||
self.copy_text_to(text, "p")
|
||||
}
|
||||
|
||||
func (self *Loop) CopyTextToClipboard(text string) {
|
||||
self.copy_text_to(text, "c")
|
||||
}
|
||||
|
||||
func (self *Loop) QueryTerminal(fields ...string) IdType {
|
||||
if len(fields) == 0 {
|
||||
return 0
|
||||
}
|
||||
q := make([]string, len(fields))
|
||||
for i, x := range fields {
|
||||
q[i] = hex.EncodeToString(utils.UnsafeStringToBytes("kitty-query-" + x))
|
||||
}
|
||||
return self.QueueWriteString(fmt.Sprintf("\x1bP+q%s\a", strings.Join(q, ";")))
|
||||
}
|
||||
|
||||
func (self *Loop) PushPointerShape(s PointerShape) {
|
||||
self.pointer_shapes = append(self.pointer_shapes, s)
|
||||
self.QueueWriteString("\x1b]22;" + s.String() + "\x1b\\")
|
||||
}
|
||||
|
||||
func (self *Loop) PopPointerShape() {
|
||||
if len(self.pointer_shapes) > 0 {
|
||||
self.pointer_shapes = self.pointer_shapes[:len(self.pointer_shapes)-1]
|
||||
self.QueueWriteString("\x1b]22;<\x1b\\")
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all pointer shapes from the shape stack resetting to default pointer
|
||||
// shape. This is called automatically on loop termination.
|
||||
func (self *Loop) ClearPointerShapes() (ans []PointerShape) {
|
||||
ans = self.pointer_shapes
|
||||
for i := len(self.pointer_shapes) - 1; i >= 0; i-- {
|
||||
self.QueueWriteString("\x1b]22;<\x1b\\")
|
||||
}
|
||||
self.pointer_shapes = nil
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Loop) CurrentPointerShape() (ans PointerShape, has_shape bool) {
|
||||
if len(self.pointer_shapes) > 0 {
|
||||
has_shape = true
|
||||
ans = self.pointer_shapes[len(self.pointer_shapes)-1]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Query the terminal for various capabilities, the OnCapabilitiesReceived
|
||||
// callback will be called once the query response is received. This
|
||||
// function should be called as early as possible ideally in OnInitialize.
|
||||
func (self *Loop) QueryCapabilities() {
|
||||
self.QueueWriteString("\x1b[?u\x1b[?996n\x1b[c")
|
||||
}
|
||||
|
||||
type Alignment int
|
||||
|
||||
const (
|
||||
ALIGN_START Alignment = iota
|
||||
ALIGN_CENTER
|
||||
ALIGN_END
|
||||
)
|
||||
|
||||
type SizedText struct {
|
||||
Scale, Subscale_numerator, Subscale_denominator int
|
||||
Horizontal_alignment, Vertical_alignment Alignment
|
||||
Width int
|
||||
}
|
||||
|
||||
func (self *Loop) RecoverFromPanicInGoRoutine() {
|
||||
if r := recover(); r != nil {
|
||||
err := parallel.Format_stacktrace_on_panic(r, 1)
|
||||
// print to kitty stdout as multiple go routines might panic but only
|
||||
// one panic is reported by the main loop panic_channel
|
||||
if f := tty.KittyStdout(); f != nil {
|
||||
fmt.Fprintln(f, err)
|
||||
}
|
||||
self.panic_channel <- err
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) DrawSizedText(text string, spec SizedText) {
|
||||
b := strings.Builder{}
|
||||
b.Grow(len(text) + 24)
|
||||
b.WriteString("\x1b]66;")
|
||||
sep := ""
|
||||
if spec.Scale > 1 {
|
||||
fmt.Fprintf(&b, "%ss=%d", sep, min(spec.Scale, 7))
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Width > 0 {
|
||||
fmt.Fprintf(&b, "%sw=%d", sep, min(spec.Width, 7))
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Subscale_numerator > 0 {
|
||||
fmt.Fprintf(&b, "%sn=%d", sep, min(spec.Subscale_numerator, 15))
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Subscale_denominator > spec.Subscale_numerator {
|
||||
fmt.Fprintf(&b, "%sd=%d", sep, min(spec.Subscale_denominator, 15))
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Horizontal_alignment > ALIGN_START {
|
||||
fmt.Fprintf(&b, "%sh=%d", sep, spec.Horizontal_alignment)
|
||||
sep = ":"
|
||||
}
|
||||
if spec.Vertical_alignment > ALIGN_START {
|
||||
fmt.Fprintf(&b, "%sv=%d", sep, spec.Vertical_alignment)
|
||||
sep = ":"
|
||||
}
|
||||
b.WriteString(";")
|
||||
b.WriteString(text)
|
||||
b.WriteString("\a")
|
||||
self.QueueWriteString(b.String())
|
||||
}
|
||||
|
||||
func (self *Loop) QueueDnDData(cmd DndCommand) IdType {
|
||||
b := strings.Builder{}
|
||||
b.Grow(64)
|
||||
as_base64 := cmd.Type == 'r' || cmd.Type == 'p'
|
||||
fmt.Fprintf(&b, "\x1b]%d;t=%c", kitty.DndCode, cmd.Type)
|
||||
add := func(key byte, val int) {
|
||||
if val != 0 {
|
||||
fmt.Fprintf(&b, ":%c=%d", key, val)
|
||||
}
|
||||
}
|
||||
add('o', cmd.Operation)
|
||||
add('x', cmd.X)
|
||||
add('y', cmd.Y)
|
||||
add('X', cmd.Xp)
|
||||
add('Y', cmd.Yp)
|
||||
payload := utils.UnsafeBytesToString(cmd.Payload)
|
||||
payload_sz := len(payload)
|
||||
if payload_sz == 0 {
|
||||
b.WriteString("\x1b\\")
|
||||
return self.QueueWriteString(b.String())
|
||||
}
|
||||
if as_base64 {
|
||||
payload_sz = base64.RawStdEncoding.EncodedLen(payload_sz)
|
||||
dest := make([]byte, payload_sz)
|
||||
base64.RawStdEncoding.Encode(dest, utils.UnsafeStringToBytes(payload))
|
||||
payload = utils.UnsafeBytesToString(dest)
|
||||
} else {
|
||||
payload = string(cmd.Payload)
|
||||
}
|
||||
const chunk_size = 4096
|
||||
var ans IdType
|
||||
for i := 0; i < len(payload); i += chunk_size {
|
||||
end := i + chunk_size
|
||||
is_last := end >= len(payload)
|
||||
end = min(end, len(payload))
|
||||
if i == 0 {
|
||||
fmt.Fprintf(&b, ":m=%d;", utils.IfElse(is_last, 0, 1))
|
||||
self.QueueWriteString(b.String())
|
||||
} else {
|
||||
self.QueueWriteString(fmt.Sprintf("\x1b]%d;m=%d;", kitty.DndCode, utils.IfElse(is_last, 0, 1)))
|
||||
}
|
||||
self.QueueWriteString(payload[i:end])
|
||||
ans = self.QueueWriteString("\x1b\\")
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func effective_machine_id(m string) string {
|
||||
if m == "" {
|
||||
if ans, err := machine_id.MachineId(); err == nil {
|
||||
m = ans
|
||||
}
|
||||
}
|
||||
if m != "" {
|
||||
mac := hmac.New(sha256.New, []byte("tty-dnd-protocol-machine-id"))
|
||||
mac.Write(utils.UnsafeStringToBytes(m))
|
||||
m = "1:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (self *Loop) StartAcceptingDrops(machine_id string, mime_types ...string) {
|
||||
self.QueueDnDData(DndCommand{Type: 'a', Payload: []byte(strings.Join(mime_types, " "))})
|
||||
if m := effective_machine_id(machine_id); m != "" {
|
||||
self.QueueDnDData(DndCommand{Type: 'a', X: 1, Payload: []byte(m)})
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) StopAcceptingDrops() {
|
||||
self.QueueDnDData(DndCommand{Type: 'A'})
|
||||
}
|
||||
|
||||
func (self *Loop) StartOfferingDrags(machine_id string) {
|
||||
payload := ""
|
||||
if m := effective_machine_id(machine_id); m != "" {
|
||||
payload = m
|
||||
}
|
||||
self.QueueDnDData(DndCommand{Type: 'o', X: 1, Payload: []byte(payload)})
|
||||
}
|
||||
|
||||
func (self *Loop) StopOfferingDrags() {
|
||||
self.QueueDnDData(DndCommand{Type: 'o', X: 2})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type ColorPreference uint8
|
||||
|
||||
const (
|
||||
NO_COLOR_PREFERENCE ColorPreference = iota
|
||||
DARK_COLOR_PREFERENCE
|
||||
LIGHT_COLOR_PREFERENCE
|
||||
)
|
||||
|
||||
func (c ColorPreference) String() string {
|
||||
switch c {
|
||||
case DARK_COLOR_PREFERENCE:
|
||||
return "dark"
|
||||
case LIGHT_COLOR_PREFERENCE:
|
||||
return "light"
|
||||
default:
|
||||
return "no-preference"
|
||||
}
|
||||
}
|
||||
|
||||
type TerminalCapabilities struct {
|
||||
KeyboardProtocol bool
|
||||
KeyboardProtocolResponseReceived bool
|
||||
|
||||
ColorPreference ColorPreference
|
||||
ColorPreferenceResponseReceived bool
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
)
|
||||
|
||||
// key encoding mappings {{{
|
||||
// start csi mapping (auto generated by gen-key-constants.py do not edit)
|
||||
var functional_key_number_to_name_map = map[int]string{57344: "ESCAPE", 57345: "ENTER", 57346: "TAB", 57347: "BACKSPACE", 57348: "INSERT", 57349: "DELETE", 57350: "LEFT", 57351: "RIGHT", 57352: "UP", 57353: "DOWN", 57354: "PAGE_UP", 57355: "PAGE_DOWN", 57356: "HOME", 57357: "END", 57358: "CAPS_LOCK", 57359: "SCROLL_LOCK", 57360: "NUM_LOCK", 57361: "PRINT_SCREEN", 57362: "PAUSE", 57363: "MENU", 57364: "F1", 57365: "F2", 57366: "F3", 57367: "F4", 57368: "F5", 57369: "F6", 57370: "F7", 57371: "F8", 57372: "F9", 57373: "F10", 57374: "F11", 57375: "F12", 57376: "F13", 57377: "F14", 57378: "F15", 57379: "F16", 57380: "F17", 57381: "F18", 57382: "F19", 57383: "F20", 57384: "F21", 57385: "F22", 57386: "F23", 57387: "F24", 57388: "F25", 57389: "F26", 57390: "F27", 57391: "F28", 57392: "F29", 57393: "F30", 57394: "F31", 57395: "F32", 57396: "F33", 57397: "F34", 57398: "F35", 57399: "KP_0", 57400: "KP_1", 57401: "KP_2", 57402: "KP_3", 57403: "KP_4", 57404: "KP_5", 57405: "KP_6", 57406: "KP_7", 57407: "KP_8", 57408: "KP_9", 57409: "KP_DECIMAL", 57410: "KP_DIVIDE", 57411: "KP_MULTIPLY", 57412: "KP_SUBTRACT", 57413: "KP_ADD", 57414: "KP_ENTER", 57415: "KP_EQUAL", 57416: "KP_SEPARATOR", 57417: "KP_LEFT", 57418: "KP_RIGHT", 57419: "KP_UP", 57420: "KP_DOWN", 57421: "KP_PAGE_UP", 57422: "KP_PAGE_DOWN", 57423: "KP_HOME", 57424: "KP_END", 57425: "KP_INSERT", 57426: "KP_DELETE", 57427: "KP_BEGIN", 57428: "MEDIA_PLAY", 57429: "MEDIA_PAUSE", 57430: "MEDIA_PLAY_PAUSE", 57431: "MEDIA_REVERSE", 57432: "MEDIA_STOP", 57433: "MEDIA_FAST_FORWARD", 57434: "MEDIA_REWIND", 57435: "MEDIA_TRACK_NEXT", 57436: "MEDIA_TRACK_PREVIOUS", 57437: "MEDIA_RECORD", 57438: "LOWER_VOLUME", 57439: "RAISE_VOLUME", 57440: "MUTE_VOLUME", 57441: "LEFT_SHIFT", 57442: "LEFT_CONTROL", 57443: "LEFT_ALT", 57444: "LEFT_SUPER", 57445: "LEFT_HYPER", 57446: "LEFT_META", 57447: "RIGHT_SHIFT", 57448: "RIGHT_CONTROL", 57449: "RIGHT_ALT", 57450: "RIGHT_SUPER", 57451: "RIGHT_HYPER", 57452: "RIGHT_META", 57453: "ISO_LEVEL3_SHIFT", 57454: "ISO_LEVEL5_SHIFT"}
|
||||
|
||||
var csi_number_to_functional_number_map = map[int]int{2: 57348, 3: 57349, 5: 57354, 6: 57355, 7: 57356, 8: 57357, 9: 57346, 11: 57364, 12: 57365, 13: 57345, 14: 57367, 15: 57368, 17: 57369, 18: 57370, 19: 57371, 20: 57372, 21: 57373, 23: 57374, 24: 57375, 27: 57344, 127: 57347}
|
||||
|
||||
var letter_trailer_to_csi_number_map = map[string]int{"A": 57352, "B": 57353, "C": 57351, "D": 57350, "E": 57427, "F": 8, "H": 7, "P": 11, "Q": 12, "S": 14}
|
||||
|
||||
var tilde_trailers = map[int]bool{57348: true, 57349: true, 57354: true, 57355: true, 57366: true, 57368: true, 57369: true, 57370: true, 57371: true, 57372: true, 57373: true, 57374: true, 57375: true}
|
||||
|
||||
// end csi mapping
|
||||
// }}}
|
||||
|
||||
var name_to_functional_number_map map[string]int
|
||||
var functional_to_csi_number_map map[int]int
|
||||
var csi_number_to_letter_trailer_map map[int]string
|
||||
|
||||
type KeyEventType uint8
|
||||
type KeyModifiers uint16
|
||||
|
||||
const (
|
||||
PRESS KeyEventType = 1
|
||||
REPEAT KeyEventType = 2
|
||||
RELEASE KeyEventType = 4
|
||||
)
|
||||
|
||||
const (
|
||||
SHIFT KeyModifiers = 1
|
||||
ALT KeyModifiers = 2
|
||||
CTRL KeyModifiers = 4
|
||||
SUPER KeyModifiers = 8
|
||||
HYPER KeyModifiers = 16
|
||||
META KeyModifiers = 32
|
||||
CAPS_LOCK KeyModifiers = 64
|
||||
NUM_LOCK KeyModifiers = 128
|
||||
)
|
||||
|
||||
func (self KeyModifiers) WithoutLocks() KeyModifiers {
|
||||
return self & ^(CAPS_LOCK | NUM_LOCK)
|
||||
}
|
||||
|
||||
func (self KeyEventType) String() string {
|
||||
switch self {
|
||||
case PRESS:
|
||||
return "PRESS"
|
||||
case REPEAT:
|
||||
return "REPEAT"
|
||||
case RELEASE:
|
||||
return "RELEASE"
|
||||
default:
|
||||
return fmt.Sprintf("KeyEventType:%d", int(self))
|
||||
}
|
||||
}
|
||||
|
||||
func (self KeyModifiers) String() string {
|
||||
ans := make([]string, 0)
|
||||
if self&SHIFT != 0 {
|
||||
ans = append(ans, "shift")
|
||||
}
|
||||
if self&ALT != 0 {
|
||||
ans = append(ans, "alt")
|
||||
}
|
||||
if self&CTRL != 0 {
|
||||
ans = append(ans, "ctrl")
|
||||
}
|
||||
if self&SUPER != 0 {
|
||||
ans = append(ans, "super")
|
||||
}
|
||||
if self&HYPER != 0 {
|
||||
ans = append(ans, "hyper")
|
||||
}
|
||||
if self&META != 0 {
|
||||
ans = append(ans, "meta")
|
||||
}
|
||||
if self&CAPS_LOCK != 0 {
|
||||
ans = append(ans, "caps_lock")
|
||||
}
|
||||
if self&NUM_LOCK != 0 {
|
||||
ans = append(ans, "num_lock")
|
||||
}
|
||||
return strings.Join(ans, "+")
|
||||
}
|
||||
|
||||
func (self KeyModifiers) HasCapsLock() bool {
|
||||
return self&CAPS_LOCK != 0
|
||||
}
|
||||
|
||||
type KeyEvent struct {
|
||||
Type KeyEventType
|
||||
Mods KeyModifiers
|
||||
Key string
|
||||
ShiftedKey string
|
||||
AlternateKey string
|
||||
Text string
|
||||
Handled bool
|
||||
|
||||
// The CSI string this key event was decoded from. Empty if not decoded from CSI.
|
||||
CSI string
|
||||
}
|
||||
|
||||
func (self *KeyEvent) String() string {
|
||||
key := self.Key
|
||||
if self.Mods > 0 {
|
||||
key = self.Mods.String() + "+" + key
|
||||
}
|
||||
ans := fmt.Sprint(self.Type, "{ ", key, " ")
|
||||
if self.Text != "" {
|
||||
ans += "Text: " + self.Text + " "
|
||||
}
|
||||
if self.ShiftedKey != "" {
|
||||
ans += "ShiftedKey: " + self.ShiftedKey + " "
|
||||
}
|
||||
if self.AlternateKey != "" {
|
||||
ans += "AlternateKey: " + self.AlternateKey + " "
|
||||
}
|
||||
return ans + "}"
|
||||
}
|
||||
|
||||
func (self *KeyEvent) HasCapsLock() bool {
|
||||
return self.Mods.HasCapsLock()
|
||||
}
|
||||
|
||||
func KeyEventFromCSI(csi string) *KeyEvent {
|
||||
if len(csi) == 0 {
|
||||
return nil
|
||||
}
|
||||
orig_csi := csi
|
||||
last_char := csi[len(csi)-1:]
|
||||
if !strings.Contains("u~ABCDEHFPQS", last_char) || (last_char == "~" && (csi == "200~" || csi == "201~")) {
|
||||
return nil
|
||||
}
|
||||
csi = csi[:len(csi)-1]
|
||||
sections := strings.Split(csi, ";")
|
||||
|
||||
get_sub_sections := func(section string, missing int32) []int32 {
|
||||
p := strings.Split(section, ":")
|
||||
ans := make([]int32, len(p))
|
||||
for i, x := range p {
|
||||
if x == "" {
|
||||
ans[i] = missing
|
||||
} else {
|
||||
q, err := strconv.ParseUint(x, 10, 32)
|
||||
if err != nil || q > math.MaxInt32 {
|
||||
return nil
|
||||
}
|
||||
ans[i] = int32(q)
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
first_section := get_sub_sections(sections[0], 0)
|
||||
second_section := []int32{}
|
||||
third_section := []int32{}
|
||||
if len(sections) > 1 {
|
||||
second_section = get_sub_sections(sections[1], 1)
|
||||
}
|
||||
if len(sections) > 2 {
|
||||
third_section = get_sub_sections(sections[2], 0)
|
||||
}
|
||||
var ans = KeyEvent{Type: PRESS, CSI: orig_csi}
|
||||
var keynum int32
|
||||
if val, ok := letter_trailer_to_csi_number_map[last_char]; ok {
|
||||
keynum = int32(val)
|
||||
} else {
|
||||
if len(first_section) == 0 {
|
||||
return nil
|
||||
}
|
||||
keynum = first_section[0]
|
||||
}
|
||||
|
||||
key_name := func(keynum int32) string {
|
||||
switch keynum {
|
||||
case 0:
|
||||
return ""
|
||||
case 13:
|
||||
if last_char == "u" {
|
||||
return "ENTER"
|
||||
}
|
||||
return "F3"
|
||||
default:
|
||||
if val, ok := csi_number_to_functional_number_map[int(keynum)]; ok {
|
||||
keynum = int32(val)
|
||||
}
|
||||
ans := ""
|
||||
if val, ok := functional_key_number_to_name_map[int(keynum)]; ok {
|
||||
ans = val
|
||||
} else {
|
||||
ans = string(rune(keynum))
|
||||
}
|
||||
return ans
|
||||
}
|
||||
}
|
||||
|
||||
ans.Key = key_name(keynum)
|
||||
if len(first_section) > 1 {
|
||||
ans.ShiftedKey = key_name(first_section[1])
|
||||
}
|
||||
if len(first_section) > 2 {
|
||||
ans.AlternateKey = key_name(first_section[2])
|
||||
}
|
||||
if len(second_section) > 0 {
|
||||
ans.Mods = KeyModifiers(second_section[0] - 1)
|
||||
}
|
||||
if len(second_section) > 1 {
|
||||
switch second_section[1] {
|
||||
case 2:
|
||||
ans.Type = REPEAT
|
||||
case 3:
|
||||
ans.Type = RELEASE
|
||||
}
|
||||
}
|
||||
if len(third_section) > 0 {
|
||||
runes := make([]rune, len(third_section))
|
||||
for i, ch := range third_section {
|
||||
runes[i] = rune(ch)
|
||||
}
|
||||
ans.Text = string(runes)
|
||||
}
|
||||
return &ans
|
||||
}
|
||||
|
||||
type ParsedShortcut struct {
|
||||
Mods KeyModifiers
|
||||
KeyName string
|
||||
}
|
||||
|
||||
func (self *ParsedShortcut) String() string {
|
||||
ans := self.KeyName
|
||||
if self.Mods > 0 {
|
||||
ans = self.Mods.String() + "+" + ans
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
var parsed_shortcut_cache map[string]*ParsedShortcut
|
||||
|
||||
func ParseShortcut(spec string) *ParsedShortcut {
|
||||
if parsed_shortcut_cache == nil {
|
||||
parsed_shortcut_cache = make(map[string]*ParsedShortcut, 128)
|
||||
}
|
||||
if val, ok := parsed_shortcut_cache[spec]; ok {
|
||||
return val
|
||||
}
|
||||
ospec := spec
|
||||
if strings.HasSuffix(spec, "+") {
|
||||
ospec = spec[:len(spec)-1] + "plus"
|
||||
}
|
||||
parts := strings.Split(ospec, "+")
|
||||
key_name := parts[len(parts)-1]
|
||||
if val, ok := kitty.FunctionalKeyNameAliases[strings.ToUpper(key_name)]; ok {
|
||||
key_name = val
|
||||
}
|
||||
if _, is_functional_key := name_to_functional_number_map[strings.ToUpper(key_name)]; is_functional_key {
|
||||
key_name = strings.ToUpper(key_name)
|
||||
} else {
|
||||
if val, ok := kitty.CharacterKeyNameAliases[strings.ToUpper(key_name)]; ok {
|
||||
key_name = val
|
||||
}
|
||||
}
|
||||
ans := ParsedShortcut{KeyName: key_name}
|
||||
if len(parts) > 1 {
|
||||
for _, q := range parts[:len(parts)-1] {
|
||||
val, ok := kitty.ConfigModMap[strings.ToUpper(q)]
|
||||
if ok {
|
||||
ans.Mods |= KeyModifiers(val)
|
||||
} else {
|
||||
ans.Mods |= META << 8
|
||||
}
|
||||
}
|
||||
}
|
||||
parsed_shortcut_cache[spec] = &ans
|
||||
return &ans
|
||||
}
|
||||
|
||||
func isNonASCIIKey(key string) bool {
|
||||
r, size := utf8.DecodeRuneInString(key)
|
||||
return size > 0 && size == len(key) && r > 127 && r < 0xE000 && r != utf8.RuneError
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesParsedShortcutWithFallback(ps *ParsedShortcut, event_type KeyEventType, allowFallback string) bool {
|
||||
return self.MatchesParsedShortcutPriorityWithFallback(ps, event_type, allowFallback) >= 0
|
||||
}
|
||||
|
||||
// MatchesParsedShortcutPriorityWithFallback returns the match priority for the given shortcut:
|
||||
// - returns -1 if the event does not match
|
||||
// - returns 0 for a direct match (no fallback needed)
|
||||
// - returns the 1-based position of the matching fallback type in allowFallback for a fallback match
|
||||
// (e.g., "shifted" at position 0 in "shifted,ascii" returns 1; "ascii" at position 1 returns 2)
|
||||
//
|
||||
// Lower values indicate higher priority, so callers should prefer matches with smaller return values.
|
||||
func (self *KeyEvent) MatchesParsedShortcutPriorityWithFallback(ps *ParsedShortcut, event_type KeyEventType, allowFallback string) int {
|
||||
if self.Type&event_type == 0 {
|
||||
return -1
|
||||
}
|
||||
mods := self.Mods.WithoutLocks()
|
||||
if mods == ps.Mods && self.Key == ps.KeyName {
|
||||
return 0
|
||||
}
|
||||
canShifted := self.ShiftedKey != "" && mods&SHIFT != 0 && (mods & ^SHIFT) == ps.Mods && self.ShiftedKey == ps.KeyName
|
||||
canASCII := self.AlternateKey != "" && isNonASCIIKey(self.Key) && mods == ps.Mods && self.AlternateKey == ps.KeyName
|
||||
for i, part := range strings.Split(allowFallback, ",") {
|
||||
switch strings.TrimSpace(part) {
|
||||
case "shifted":
|
||||
if canShifted {
|
||||
return i + 1
|
||||
}
|
||||
case "ascii":
|
||||
if canASCII {
|
||||
return i + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// MatchesPressOrRepeatPriorityWithFallback returns the match priority (see MatchesParsedShortcutPriorityWithFallback).
|
||||
func (self *KeyEvent) MatchesPressOrRepeatPriorityWithFallback(spec string, allowFallback string) int {
|
||||
return self.MatchesParsedShortcutPriorityWithFallback(ParseShortcut(spec), PRESS|REPEAT, allowFallback)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesParsedShortcut(ps *ParsedShortcut, event_type KeyEventType) bool {
|
||||
return self.MatchesParsedShortcutWithFallback(ps, event_type, "shifted,ascii")
|
||||
}
|
||||
|
||||
func (self *KeyEvent) Matches(spec string, event_type KeyEventType) bool {
|
||||
return self.MatchesParsedShortcut(ParseShortcut(spec), event_type)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesPressOrRepeat(spec string) bool {
|
||||
return self.MatchesParsedShortcut(ParseShortcut(spec), PRESS|REPEAT)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesPressOrRepeatWithFallback(spec string, allowFallback string) bool {
|
||||
return self.MatchesParsedShortcutWithFallback(ParseShortcut(spec), PRESS|REPEAT, allowFallback)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesCaseSensitiveTextOrKey(spec string) bool {
|
||||
if self.MatchesParsedShortcut(ParseShortcut(spec), PRESS|REPEAT) {
|
||||
return true
|
||||
}
|
||||
return self.Text == spec
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesCaseInsensitiveTextOrKey(spec string) bool {
|
||||
if self.MatchesParsedShortcut(ParseShortcut(spec), PRESS|REPEAT) {
|
||||
return true
|
||||
}
|
||||
return strings.EqualFold(self.Text, spec)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) MatchesRelease(spec string) bool {
|
||||
return self.MatchesParsedShortcut(ParseShortcut(spec), RELEASE)
|
||||
}
|
||||
|
||||
func (self *KeyEvent) AsCSI() string {
|
||||
key := csi_number_for_name(self.Key)
|
||||
shifted_key := csi_number_for_name(self.ShiftedKey)
|
||||
alternate_key := csi_number_for_name(self.AlternateKey)
|
||||
trailer, found := csi_number_to_letter_trailer_map[key]
|
||||
if !found {
|
||||
trailer = "u"
|
||||
}
|
||||
if self.Key == "ENTER" {
|
||||
trailer = "u"
|
||||
}
|
||||
if trailer != "u" {
|
||||
key = 1
|
||||
}
|
||||
ans := strings.Builder{}
|
||||
ans.Grow(32)
|
||||
ans.WriteString("\033[")
|
||||
if key != 1 || self.Mods != 0 || shifted_key != 0 || alternate_key != 0 || self.Text != "" {
|
||||
fmt.Fprint(&ans, key)
|
||||
}
|
||||
if shifted_key != 0 || alternate_key != 0 {
|
||||
ans.WriteString(":")
|
||||
if shifted_key != 0 {
|
||||
fmt.Fprint(&ans, shifted_key)
|
||||
}
|
||||
if alternate_key != 0 {
|
||||
fmt.Fprint(&ans, ":", alternate_key)
|
||||
}
|
||||
}
|
||||
action := 1
|
||||
switch self.Type {
|
||||
case REPEAT:
|
||||
action = 2
|
||||
case RELEASE:
|
||||
action = 3
|
||||
}
|
||||
if self.Mods != 0 || action > 1 || self.Text != "" {
|
||||
m := uint(self.Mods)
|
||||
if action > 1 || m != 0 {
|
||||
fmt.Fprintf(&ans, ";%d", m+1)
|
||||
if action > 1 {
|
||||
fmt.Fprintf(&ans, ":%d", action)
|
||||
}
|
||||
} else if self.Text != "" {
|
||||
ans.WriteString(";")
|
||||
}
|
||||
}
|
||||
if self.Text != "" {
|
||||
runes := []rune(self.Text)
|
||||
codes := make([]string, len(runes))
|
||||
for i, r := range runes {
|
||||
codes[i] = strconv.Itoa(int(r))
|
||||
}
|
||||
ans.WriteString(";")
|
||||
ans.WriteString(strings.Join(codes, ":"))
|
||||
}
|
||||
fn, found := name_to_functional_number_map[self.Key]
|
||||
if found && tilde_trailers[fn] {
|
||||
trailer = "~"
|
||||
}
|
||||
ans.WriteString(trailer)
|
||||
return ans.String()
|
||||
}
|
||||
|
||||
func csi_number_for_name(key_name string) int {
|
||||
if key_name == "" {
|
||||
return 0
|
||||
}
|
||||
if key_name == "F3" || key_name == "ENTER" {
|
||||
return 13
|
||||
}
|
||||
fn, ok := name_to_functional_number_map[key_name]
|
||||
if !ok {
|
||||
return int(rune(key_name[0]))
|
||||
}
|
||||
ans, ok := functional_to_csi_number_map[fn]
|
||||
if ok {
|
||||
return ans
|
||||
}
|
||||
return fn
|
||||
}
|
||||
|
||||
func init() {
|
||||
name_to_functional_number_map = make(map[string]int, len(functional_key_number_to_name_map))
|
||||
for k, v := range functional_key_number_to_name_map {
|
||||
name_to_functional_number_map[v] = k
|
||||
}
|
||||
functional_to_csi_number_map = make(map[int]int, len(csi_number_to_functional_number_map))
|
||||
for k, v := range csi_number_to_functional_number_map {
|
||||
functional_to_csi_number_map[v] = k
|
||||
}
|
||||
csi_number_to_letter_trailer_map = make(map[int]string, len(letter_trailer_to_csi_number_map))
|
||||
for k, v := range letter_trailer_to_csi_number_map {
|
||||
csi_number_to_letter_trailer_map[v] = k
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestKeyEventFromCSI(t *testing.T) {
|
||||
|
||||
test_text := func(csi string, expected, alternate string) {
|
||||
ev := KeyEventFromCSI(csi)
|
||||
if ev == nil {
|
||||
t.Fatalf("Failed to get parse %#v", csi)
|
||||
}
|
||||
if diff := cmp.Diff(expected, ev.Text); diff != "" {
|
||||
t.Fatalf("Failed to get text from %#v:\n%s", csi, diff)
|
||||
}
|
||||
if diff := cmp.Diff(alternate, ev.AlternateKey); diff != "" {
|
||||
t.Fatalf("Failed to get alternate from %#v:\n%s", csi, diff)
|
||||
}
|
||||
}
|
||||
test_text("121;;121u", "y", "")
|
||||
test_text("121::122;;121u", "y", "z")
|
||||
}
|
||||
|
||||
func TestIsNonASCIIKey(t *testing.T) {
|
||||
if !isNonASCIIKey("с") { // Cyrillic с (U+0441)
|
||||
t.Fatal("Cyrillic с should be non-ASCII")
|
||||
}
|
||||
if isNonASCIIKey("c") { // Latin c
|
||||
t.Fatal("Latin c should be ASCII")
|
||||
}
|
||||
if isNonASCIIKey("") {
|
||||
t.Fatal("empty string should not be non-ASCII")
|
||||
}
|
||||
// boundary: U+0080 (first non-ASCII) should be true
|
||||
if !isNonASCIIKey("\u0080") {
|
||||
t.Fatal("U+0080 should be non-ASCII")
|
||||
}
|
||||
// boundary: U+007F (DEL, last ASCII) should be false
|
||||
if isNonASCIIKey("\u007f") {
|
||||
t.Fatal("U+007F should be ASCII")
|
||||
}
|
||||
// boundary: U+D7FF (last valid BMP char before surrogates) should be true
|
||||
if !isNonASCIIKey("\uD7FF") {
|
||||
t.Fatal("U+D7FF should be non-ASCII (before PUA)")
|
||||
}
|
||||
// boundary: U+E000 (first PUA, functional key range) should be false
|
||||
if isNonASCIIKey("\uE000") {
|
||||
t.Fatal("U+E000 should be excluded (functional key range)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesParsedShortcutWithFallback(t *testing.T) {
|
||||
ps := ParseShortcut("ctrl+c")
|
||||
|
||||
// Per-mapping ascii match: Cyrillic key + AlternateKey=c + allow_fallback contains ascii
|
||||
ev := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "с", AlternateKey: "c"}
|
||||
if !ev.MatchesParsedShortcutWithFallback(ps, PRESS, "shifted,ascii") {
|
||||
t.Fatal("should match via AlternateKey with allow_fallback=shifted,ascii")
|
||||
}
|
||||
if !ev.MatchesParsedShortcutWithFallback(ps, PRESS, "ascii") {
|
||||
t.Fatal("should match via AlternateKey with allow_fallback=ascii")
|
||||
}
|
||||
|
||||
// Per-mapping no ascii match when allow_fallback=shifted only
|
||||
if ev.MatchesParsedShortcutWithFallback(ps, PRESS, "shifted") {
|
||||
t.Fatal("should NOT match via AlternateKey with allow_fallback=shifted (no ascii)")
|
||||
}
|
||||
|
||||
// No fallback at all
|
||||
if ev.MatchesParsedShortcutWithFallback(ps, PRESS, "") {
|
||||
t.Fatal("should NOT match with empty allow_fallback")
|
||||
}
|
||||
|
||||
// Direct Key match takes priority (always works regardless of allow_fallback)
|
||||
evDirect := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "c"}
|
||||
if !evDirect.MatchesParsedShortcutWithFallback(ps, PRESS, "") {
|
||||
t.Fatal("direct Key match should work even with empty allow_fallback")
|
||||
}
|
||||
if !evDirect.MatchesParsedShortcutWithFallback(ps, PRESS, "shifted") {
|
||||
t.Fatal("direct Key match should work with any allow_fallback")
|
||||
}
|
||||
|
||||
// No AlternateKey match when Key is ASCII (Dvorak safety: non-ASCII guard)
|
||||
evDvorak := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "x", AlternateKey: "c"}
|
||||
if evDvorak.MatchesParsedShortcutWithFallback(ps, PRESS, "ascii") {
|
||||
t.Fatal("should NOT match via AlternateKey when Key is ASCII (Dvorak)")
|
||||
}
|
||||
|
||||
// Shifted fallback respects per-mapping allow_fallback
|
||||
psA := ParseShortcut("a")
|
||||
evShifted := &KeyEvent{Type: PRESS, Mods: SHIFT, Key: "A", ShiftedKey: "a"}
|
||||
if !evShifted.MatchesParsedShortcutWithFallback(psA, PRESS, "shifted") {
|
||||
t.Fatal("shifted fallback should work with allow_fallback=shifted")
|
||||
}
|
||||
if evShifted.MatchesParsedShortcutWithFallback(psA, PRESS, "ascii") {
|
||||
t.Fatal("shifted fallback should NOT work with allow_fallback=ascii only")
|
||||
}
|
||||
if evShifted.MatchesParsedShortcutWithFallback(psA, PRESS, "") {
|
||||
t.Fatal("shifted fallback should NOT work with empty allow_fallback")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesParsedShortcutPriorityWithFallback(t *testing.T) {
|
||||
psA := ParseShortcut("a")
|
||||
psCtrlC := ParseShortcut("ctrl+c")
|
||||
|
||||
// Direct match: priority 0
|
||||
evDirect := &KeyEvent{Type: PRESS, Key: "a"}
|
||||
if p := evDirect.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, ""); p != 0 {
|
||||
t.Fatalf("direct match should have priority 0, got %d", p)
|
||||
}
|
||||
|
||||
// No match: priority -1
|
||||
evNoMatch := &KeyEvent{Type: PRESS, Key: "b"}
|
||||
if p := evNoMatch.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "shifted,ascii"); p != -1 {
|
||||
t.Fatalf("no match should have priority -1, got %d", p)
|
||||
}
|
||||
|
||||
// Shifted fallback at position 0 in "shifted,ascii": priority 1
|
||||
evShifted := &KeyEvent{Type: PRESS, Mods: SHIFT, Key: "A", ShiftedKey: "a"}
|
||||
if p := evShifted.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "shifted,ascii"); p != 1 {
|
||||
t.Fatalf("shifted fallback first in 'shifted,ascii' should have priority 1, got %d", p)
|
||||
}
|
||||
|
||||
// Shifted fallback at position 1 in "ascii,shifted": priority 2
|
||||
if p := evShifted.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "ascii,shifted"); p != 2 {
|
||||
t.Fatalf("shifted fallback second in 'ascii,shifted' should have priority 2, got %d", p)
|
||||
}
|
||||
|
||||
// Shifted fallback only in "shifted": priority 1 (same as first position)
|
||||
if p := evShifted.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "shifted"); p != 1 {
|
||||
t.Fatalf("shifted fallback only in 'shifted' should have priority 1, got %d", p)
|
||||
}
|
||||
|
||||
// Shifted fallback not allowed: priority -1
|
||||
if p := evShifted.MatchesParsedShortcutPriorityWithFallback(psA, PRESS, "ascii"); p != -1 {
|
||||
t.Fatalf("shifted fallback not in 'ascii' should have priority -1, got %d", p)
|
||||
}
|
||||
|
||||
// ASCII (alternate key) fallback at position 1 in "shifted,ascii": priority 2
|
||||
evASCII := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "с", AlternateKey: "c"}
|
||||
if p := evASCII.MatchesParsedShortcutPriorityWithFallback(psCtrlC, PRESS, "shifted,ascii"); p != 2 {
|
||||
t.Fatalf("ascii fallback second in 'shifted,ascii' should have priority 2, got %d", p)
|
||||
}
|
||||
|
||||
// ASCII fallback at position 0 in "ascii,shifted": priority 1
|
||||
if p := evASCII.MatchesParsedShortcutPriorityWithFallback(psCtrlC, PRESS, "ascii,shifted"); p != 1 {
|
||||
t.Fatalf("ascii fallback first in 'ascii,shifted' should have priority 1, got %d", p)
|
||||
}
|
||||
|
||||
// ASCII fallback only in "ascii": priority 1
|
||||
if p := evASCII.MatchesParsedShortcutPriorityWithFallback(psCtrlC, PRESS, "ascii"); p != 1 {
|
||||
t.Fatalf("ascii fallback only in 'ascii' should have priority 1, got %d", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesParsedShortcutUnconditionalAlternateKey(t *testing.T) {
|
||||
// Unconditional match via MatchesPressOrRepeat (hardcoded shortcuts)
|
||||
ev := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "с", AlternateKey: "c"}
|
||||
if !ev.MatchesPressOrRepeat("ctrl+c") {
|
||||
t.Fatal("MatchesPressOrRepeat should match via AlternateKey with non-ASCII guard")
|
||||
}
|
||||
|
||||
// Direct Key match takes priority in unconditional mode too
|
||||
evDirect := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "c"}
|
||||
if !evDirect.MatchesPressOrRepeat("ctrl+c") {
|
||||
t.Fatal("direct Key match should work in unconditional mode")
|
||||
}
|
||||
|
||||
// No AlternateKey match when Key is ASCII (Dvorak safety)
|
||||
evDvorak := &KeyEvent{Type: PRESS, Mods: CTRL, Key: "x", AlternateKey: "c"}
|
||||
if evDvorak.MatchesPressOrRepeat("ctrl+c") {
|
||||
t.Fatal("should NOT match via AlternateKey when Key is ASCII in unconditional mode")
|
||||
}
|
||||
|
||||
// ShiftedKey still works unconditionally
|
||||
evShifted := &KeyEvent{Type: PRESS, Mods: SHIFT, Key: "A", ShiftedKey: "a"}
|
||||
if !evShifted.MatchesPressOrRepeat("a") {
|
||||
t.Fatal("ShiftedKey should match unconditionally in MatchesParsedShortcut")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type MouseEventType uint
|
||||
type MouseButtonFlag uint
|
||||
|
||||
const (
|
||||
MOUSE_PRESS MouseEventType = iota
|
||||
MOUSE_RELEASE
|
||||
MOUSE_MOVE
|
||||
MOUSE_CLICK
|
||||
MOUSE_LEAVE
|
||||
)
|
||||
|
||||
func (e MouseEventType) String() string {
|
||||
switch e {
|
||||
case MOUSE_PRESS:
|
||||
return "press"
|
||||
case MOUSE_RELEASE:
|
||||
return "release"
|
||||
case MOUSE_MOVE:
|
||||
return "move"
|
||||
case MOUSE_CLICK:
|
||||
return "click"
|
||||
}
|
||||
return strconv.Itoa(int(e))
|
||||
}
|
||||
|
||||
type PointerShape uint8
|
||||
|
||||
const (
|
||||
// start pointer shape enum (auto generated by gen-key-constants.py do not edit)
|
||||
DEFAULT_POINTER PointerShape = 0
|
||||
TEXT_POINTER PointerShape = 1
|
||||
POINTER_POINTER PointerShape = 2
|
||||
HELP_POINTER PointerShape = 3
|
||||
WAIT_POINTER PointerShape = 4
|
||||
PROGRESS_POINTER PointerShape = 5
|
||||
CROSSHAIR_POINTER PointerShape = 6
|
||||
CELL_POINTER PointerShape = 7
|
||||
VERTICAL_TEXT_POINTER PointerShape = 8
|
||||
MOVE_POINTER PointerShape = 9
|
||||
E_RESIZE_POINTER PointerShape = 10
|
||||
NE_RESIZE_POINTER PointerShape = 11
|
||||
NW_RESIZE_POINTER PointerShape = 12
|
||||
N_RESIZE_POINTER PointerShape = 13
|
||||
SE_RESIZE_POINTER PointerShape = 14
|
||||
SW_RESIZE_POINTER PointerShape = 15
|
||||
S_RESIZE_POINTER PointerShape = 16
|
||||
W_RESIZE_POINTER PointerShape = 17
|
||||
EW_RESIZE_POINTER PointerShape = 18
|
||||
NS_RESIZE_POINTER PointerShape = 19
|
||||
NESW_RESIZE_POINTER PointerShape = 20
|
||||
NWSE_RESIZE_POINTER PointerShape = 21
|
||||
ZOOM_IN_POINTER PointerShape = 22
|
||||
ZOOM_OUT_POINTER PointerShape = 23
|
||||
ALIAS_POINTER PointerShape = 24
|
||||
COPY_POINTER PointerShape = 25
|
||||
NOT_ALLOWED_POINTER PointerShape = 26
|
||||
NO_DROP_POINTER PointerShape = 27
|
||||
GRAB_POINTER PointerShape = 28
|
||||
GRABBING_POINTER PointerShape = 29
|
||||
|
||||
// end pointer shape enum
|
||||
)
|
||||
|
||||
func (e PointerShape) String() string {
|
||||
switch e {
|
||||
// start pointer shape tostring (auto generated by gen-key-constants.py do not edit)
|
||||
case DEFAULT_POINTER:
|
||||
return "default"
|
||||
case TEXT_POINTER:
|
||||
return "text"
|
||||
case POINTER_POINTER:
|
||||
return "pointer"
|
||||
case HELP_POINTER:
|
||||
return "help"
|
||||
case WAIT_POINTER:
|
||||
return "wait"
|
||||
case PROGRESS_POINTER:
|
||||
return "progress"
|
||||
case CROSSHAIR_POINTER:
|
||||
return "crosshair"
|
||||
case CELL_POINTER:
|
||||
return "cell"
|
||||
case VERTICAL_TEXT_POINTER:
|
||||
return "vertical-text"
|
||||
case MOVE_POINTER:
|
||||
return "move"
|
||||
case E_RESIZE_POINTER:
|
||||
return "e-resize"
|
||||
case NE_RESIZE_POINTER:
|
||||
return "ne-resize"
|
||||
case NW_RESIZE_POINTER:
|
||||
return "nw-resize"
|
||||
case N_RESIZE_POINTER:
|
||||
return "n-resize"
|
||||
case SE_RESIZE_POINTER:
|
||||
return "se-resize"
|
||||
case SW_RESIZE_POINTER:
|
||||
return "sw-resize"
|
||||
case S_RESIZE_POINTER:
|
||||
return "s-resize"
|
||||
case W_RESIZE_POINTER:
|
||||
return "w-resize"
|
||||
case EW_RESIZE_POINTER:
|
||||
return "ew-resize"
|
||||
case NS_RESIZE_POINTER:
|
||||
return "ns-resize"
|
||||
case NESW_RESIZE_POINTER:
|
||||
return "nesw-resize"
|
||||
case NWSE_RESIZE_POINTER:
|
||||
return "nwse-resize"
|
||||
case ZOOM_IN_POINTER:
|
||||
return "zoom-in"
|
||||
case ZOOM_OUT_POINTER:
|
||||
return "zoom-out"
|
||||
case ALIAS_POINTER:
|
||||
return "alias"
|
||||
case COPY_POINTER:
|
||||
return "copy"
|
||||
case NOT_ALLOWED_POINTER:
|
||||
return "not-allowed"
|
||||
case NO_DROP_POINTER:
|
||||
return "no-drop"
|
||||
case GRAB_POINTER:
|
||||
return "grab"
|
||||
case GRABBING_POINTER:
|
||||
return "grabbing"
|
||||
// end pointer shape tostring
|
||||
}
|
||||
return strconv.Itoa(int(e))
|
||||
}
|
||||
|
||||
const (
|
||||
SHIFT_INDICATOR int = 1 << 2
|
||||
ALT_INDICATOR = 1 << 3
|
||||
CTRL_INDICATOR = 1 << 4
|
||||
MOTION_INDICATOR = 1 << 5
|
||||
SCROLL_BUTTON_INDICATOR = 1 << 6
|
||||
EXTRA_BUTTON_INDICATOR = 1 << 7
|
||||
LEAVE_INDICATOR = 1 << 8
|
||||
)
|
||||
|
||||
const (
|
||||
NO_MOUSE_BUTTON MouseButtonFlag = 0
|
||||
LEFT_MOUSE_BUTTON MouseButtonFlag = 1 << iota
|
||||
MIDDLE_MOUSE_BUTTON
|
||||
RIGHT_MOUSE_BUTTON
|
||||
FOURTH_MOUSE_BUTTON
|
||||
FIFTH_MOUSE_BUTTON
|
||||
SIXTH_MOUSE_BUTTON
|
||||
SEVENTH_MOUSE_BUTTON
|
||||
MOUSE_WHEEL_UP
|
||||
MOUSE_WHEEL_DOWN
|
||||
MOUSE_WHEEL_LEFT
|
||||
MOUSE_WHEEL_RIGHT
|
||||
)
|
||||
|
||||
var bmap = [...]MouseButtonFlag{LEFT_MOUSE_BUTTON, MIDDLE_MOUSE_BUTTON, RIGHT_MOUSE_BUTTON}
|
||||
var ebmap = [...]MouseButtonFlag{FOURTH_MOUSE_BUTTON, FIFTH_MOUSE_BUTTON, SIXTH_MOUSE_BUTTON, SEVENTH_MOUSE_BUTTON}
|
||||
var wbmap = [...]MouseButtonFlag{MOUSE_WHEEL_UP, MOUSE_WHEEL_DOWN, MOUSE_WHEEL_LEFT, MOUSE_WHEEL_RIGHT}
|
||||
|
||||
func (b MouseButtonFlag) String() string {
|
||||
ans := ""
|
||||
switch {
|
||||
case b&LEFT_MOUSE_BUTTON != 0:
|
||||
ans += "|LEFT"
|
||||
case b&MIDDLE_MOUSE_BUTTON != 0:
|
||||
ans += "|MIDDLE"
|
||||
case b&RIGHT_MOUSE_BUTTON != 0:
|
||||
ans += "|RIGHT"
|
||||
case b&FOURTH_MOUSE_BUTTON != 0:
|
||||
ans += "|FOURTH"
|
||||
case b&FIFTH_MOUSE_BUTTON != 0:
|
||||
ans += "|FIFTH"
|
||||
case b&SIXTH_MOUSE_BUTTON != 0:
|
||||
ans += "|SIXTH"
|
||||
case b&SEVENTH_MOUSE_BUTTON != 0:
|
||||
ans += "|SEVENTH"
|
||||
case b&MOUSE_WHEEL_UP != 0:
|
||||
ans += "|WHEEL_UP"
|
||||
case b&MOUSE_WHEEL_DOWN != 0:
|
||||
ans += "|WHEEL_DOWN"
|
||||
case b&MOUSE_WHEEL_LEFT != 0:
|
||||
ans += "|WHEEL_LEFT"
|
||||
case b&MOUSE_WHEEL_RIGHT != 0:
|
||||
ans += "|WHEEL_RIGHT"
|
||||
}
|
||||
ans = strings.TrimLeft(ans, "|")
|
||||
if ans == "" {
|
||||
ans = "NONE"
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
type MouseEvent struct {
|
||||
Event_type MouseEventType
|
||||
Buttons MouseButtonFlag
|
||||
Mods KeyModifiers
|
||||
Cell, Pixel struct{ X, Y int }
|
||||
}
|
||||
|
||||
func (e MouseEvent) String() string {
|
||||
return fmt.Sprintf("MouseEvent{%s %s %s Cell:%v Pixel:%v}", e.Event_type, e.Buttons, e.Mods, e.Cell, e.Pixel)
|
||||
}
|
||||
|
||||
func pixel_to_cell(px, length, cell_length int) int {
|
||||
px = max(0, min(px, length-1))
|
||||
if cell_length > 0 {
|
||||
return px / cell_length
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func decode_sgr_mouse(text string, screen_size ScreenSize, last_letter byte) *MouseEvent {
|
||||
text = text[:len(text)-1]
|
||||
parts := strings.Split(text, ";")
|
||||
if len(parts) != 3 {
|
||||
return nil
|
||||
}
|
||||
cb, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
ans := MouseEvent{}
|
||||
ans.Pixel.X, err = strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if len(parts[2]) < 1 {
|
||||
return nil
|
||||
}
|
||||
if ans.Pixel.Y, err = strconv.Atoi(parts[2]); err != nil {
|
||||
return nil
|
||||
}
|
||||
if last_letter == 'm' {
|
||||
ans.Event_type = MOUSE_RELEASE
|
||||
} else if cb&MOTION_INDICATOR != 0 {
|
||||
ans.Event_type = MOUSE_MOVE
|
||||
}
|
||||
cb3 := cb & 3
|
||||
switch {
|
||||
case cb&LEAVE_INDICATOR != 0:
|
||||
ans.Event_type = MOUSE_LEAVE
|
||||
case cb&EXTRA_BUTTON_INDICATOR != 0:
|
||||
ans.Buttons |= ebmap[cb3]
|
||||
case cb&SCROLL_BUTTON_INDICATOR != 0:
|
||||
ans.Buttons |= wbmap[cb3]
|
||||
case cb3 < 3:
|
||||
ans.Buttons |= bmap[cb3]
|
||||
}
|
||||
if cb&SHIFT_INDICATOR != 0 {
|
||||
ans.Mods |= SHIFT
|
||||
}
|
||||
if cb&ALT_INDICATOR != 0 {
|
||||
ans.Mods |= ALT
|
||||
}
|
||||
if cb&CTRL_INDICATOR != 0 {
|
||||
ans.Mods |= CTRL
|
||||
}
|
||||
ans.Cell.X = pixel_to_cell(ans.Pixel.X, int(screen_size.WidthPx), int(screen_size.CellWidth))
|
||||
ans.Cell.Y = pixel_to_cell(ans.Pixel.Y, int(screen_size.HeightPx), int(screen_size.CellHeight))
|
||||
|
||||
return &ans
|
||||
}
|
||||
|
||||
func MouseEventFromCSI(csi string, screen_size ScreenSize) *MouseEvent {
|
||||
if len(csi) == 0 {
|
||||
return nil
|
||||
}
|
||||
last_char := csi[len(csi)-1]
|
||||
if last_char != 'm' && last_char != 'M' {
|
||||
return nil
|
||||
}
|
||||
switch csi[0] {
|
||||
case '<':
|
||||
return decode_sgr_mouse(csi[1:], screen_size, last_char)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/go-parallel"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func (self *Loop) dispatch_input_data(data []byte) error {
|
||||
if self.OnReceivedData != nil {
|
||||
err := self.OnReceivedData(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err := self.escape_code_parser.Parse(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func read_ignoring_temporary_errors(f *tty.Term, buf []byte) (int, error) {
|
||||
n, err := f.Read(buf)
|
||||
if is_temporary_error(err) {
|
||||
return 0, nil
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func read_from_tty(pipe_r *os.File, term *tty.Term, results_channel chan<- []byte, err_channel chan<- error, quit_channel <-chan byte, leftover_channel chan<- []byte) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err := parallel.Format_stacktrace_on_panic(r, 1)
|
||||
err_channel <- err
|
||||
}
|
||||
}()
|
||||
keep_going := true
|
||||
pipe_fd := int(pipe_r.Fd())
|
||||
tty_fd := term.Fd()
|
||||
selector := utils.CreateSelect(2)
|
||||
selector.RegisterRead(pipe_fd)
|
||||
selector.RegisterRead(tty_fd)
|
||||
|
||||
defer func() {
|
||||
close(results_channel)
|
||||
pipe_r.Close()
|
||||
}()
|
||||
|
||||
const bufsize = 2 * utils.DEFAULT_IO_BUFFER_SIZE
|
||||
|
||||
wait_for_read_available := func() {
|
||||
for {
|
||||
n, err := selector.WaitForever()
|
||||
if err != nil && err != unix.EINTR {
|
||||
err_channel <- err
|
||||
keep_going = false
|
||||
return
|
||||
}
|
||||
if n > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if selector.IsReadyToRead(pipe_fd) {
|
||||
keep_going = false
|
||||
}
|
||||
}
|
||||
|
||||
buf := make([]byte, bufsize)
|
||||
for keep_going {
|
||||
if len(buf) < 64 {
|
||||
buf = make([]byte, bufsize)
|
||||
}
|
||||
if wait_for_read_available(); !keep_going {
|
||||
break
|
||||
}
|
||||
n, err := read_ignoring_temporary_errors(term, buf)
|
||||
if err != nil {
|
||||
err_channel <- err
|
||||
keep_going = false
|
||||
break
|
||||
}
|
||||
if n == 0 { // temporary error
|
||||
continue
|
||||
}
|
||||
send := buf[:n]
|
||||
buf = buf[n:]
|
||||
select {
|
||||
case results_channel <- send:
|
||||
case <-quit_channel:
|
||||
leftover_channel <- send
|
||||
keep_going = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func has_da1_response(s string) bool {
|
||||
return utils.MustCompile("\x1b\\[\\?[0-9:;]+c").FindString(s) != ""
|
||||
}
|
||||
|
||||
func do_roundtrip_to_terminal(term *tty.Term, timeout time.Duration) {
|
||||
// ask for primary device attributes
|
||||
for {
|
||||
if err := term.WriteAllString("\x1b[c"); err != nil && !is_temporary_error(err) {
|
||||
return
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
s := strings.Builder{}
|
||||
s.Grow(256)
|
||||
received := make(chan error, 1)
|
||||
go func() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
text := parallel.Format_stacktrace_on_panic(r, 1).Error()
|
||||
received <- fmt.Errorf("%s", text)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
buf := make([]byte, 1024)
|
||||
n, err := read_ignoring_temporary_errors(term, buf)
|
||||
if n > 0 {
|
||||
s.Write(buf[:n])
|
||||
if has_da1_response(s.String()) {
|
||||
received <- nil
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
received <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-received:
|
||||
case <-time.After(timeout):
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var SIGNULL unix.Signal
|
||||
|
||||
func new_loop() *Loop {
|
||||
l := Loop{controlling_term: nil}
|
||||
l.terminal_options.Alternate_screen = true
|
||||
l.terminal_options.restore_colors = true
|
||||
l.terminal_options.focus_tracking = true
|
||||
l.terminal_options.in_band_resize_notification = true
|
||||
l.terminal_options.color_scheme_change_notification = false
|
||||
l.terminal_options.kitty_keyboard_mode = DISAMBIGUATE_KEYS | REPORT_ALTERNATE_KEYS | REPORT_ALL_KEYS_AS_ESCAPE_CODES | REPORT_TEXT_WITH_KEYS
|
||||
l.terminal_options.roundtrip_on_exit = true
|
||||
l.escape_code_parser.HandleCSI = l.handle_csi
|
||||
l.escape_code_parser.HandleOSC = l.handle_osc
|
||||
l.escape_code_parser.HandleDCS = l.handle_dcs
|
||||
l.escape_code_parser.HandleAPC = l.handle_apc
|
||||
l.escape_code_parser.HandleSOS = l.handle_sos
|
||||
l.escape_code_parser.HandlePM = l.handle_pm
|
||||
l.escape_code_parser.HandleRune = l.handle_rune
|
||||
l.escape_code_parser.HandleEndOfBracketedPaste = l.handle_end_of_bracketed_paste
|
||||
l.style_cache = make(map[string]func(...any) string)
|
||||
l.style_ctx.AllowEscapeCodes = true
|
||||
return &l
|
||||
}
|
||||
|
||||
func is_temporary_error(err error) bool {
|
||||
return errors.Is(err, unix.EINTR) || errors.Is(err, unix.EAGAIN) || errors.Is(err, unix.EWOULDBLOCK) || errors.Is(err, io.ErrShortWrite)
|
||||
}
|
||||
|
||||
func kill_self(sig unix.Signal) {
|
||||
_ = unix.Kill(os.Getpid(), sig)
|
||||
// Give the signal time to be delivered
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
|
||||
func (self *Loop) set_pointer_shapes(ps []PointerShape) {
|
||||
self.pointer_shapes = ps
|
||||
if len(ps) > 0 {
|
||||
s := strings.Builder{}
|
||||
s.WriteString("\x1b]22;>")
|
||||
for i, x := range ps {
|
||||
s.WriteString(x.String())
|
||||
if i+1 < len(ps) {
|
||||
s.WriteByte(',')
|
||||
}
|
||||
}
|
||||
s.WriteString("\x1b\\")
|
||||
self.QueueWriteString(s.String())
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) update_screen_size() error {
|
||||
if self.controlling_term == nil {
|
||||
return fmt.Errorf("No controlling terminal cannot update screen size")
|
||||
}
|
||||
ws, err := self.controlling_term.GetSize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s := &self.screen_size
|
||||
s.updated = true
|
||||
s.HeightCells, s.WidthCells = uint(ws.Row), uint(ws.Col)
|
||||
s.HeightPx, s.WidthPx = uint(ws.Ypixel), uint(ws.Xpixel)
|
||||
s.update_cell_size()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ScreenSize) update_cell_size() {
|
||||
s.CellWidth, s.CellHeight = 0, 0
|
||||
if s.WidthCells > 0 {
|
||||
s.CellWidth = s.WidthPx / s.WidthCells
|
||||
}
|
||||
if s.HeightCells > 0 {
|
||||
s.CellHeight = s.HeightPx / s.HeightCells
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) handle_csi(raw []byte) (err error) {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
csi := string(raw)
|
||||
switch raw[len(raw)-1] {
|
||||
case 't':
|
||||
if rest, found := strings.CutPrefix(csi, "48;"); found {
|
||||
if parts := strings.Split(rest[:len(rest)-1], ";"); len(parts) >= 4 {
|
||||
var parsed [4]uint
|
||||
ok := true
|
||||
for i := range parsed {
|
||||
x, _, _ := strings.Cut(parts[i], ":")
|
||||
n, perr := strconv.ParseUint(x, 10, 0)
|
||||
if perr != nil {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
parsed[i] = uint(n)
|
||||
}
|
||||
if ok {
|
||||
self.seen_inband_resize = true
|
||||
old_size := self.screen_size
|
||||
s := &self.screen_size
|
||||
s.updated = true
|
||||
s.HeightCells, s.WidthCells = parsed[0], parsed[1]
|
||||
s.HeightPx, s.WidthPx = parsed[2], parsed[3]
|
||||
s.update_cell_size()
|
||||
if self.OnResize != nil {
|
||||
return self.OnResize(old_size, self.screen_size)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
case 'I', 'O':
|
||||
if len(csi) == 1 {
|
||||
if self.OnFocusChange != nil {
|
||||
return self.OnFocusChange(csi == "I")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
case 'c':
|
||||
if strings.HasPrefix(csi, "?") {
|
||||
if self.OnCapabilitiesReceived != nil {
|
||||
if err = self.OnCapabilitiesReceived(self.TerminalCapabilities); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
case 'u':
|
||||
if strings.HasPrefix(csi, "?") {
|
||||
self.TerminalCapabilities.KeyboardProtocol = true
|
||||
self.TerminalCapabilities.KeyboardProtocolResponseReceived = true
|
||||
}
|
||||
case 'n':
|
||||
if strings.HasPrefix(csi, "?997;") {
|
||||
switch csi[len(csi)-2] {
|
||||
case '1':
|
||||
self.TerminalCapabilities.ColorPreference = DARK_COLOR_PREFERENCE
|
||||
case '2':
|
||||
self.TerminalCapabilities.ColorPreference = LIGHT_COLOR_PREFERENCE
|
||||
}
|
||||
self.TerminalCapabilities.ColorPreferenceResponseReceived = true
|
||||
if self.OnColorSchemeChange != nil {
|
||||
return self.OnColorSchemeChange(self.TerminalCapabilities.ColorPreference)
|
||||
}
|
||||
}
|
||||
}
|
||||
ke := KeyEventFromCSI(csi)
|
||||
if ke != nil {
|
||||
return self.handle_key_event(ke)
|
||||
}
|
||||
sz, err := self.ScreenSize()
|
||||
if err == nil {
|
||||
me := MouseEventFromCSI(csi, sz)
|
||||
if me != nil {
|
||||
return self.handle_mouse_event(me)
|
||||
}
|
||||
}
|
||||
if self.OnEscapeCode != nil {
|
||||
return self.OnEscapeCode(CSI, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func is_click(a, b *MouseEvent) bool {
|
||||
if a.Event_type != MOUSE_PRESS || b.Event_type != MOUSE_RELEASE {
|
||||
return false
|
||||
}
|
||||
x := a.Cell.X - b.Cell.X
|
||||
y := a.Cell.Y - b.Cell.Y
|
||||
return x*x+y*y <= 4
|
||||
|
||||
}
|
||||
|
||||
func (self *Loop) handle_mouse_event(ev *MouseEvent) error {
|
||||
if self.OnMouseEvent != nil {
|
||||
err := self.OnMouseEvent(ev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch ev.Event_type {
|
||||
case MOUSE_PRESS:
|
||||
self.pending_mouse_events.WriteAllAndDiscardOld(*ev)
|
||||
case MOUSE_RELEASE:
|
||||
self.pending_mouse_events.WriteAllAndDiscardOld(*ev)
|
||||
if self.pending_mouse_events.Len() > 1 {
|
||||
events := self.pending_mouse_events.ReadAll()
|
||||
if is_click(&events[len(events)-2], &events[len(events)-1]) {
|
||||
e := events[len(events)-1]
|
||||
e.Event_type = MOUSE_CLICK
|
||||
err = self.OnMouseEvent(&e)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) handle_key_event(ev *KeyEvent) error {
|
||||
if self.OnKeyEvent != nil {
|
||||
err := self.OnKeyEvent(ev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ev.Handled {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if ev.MatchesPressOrRepeat("ctrl+c") {
|
||||
ev.Handled = true
|
||||
return self.on_SIGINT()
|
||||
}
|
||||
if ev.MatchesPressOrRepeat("ctrl+z") {
|
||||
ev.Handled = true
|
||||
return self.on_SIGTSTP()
|
||||
}
|
||||
if ev.Text != "" && self.OnText != nil {
|
||||
return self.OnText(ev.Text, true, false)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) handle_dnd(data []byte) error {
|
||||
var payload []byte
|
||||
if idx := bytes.IndexByte(data, ';'); idx >= 0 {
|
||||
payload = data[idx+1:]
|
||||
data = data[:idx]
|
||||
}
|
||||
cmd := DndCommand{Payload: payload}
|
||||
for field := range bytes.SplitSeq(data, []byte{':'}) {
|
||||
if k, v, found := bytes.Cut(field, []byte{'='}); found && len(k) == 1 && len(v) > 0 {
|
||||
switch k[0] {
|
||||
case 't':
|
||||
cmd.Type = v[0]
|
||||
case 'm':
|
||||
cmd.Has_more = v[0] == '1'
|
||||
case 'o':
|
||||
if val, err := strconv.Atoi(utils.UnsafeBytesToString(v)); err == nil {
|
||||
cmd.Operation = val
|
||||
}
|
||||
case 'x':
|
||||
if val, err := strconv.Atoi(utils.UnsafeBytesToString(v)); err == nil {
|
||||
cmd.X = val
|
||||
}
|
||||
case 'y':
|
||||
if val, err := strconv.Atoi(utils.UnsafeBytesToString(v)); err == nil {
|
||||
cmd.Y = val
|
||||
}
|
||||
case 'X':
|
||||
if val, err := strconv.Atoi(utils.UnsafeBytesToString(v)); err == nil {
|
||||
cmd.Xp = val
|
||||
}
|
||||
case 'Y':
|
||||
if val, err := strconv.Atoi(utils.UnsafeBytesToString(v)); err == nil {
|
||||
cmd.Yp = val
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.dnd_chunking.active {
|
||||
self.dnd_chunking.metadata.Payload = cmd.Payload
|
||||
self.dnd_chunking.metadata.Has_more = cmd.Has_more
|
||||
self.dnd_chunking.active = cmd.Has_more
|
||||
return self.OnDnDData(self.dnd_chunking.metadata)
|
||||
}
|
||||
if cmd.Has_more {
|
||||
self.dnd_chunking.active = true
|
||||
self.dnd_chunking.metadata = cmd
|
||||
}
|
||||
return self.OnDnDData(cmd)
|
||||
}
|
||||
|
||||
func (self *Loop) handle_osc(raw []byte) error {
|
||||
if idx := bytes.IndexByte(raw, ';'); idx >= 2 {
|
||||
if code, err := strconv.ParseUint(utils.UnsafeBytesToString(raw[:idx]), 10, 0); err == nil {
|
||||
switch code {
|
||||
case uint64(kitty.DndCode):
|
||||
if self.OnDnDData != nil {
|
||||
return self.handle_dnd(raw[idx+1:])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.OnEscapeCode != nil {
|
||||
return self.OnEscapeCode(OSC, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) handle_dcs(raw []byte) error {
|
||||
if self.OnRCResponse != nil && bytes.HasPrefix(raw, utils.UnsafeStringToBytes("@kitty-cmd")) {
|
||||
return self.OnRCResponse(raw[len("@kitty-cmd"):])
|
||||
}
|
||||
if self.OnQueryResponse != nil && (bytes.HasPrefix(raw, utils.UnsafeStringToBytes("1+r")) || bytes.HasPrefix(raw, utils.UnsafeStringToBytes("0+r"))) {
|
||||
valid := raw[0] == '1'
|
||||
s := utils.NewSeparatorScanner(utils.UnsafeBytesToString(raw[3:]), ";")
|
||||
for s.Scan() {
|
||||
key, val, _ := strings.Cut(s.Text(), "=")
|
||||
if k, err := hex.DecodeString(key); err == nil {
|
||||
if bytes.HasPrefix(k, utils.UnsafeStringToBytes("kitty-query-")) {
|
||||
k = k[len("kitty-query-"):]
|
||||
if v, err := hex.DecodeString(val); err == nil {
|
||||
if err = self.OnQueryResponse(string(k), string(v), valid); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if self.OnEscapeCode != nil {
|
||||
return self.OnEscapeCode(DCS, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) handle_apc(raw []byte) error {
|
||||
if self.OnEscapeCode != nil {
|
||||
return self.OnEscapeCode(APC, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) handle_sos(raw []byte) error {
|
||||
if self.OnEscapeCode != nil {
|
||||
return self.OnEscapeCode(SOS, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) handle_pm(raw []byte) error {
|
||||
if self.OnEscapeCode != nil {
|
||||
return self.OnEscapeCode(PM, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) handle_rune(raw rune) error {
|
||||
if self.OnText != nil {
|
||||
return self.OnText(string(raw), false, self.escape_code_parser.InBracketedPaste())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) handle_end_of_bracketed_paste() error {
|
||||
if self.OnText != nil {
|
||||
return self.OnText("", false, false)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) on_signal(s unix.Signal) error {
|
||||
switch s {
|
||||
case unix.SIGINT:
|
||||
if self.OnSIGINT != nil {
|
||||
if handled, err := self.OnSIGINT(); handled {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return self.on_SIGINT()
|
||||
case unix.SIGPIPE:
|
||||
return self.on_SIGPIPE()
|
||||
case unix.SIGWINCH:
|
||||
return self.on_SIGWINCH()
|
||||
case unix.SIGTERM:
|
||||
if self.OnSIGTERM != nil {
|
||||
if handled, err := self.OnSIGTERM(); handled {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return self.on_SIGTERM()
|
||||
case unix.SIGTSTP:
|
||||
return self.on_SIGTSTP()
|
||||
case unix.SIGHUP:
|
||||
return self.on_SIGHUP()
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) on_SIGINT() error {
|
||||
self.death_signal = unix.SIGINT
|
||||
self.keep_going = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) on_SIGPIPE() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) on_SIGWINCH() error {
|
||||
self.update_screen_size()
|
||||
if self.seen_inband_resize {
|
||||
return nil
|
||||
}
|
||||
self.screen_size.updated = false
|
||||
if self.OnResize != nil {
|
||||
old_size := self.screen_size
|
||||
err := self.update_screen_size()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return self.OnResize(old_size, self.screen_size)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) on_SIGTERM() error {
|
||||
self.death_signal = unix.SIGTERM
|
||||
self.keep_going = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) on_SIGHUP() error {
|
||||
self.death_signal = unix.SIGHUP
|
||||
self.keep_going = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) run() (err error) {
|
||||
signal_channel := make(chan os.Signal, 256)
|
||||
handled_signals := []os.Signal{unix.SIGINT, unix.SIGTERM, unix.SIGTSTP, unix.SIGHUP, unix.SIGWINCH, unix.SIGPIPE}
|
||||
signal.Notify(signal_channel, handled_signals...)
|
||||
defer signal.Reset(handled_signals...)
|
||||
|
||||
controlling_term, err := tty.OpenControllingTerm(tty.SetRaw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.controlling_term = controlling_term
|
||||
defer func() {
|
||||
controlling_term.RestoreAndClose()
|
||||
self.controlling_term = nil
|
||||
}()
|
||||
|
||||
self.keep_going = true
|
||||
self.seen_inband_resize = false
|
||||
self.pending_mouse_events = utils.NewRingBuffer[MouseEvent](4)
|
||||
// tty_write_channel is buffered so there is no race between initial
|
||||
// queueing and startup of writer thread and also as a performance
|
||||
// optimization to avoid copying unnecessarily to pending_writes
|
||||
self.tty_write_channel = make(chan write_msg, 512)
|
||||
self.write_msg_id_counter = 0
|
||||
write_done_channel := make(chan IdType)
|
||||
self.wakeup_channel = make(chan byte, 256)
|
||||
self.panic_channel = make(chan error)
|
||||
self.pending_writes = make([]write_msg, 0, 256)
|
||||
err_channel := make(chan error, 8)
|
||||
self.death_signal = SIGNULL
|
||||
self.escape_code_parser.Reset()
|
||||
self.exit_code = 0
|
||||
self.atomic_update_active = false
|
||||
self.timers, self.timers_temp = make([]*timer, 0, 8), make([]*timer, 0, 8)
|
||||
no_timeout_channel := make(<-chan time.Time)
|
||||
finalizer := ""
|
||||
|
||||
var r_r, r_w, w_r, w_w *os.File
|
||||
var tty_reading_done_channel chan byte
|
||||
var tty_read_channel chan []byte
|
||||
var tty_leftover_read_channel chan []byte
|
||||
|
||||
start_tty_reader := func() (err error) {
|
||||
r_r, r_w, err = os.Pipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tty_read_channel = make(chan []byte)
|
||||
tty_reading_done_channel = make(chan byte)
|
||||
tty_leftover_read_channel = make(chan []byte, 1)
|
||||
go read_from_tty(r_r, controlling_term, tty_read_channel, err_channel, tty_reading_done_channel, tty_leftover_read_channel)
|
||||
return
|
||||
}
|
||||
err = start_tty_reader()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w_r, w_w, err = os.Pipe() // these are closed in the writer thread and the shutdown defer in this thread
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
self.QueueWriteString(self.terminal_options.SetStateEscapeCodes())
|
||||
needs_reset_escape_codes := true
|
||||
|
||||
shutdown_tty_reader := func() {
|
||||
// notify tty reader that we are shutting down
|
||||
if r_w != nil {
|
||||
r_w.Close()
|
||||
close(tty_reading_done_channel)
|
||||
r_w = nil
|
||||
tty_reading_done_channel = nil
|
||||
}
|
||||
}
|
||||
wait_for_tty_reader_to_quit := func() {
|
||||
// wait for tty reader to exit cleanly
|
||||
for range tty_read_channel {
|
||||
}
|
||||
select {
|
||||
case <-tty_leftover_read_channel:
|
||||
default:
|
||||
}
|
||||
if self.terminal_options.roundtrip_on_exit {
|
||||
// ensure that any terminal responses such as kitty keyboard events,
|
||||
// color scheme changes, in-band resize notifications, etc. do not
|
||||
// bleed into the shell.
|
||||
do_roundtrip_to_terminal(controlling_term, 2*time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
defer func() {
|
||||
shutdown_tty_reader()
|
||||
|
||||
if self.OnFinalize != nil {
|
||||
finalizer += self.OnFinalize()
|
||||
}
|
||||
if finalizer != "" {
|
||||
self.QueueWriteString(finalizer)
|
||||
}
|
||||
if needs_reset_escape_codes {
|
||||
self.ClearPointerShapes()
|
||||
self.QueueWriteString(self.terminal_options.ResetStateEscapeCodes())
|
||||
}
|
||||
// flush queued data and wait for it to be written for a timeout, then wait for writer to shutdown
|
||||
flush_writer(w_w, self.tty_write_channel, write_done_channel, self.pending_writes, 2*time.Second)
|
||||
self.pending_writes = nil
|
||||
self.tty_write_channel = nil
|
||||
wait_for_tty_reader_to_quit()
|
||||
}()
|
||||
|
||||
go write_to_tty(w_r, controlling_term, self.tty_write_channel, err_channel, write_done_channel)
|
||||
|
||||
if self.OnInitialize != nil {
|
||||
finalizer, err = self.OnInitialize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
self.SuspendAndRun = func(run func() error) (err error) {
|
||||
ps := self.ClearPointerShapes()
|
||||
write_id := self.QueueWriteString(self.terminal_options.ResetStateEscapeCodes())
|
||||
needs_reset_escape_codes = false
|
||||
if err = self.wait_for_write_to_complete(write_id, self.tty_write_channel, write_done_channel, 2*time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
shutdown_tty_reader()
|
||||
wait_for_tty_reader_to_quit()
|
||||
resume, err := controlling_term.Suspend()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = run(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = start_tty_reader(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = resume(); err != nil {
|
||||
return err
|
||||
}
|
||||
write_id = self.QueueWriteString(self.terminal_options.SetStateEscapeCodes())
|
||||
self.set_pointer_shapes(ps)
|
||||
needs_reset_escape_codes = true
|
||||
return self.wait_for_write_to_complete(write_id, self.tty_write_channel, write_done_channel, 2*time.Second)
|
||||
}
|
||||
|
||||
self.on_SIGTSTP = func() error {
|
||||
ps := self.ClearPointerShapes()
|
||||
write_id := self.QueueWriteString(self.terminal_options.ResetStateEscapeCodes())
|
||||
needs_reset_escape_codes = false
|
||||
err := self.wait_for_write_to_complete(write_id, self.tty_write_channel, write_done_channel, 2*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = controlling_term.SuspendAndRun(func() error {
|
||||
_ = unix.Kill(os.Getpid(), unix.SIGSTOP)
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
write_id = self.QueueWriteString(self.terminal_options.SetStateEscapeCodes())
|
||||
self.set_pointer_shapes(ps)
|
||||
needs_reset_escape_codes = true
|
||||
err = self.wait_for_write_to_complete(write_id, self.tty_write_channel, write_done_channel, 2*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if self.OnResumeFromStop != nil {
|
||||
return self.OnResumeFromStop()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for self.keep_going {
|
||||
self.flush_pending_writes(self.tty_write_channel)
|
||||
timeout_chan := no_timeout_channel
|
||||
if len(self.timers) > 0 {
|
||||
now := time.Now()
|
||||
err = self.dispatch_timers(now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var timeout time.Duration
|
||||
if len(self.timers) > 0 {
|
||||
timeout = max(0, self.timers[0].deadline.Sub(now))
|
||||
}
|
||||
timeout_chan = time.After(timeout)
|
||||
}
|
||||
select {
|
||||
case <-timeout_chan:
|
||||
case p := <-self.panic_channel:
|
||||
return p
|
||||
case <-self.wakeup_channel:
|
||||
for len(self.wakeup_channel) > 0 {
|
||||
<-self.wakeup_channel
|
||||
}
|
||||
if self.OnWakeup != nil {
|
||||
err = self.OnWakeup()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case msg_id := <-write_done_channel:
|
||||
self.flush_pending_writes(self.tty_write_channel)
|
||||
if self.OnWriteComplete != nil {
|
||||
err = self.OnWriteComplete(msg_id, msg_id < self.write_msg_id_counter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case rwerr := <-err_channel:
|
||||
return fmt.Errorf("Failed doing I/O with terminal: %w", rwerr)
|
||||
case s := <-signal_channel:
|
||||
err = self.on_signal(s.(unix.Signal))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case input_data, more := <-tty_read_channel:
|
||||
if !more {
|
||||
select {
|
||||
case rwerr := <-err_channel:
|
||||
return fmt.Errorf("Failed to read from terminal: %w", rwerr)
|
||||
default:
|
||||
return fmt.Errorf("Failed to read from terminal: %w", io.EOF)
|
||||
}
|
||||
}
|
||||
err := self.dispatch_input_data(input_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestZeroScreenSize(t *testing.T) {
|
||||
lp := Loop{}
|
||||
if err := lp.handle_csi([]byte("48;0;0;0;0t")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := lp.handle_csi([]byte("48;24;0;480;0t")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := lp.screen_size
|
||||
if s.WidthCells != 0 || s.CellWidth != 0 || s.HeightCells != 24 || s.CellHeight != 20 {
|
||||
t.Fatalf("unexpected screen size: %#v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedResizeReport(t *testing.T) {
|
||||
lp := Loop{}
|
||||
for _, csi := range []string{"t", "1t", "48t", "48;t", "8;24;80;0;0t", "48;-1;80;0;0t", "48;a;b;c;dt"} {
|
||||
if err := lp.handle_csi([]byte(csi)); err != nil {
|
||||
t.Fatalf("unexpected error for %#v: %s", csi, err)
|
||||
}
|
||||
if lp.seen_inband_resize {
|
||||
t.Fatalf("malformed resize report %#v was accepted", csi)
|
||||
}
|
||||
}
|
||||
if err := lp.handle_csi([]byte("48;24;80;480;800;1t")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := lp.screen_size
|
||||
if s.HeightCells != 24 || s.WidthCells != 80 || s.HeightPx != 480 || s.WidthPx != 800 {
|
||||
t.Fatalf("unexpected screen size: %#v", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
)
|
||||
|
||||
type KeyboardStateBits uint8
|
||||
|
||||
const (
|
||||
LEGACY_KEYS KeyboardStateBits = 0
|
||||
DISAMBIGUATE_KEYS = 1
|
||||
REPORT_KEY_EVENT_TYPES = 2
|
||||
REPORT_ALTERNATE_KEYS = 4
|
||||
REPORT_ALL_KEYS_AS_ESCAPE_CODES = 8
|
||||
REPORT_TEXT_WITH_KEYS = 16
|
||||
FULL_KEYBOARD_PROTOCOL = DISAMBIGUATE_KEYS | REPORT_ALTERNATE_KEYS | REPORT_ALL_KEYS_AS_ESCAPE_CODES | REPORT_TEXT_WITH_KEYS | REPORT_KEY_EVENT_TYPES
|
||||
NO_KEYBOARD_STATE_CHANGE = 32
|
||||
)
|
||||
|
||||
const (
|
||||
SAVE_CURSOR = "\0337"
|
||||
RESTORE_CURSOR = "\0338"
|
||||
SAVE_PRIVATE_MODE_VALUES = "\033[?s"
|
||||
RESTORE_PRIVATE_MODE_VALUES = "\033[?r"
|
||||
SAVE_COLORS = "\033[#P"
|
||||
RESTORE_COLORS = "\033[#Q"
|
||||
DECSACE_DEFAULT_REGION_SELECT = "\033[*x"
|
||||
CLEAR_SCREEN = "\033[H\033[2J"
|
||||
POP_KEY_FLAGS = "\033[<u"
|
||||
PUSH_KEY_FLAGS = "\033[>u"
|
||||
)
|
||||
|
||||
type CursorShapes uint
|
||||
|
||||
const (
|
||||
BLOCK_CURSOR CursorShapes = 1
|
||||
UNDERLINE_CURSOR CursorShapes = 3
|
||||
BAR_CURSOR CursorShapes = 5
|
||||
)
|
||||
|
||||
type Mode uint32
|
||||
|
||||
const private Mode = 1 << 31
|
||||
|
||||
const (
|
||||
LNM Mode = 20
|
||||
IRM Mode = 4
|
||||
DECKM Mode = 1 | private
|
||||
DECSCNM Mode = 5 | private
|
||||
DECOM Mode = 6 | private
|
||||
DECAWM Mode = 7 | private
|
||||
DECARM Mode = 8 | private
|
||||
DECTCEM Mode = 25 | private
|
||||
MOUSE_BUTTON_TRACKING Mode = 1000 | private
|
||||
MOUSE_MOTION_TRACKING Mode = 1002 | private
|
||||
MOUSE_MOVE_TRACKING Mode = 1003 | private
|
||||
FOCUS_TRACKING Mode = 1004 | private
|
||||
MOUSE_UTF8_MODE Mode = 1005 | private
|
||||
MOUSE_SGR_MODE Mode = 1006 | private
|
||||
MOUSE_URXVT_MODE Mode = 1015 | private
|
||||
MOUSE_SGR_PIXEL_MODE Mode = 1016 | private
|
||||
ALTERNATE_SCREEN Mode = 1049 | private
|
||||
BRACKETED_PASTE Mode = 2004 | private
|
||||
PENDING_UPDATE Mode = 2026 | private
|
||||
COLOR_SCHEME_CHANGE_NOTIFICATION Mode = 2031 | private
|
||||
INBAND_RESIZE_NOTIFICATION Mode = 2048 | private
|
||||
HANDLE_TERMIOS_SIGNALS Mode = kitty.HandleTermiosSignals | private
|
||||
)
|
||||
|
||||
func (self Mode) escape_code(which string) string {
|
||||
num := self
|
||||
priv := ""
|
||||
if num&private > 0 {
|
||||
priv = "?"
|
||||
num &^= private
|
||||
}
|
||||
return fmt.Sprintf("\033[%s%d%s", priv, uint32(num), which)
|
||||
}
|
||||
|
||||
func (self Mode) EscapeCodeToSet() string {
|
||||
return self.escape_code("h")
|
||||
}
|
||||
|
||||
func (self Mode) EscapeCodeToReset() string {
|
||||
return self.escape_code("l")
|
||||
}
|
||||
|
||||
type MouseTracking uint8
|
||||
|
||||
const (
|
||||
NO_MOUSE_TRACKING MouseTracking = iota
|
||||
BUTTONS_ONLY_MOUSE_TRACKING
|
||||
BUTTONS_AND_DRAG_MOUSE_TRACKING
|
||||
FULL_MOUSE_TRACKING
|
||||
)
|
||||
|
||||
type TerminalStateOptions struct {
|
||||
Alternate_screen, restore_colors bool
|
||||
mouse_tracking MouseTracking
|
||||
kitty_keyboard_mode KeyboardStateBits
|
||||
in_band_resize_notification bool
|
||||
focus_tracking bool
|
||||
color_scheme_change_notification bool
|
||||
// Set this to true to avoid doing a query response loop to the terminal at
|
||||
// exit. This loop is needed for most kittens to ensure that in-flight
|
||||
// responses such as in-band resize notifications, color queries, kitty
|
||||
// keyboard events, etc. are not leaked to the shell. For some special
|
||||
// purpose uses of the loop, this is not appropriate, hence this setting.
|
||||
roundtrip_on_exit bool
|
||||
}
|
||||
|
||||
func set_modes(sb *strings.Builder, modes ...Mode) {
|
||||
for _, m := range modes {
|
||||
sb.WriteString(m.EscapeCodeToSet())
|
||||
}
|
||||
}
|
||||
|
||||
func reset_modes(sb *strings.Builder, modes ...Mode) {
|
||||
for _, m := range modes {
|
||||
sb.WriteString(m.EscapeCodeToReset())
|
||||
}
|
||||
}
|
||||
|
||||
func (self *TerminalStateOptions) SetStateEscapeCodes() string {
|
||||
var sb strings.Builder
|
||||
sb.Grow(256)
|
||||
if self.Alternate_screen {
|
||||
sb.WriteString(SAVE_CURSOR)
|
||||
}
|
||||
sb.WriteString(SAVE_PRIVATE_MODE_VALUES)
|
||||
if self.restore_colors {
|
||||
sb.WriteString(SAVE_COLORS)
|
||||
}
|
||||
sb.WriteString(DECSACE_DEFAULT_REGION_SELECT)
|
||||
reset_modes(&sb,
|
||||
IRM, DECKM, DECSCNM, BRACKETED_PASTE,
|
||||
MOUSE_BUTTON_TRACKING, MOUSE_MOTION_TRACKING, MOUSE_MOVE_TRACKING, MOUSE_UTF8_MODE, MOUSE_SGR_MODE)
|
||||
set_modes(&sb, DECARM, DECAWM, DECTCEM)
|
||||
if self.focus_tracking {
|
||||
set_modes(&sb, FOCUS_TRACKING)
|
||||
}
|
||||
if self.in_band_resize_notification {
|
||||
set_modes(&sb, INBAND_RESIZE_NOTIFICATION)
|
||||
}
|
||||
if self.color_scheme_change_notification {
|
||||
set_modes(&sb, COLOR_SCHEME_CHANGE_NOTIFICATION)
|
||||
}
|
||||
if self.Alternate_screen {
|
||||
set_modes(&sb, ALTERNATE_SCREEN)
|
||||
sb.WriteString(CLEAR_SCREEN)
|
||||
}
|
||||
switch self.kitty_keyboard_mode {
|
||||
case LEGACY_KEYS:
|
||||
sb.WriteString("\033[>u")
|
||||
case NO_KEYBOARD_STATE_CHANGE:
|
||||
default:
|
||||
fmt.Fprintf(&sb, "\033[>%du", self.kitty_keyboard_mode)
|
||||
}
|
||||
if self.mouse_tracking != NO_MOUSE_TRACKING {
|
||||
sb.WriteString(MOUSE_SGR_PIXEL_MODE.EscapeCodeToSet())
|
||||
switch self.mouse_tracking {
|
||||
case BUTTONS_ONLY_MOUSE_TRACKING:
|
||||
sb.WriteString(MOUSE_BUTTON_TRACKING.EscapeCodeToSet())
|
||||
case BUTTONS_AND_DRAG_MOUSE_TRACKING:
|
||||
sb.WriteString(MOUSE_MOTION_TRACKING.EscapeCodeToSet())
|
||||
case FULL_MOUSE_TRACKING:
|
||||
sb.WriteString(MOUSE_MOVE_TRACKING.EscapeCodeToSet())
|
||||
}
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (self *TerminalStateOptions) ResetStateEscapeCodes() string {
|
||||
var sb strings.Builder
|
||||
sb.Grow(64)
|
||||
if self.kitty_keyboard_mode != NO_KEYBOARD_STATE_CHANGE {
|
||||
sb.WriteString("\033[<u")
|
||||
}
|
||||
if self.Alternate_screen {
|
||||
sb.WriteString(ALTERNATE_SCREEN.EscapeCodeToReset())
|
||||
} else {
|
||||
sb.WriteString(SAVE_CURSOR)
|
||||
}
|
||||
// Explictly turn off this mode as there are some terminals that dont
|
||||
// support restoring all modes and people tend to use the show-key kitten
|
||||
// in other terminals. Since I do want to encourage adoption of the kitty
|
||||
// keyboard protocol, the extra bytes are worth it in this case.
|
||||
if self.in_band_resize_notification {
|
||||
reset_modes(&sb, INBAND_RESIZE_NOTIFICATION)
|
||||
}
|
||||
sb.WriteString(RESTORE_PRIVATE_MODE_VALUES)
|
||||
if self.restore_colors {
|
||||
sb.WriteString(RESTORE_COLORS)
|
||||
}
|
||||
sb.WriteString(RESTORE_CURSOR)
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func CursorShape(shape CursorShapes, blink bool) string {
|
||||
if !blink {
|
||||
shape += 1
|
||||
}
|
||||
return fmt.Sprintf("\x1b[%d q", shape)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
type timer struct {
|
||||
interval time.Duration
|
||||
deadline time.Time
|
||||
repeats bool
|
||||
id IdType
|
||||
callback TimerCallback
|
||||
}
|
||||
|
||||
func (self *timer) update_deadline(now time.Time) {
|
||||
self.deadline = now.Add(self.interval)
|
||||
}
|
||||
|
||||
func (self timer) String() string {
|
||||
return fmt.Sprintf("Timer(id=%d, callback=%s, deadline=%s, repeats=%v)", self.id, utils.FunctionName(self.callback), time.Until(self.deadline), self.repeats)
|
||||
}
|
||||
|
||||
func (self *Loop) add_timer(interval time.Duration, repeats bool, callback TimerCallback) (IdType, error) {
|
||||
if self.timers == nil {
|
||||
return 0, fmt.Errorf("Cannot add timers before starting the run loop, add them in OnInitialize instead")
|
||||
}
|
||||
self.timer_id_counter++
|
||||
t := timer{interval: interval, repeats: repeats, callback: callback, id: self.timer_id_counter}
|
||||
t.update_deadline(time.Now())
|
||||
self.timers = append(self.timers, &t)
|
||||
self.sort_timers()
|
||||
return t.id, nil
|
||||
}
|
||||
|
||||
func (self *Loop) remove_timer(id IdType) bool {
|
||||
if self.timers == nil {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(self.timers); i++ {
|
||||
if self.timers[i].id == id {
|
||||
self.timers = append(self.timers[:i], self.timers[i+1:]...)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Loop) dispatch_timers(now time.Time) error {
|
||||
self.timers_temp = self.timers_temp[:0]
|
||||
self.timers, self.timers_temp = self.timers_temp, self.timers
|
||||
dispatched := false
|
||||
for _, t := range self.timers_temp {
|
||||
if now.After(t.deadline) {
|
||||
dispatched = true
|
||||
err := t.callback(t.id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t.repeats {
|
||||
t.update_deadline(now)
|
||||
self.timers = append(self.timers, t)
|
||||
}
|
||||
} else {
|
||||
self.timers = append(self.timers, t)
|
||||
}
|
||||
}
|
||||
if dispatched {
|
||||
self.sort_timers() // needed because a timer callback could have added a new timer
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self *Loop) sort_timers() {
|
||||
slices.SortStableFunc(self.timers, func(a, b *timer) int { return a.deadline.Compare(b.deadline) })
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package loop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/go-parallel"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
type write_msg struct {
|
||||
id IdType
|
||||
bytes []byte
|
||||
str string
|
||||
}
|
||||
|
||||
func (self *write_msg) String() string {
|
||||
return fmt.Sprintf("write_msg{%v %#v %#v}", self.id, string(self.bytes), self.str)
|
||||
}
|
||||
|
||||
func write_ignoring_temporary_errors(f *tty.Term, buf []byte) (int, error) {
|
||||
n, err := f.Write(buf)
|
||||
if err != nil {
|
||||
if is_temporary_error(err) {
|
||||
err = nil
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func writestring_ignoring_temporary_errors(f *tty.Term, buf string) (int, error) {
|
||||
n, err := f.WriteString(buf)
|
||||
if err != nil {
|
||||
if is_temporary_error(err) {
|
||||
err = nil
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Remove the first n entries from pending_writes. This must not copy the
|
||||
// remaining entries, as when there are lots of small writes queued up (for
|
||||
// example when redrawing the screen in response to a flood of mouse events) that
|
||||
// becomes quadratic, see https://github.com/kovidgoyal/kitty/issues/10634
|
||||
func (self *Loop) discard_sent_pending_writes(n int) {
|
||||
clear(self.pending_writes[:n])
|
||||
if n >= len(self.pending_writes) {
|
||||
// reuse the underlying array
|
||||
self.pending_writes = self.pending_writes[:0]
|
||||
} else {
|
||||
self.pending_writes = self.pending_writes[n:]
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) flush_pending_writes(tty_write_channel chan<- write_msg) (num_sent int) {
|
||||
defer func() {
|
||||
if num_sent > 0 {
|
||||
self.discard_sent_pending_writes(num_sent)
|
||||
}
|
||||
}()
|
||||
for len(self.pending_writes) > num_sent {
|
||||
select {
|
||||
case tty_write_channel <- self.pending_writes[num_sent]:
|
||||
num_sent++
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Loop) wait_for_write_to_complete(sentinel IdType, tty_write_channel chan<- write_msg, write_done_channel <-chan IdType, timeout time.Duration) error {
|
||||
num_sent := 0
|
||||
defer func() {
|
||||
if num_sent > 0 {
|
||||
self.discard_sent_pending_writes(num_sent)
|
||||
}
|
||||
}()
|
||||
|
||||
end_time := time.Now().Add(timeout)
|
||||
for num_sent < len(self.pending_writes) {
|
||||
timeout = time.Until(end_time)
|
||||
if timeout <= 0 {
|
||||
return os.ErrDeadlineExceeded
|
||||
}
|
||||
select {
|
||||
case tty_write_channel <- self.pending_writes[num_sent]:
|
||||
num_sent++
|
||||
case write_id, more := <-write_done_channel:
|
||||
if self.OnWriteComplete != nil {
|
||||
err := self.OnWriteComplete(write_id, write_id < self.write_msg_id_counter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if write_id == sentinel {
|
||||
return nil
|
||||
}
|
||||
if !more {
|
||||
return fmt.Errorf("The write_done_channel was unexpectedly closed")
|
||||
}
|
||||
case <-time.After(timeout):
|
||||
return os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
for {
|
||||
timeout = time.Until(end_time)
|
||||
if timeout <= 0 {
|
||||
return os.ErrDeadlineExceeded
|
||||
}
|
||||
select {
|
||||
case write_id, more := <-write_done_channel:
|
||||
if self.OnWriteComplete != nil {
|
||||
err := self.OnWriteComplete(write_id, write_id < self.write_msg_id_counter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if write_id == sentinel {
|
||||
return nil
|
||||
}
|
||||
if !more {
|
||||
return fmt.Errorf("The write_done_channel was unexpectedly closed")
|
||||
}
|
||||
case <-time.After(timeout):
|
||||
return os.ErrDeadlineExceeded
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Loop) add_write_to_pending_queue(data write_msg) {
|
||||
if len(self.pending_writes) > 0 || self.tty_write_channel == nil {
|
||||
self.pending_writes = append(self.pending_writes, data)
|
||||
} else {
|
||||
select {
|
||||
case self.tty_write_channel <- data:
|
||||
default:
|
||||
self.pending_writes = append(self.pending_writes, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self write_msg) is_empty() bool {
|
||||
if self.bytes == nil {
|
||||
return self.str == ""
|
||||
}
|
||||
return len(self.bytes) == 0
|
||||
}
|
||||
|
||||
func (self *write_msg) write(f *tty.Term) (err error) {
|
||||
n := 0
|
||||
if self.bytes == nil {
|
||||
n, err = writestring_ignoring_temporary_errors(f, self.str)
|
||||
} else {
|
||||
n, err = write_ignoring_temporary_errors(f, self.bytes)
|
||||
}
|
||||
if n > 0 {
|
||||
if self.bytes == nil {
|
||||
self.str = self.str[n:]
|
||||
} else {
|
||||
self.bytes = self.bytes[n:]
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func write_to_tty(
|
||||
pipe_r *os.File, term *tty.Term,
|
||||
job_channel <-chan write_msg, err_channel chan<- error, write_done_channel chan<- IdType,
|
||||
) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
err_channel <- parallel.Format_stacktrace_on_panic(r, 1)
|
||||
}
|
||||
}()
|
||||
keep_going := true
|
||||
defer func() {
|
||||
pipe_r.Close()
|
||||
close(write_done_channel)
|
||||
}()
|
||||
selector := utils.CreateSelect(2)
|
||||
pipe_fd := int(pipe_r.Fd())
|
||||
tty_fd := term.Fd()
|
||||
selector.RegisterRead(pipe_fd)
|
||||
selector.RegisterWrite(tty_fd)
|
||||
|
||||
wait_for_write_available := func() {
|
||||
for {
|
||||
n, err := selector.WaitForever()
|
||||
if err != nil && err != unix.EINTR {
|
||||
err_channel <- err
|
||||
keep_going = false
|
||||
return
|
||||
}
|
||||
if n > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if selector.IsReadyToRead(pipe_fd) {
|
||||
keep_going = false
|
||||
}
|
||||
}
|
||||
|
||||
write_data := func(msg write_msg) {
|
||||
for !msg.is_empty() {
|
||||
wait_for_write_available()
|
||||
if !keep_going {
|
||||
return
|
||||
}
|
||||
if err := msg.write(term); err != nil {
|
||||
err_channel <- err
|
||||
keep_going = false
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
data, more := <-job_channel
|
||||
if !more {
|
||||
keep_going = false
|
||||
break
|
||||
}
|
||||
write_data(data)
|
||||
if keep_going {
|
||||
write_done_channel <- data.id
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func flush_writer(pipe_w *os.File, tty_write_channel chan<- write_msg, write_done_channel <-chan IdType, pending_writes []write_msg, timeout time.Duration) {
|
||||
writer_quit := false
|
||||
defer func() {
|
||||
if tty_write_channel != nil {
|
||||
close(tty_write_channel)
|
||||
tty_write_channel = nil
|
||||
}
|
||||
pipe_w.Close()
|
||||
if !writer_quit {
|
||||
for {
|
||||
_, more := <-write_done_channel
|
||||
if !more {
|
||||
writer_quit = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
deadline := time.Now().Add(timeout)
|
||||
for len(pending_writes) > 0 && !writer_quit {
|
||||
timeout = time.Until(deadline)
|
||||
if timeout <= 0 {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-time.After(timeout):
|
||||
return
|
||||
case _, more := <-write_done_channel:
|
||||
if !more {
|
||||
writer_quit = true
|
||||
}
|
||||
case tty_write_channel <- pending_writes[0]:
|
||||
pending_writes = pending_writes[1:]
|
||||
}
|
||||
}
|
||||
close(tty_write_channel)
|
||||
tty_write_channel = nil
|
||||
timeout = time.Until(deadline)
|
||||
if timeout <= 0 {
|
||||
return
|
||||
}
|
||||
for !writer_quit {
|
||||
select {
|
||||
case _, more := <-write_done_channel:
|
||||
if !more {
|
||||
writer_quit = true
|
||||
}
|
||||
case <-time.After(timeout):
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type LinePos interface {
|
||||
LessThan(other LinePos) bool
|
||||
Equal(other LinePos) bool
|
||||
MinX() int
|
||||
MaxX() int
|
||||
}
|
||||
|
||||
type SelectionBoundary struct {
|
||||
line LinePos
|
||||
x int
|
||||
in_first_half_of_cell bool
|
||||
}
|
||||
|
||||
func (self *SelectionBoundary) LessThan(other *SelectionBoundary) bool {
|
||||
if self.line.LessThan(other.line) {
|
||||
return true
|
||||
}
|
||||
if !self.line.Equal(other.line) {
|
||||
return false
|
||||
}
|
||||
if self.x == other.x {
|
||||
return !self.in_first_half_of_cell && other.in_first_half_of_cell
|
||||
}
|
||||
return self.x < other.x
|
||||
}
|
||||
|
||||
func (self *SelectionBoundary) Equal(other SelectionBoundary) bool {
|
||||
if self.x != other.x || self.in_first_half_of_cell != other.in_first_half_of_cell {
|
||||
return false
|
||||
}
|
||||
if self.line == nil {
|
||||
return other.line == nil
|
||||
}
|
||||
return self.line.Equal(other.line)
|
||||
}
|
||||
|
||||
type MouseSelection struct {
|
||||
start, end SelectionBoundary
|
||||
is_active bool
|
||||
min_y, max_y int
|
||||
cell_width, cell_height int
|
||||
drag_scroll struct {
|
||||
timer_id loop.IdType
|
||||
pixel_gap int
|
||||
mouse_event loop.MouseEvent
|
||||
}
|
||||
}
|
||||
|
||||
func (self *MouseSelection) IsEmpty() bool { return self.start.Equal(self.end) }
|
||||
func (self *MouseSelection) IsActive() bool { return self.is_active }
|
||||
func (self *MouseSelection) Finish() { self.is_active = false }
|
||||
func (self *MouseSelection) Clear() { *self = MouseSelection{} }
|
||||
|
||||
func (ms *MouseSelection) StartNewSelection(ev *loop.MouseEvent, line LinePos, min_y, max_y, cell_width, cell_height int) {
|
||||
*ms = MouseSelection{cell_width: cell_width, cell_height: cell_height, min_y: min_y, max_y: max_y}
|
||||
ms.start.line = line
|
||||
ms.start.x = max(line.MinX(), min(ev.Cell.X, line.MaxX()))
|
||||
cell_start := cell_width * ev.Cell.X
|
||||
ms.start.in_first_half_of_cell = ev.Pixel.X <= cell_start+cell_width/2
|
||||
ms.end = ms.start
|
||||
ms.is_active = true
|
||||
}
|
||||
|
||||
// Update the end of the selection, returning true if it changed
|
||||
func (ms *MouseSelection) Update(ev *loop.MouseEvent, line LinePos) (changed bool) {
|
||||
ms.drag_scroll.timer_id = 0
|
||||
if ms.is_active {
|
||||
prev := ms.end
|
||||
ms.end.x = max(line.MinX(), min(ev.Cell.X, line.MaxX()))
|
||||
cell_start := ms.cell_width * ms.end.x
|
||||
ms.end.in_first_half_of_cell = ev.Pixel.X <= cell_start+ms.cell_width/2
|
||||
ms.end.line = line
|
||||
changed = !prev.Equal(ms.end)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (ms *MouseSelection) LineBounds(line_pos LinePos) (start_x, end_x int) {
|
||||
if ms.IsEmpty() {
|
||||
return -1, -1
|
||||
}
|
||||
a, b := &ms.start, &ms.end
|
||||
if b.LessThan(a) {
|
||||
a, b = b, a
|
||||
}
|
||||
|
||||
adjust_end := func(x int, b *SelectionBoundary) (int, int) {
|
||||
if b.in_first_half_of_cell {
|
||||
if b.x > x {
|
||||
return x, b.x - 1
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
return x, b.x
|
||||
}
|
||||
|
||||
adjust_start := func(a *SelectionBoundary, x int) (int, int) {
|
||||
if a.in_first_half_of_cell {
|
||||
return a.x, x
|
||||
}
|
||||
if x > a.x {
|
||||
return a.x + 1, x
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
adjust_both := func(a, b *SelectionBoundary) (int, int) {
|
||||
if a.in_first_half_of_cell {
|
||||
return adjust_end(a.x, b)
|
||||
} else {
|
||||
if b.in_first_half_of_cell {
|
||||
s, e := a.x+1, b.x-1
|
||||
if e <= s {
|
||||
return -1, -1
|
||||
}
|
||||
return s, e
|
||||
} else {
|
||||
return adjust_start(a, b.x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if a.line.LessThan(line_pos) {
|
||||
if line_pos.LessThan(b.line) {
|
||||
return line_pos.MinX(), line_pos.MaxX()
|
||||
} else if b.line.Equal(line_pos) {
|
||||
return adjust_end(line_pos.MinX(), b)
|
||||
}
|
||||
} else if a.line.Equal(line_pos) {
|
||||
if line_pos.LessThan(b.line) {
|
||||
return adjust_start(a, line_pos.MaxX())
|
||||
} else if b.line.Equal(line_pos) {
|
||||
return adjust_both(a, b)
|
||||
}
|
||||
}
|
||||
return -1, -1
|
||||
}
|
||||
|
||||
func FormatPartOfLine(sgr string, start_x, end_x, y int) string { // uses zero based indices
|
||||
// DECCARA used to set formatting in specified region using zero based indexing
|
||||
return fmt.Sprintf("\x1b[%d;%d;%d;%d;%s$r", y+1, start_x+1, y+1, end_x+1, sgr)
|
||||
}
|
||||
|
||||
func (ms *MouseSelection) LineFormatSuffix(line_pos LinePos, sgr string, y int) string {
|
||||
s, e := ms.LineBounds(line_pos)
|
||||
if s > -1 {
|
||||
return FormatPartOfLine(sgr, s, e, y)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (ms *MouseSelection) StartLine() LinePos {
|
||||
return ms.start.line
|
||||
}
|
||||
|
||||
func (ms *MouseSelection) EndLine() LinePos {
|
||||
return ms.end.line
|
||||
}
|
||||
|
||||
func (ms *MouseSelection) OutOfVerticalBounds(ev *loop.MouseEvent) bool {
|
||||
return ev.Pixel.Y < ms.min_y*ms.cell_height || ev.Pixel.Y > (ms.max_y+1)*ms.cell_height
|
||||
}
|
||||
|
||||
func (ms *MouseSelection) DragScrollTick(timer_id loop.IdType, lp *loop.Loop, callback loop.TimerCallback, do_scroll func(int, *loop.MouseEvent) error) error {
|
||||
if !ms.is_active || ms.drag_scroll.timer_id != timer_id || ms.drag_scroll.pixel_gap == 0 {
|
||||
return nil
|
||||
}
|
||||
amt := 1
|
||||
if ms.drag_scroll.pixel_gap < 0 {
|
||||
amt *= -1
|
||||
}
|
||||
err := do_scroll(amt, &ms.drag_scroll.mouse_event)
|
||||
if err == nil {
|
||||
ms.drag_scroll.timer_id, _ = lp.AddTimer(50*time.Millisecond, false, callback)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (ms *MouseSelection) DragScroll(ev *loop.MouseEvent, lp *loop.Loop, callback loop.TimerCallback) {
|
||||
if !ms.is_active {
|
||||
return
|
||||
}
|
||||
upper := ms.min_y * ms.cell_height
|
||||
lower := (ms.max_y + 1) * ms.cell_height
|
||||
if ev.Pixel.Y < upper {
|
||||
ms.drag_scroll.pixel_gap = ev.Pixel.Y - upper
|
||||
} else if ev.Pixel.Y > lower {
|
||||
ms.drag_scroll.pixel_gap = ev.Pixel.Y - lower
|
||||
}
|
||||
if ms.drag_scroll.timer_id == 0 && ms.drag_scroll.pixel_gap != 0 {
|
||||
ms.drag_scroll.timer_id, _ = lp.AddTimer(50*time.Millisecond, false, callback)
|
||||
}
|
||||
ms.drag_scroll.mouse_event = *ev
|
||||
}
|
||||
|
||||
type Point struct {
|
||||
X, Y int
|
||||
}
|
||||
|
||||
func (p Point) Sub(other Point) Point {
|
||||
return Point{X: p.X - other.X, Y: p.Y - other.Y}
|
||||
}
|
||||
|
||||
type CellRegion struct {
|
||||
TopLeft, BottomRight Point
|
||||
Id string
|
||||
OnClick []func(id string) error // simple left click ignoring modifiers
|
||||
OnClickEvent func(id string, ev *loop.MouseEvent, cell_offset Point) error // any click event
|
||||
PointerShape loop.PointerShape
|
||||
HoverStyle string // set to "default" for the global hover style
|
||||
}
|
||||
|
||||
func (c CellRegion) Contains(x, y int) bool { // 0-based
|
||||
if c.TopLeft.Y > y || c.BottomRight.Y < y {
|
||||
return false
|
||||
}
|
||||
return (y > c.TopLeft.Y || (y == c.TopLeft.Y && x >= c.TopLeft.X)) && (y < c.BottomRight.Y || (y == c.BottomRight.Y && x <= c.BottomRight.X))
|
||||
}
|
||||
|
||||
type MouseState struct {
|
||||
Cell, Pixel Point
|
||||
Pressed struct{ Left, Right, Middle, Fourth, Fifth, Sixth, Seventh bool }
|
||||
|
||||
regions []*CellRegion
|
||||
region_id_map map[string][]*CellRegion
|
||||
region_line_map map[int][]*CellRegion
|
||||
hovered_ids *utils.Set[string]
|
||||
default_url_style struct {
|
||||
value string
|
||||
loaded bool
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MouseState) add_region(cr CellRegion) *CellRegion {
|
||||
m.regions = append(m.regions, &cr)
|
||||
if m.region_id_map == nil {
|
||||
m.region_id_map = make(map[string][]*CellRegion)
|
||||
m.region_line_map = make(map[int][]*CellRegion)
|
||||
}
|
||||
m.region_id_map[cr.Id] = append(m.region_id_map[cr.Id], &cr)
|
||||
for y := cr.TopLeft.Y; y <= cr.BottomRight.Y; y++ {
|
||||
m.region_line_map[y] = append(m.region_line_map[y], &cr)
|
||||
}
|
||||
return &cr
|
||||
}
|
||||
|
||||
func (m *MouseState) AddCellRegion(id string, start_x, start_y, end_x, end_y int, on_click ...func(id string) error) *CellRegion {
|
||||
return m.add_region(CellRegion{
|
||||
TopLeft: Point{start_x, start_y}, BottomRight: Point{end_x, end_y}, Id: id, OnClick: on_click, PointerShape: loop.POINTER_POINTER, HoverStyle: "default"})
|
||||
}
|
||||
|
||||
func (m *MouseState) ClearCellRegions() {
|
||||
m.regions = nil
|
||||
m.region_id_map = nil
|
||||
m.hovered_ids = nil
|
||||
m.region_line_map = nil
|
||||
}
|
||||
|
||||
func (m *MouseState) UpdateHoveredIds() (changed bool) {
|
||||
h := utils.NewSet[string]()
|
||||
for _, r := range m.region_line_map[m.Cell.Y] {
|
||||
if r.Contains(m.Cell.X, m.Cell.Y) {
|
||||
h.Add(r.Id)
|
||||
}
|
||||
}
|
||||
changed = !h.Equal(m.hovered_ids)
|
||||
m.hovered_ids = h
|
||||
return
|
||||
}
|
||||
|
||||
func (m *MouseState) ApplyHoverStyles(lp *loop.Loop, style ...string) {
|
||||
if m.hovered_ids == nil || m.hovered_ids.Len() == 0 {
|
||||
lp.ClearPointerShapes()
|
||||
return
|
||||
}
|
||||
hs := ""
|
||||
if len(style) == 0 {
|
||||
if !m.default_url_style.loaded {
|
||||
m.default_url_style.loaded = true
|
||||
color, style := kitty.DefaultUrlColor, kitty.DefaultUrlStyle
|
||||
line_handler := func(key, val string) error {
|
||||
switch key {
|
||||
case "url_color":
|
||||
color = val
|
||||
case "url_style":
|
||||
style = val
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config.ReadKittyConfig(line_handler)
|
||||
if style != "none" && style != "" {
|
||||
m.default_url_style.value = fmt.Sprintf("u=%s uc=%s", style, color)
|
||||
}
|
||||
}
|
||||
hs = m.default_url_style.value
|
||||
} else {
|
||||
hs = style[0]
|
||||
}
|
||||
is_hovered := false
|
||||
ps := loop.DEFAULT_POINTER
|
||||
for id := range m.hovered_ids.Iterable() {
|
||||
for _, r := range m.region_id_map[id] {
|
||||
if r.HoverStyle != "" {
|
||||
s := strings.Replace(r.HoverStyle, "default", hs, 1)
|
||||
lp.StyleRegion(s, r.TopLeft.X, r.TopLeft.Y, r.BottomRight.X, r.BottomRight.Y)
|
||||
}
|
||||
is_hovered = true
|
||||
ps = r.PointerShape
|
||||
}
|
||||
}
|
||||
if is_hovered {
|
||||
if s, has := lp.CurrentPointerShape(); !has || s != ps {
|
||||
lp.PushPointerShape(ps)
|
||||
}
|
||||
} else {
|
||||
lp.ClearPointerShapes()
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MouseState) DispatchEventToHoveredRegions(ev *loop.MouseEvent) error {
|
||||
if ev.Event_type != loop.MOUSE_CLICK {
|
||||
return nil
|
||||
}
|
||||
is_simple_click := ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0
|
||||
seen := utils.NewSet[string]()
|
||||
for id := range m.hovered_ids.Iterable() {
|
||||
for _, r := range m.region_id_map[id] {
|
||||
if seen.Has(r.Id) {
|
||||
continue
|
||||
}
|
||||
seen.Add(r.Id)
|
||||
if is_simple_click {
|
||||
for _, f := range r.OnClick {
|
||||
if err := f(r.Id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.OnClickEvent != nil {
|
||||
if err := r.OnClickEvent(r.Id, ev, m.Cell.Sub(r.TopLeft)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MouseState) ClickHoveredRegions() error {
|
||||
seen := utils.NewSet[string]()
|
||||
for id := range m.hovered_ids.Iterable() {
|
||||
for _, r := range m.region_id_map[id] {
|
||||
if seen.Has(r.Id) {
|
||||
continue
|
||||
}
|
||||
seen.Add(r.Id)
|
||||
for _, f := range r.OnClick {
|
||||
if err := f(r.Id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MouseState) UpdateState(ev *loop.MouseEvent) (hovered_ids_changed bool) {
|
||||
m.Cell = ev.Cell
|
||||
m.Pixel = ev.Pixel
|
||||
if ev.Event_type == loop.MOUSE_PRESS || ev.Event_type == loop.MOUSE_RELEASE {
|
||||
pressed := ev.Event_type == loop.MOUSE_PRESS
|
||||
if ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
|
||||
m.Pressed.Left = pressed
|
||||
}
|
||||
if ev.Buttons&loop.RIGHT_MOUSE_BUTTON != 0 {
|
||||
m.Pressed.Right = pressed
|
||||
}
|
||||
if ev.Buttons&loop.MIDDLE_MOUSE_BUTTON != 0 {
|
||||
m.Pressed.Middle = pressed
|
||||
}
|
||||
if ev.Buttons&loop.FOURTH_MOUSE_BUTTON != 0 {
|
||||
m.Pressed.Fourth = pressed
|
||||
}
|
||||
if ev.Buttons&loop.FIFTH_MOUSE_BUTTON != 0 {
|
||||
m.Pressed.Fifth = pressed
|
||||
}
|
||||
if ev.Buttons&loop.SIXTH_MOUSE_BUTTON != 0 {
|
||||
m.Pressed.Sixth = pressed
|
||||
}
|
||||
if ev.Buttons&loop.SEVENTH_MOUSE_BUTTON != 0 {
|
||||
m.Pressed.Seventh = pressed
|
||||
}
|
||||
}
|
||||
return m.UpdateHoveredIds()
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
type KilledBySignal struct {
|
||||
Msg string
|
||||
SignalName string
|
||||
}
|
||||
|
||||
func (self *KilledBySignal) Error() string { return self.Msg }
|
||||
|
||||
var Canceled = errors.New("Canceled by user")
|
||||
|
||||
const password_symbol = "🔒"
|
||||
const blink_interval = 500 * time.Millisecond
|
||||
|
||||
func ReadPassword(prompt string, kill_if_signaled bool) (password string, err error) {
|
||||
lp, err := loop.New(loop.NoAlternateScreen, loop.NoRestoreColors, loop.FullKeyboardProtocol)
|
||||
shadow := ""
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
capspress_was_locked := false
|
||||
has_caps_lock := false
|
||||
lock_visible := true
|
||||
|
||||
redraw_prompt := func() {
|
||||
lp.QueueWriteString("\r")
|
||||
lp.ClearToEndOfLine()
|
||||
if has_caps_lock {
|
||||
lp.QueueWriteString("\x1b[31m[CapsLock on!]\x1b[39m ")
|
||||
}
|
||||
symbol := password_symbol
|
||||
if !lock_visible {
|
||||
symbol = strings.Repeat(" ", wcswidth.Stringwidth(password_symbol))
|
||||
}
|
||||
lp.QueueWriteString(prompt + shadow + symbol)
|
||||
}
|
||||
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
lp.SetCursorVisible(false)
|
||||
redraw_prompt()
|
||||
if _, err := lp.AddTimer(blink_interval, true, func(loop.IdType) error {
|
||||
lock_visible = !lock_visible
|
||||
redraw_prompt()
|
||||
return nil
|
||||
}); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
lp.OnFinalize = func() string {
|
||||
lp.SetCursorVisible(true)
|
||||
lp.SetCursorShape(loop.BLOCK_CURSOR, true)
|
||||
return "\r\n"
|
||||
}
|
||||
|
||||
lp.OnText = func(text string, from_key_event bool, in_bracketed_paste bool) error {
|
||||
old_width := wcswidth.Stringwidth(password)
|
||||
password += text
|
||||
new_width := wcswidth.Stringwidth(password)
|
||||
if new_width > old_width {
|
||||
shadow += strings.Repeat("*", new_width-old_width)
|
||||
}
|
||||
redraw_prompt()
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnKeyEvent = func(event *loop.KeyEvent) error {
|
||||
has_caps := false
|
||||
if strings.ToLower(event.Key) == "caps_lock" {
|
||||
if event.Type == loop.RELEASE {
|
||||
has_caps = !capspress_was_locked
|
||||
capspress_was_locked = false
|
||||
} else {
|
||||
capspress_was_locked = event.HasCapsLock()
|
||||
has_caps = true
|
||||
}
|
||||
} else {
|
||||
has_caps = event.HasCapsLock()
|
||||
}
|
||||
if has_caps_lock != has_caps {
|
||||
has_caps_lock = has_caps
|
||||
redraw_prompt()
|
||||
}
|
||||
if event.MatchesPressOrRepeat("backspace") || event.MatchesPressOrRepeat("delete") {
|
||||
event.Handled = true
|
||||
if len(password) > 0 {
|
||||
old_width := wcswidth.Stringwidth(password)
|
||||
password = password[:len(password)-1]
|
||||
new_width := wcswidth.Stringwidth(password)
|
||||
delta := old_width - new_width
|
||||
if delta > 0 {
|
||||
if delta > len(shadow) {
|
||||
delta = len(shadow)
|
||||
}
|
||||
shadow = shadow[:len(shadow)-delta]
|
||||
}
|
||||
redraw_prompt()
|
||||
} else {
|
||||
lp.Beep()
|
||||
}
|
||||
}
|
||||
if event.MatchesPressOrRepeat("enter") || event.MatchesPressOrRepeat("return") {
|
||||
event.Handled = true
|
||||
if password == "" {
|
||||
lp.Quit(1)
|
||||
} else {
|
||||
lp.Quit(0)
|
||||
}
|
||||
}
|
||||
if event.MatchesPressOrRepeat("esc") {
|
||||
event.Handled = true
|
||||
lp.Quit(1)
|
||||
return Canceled
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
lp.OnResumeFromStop = func() error {
|
||||
redraw_prompt()
|
||||
return nil
|
||||
}
|
||||
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ds := lp.DeathSignalName()
|
||||
if ds != "" {
|
||||
if kill_if_signaled {
|
||||
lp.KillIfSignalled()
|
||||
return
|
||||
}
|
||||
return "", &KilledBySignal{Msg: fmt.Sprint("Killed by signal: ", ds), SignalName: ds}
|
||||
}
|
||||
if lp.ExitCode() != 0 {
|
||||
password = ""
|
||||
}
|
||||
return password, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func RepeatChar(char string, count int) string {
|
||||
if count <= 5 {
|
||||
return strings.Repeat(char, count)
|
||||
}
|
||||
return fmt.Sprintf("%s\x1b[%db", char, count-1)
|
||||
}
|
||||
|
||||
func RenderProgressBar(frac float64, width int) string {
|
||||
fc := markup.New(true)
|
||||
if frac >= 1 {
|
||||
return fc.Green(RepeatChar("🬋", width))
|
||||
}
|
||||
if frac <= 0 {
|
||||
return fc.Dim(RepeatChar("🬋", width))
|
||||
}
|
||||
w := frac * float64(width)
|
||||
fl := int(w)
|
||||
overhang := w - float64(fl)
|
||||
filled := RepeatChar("🬋", fl)
|
||||
needs_break := false
|
||||
if overhang < 0.2 {
|
||||
needs_break = true
|
||||
} else if overhang < 0.8 {
|
||||
filled += "🬃"
|
||||
fl += 1
|
||||
} else {
|
||||
if fl < width-1 {
|
||||
filled += "🬋"
|
||||
fl += 1
|
||||
needs_break = true
|
||||
} else {
|
||||
filled += "🬃"
|
||||
fl += 1
|
||||
}
|
||||
}
|
||||
ans := fc.Blue(filled)
|
||||
unfilled := ""
|
||||
ul := 0
|
||||
if width > fl && needs_break {
|
||||
unfilled = "🬇"
|
||||
ul = 1
|
||||
}
|
||||
filler := width - fl - ul
|
||||
if filler > 0 {
|
||||
unfilled += RepeatChar("🬋", filler)
|
||||
}
|
||||
if unfilled != "" {
|
||||
ans += fc.Dim(unfilled)
|
||||
}
|
||||
return ans
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestRenderProgressBar(t *testing.T) {
|
||||
|
||||
test := func(frac float64, width int) {
|
||||
b := RenderProgressBar(frac, width)
|
||||
a := wcswidth.Stringwidth(b)
|
||||
if a != width {
|
||||
t.Fatalf("Actual length %d != Expected length %d with fraction: %v\n%s", a, width, frac, b)
|
||||
}
|
||||
}
|
||||
test(0.9376609994848016, 47)
|
||||
test(0.9459041731066461, 47)
|
||||
test(0.9500257599175682, 47)
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package readline
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func (self *Readline) text_upto_cursor_pos() string {
|
||||
buf := strings.Builder{}
|
||||
buf.Grow(1024)
|
||||
for i, line := range self.input_state.lines {
|
||||
if i == self.input_state.cursor.Y {
|
||||
buf.WriteString(line[:min(len(line), self.input_state.cursor.X)])
|
||||
break
|
||||
} else {
|
||||
buf.WriteString(line)
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (self *Readline) text_after_cursor_pos() string {
|
||||
buf := strings.Builder{}
|
||||
buf.Grow(1024)
|
||||
for i, line := range self.input_state.lines {
|
||||
if i == self.input_state.cursor.Y {
|
||||
buf.WriteString(line[min(len(line), self.input_state.cursor.X):])
|
||||
buf.WriteString("\n")
|
||||
} else if i > self.input_state.cursor.Y {
|
||||
buf.WriteString(line)
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
}
|
||||
ans := buf.String()
|
||||
if ans != "" {
|
||||
ans = ans[:len(ans)-1]
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Readline) all_text() string {
|
||||
return strings.Join(self.input_state.lines, "\n")
|
||||
}
|
||||
|
||||
func (self *Readline) set_text(text string) {
|
||||
self.move_to_start()
|
||||
self.erase_chars_after_cursor(123456789, true)
|
||||
if text != "" {
|
||||
self.add_text(text)
|
||||
}
|
||||
self.move_to_end()
|
||||
}
|
||||
|
||||
func (self *Readline) add_text(text string) {
|
||||
new_lines := make([]string, 0, len(self.input_state.lines)+4)
|
||||
new_lines = append(new_lines, self.input_state.lines[:self.input_state.cursor.Y]...)
|
||||
var lines_after []string
|
||||
if len(self.input_state.lines) > self.input_state.cursor.Y+1 {
|
||||
lines_after = self.input_state.lines[self.input_state.cursor.Y+1:]
|
||||
}
|
||||
has_trailing_newline := strings.HasSuffix(text, "\n")
|
||||
|
||||
add_line_break := func(line string) {
|
||||
new_lines = append(new_lines, line)
|
||||
self.input_state.cursor.X = len(line)
|
||||
self.input_state.cursor.Y += 1
|
||||
}
|
||||
cline := self.input_state.lines[self.input_state.cursor.Y]
|
||||
before_first_line := cline[:self.input_state.cursor.X]
|
||||
after_first_line := ""
|
||||
if self.input_state.cursor.X < len(cline) {
|
||||
after_first_line = cline[self.input_state.cursor.X:]
|
||||
}
|
||||
for i, line := range utils.Splitlines(text) {
|
||||
if i > 0 {
|
||||
add_line_break(line)
|
||||
} else {
|
||||
line := before_first_line + line
|
||||
self.input_state.cursor.X = len(line)
|
||||
new_lines = append(new_lines, line)
|
||||
}
|
||||
}
|
||||
if has_trailing_newline {
|
||||
add_line_break("")
|
||||
}
|
||||
if after_first_line != "" {
|
||||
if len(new_lines) == 0 {
|
||||
new_lines = append(new_lines, "")
|
||||
}
|
||||
new_lines[len(new_lines)-1] += after_first_line
|
||||
}
|
||||
if len(lines_after) > 0 {
|
||||
new_lines = append(new_lines, lines_after...)
|
||||
}
|
||||
self.input_state.lines = new_lines
|
||||
}
|
||||
|
||||
func (self *Readline) move_cursor_left(amt uint, traverse_line_breaks bool) (amt_moved uint) {
|
||||
for amt_moved < amt {
|
||||
if self.input_state.cursor.X == 0 {
|
||||
if !traverse_line_breaks || self.input_state.cursor.Y == 0 {
|
||||
return amt_moved
|
||||
}
|
||||
self.input_state.cursor.Y -= 1
|
||||
self.input_state.cursor.X = len(self.input_state.lines[self.input_state.cursor.Y])
|
||||
amt_moved++
|
||||
continue
|
||||
}
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
for ci := wcswidth.NewCellIterator(line[:self.input_state.cursor.X]).GotoEnd(); amt_moved < amt && ci.Backward(); amt_moved++ {
|
||||
self.input_state.cursor.X -= len(ci.Current())
|
||||
}
|
||||
}
|
||||
return amt_moved
|
||||
}
|
||||
|
||||
func (self *Readline) move_cursor_right(amt uint, traverse_line_breaks bool) (amt_moved uint) {
|
||||
for amt_moved < amt {
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
if self.input_state.cursor.X >= len(line) {
|
||||
if !traverse_line_breaks || self.input_state.cursor.Y == len(self.input_state.lines)-1 {
|
||||
return amt_moved
|
||||
}
|
||||
self.input_state.cursor.Y += 1
|
||||
self.input_state.cursor.X = 0
|
||||
amt_moved++
|
||||
continue
|
||||
}
|
||||
|
||||
for ci := wcswidth.NewCellIterator(line[self.input_state.cursor.X:]); amt_moved < amt && ci.Forward(); amt_moved++ {
|
||||
self.input_state.cursor.X += len(ci.Current())
|
||||
}
|
||||
}
|
||||
return amt_moved
|
||||
}
|
||||
|
||||
func (self *Readline) move_cursor_to_target_line(source_line, target_line *ScreenLine) {
|
||||
if source_line != target_line {
|
||||
visual_distance_into_text := source_line.CursorCell - source_line.Prompt.Length
|
||||
self.input_state.cursor.Y = target_line.ParentLineNumber
|
||||
tp := wcswidth.TruncateToVisualLength(target_line.Text, visual_distance_into_text)
|
||||
self.input_state.cursor.X = target_line.OffsetInParentLine + len(tp)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Readline) move_cursor_vertically(amt int) (ans int) {
|
||||
if self.screen_width == 0 {
|
||||
self.update_current_screen_size()
|
||||
}
|
||||
screen_lines := self.get_screen_lines()
|
||||
cursor_line_num := 0
|
||||
for i, sl := range screen_lines {
|
||||
if sl.CursorCell > -1 {
|
||||
cursor_line_num = i
|
||||
break
|
||||
}
|
||||
}
|
||||
target_line_num := min(max(0, cursor_line_num+amt), len(screen_lines)-1)
|
||||
ans = target_line_num - cursor_line_num
|
||||
if ans != 0 {
|
||||
self.move_cursor_to_target_line(screen_lines[cursor_line_num], screen_lines[target_line_num])
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Readline) move_cursor_down(amt uint) uint {
|
||||
ans := uint(0)
|
||||
if self.screen_width == 0 {
|
||||
self.update_current_screen_size()
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Readline) move_to_start_of_line() bool {
|
||||
if self.input_state.cursor.X > 0 {
|
||||
self.input_state.cursor.X = 0
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Readline) move_to_end_of_line() bool {
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
if self.input_state.cursor.X >= len(line) {
|
||||
return false
|
||||
}
|
||||
self.input_state.cursor.X = len(line)
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) move_to_start() bool {
|
||||
if self.input_state.cursor.Y == 0 && self.input_state.cursor.X == 0 {
|
||||
return false
|
||||
}
|
||||
self.input_state.cursor.Y = 0
|
||||
self.move_to_start_of_line()
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) move_to_end() bool {
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
if self.input_state.cursor.Y == len(self.input_state.lines)-1 && self.input_state.cursor.X >= len(line) {
|
||||
return false
|
||||
}
|
||||
self.input_state.cursor.Y = len(self.input_state.lines) - 1
|
||||
self.move_to_end_of_line()
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) erase_between(start, end Position) string {
|
||||
if end.Less(start) {
|
||||
start, end = end, start
|
||||
}
|
||||
buf := strings.Builder{}
|
||||
if start.Y == end.Y {
|
||||
line := self.input_state.lines[start.Y]
|
||||
buf.WriteString(line[start.X:end.X])
|
||||
self.input_state.lines[start.Y] = line[:start.X] + line[end.X:]
|
||||
if self.input_state.cursor.Y == start.Y && self.input_state.cursor.X >= start.X {
|
||||
if self.input_state.cursor.X < end.X {
|
||||
self.input_state.cursor.X = start.X
|
||||
} else {
|
||||
self.input_state.cursor.X -= end.X - start.X
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
lines := make([]string, 0, len(self.input_state.lines))
|
||||
for i, line := range self.input_state.lines {
|
||||
if i < start.Y || i > end.Y {
|
||||
lines = append(lines, line)
|
||||
} else if i == start.Y {
|
||||
lines = append(lines, line[:start.X])
|
||||
buf.WriteString(line[start.X:])
|
||||
if self.input_state.cursor.Y == i && self.input_state.cursor.X > start.X {
|
||||
self.input_state.cursor.X = start.X
|
||||
}
|
||||
} else if i == end.Y {
|
||||
lines[len(lines)-1] += line[end.X:]
|
||||
buf.WriteString(line[:end.X])
|
||||
if i == self.input_state.cursor.Y {
|
||||
self.input_state.cursor.Y = start.Y
|
||||
if self.input_state.cursor.X < end.X {
|
||||
self.input_state.cursor.X = start.X
|
||||
} else {
|
||||
self.input_state.cursor.X -= end.X - start.X
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if i == self.input_state.cursor.Y {
|
||||
self.input_state.cursor = start
|
||||
}
|
||||
buf.WriteString(line)
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
}
|
||||
self.input_state.lines = lines
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (self *Readline) erase_chars_before_cursor(amt uint, traverse_line_breaks bool) uint {
|
||||
pos := self.input_state.cursor
|
||||
num := self.move_cursor_left(amt, traverse_line_breaks)
|
||||
if num == 0 {
|
||||
return num
|
||||
}
|
||||
self.erase_between(self.input_state.cursor, pos)
|
||||
return num
|
||||
}
|
||||
|
||||
func (self *Readline) erase_chars_after_cursor(amt uint, traverse_line_breaks bool) uint {
|
||||
pos := self.input_state.cursor
|
||||
num := self.move_cursor_right(amt, traverse_line_breaks)
|
||||
if num == 0 {
|
||||
return num
|
||||
}
|
||||
self.erase_between(pos, self.input_state.cursor)
|
||||
return num
|
||||
}
|
||||
|
||||
func has_word_chars(text string) bool {
|
||||
for _, ch := range text {
|
||||
if unicode.IsLetter(ch) || unicode.IsDigit(ch) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Readline) move_to_end_of_word(amt uint, traverse_line_breaks bool, is_part_of_word func(string) bool) (num_of_words_moved uint) {
|
||||
if amt == 0 {
|
||||
return 0
|
||||
}
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
in_word := false
|
||||
ci := wcswidth.NewCellIterator(line[self.input_state.cursor.X:])
|
||||
sz := 0
|
||||
|
||||
for ci.Forward() {
|
||||
current_is_word_char := is_part_of_word(ci.Current())
|
||||
plen := sz
|
||||
sz += len(ci.Current())
|
||||
if current_is_word_char {
|
||||
in_word = true
|
||||
} else if in_word {
|
||||
self.input_state.cursor.X += plen
|
||||
amt--
|
||||
num_of_words_moved++
|
||||
if amt == 0 {
|
||||
return
|
||||
}
|
||||
in_word = false
|
||||
}
|
||||
}
|
||||
if self.move_to_end_of_line() {
|
||||
amt--
|
||||
num_of_words_moved++
|
||||
}
|
||||
if amt > 0 {
|
||||
if traverse_line_breaks && self.input_state.cursor.Y < len(self.input_state.lines)-1 {
|
||||
self.input_state.cursor.Y++
|
||||
self.input_state.cursor.X = 0
|
||||
num_of_words_moved += self.move_to_end_of_word(amt, traverse_line_breaks, is_part_of_word)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Readline) move_to_start_of_word(amt uint, traverse_line_breaks bool, is_part_of_word func(string) bool) (num_of_words_moved uint) {
|
||||
if amt == 0 {
|
||||
return 0
|
||||
}
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
in_word := false
|
||||
ci := wcswidth.NewCellIterator(line[:self.input_state.cursor.X]).GotoEnd()
|
||||
sz := 0
|
||||
|
||||
for ci.Backward() {
|
||||
current_is_word_char := is_part_of_word(ci.Current())
|
||||
plen := sz
|
||||
sz += len(ci.Current())
|
||||
if current_is_word_char {
|
||||
in_word = true
|
||||
} else if in_word {
|
||||
self.input_state.cursor.X -= plen
|
||||
amt--
|
||||
num_of_words_moved++
|
||||
if amt == 0 {
|
||||
return
|
||||
}
|
||||
in_word = false
|
||||
}
|
||||
}
|
||||
if self.move_to_start_of_line() {
|
||||
amt--
|
||||
num_of_words_moved++
|
||||
}
|
||||
if amt > 0 {
|
||||
if traverse_line_breaks && self.input_state.cursor.Y > 0 {
|
||||
self.input_state.cursor.Y--
|
||||
self.input_state.cursor.X = len(self.input_state.lines[self.input_state.cursor.Y])
|
||||
num_of_words_moved += self.move_to_start_of_word(amt, traverse_line_breaks, has_word_chars)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Readline) kill_text(text string) {
|
||||
if ActionStartKillActions < self.last_action && self.last_action < ActionEndKillActions {
|
||||
self.kill_ring.append_to_existing_item(text)
|
||||
} else {
|
||||
self.kill_ring.add_new_item(text)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Readline) kill_to_end_of_line() bool {
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
if self.input_state.cursor.X >= len(line) {
|
||||
return false
|
||||
}
|
||||
self.input_state.lines[self.input_state.cursor.Y] = line[:self.input_state.cursor.X]
|
||||
self.kill_text(line[self.input_state.cursor.X:])
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) kill_to_start_of_line() bool {
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
if self.input_state.cursor.X <= 0 {
|
||||
return false
|
||||
}
|
||||
self.input_state.lines[self.input_state.cursor.Y] = line[self.input_state.cursor.X:]
|
||||
self.kill_text(line[:self.input_state.cursor.X])
|
||||
self.input_state.cursor.X = 0
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) kill_next_word(amt uint, traverse_line_breaks bool) (num_killed uint) {
|
||||
before := self.input_state.cursor
|
||||
num_killed = self.move_to_end_of_word(amt, traverse_line_breaks, has_word_chars)
|
||||
if num_killed > 0 {
|
||||
self.kill_text(self.erase_between(before, self.input_state.cursor))
|
||||
}
|
||||
return num_killed
|
||||
}
|
||||
|
||||
func (self *Readline) kill_previous_word(amt uint, traverse_line_breaks bool) (num_killed uint) {
|
||||
before := self.input_state.cursor
|
||||
num_killed = self.move_to_start_of_word(amt, traverse_line_breaks, has_word_chars)
|
||||
if num_killed > 0 {
|
||||
self.kill_text(self.erase_between(self.input_state.cursor, before))
|
||||
}
|
||||
return num_killed
|
||||
}
|
||||
|
||||
func has_no_space_chars(text string) bool {
|
||||
for _, r := range text {
|
||||
if unicode.IsSpace(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) kill_previous_space_delimited_word(amt uint, traverse_line_breaks bool) (num_killed uint) {
|
||||
before := self.input_state.cursor
|
||||
num_killed = self.move_to_start_of_word(amt, traverse_line_breaks, has_no_space_chars)
|
||||
if num_killed > 0 {
|
||||
self.kill_text(self.erase_between(self.input_state.cursor, before))
|
||||
}
|
||||
return num_killed
|
||||
}
|
||||
|
||||
func (self *Readline) ensure_position_in_bounds(pos *Position) *Position {
|
||||
pos.Y = max(0, min(pos.Y, len(self.input_state.lines)-1))
|
||||
line := self.input_state.lines[pos.Y]
|
||||
pos.X = max(0, min(pos.X, len(line)))
|
||||
return pos
|
||||
}
|
||||
|
||||
func (self *Readline) yank(repeat_count uint, pop bool) bool {
|
||||
if pop && self.last_action != ActionYank && self.last_action != ActionPopYank {
|
||||
return false
|
||||
}
|
||||
text := ""
|
||||
if pop {
|
||||
text = self.kill_ring.pop_yank()
|
||||
} else {
|
||||
text = self.kill_ring.yank()
|
||||
}
|
||||
if text == "" {
|
||||
return false
|
||||
}
|
||||
before := self.input_state.cursor
|
||||
if pop {
|
||||
self.ensure_position_in_bounds(&self.last_yank_extent.start)
|
||||
self.ensure_position_in_bounds(&self.last_yank_extent.end)
|
||||
self.erase_between(self.last_yank_extent.start, self.last_yank_extent.end)
|
||||
self.input_state.cursor = self.last_yank_extent.start
|
||||
before = self.input_state.cursor
|
||||
}
|
||||
self.add_text(text)
|
||||
self.last_yank_extent.start = before
|
||||
self.last_yank_extent.end = self.input_state.cursor
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) history_first() bool {
|
||||
self.create_history_matches()
|
||||
return self.history_matches.first(self)
|
||||
}
|
||||
|
||||
func (self *Readline) history_last() bool {
|
||||
self.create_history_matches()
|
||||
return self.history_matches.last(self)
|
||||
}
|
||||
|
||||
func (self *Readline) history_prev(repeat_count uint) bool {
|
||||
self.create_history_matches()
|
||||
return self.history_matches.previous(repeat_count, self)
|
||||
}
|
||||
|
||||
func (self *Readline) history_next(repeat_count uint) bool {
|
||||
self.create_history_matches()
|
||||
return self.history_matches.next(repeat_count, self)
|
||||
}
|
||||
|
||||
func (self *Readline) _perform_action(ac Action, repeat_count uint) (err error, dont_set_last_action bool) {
|
||||
switch ac {
|
||||
case ActionBackspace:
|
||||
if self.history_search != nil {
|
||||
if self.remove_text_from_history_search(repeat_count) > 0 {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if self.erase_chars_before_cursor(repeat_count, true) > 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
case ActionDelete:
|
||||
if self.erase_chars_after_cursor(repeat_count, true) > 0 {
|
||||
return
|
||||
}
|
||||
case ActionMoveToStartOfLine:
|
||||
if self.move_to_start_of_line() {
|
||||
return
|
||||
}
|
||||
case ActionMoveToEndOfLine:
|
||||
if self.move_to_end_of_line() {
|
||||
return
|
||||
}
|
||||
case ActionMoveToEndOfWord:
|
||||
if self.move_to_end_of_word(repeat_count, true, has_word_chars) > 0 {
|
||||
return
|
||||
}
|
||||
case ActionMoveToStartOfWord:
|
||||
if self.move_to_start_of_word(repeat_count, true, has_word_chars) > 0 {
|
||||
return
|
||||
}
|
||||
case ActionMoveToStartOfDocument:
|
||||
if self.move_to_start() {
|
||||
return
|
||||
}
|
||||
case ActionMoveToEndOfDocument:
|
||||
if self.move_to_end() {
|
||||
return
|
||||
}
|
||||
case ActionCursorLeft:
|
||||
if self.move_cursor_left(repeat_count, true) > 0 {
|
||||
return
|
||||
}
|
||||
case ActionCursorRight:
|
||||
if self.move_cursor_right(repeat_count, true) > 0 {
|
||||
return
|
||||
}
|
||||
case ActionEndInput:
|
||||
line := self.input_state.lines[self.input_state.cursor.Y]
|
||||
if line == "" {
|
||||
err = io.EOF
|
||||
|
||||
} else {
|
||||
err = self.perform_action(ActionAcceptInput, 1)
|
||||
}
|
||||
return
|
||||
case ActionAcceptInput:
|
||||
err = ErrAcceptInput
|
||||
return
|
||||
case ActionCursorUp:
|
||||
if self.move_cursor_vertically(-int(repeat_count)) != 0 {
|
||||
return
|
||||
}
|
||||
case ActionCursorDown:
|
||||
if self.move_cursor_vertically(int(repeat_count)) != 0 {
|
||||
return
|
||||
}
|
||||
case ActionHistoryPreviousOrCursorUp:
|
||||
dont_set_last_action = true
|
||||
if self.perform_action(ActionCursorUp, repeat_count) == ErrCouldNotPerformAction {
|
||||
err = self.perform_action(ActionHistoryPrevious, repeat_count)
|
||||
}
|
||||
return
|
||||
case ActionHistoryNextOrCursorDown:
|
||||
dont_set_last_action = true
|
||||
if self.perform_action(ActionCursorDown, repeat_count) == ErrCouldNotPerformAction {
|
||||
err = self.perform_action(ActionHistoryNext, repeat_count)
|
||||
}
|
||||
return
|
||||
case ActionHistoryFirst:
|
||||
if self.history_first() {
|
||||
return
|
||||
}
|
||||
case ActionHistoryPrevious:
|
||||
if self.history_prev(repeat_count) {
|
||||
return
|
||||
}
|
||||
case ActionHistoryNext:
|
||||
if self.history_next(repeat_count) {
|
||||
return
|
||||
}
|
||||
case ActionHistoryLast:
|
||||
if self.history_last() {
|
||||
return
|
||||
}
|
||||
case ActionClearScreen:
|
||||
self.loop.StartAtomicUpdate()
|
||||
self.loop.ClearScreen()
|
||||
self.RedrawNonAtomic()
|
||||
self.loop.EndAtomicUpdate()
|
||||
return
|
||||
case ActionKillToEndOfLine:
|
||||
if self.kill_to_end_of_line() {
|
||||
return
|
||||
}
|
||||
case ActionKillToStartOfLine:
|
||||
if self.kill_to_start_of_line() {
|
||||
return
|
||||
}
|
||||
case ActionKillNextWord:
|
||||
if self.kill_next_word(repeat_count, true) > 0 {
|
||||
return
|
||||
}
|
||||
case ActionKillPreviousWord:
|
||||
if self.kill_previous_word(repeat_count, true) > 0 {
|
||||
return
|
||||
}
|
||||
case ActionKillPreviousSpaceDelimitedWord:
|
||||
if self.kill_previous_space_delimited_word(repeat_count, true) > 0 {
|
||||
return
|
||||
}
|
||||
case ActionYank:
|
||||
if self.yank(repeat_count, false) {
|
||||
return
|
||||
}
|
||||
case ActionPopYank:
|
||||
if self.yank(repeat_count, true) {
|
||||
return
|
||||
}
|
||||
case ActionAbortCurrentLine:
|
||||
self.loop.QueueWriteString("\r\n")
|
||||
self.ResetText()
|
||||
return
|
||||
case ActionHistoryIncrementalSearchForwards:
|
||||
if self.history_search == nil {
|
||||
self.create_history_search(false, repeat_count)
|
||||
return
|
||||
}
|
||||
if self.next_history_search(false, repeat_count) {
|
||||
return
|
||||
}
|
||||
case ActionHistoryIncrementalSearchBackwards:
|
||||
if self.history_search == nil {
|
||||
self.create_history_search(true, repeat_count)
|
||||
return
|
||||
}
|
||||
if self.next_history_search(true, repeat_count) {
|
||||
return
|
||||
}
|
||||
case ActionAddText:
|
||||
text := strings.Repeat(self.text_to_be_added, int(repeat_count))
|
||||
self.text_to_be_added = ""
|
||||
if self.history_search != nil {
|
||||
self.add_text_to_history_search(text)
|
||||
} else {
|
||||
self.add_text(text)
|
||||
}
|
||||
return
|
||||
case ActionTerminateHistorySearchAndRestore:
|
||||
if self.history_search != nil {
|
||||
self.end_history_search(false)
|
||||
return
|
||||
}
|
||||
case ActionTerminateHistorySearchAndApply:
|
||||
if self.history_search != nil {
|
||||
self.end_history_search(true)
|
||||
return
|
||||
}
|
||||
case ActionCompleteForward:
|
||||
if self.complete(true, repeat_count) {
|
||||
return
|
||||
}
|
||||
case ActionCompleteBackward:
|
||||
if self.complete(false, repeat_count) {
|
||||
return
|
||||
}
|
||||
}
|
||||
err = ErrCouldNotPerformAction
|
||||
return
|
||||
}
|
||||
|
||||
func (self *Readline) perform_action(ac Action, repeat_count uint) error {
|
||||
err, dont_set_last_action := self._perform_action(ac, repeat_count)
|
||||
if err == nil && !dont_set_last_action {
|
||||
self.last_action = ac
|
||||
if self.completions.current.results != nil && ac != ActionCompleteForward && ac != ActionCompleteBackward {
|
||||
self.completions.current = completion{}
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,567 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package readline
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func new_rl() *Readline {
|
||||
lp, _ := loop.New()
|
||||
rl := New(lp, RlInit{Prompt: "$$ "})
|
||||
rl.screen_width = 10
|
||||
rl.screen_height = 100
|
||||
return rl
|
||||
}
|
||||
|
||||
func test_func(t *testing.T) func(string, func(*Readline), ...string) *Readline {
|
||||
return func(initial string, prepare func(rl *Readline), expected ...string) *Readline {
|
||||
rl := new_rl()
|
||||
rl.add_text(initial)
|
||||
if prepare != nil {
|
||||
prepare(rl)
|
||||
}
|
||||
if len(expected) > 0 {
|
||||
if expected[0] != rl.text_upto_cursor_pos() {
|
||||
t.Fatalf("Text upto cursor pos not as expected for: %#v\n%#v != %#v", initial, expected[0], rl.text_upto_cursor_pos())
|
||||
}
|
||||
}
|
||||
if len(expected) > 1 {
|
||||
if expected[1] != rl.text_after_cursor_pos() {
|
||||
t.Fatalf("Text after cursor pos not as expected for: %#v\n%#v != %#v", initial, expected[1], rl.text_after_cursor_pos())
|
||||
}
|
||||
}
|
||||
if len(expected) > 2 {
|
||||
if expected[2] != rl.all_text() {
|
||||
t.Fatalf("Text not as expected for: %#v\n%#v != %#v", initial, expected[2], rl.all_text())
|
||||
}
|
||||
}
|
||||
return rl
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestAddText(t *testing.T) {
|
||||
dt := test_func(t)
|
||||
dt("test", nil, "test", "", "test")
|
||||
dt("1234\n", nil, "1234\n", "", "1234\n")
|
||||
dt("abcd", func(rl *Readline) {
|
||||
rl.input_state.cursor.X = 2
|
||||
rl.add_text("12")
|
||||
}, "ab12", "cd", "ab12cd")
|
||||
dt("abcd", func(rl *Readline) {
|
||||
rl.input_state.cursor.X = 2
|
||||
rl.add_text("12\n34")
|
||||
}, "ab12\n34", "cd", "ab12\n34cd")
|
||||
dt("abcd\nxyz", func(rl *Readline) {
|
||||
rl.input_state.cursor.X = 2
|
||||
rl.add_text("12\n34")
|
||||
}, "abcd\nxy12\n34", "z", "abcd\nxy12\n34z")
|
||||
}
|
||||
|
||||
func TestGetScreenLines(t *testing.T) {
|
||||
rl := new_rl()
|
||||
|
||||
p := func(primary bool) Prompt {
|
||||
if primary {
|
||||
return rl.prompt
|
||||
}
|
||||
return rl.continuation_prompt
|
||||
}
|
||||
|
||||
tsl := func(expected ...ScreenLine) {
|
||||
q := rl.get_screen_lines()
|
||||
actual := make([]ScreenLine, len(q))
|
||||
for i, x := range q {
|
||||
actual[i] = *x
|
||||
}
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("Did not get expected screen lines for: %#v and cursor: %+v\n%s", rl.AllText(), rl.input_state.cursor, diff)
|
||||
}
|
||||
}
|
||||
tsl(ScreenLine{Prompt: p(true), CursorCell: 3, AfterLineBreak: true})
|
||||
rl.add_text("123")
|
||||
tsl(ScreenLine{Prompt: p(true), CursorCell: 6, Text: "123", CursorTextPos: 3, TextLengthInCells: 3, AfterLineBreak: true})
|
||||
rl.add_text("456")
|
||||
tsl(ScreenLine{Prompt: p(true), CursorCell: 9, Text: "123456", CursorTextPos: 6, TextLengthInCells: 6, AfterLineBreak: true})
|
||||
rl.add_text("7")
|
||||
tsl(
|
||||
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "1234567", CursorTextPos: -1, TextLengthInCells: 7, AfterLineBreak: true},
|
||||
ScreenLine{OffsetInParentLine: 7},
|
||||
)
|
||||
rl.add_text("89")
|
||||
tsl(
|
||||
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "1234567", CursorTextPos: -1, TextLengthInCells: 7, AfterLineBreak: true},
|
||||
ScreenLine{OffsetInParentLine: 7, Text: "89", CursorCell: 2, TextLengthInCells: 2, CursorTextPos: 2},
|
||||
)
|
||||
rl.ResetText()
|
||||
rl.add_text("123\n456abcdeXYZ")
|
||||
tsl(
|
||||
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "123", CursorTextPos: -1, TextLengthInCells: 3, AfterLineBreak: true},
|
||||
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "456abcde", TextLengthInCells: 8, CursorCell: -1, CursorTextPos: -1, AfterLineBreak: true},
|
||||
ScreenLine{OffsetInParentLine: 8, ParentLineNumber: 1, TextLengthInCells: 3, CursorCell: 3, CursorTextPos: 3, Text: "XYZ"},
|
||||
)
|
||||
rl.input_state.cursor = Position{X: 2}
|
||||
tsl(
|
||||
ScreenLine{Prompt: p(true), CursorCell: 5, Text: "123", CursorTextPos: 2, TextLengthInCells: 3, AfterLineBreak: true},
|
||||
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "456abcde", TextLengthInCells: 8, CursorCell: -1, CursorTextPos: -1, AfterLineBreak: true},
|
||||
ScreenLine{OffsetInParentLine: 8, ParentLineNumber: 1, TextLengthInCells: 3, CursorCell: -1, CursorTextPos: -1, Text: "XYZ"},
|
||||
)
|
||||
rl.input_state.cursor = Position{X: 2, Y: 1}
|
||||
tsl(
|
||||
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "123", CursorTextPos: -1, TextLengthInCells: 3, AfterLineBreak: true},
|
||||
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "456abcde", TextLengthInCells: 8, CursorCell: 4, CursorTextPos: 2, AfterLineBreak: true},
|
||||
ScreenLine{OffsetInParentLine: 8, ParentLineNumber: 1, TextLengthInCells: 3, CursorCell: -1, CursorTextPos: -1, Text: "XYZ"},
|
||||
)
|
||||
rl.input_state.cursor = Position{X: 8, Y: 1}
|
||||
tsl(
|
||||
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "123", CursorTextPos: -1, TextLengthInCells: 3, AfterLineBreak: true},
|
||||
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "456abcde", TextLengthInCells: 8, CursorCell: -1, CursorTextPos: -1, AfterLineBreak: true},
|
||||
ScreenLine{OffsetInParentLine: 8, ParentLineNumber: 1, TextLengthInCells: 3, CursorCell: 0, CursorTextPos: 0, Text: "XYZ"},
|
||||
)
|
||||
rl.ResetText()
|
||||
rl.add_text("1234567\nabc")
|
||||
rl.input_state.cursor = Position{X: 7}
|
||||
tsl(
|
||||
ScreenLine{Prompt: p(true), CursorCell: -1, Text: "1234567", CursorTextPos: -1, TextLengthInCells: 7, AfterLineBreak: true},
|
||||
ScreenLine{ParentLineNumber: 1, Prompt: p(false), Text: "abc", CursorCell: 2, TextLengthInCells: 3, CursorTextPos: 0, AfterLineBreak: true},
|
||||
)
|
||||
}
|
||||
|
||||
func TestCursorMovement(t *testing.T) {
|
||||
dt := test_func(t)
|
||||
|
||||
left := func(rl *Readline, amt uint, moved_amt uint, traverse_line_breaks bool) {
|
||||
actual := rl.move_cursor_left(amt, traverse_line_breaks)
|
||||
if actual != moved_amt {
|
||||
t.Fatalf("Failed to move cursor by %#v\nactual != expected: %#v != %#v", amt, actual, moved_amt)
|
||||
}
|
||||
}
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
left(rl, 2, 2, false)
|
||||
}, "one\nt", "wo")
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
left(rl, 4, 3, false)
|
||||
}, "one\n", "two")
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
left(rl, 4, 4, true)
|
||||
}, "one", "\ntwo")
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
left(rl, 7, 7, true)
|
||||
}, "", "one\ntwo")
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
left(rl, 10, 7, true)
|
||||
}, "", "one\ntwo")
|
||||
dt("one😀", func(rl *Readline) {
|
||||
left(rl, 1, 1, false)
|
||||
}, "one", "😀")
|
||||
dt("oneà", func(rl *Readline) {
|
||||
left(rl, 1, 1, false)
|
||||
}, "one", "à")
|
||||
|
||||
right := func(rl *Readline, amt uint, moved_amt uint, traverse_line_breaks bool) {
|
||||
rl.input_state.cursor.Y = 0
|
||||
rl.input_state.cursor.X = 0
|
||||
actual := rl.move_cursor_right(amt, traverse_line_breaks)
|
||||
if actual != moved_amt {
|
||||
t.Fatalf("Failed to move cursor by %d\nactual != expected: %d != %d", amt, actual, moved_amt)
|
||||
}
|
||||
}
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
right(rl, 2, 2, false)
|
||||
}, "on", "e\ntwo")
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
right(rl, 4, 3, false)
|
||||
}, "one", "\ntwo")
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
right(rl, 4, 4, true)
|
||||
}, "one\n", "two")
|
||||
dt("😀one", func(rl *Readline) {
|
||||
right(rl, 1, 1, false)
|
||||
}, "😀", "one")
|
||||
dt("àb", func(rl *Readline) {
|
||||
right(rl, 1, 1, false)
|
||||
}, "à", "b")
|
||||
|
||||
rl := new_rl()
|
||||
|
||||
vert := func(amt int, moved_amt int, text_upto_cursor_pos string, initials ...Position) {
|
||||
initial := Position{}
|
||||
if len(initials) > 0 {
|
||||
initial = initials[0]
|
||||
}
|
||||
rl.input_state.cursor = initial
|
||||
actual := rl.move_cursor_vertically(amt)
|
||||
if actual != moved_amt {
|
||||
t.Fatalf("Failed to move cursor by %#v for: %#v \nactual != expected: %#v != %#v", amt, rl.AllText(), actual, moved_amt)
|
||||
}
|
||||
if diff := cmp.Diff(text_upto_cursor_pos, rl.text_upto_cursor_pos()); diff != "" {
|
||||
t.Fatalf("Did not get expected screen lines for: %#v and cursor: %+v\n%s", rl.AllText(), initial, diff)
|
||||
}
|
||||
}
|
||||
|
||||
rl.ResetText()
|
||||
rl.add_text("1234567xy\nabcd\n123")
|
||||
vert(-1, -1, "1234567xy\nabc", Position{X: 3, Y: 2})
|
||||
vert(-2, -2, "1234567xy", Position{X: 3, Y: 2})
|
||||
vert(-30, -3, "123", Position{X: 3, Y: 2})
|
||||
|
||||
rl.ResetText()
|
||||
rl.add_text("o\u0300ne two three\nfour five")
|
||||
|
||||
wf := func(amt uint, expected_amt uint, text_before_cursor string) {
|
||||
pos := rl.input_state.cursor
|
||||
actual_amt := rl.move_to_end_of_word(amt, true, has_word_chars)
|
||||
if actual_amt != expected_amt {
|
||||
t.Fatalf("Failed to move to word end, expected amt (%d) != actual amt (%d)", expected_amt, actual_amt)
|
||||
}
|
||||
if diff := cmp.Diff(text_before_cursor, rl.TextBeforeCursor()); diff != "" {
|
||||
t.Fatalf("Did not get expected text before cursor for: %#v and cursor: %+v\n%s", rl.AllText(), pos, diff)
|
||||
}
|
||||
}
|
||||
rl.input_state.cursor = Position{}
|
||||
wf(1, 1, "òne")
|
||||
wf(1, 1, "òne two")
|
||||
wf(1, 1, "òne two three")
|
||||
wf(1, 1, "òne two three\nfour")
|
||||
wf(1, 1, "òne two three\nfour five")
|
||||
wf(1, 0, "òne two three\nfour five")
|
||||
rl.input_state.cursor = Position{}
|
||||
wf(5, 5, "òne two three\nfour five")
|
||||
rl.input_state.cursor = Position{X: 5}
|
||||
wf(1, 1, "òne two")
|
||||
|
||||
wb := func(amt uint, expected_amt uint, text_before_cursor string) {
|
||||
pos := rl.input_state.cursor
|
||||
actual_amt := rl.move_to_start_of_word(amt, true, has_word_chars)
|
||||
if actual_amt != expected_amt {
|
||||
t.Fatalf("Failed to move to word end, expected amt (%d) != actual amt (%d)", expected_amt, actual_amt)
|
||||
}
|
||||
if diff := cmp.Diff(text_before_cursor, rl.TextBeforeCursor()); diff != "" {
|
||||
t.Fatalf("Did not get expected text before cursor for: %#v and cursor: %+v\n%s", rl.AllText(), pos, diff)
|
||||
}
|
||||
}
|
||||
rl.input_state.cursor = Position{X: 2}
|
||||
wb(1, 1, "")
|
||||
rl.input_state.cursor = Position{X: 8, Y: 1}
|
||||
wb(1, 1, "òne two three\nfour ")
|
||||
wb(1, 1, "òne two three\n")
|
||||
wb(1, 1, "òne two ")
|
||||
wb(1, 1, "òne ")
|
||||
wb(1, 1, "")
|
||||
wb(1, 0, "")
|
||||
rl.input_state.cursor = Position{X: 8, Y: 1}
|
||||
wb(5, 5, "")
|
||||
rl.input_state.cursor = Position{X: 5}
|
||||
wb(1, 1, "")
|
||||
|
||||
}
|
||||
|
||||
func TestYanking(t *testing.T) {
|
||||
rl := new_rl()
|
||||
|
||||
as_slice := func(l *list.List) []string {
|
||||
ans := make([]string, 0, l.Len())
|
||||
for e := l.Front(); e != nil; e = e.Next() {
|
||||
ans = append(ans, e.Value.(string))
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
assert_items := func(expected ...string) {
|
||||
if diff := cmp.Diff(expected, as_slice(rl.kill_ring.items)); diff != "" {
|
||||
t.Fatalf("kill ring items not as expected\n%s", diff)
|
||||
}
|
||||
}
|
||||
assert_text := func(expected string) {
|
||||
if diff := cmp.Diff(expected, rl.all_text()); diff != "" {
|
||||
t.Fatalf("text not as expected:\n%s", diff)
|
||||
}
|
||||
}
|
||||
|
||||
rl.add_text("1 2 3\none two three")
|
||||
rl.perform_action(ActionKillToStartOfLine, 1)
|
||||
assert_items("one two three")
|
||||
rl.perform_action(ActionCursorUp, 1)
|
||||
rl.perform_action(ActionKillToEndOfLine, 1)
|
||||
assert_items("1 2 3", "one two three")
|
||||
rl.perform_action(ActionYank, 1)
|
||||
assert_text("1 2 3\n")
|
||||
rl.perform_action(ActionYank, 1)
|
||||
assert_text("1 2 31 2 3\n")
|
||||
rl.perform_action(ActionPopYank, 1)
|
||||
assert_text("1 2 3one two three\n")
|
||||
rl.perform_action(ActionPopYank, 1)
|
||||
assert_text("1 2 31 2 3\n")
|
||||
|
||||
rl.ResetText()
|
||||
rl.kill_ring.clear()
|
||||
rl.add_text("one two three")
|
||||
rl.perform_action(ActionMoveToStartOfLine, 1)
|
||||
rl.perform_action(ActionKillNextWord, 1)
|
||||
assert_items("one")
|
||||
assert_text(" two three")
|
||||
rl.perform_action(ActionKillNextWord, 1)
|
||||
assert_items("one two")
|
||||
assert_text(" three")
|
||||
rl.perform_action(ActionCursorRight, 1)
|
||||
rl.perform_action(ActionKillNextWord, 1)
|
||||
assert_items("three", "one two")
|
||||
assert_text(" ")
|
||||
}
|
||||
|
||||
func TestEraseChars(t *testing.T) {
|
||||
dt := test_func(t)
|
||||
|
||||
backspace := func(rl *Readline, amt uint, erased_amt uint, traverse_line_breaks bool) {
|
||||
actual := rl.erase_chars_before_cursor(amt, traverse_line_breaks)
|
||||
if actual != erased_amt {
|
||||
t.Fatalf("Failed to move cursor by %#v\nactual != expected: %d != %d", amt, actual, erased_amt)
|
||||
}
|
||||
}
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
backspace(rl, 2, 2, false)
|
||||
}, "one\nt", "")
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
rl.input_state.cursor.X = 1
|
||||
backspace(rl, 2, 1, false)
|
||||
}, "one\n", "wo")
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
rl.input_state.cursor.X = 1
|
||||
backspace(rl, 2, 2, true)
|
||||
}, "one", "wo")
|
||||
dt("a😀", func(rl *Readline) {
|
||||
backspace(rl, 1, 1, false)
|
||||
}, "a", "")
|
||||
dt("bà", func(rl *Readline) {
|
||||
backspace(rl, 1, 1, false)
|
||||
}, "b", "")
|
||||
|
||||
del := func(rl *Readline, amt uint, erased_amt uint, traverse_line_breaks bool) {
|
||||
rl.input_state.cursor.Y = 0
|
||||
rl.input_state.cursor.X = 0
|
||||
actual := rl.erase_chars_after_cursor(amt, traverse_line_breaks)
|
||||
if actual != erased_amt {
|
||||
t.Fatalf("Failed to move cursor by %#v\nactual != expected: %d != %d", amt, actual, erased_amt)
|
||||
}
|
||||
}
|
||||
dt("one\ntwo", func(rl *Readline) {
|
||||
del(rl, 2, 2, false)
|
||||
}, "", "e\ntwo")
|
||||
dt("😀a", func(rl *Readline) {
|
||||
del(rl, 1, 1, false)
|
||||
}, "", "a")
|
||||
dt("àb", func(rl *Readline) {
|
||||
del(rl, 1, 1, false)
|
||||
}, "", "b")
|
||||
|
||||
dt("one\ntwo\nthree", func(rl *Readline) {
|
||||
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
|
||||
}, "oree", "")
|
||||
dt("one\ntwo\nthree", func(rl *Readline) {
|
||||
rl.input_state.cursor.X = 1
|
||||
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
|
||||
}, "o", "ree")
|
||||
dt("one\ntwo\nthree", func(rl *Readline) {
|
||||
rl.input_state.cursor = Position{X: 1, Y: 1}
|
||||
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
|
||||
}, "o", "ree")
|
||||
dt("one\ntwo\nthree", func(rl *Readline) {
|
||||
rl.input_state.cursor = Position{X: 1, Y: 0}
|
||||
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
|
||||
}, "o", "ree")
|
||||
dt("one\ntwo\nthree", func(rl *Readline) {
|
||||
rl.input_state.cursor = Position{X: 0, Y: 0}
|
||||
rl.erase_between(Position{X: 1}, Position{X: 2, Y: 2})
|
||||
}, "", "oree")
|
||||
}
|
||||
|
||||
func TestNumberArgument(t *testing.T) {
|
||||
rl := new_rl()
|
||||
rl.screen_width = 100
|
||||
|
||||
test := func(ac Action, before_cursor, after_cursor string) {
|
||||
rl.dispatch_key_action(ac)
|
||||
if diff := cmp.Diff(before_cursor, rl.text_upto_cursor_pos()); diff != "" {
|
||||
t.Fatalf("The text before the cursor was not as expected for action: %#v\n%s", ac, diff)
|
||||
}
|
||||
if diff := cmp.Diff(after_cursor, rl.text_after_cursor_pos()); diff != "" {
|
||||
t.Fatalf("The text after the cursor was not as expected for action: %#v\n%s", ac, diff)
|
||||
}
|
||||
}
|
||||
sw := func(num int) {
|
||||
q := rl.format_arg_prompt(strconv.Itoa(num))
|
||||
for _, sl := range rl.get_screen_lines() {
|
||||
if num <= 0 && !strings.Contains(sl.Prompt.Text, "$$") {
|
||||
t.Fatalf("arg prompt unexpectedly present for: %#v", rl.AllText())
|
||||
}
|
||||
if num > 0 && !strings.Contains(sl.Prompt.Text, q) {
|
||||
t.Fatalf("arg prompt unexpectedly not present for: %#v prompt: %#v", rl.AllText(), sl.Prompt.Text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sw(0)
|
||||
rl.dispatch_key_action(ActionNumericArgumentDigit1)
|
||||
sw(1)
|
||||
rl.dispatch_key_action(ActionNumericArgumentDigit0)
|
||||
sw(10)
|
||||
rl.text_to_be_added = "x"
|
||||
test(ActionAddText, "xxxxxxxxxx", "")
|
||||
sw(0)
|
||||
test(ActionNumericArgumentDigit0, "xxxxxxxxxx0", "")
|
||||
sw(0)
|
||||
rl.dispatch_key_action(ActionNumericArgumentDigit1)
|
||||
test(ActionNumericArgumentDigitMinus, "xxxxxxxxxx0-", "")
|
||||
sw(0)
|
||||
rl.dispatch_key_action(ActionNumericArgumentDigit1)
|
||||
sw(1)
|
||||
rl.dispatch_key_action(ActionNumericArgumentDigit1)
|
||||
sw(11)
|
||||
test(ActionCursorLeft, "x", "xxxxxxxxx0-")
|
||||
sw(0)
|
||||
}
|
||||
|
||||
func TestHistory(t *testing.T) {
|
||||
rl := new_rl()
|
||||
|
||||
add_item := func(x string) {
|
||||
rl.history.AddItem(x, 0)
|
||||
}
|
||||
add_item("a one")
|
||||
add_item("a two")
|
||||
add_item("b three")
|
||||
add_item("b four")
|
||||
|
||||
test := func(ac Action, before_cursor, after_cursor string) {
|
||||
rl.perform_action(ac, 1)
|
||||
if diff := cmp.Diff(before_cursor, rl.text_upto_cursor_pos()); diff != "" {
|
||||
t.Fatalf("The text before the cursor was not as expected for action: %#v\n%s", ac, diff)
|
||||
}
|
||||
if diff := cmp.Diff(after_cursor, rl.text_after_cursor_pos()); diff != "" {
|
||||
t.Fatalf("The text after the cursor was not as expected for action: %#v\n%s", ac, diff)
|
||||
}
|
||||
}
|
||||
|
||||
test(ActionHistoryPreviousOrCursorUp, "b four", "")
|
||||
test(ActionHistoryPreviousOrCursorUp, "b three", "")
|
||||
test(ActionHistoryPrevious, "a two", "")
|
||||
test(ActionHistoryPrevious, "a one", "")
|
||||
test(ActionHistoryPrevious, "a one", "")
|
||||
test(ActionHistoryNext, "a two", "")
|
||||
test(ActionHistoryNext, "b three", "")
|
||||
test(ActionHistoryNext, "b four", "")
|
||||
test(ActionHistoryNext, "", "")
|
||||
test(ActionHistoryNext, "", "")
|
||||
|
||||
test(ActionHistoryPrevious, "b four", "")
|
||||
test(ActionHistoryPrevious, "b three", "")
|
||||
test(ActionHistoryNext, "b four", "")
|
||||
|
||||
rl.ResetText()
|
||||
rl.add_text("a")
|
||||
test(ActionHistoryPrevious, "a two", "")
|
||||
test(ActionHistoryPrevious, "a one", "")
|
||||
test(ActionHistoryPrevious, "a one", "")
|
||||
test(ActionHistoryNext, "a two", "")
|
||||
test(ActionHistoryNext, "a", "")
|
||||
test(ActionHistoryNext, "a", "")
|
||||
|
||||
ah := func(before_cursor, after_cursor string) {
|
||||
ab := rl.text_upto_cursor_pos()
|
||||
aa := rl.text_after_cursor_pos()
|
||||
if diff := cmp.Diff(before_cursor, ab); diff != "" {
|
||||
t.Fatalf("Text before cursor not as expected:\n%s", diff)
|
||||
}
|
||||
if diff := cmp.Diff(after_cursor, aa); diff != "" {
|
||||
t.Fatalf("Text after cursor not as expected:\n%s", diff)
|
||||
}
|
||||
}
|
||||
add_item("xyz1")
|
||||
add_item("xyz2")
|
||||
add_item("xyz11")
|
||||
rl.perform_action(ActionHistoryIncrementalSearchBackwards, 1)
|
||||
ah("", "")
|
||||
|
||||
rl.text_to_be_added = "z"
|
||||
rl.perform_action(ActionAddText, 1)
|
||||
ah("xy", "z11")
|
||||
rl.text_to_be_added = "2"
|
||||
rl.perform_action(ActionAddText, 1)
|
||||
ah("xy", "z2")
|
||||
rl.text_to_be_added = "m"
|
||||
rl.perform_action(ActionAddText, 1)
|
||||
ah("No matches for: z2m", "")
|
||||
rl.perform_action(ActionBackspace, 1)
|
||||
ah("xy", "z2")
|
||||
rl.perform_action(ActionBackspace, 1)
|
||||
ah("xy", "z2")
|
||||
rl.perform_action(ActionHistoryIncrementalSearchBackwards, 1)
|
||||
ah("xy", "z1")
|
||||
rl.perform_action(ActionHistoryIncrementalSearchBackwards, 1)
|
||||
ah("xy", "z1")
|
||||
rl.perform_action(ActionHistoryIncrementalSearchForwards, 1)
|
||||
ah("xy", "z2")
|
||||
rl.perform_action(ActionTerminateHistorySearchAndRestore, 1)
|
||||
ah("a", "")
|
||||
}
|
||||
|
||||
func TestReadlineCompletion(t *testing.T) {
|
||||
completer := func(before_cursor, after_cursor string) (ans *cli.Completions) {
|
||||
root := cli.NewRootCommand()
|
||||
c := root.AddSubCommand(&cli.Command{Name: "test-completion"})
|
||||
c.AddSubCommand(&cli.Command{Name: "a1"})
|
||||
c.AddSubCommand(&cli.Command{Name: "a11"})
|
||||
c.AddSubCommand(&cli.Command{Name: "a2"})
|
||||
prefix := c.Name + " "
|
||||
text := prefix + before_cursor
|
||||
argv, position_of_last_arg := shlex.SplitForCompletion(text)
|
||||
if len(argv) == 0 || position_of_last_arg < len(prefix) {
|
||||
return
|
||||
}
|
||||
ans = root.GetCompletions(argv, nil)
|
||||
ans.CurrentWordIdx = position_of_last_arg - len(prefix)
|
||||
return
|
||||
|
||||
}
|
||||
rl := new_rl()
|
||||
rl.completions.completer = completer
|
||||
|
||||
ah := func(before_cursor, after_cursor string) {
|
||||
ab := rl.text_upto_cursor_pos()
|
||||
aa := rl.text_after_cursor_pos()
|
||||
if diff := cmp.Diff(before_cursor, ab); diff != "" {
|
||||
t.Fatalf("Text before cursor not as expected:\n%s", diff)
|
||||
}
|
||||
if diff := cmp.Diff(after_cursor, aa); diff != "" {
|
||||
t.Fatalf("Text after cursor not as expected:\n%s", diff)
|
||||
}
|
||||
actual, _ := rl.completion_screen_lines()
|
||||
expected := []string{"a1 a11 a2 "}
|
||||
if diff := cmp.Diff(expected, actual[1:]); diff != "" {
|
||||
t.Fatalf("Completion screen lines not as expected:\n%s", diff)
|
||||
}
|
||||
}
|
||||
rl.add_text("a")
|
||||
rl.perform_action(ActionCompleteForward, 1)
|
||||
ah("a", "")
|
||||
rl.perform_action(ActionCompleteForward, 1)
|
||||
ah("a1 ", "")
|
||||
rl.perform_action(ActionCompleteForward, 1)
|
||||
ah("a11 ", "")
|
||||
rl.perform_action(ActionCompleteForward, 1)
|
||||
ah("a2 ", "")
|
||||
rl.perform_action(ActionCompleteBackward, 1)
|
||||
ah("a11 ", "")
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package readline
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"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/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
const ST = "\x1b\\"
|
||||
const PROMPT_MARK = "\x1b]133;"
|
||||
|
||||
type SyntaxHighlightFunction = func(text string, x, y int) string
|
||||
type CompleterFunction = func(before_cursor, after_cursor string) *cli.Completions
|
||||
|
||||
type RlInit struct {
|
||||
Prompt string
|
||||
HistoryPath string
|
||||
HistoryCount int
|
||||
ContinuationPrompt string
|
||||
EmptyContinuationPrompt bool
|
||||
DontMarkPrompts bool
|
||||
SyntaxHighlighter SyntaxHighlightFunction
|
||||
Completer CompleterFunction
|
||||
}
|
||||
|
||||
type Position struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
|
||||
func (self Position) Less(other Position) bool {
|
||||
return self.Y < other.Y || (self.Y == other.Y && self.X < other.X)
|
||||
}
|
||||
|
||||
type kill_ring struct {
|
||||
items *list.List
|
||||
}
|
||||
|
||||
func (self *kill_ring) append_to_existing_item(text string) {
|
||||
e := self.items.Front()
|
||||
if e == nil {
|
||||
self.add_new_item(text)
|
||||
}
|
||||
e.Value = e.Value.(string) + text
|
||||
}
|
||||
|
||||
func (self *kill_ring) add_new_item(text string) {
|
||||
if text != "" {
|
||||
self.items.PushFront(text)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *kill_ring) yank() string {
|
||||
e := self.items.Front()
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
return e.Value.(string)
|
||||
}
|
||||
|
||||
func (self *kill_ring) pop_yank() string {
|
||||
e := self.items.Front()
|
||||
if e == nil {
|
||||
return ""
|
||||
}
|
||||
self.items.MoveToBack(e)
|
||||
return self.yank()
|
||||
}
|
||||
|
||||
func (self *kill_ring) clear() {
|
||||
self.items = self.items.Init()
|
||||
}
|
||||
|
||||
type Prompt struct {
|
||||
Text string
|
||||
Length int
|
||||
}
|
||||
|
||||
type InputState struct {
|
||||
// Input lines
|
||||
lines []string
|
||||
// The cursor position in the text
|
||||
cursor Position
|
||||
}
|
||||
|
||||
func (self InputState) copy() InputState {
|
||||
ans := self
|
||||
l := make([]string, len(self.lines))
|
||||
copy(l, self.lines)
|
||||
ans.lines = l
|
||||
return ans
|
||||
}
|
||||
|
||||
type syntax_highlighted struct {
|
||||
lines []string
|
||||
src_for_last_highlight string
|
||||
highlighter SyntaxHighlightFunction
|
||||
last_highlighter_name string
|
||||
}
|
||||
|
||||
type Readline struct {
|
||||
prompt, continuation_prompt Prompt
|
||||
|
||||
mark_prompts bool
|
||||
loop *loop.Loop
|
||||
history *History
|
||||
kill_ring kill_ring
|
||||
|
||||
input_state InputState
|
||||
// The number of lines after the initial line on the screen
|
||||
cursor_y int
|
||||
screen_width, screen_height int
|
||||
last_yank_extent struct {
|
||||
start, end Position
|
||||
}
|
||||
bracketed_paste_buffer strings.Builder
|
||||
last_action Action
|
||||
history_matches *HistoryMatches
|
||||
history_search *HistorySearch
|
||||
keyboard_state KeyboardState
|
||||
fmt_ctx *markup.Context
|
||||
text_to_be_added string
|
||||
syntax_highlighted syntax_highlighted
|
||||
completions completions
|
||||
}
|
||||
|
||||
func (self *Readline) make_prompt(text string, is_secondary bool) Prompt {
|
||||
if self.mark_prompts {
|
||||
m := PROMPT_MARK + "A"
|
||||
if is_secondary {
|
||||
m += ";k=s"
|
||||
}
|
||||
text = m + ST + text
|
||||
}
|
||||
return Prompt{Text: text, Length: wcswidth.Stringwidth(text)}
|
||||
}
|
||||
|
||||
func New(loop *loop.Loop, r RlInit) *Readline {
|
||||
hc := r.HistoryCount
|
||||
if hc == 0 {
|
||||
hc = 8192
|
||||
}
|
||||
ans := &Readline{
|
||||
mark_prompts: !r.DontMarkPrompts, fmt_ctx: markup.New(true),
|
||||
loop: loop, input_state: InputState{lines: []string{""}}, history: NewHistory(r.HistoryPath, hc),
|
||||
syntax_highlighted: syntax_highlighted{highlighter: r.SyntaxHighlighter},
|
||||
completions: completions{completer: r.Completer},
|
||||
kill_ring: kill_ring{items: list.New().Init()},
|
||||
}
|
||||
if ans.completions.completer == nil && r.HistoryPath != "" {
|
||||
ans.completions.completer = ans.HistoryCompleter
|
||||
}
|
||||
ans.prompt = ans.make_prompt(r.Prompt, false)
|
||||
t := ""
|
||||
if r.ContinuationPrompt != "" || !r.EmptyContinuationPrompt {
|
||||
t = r.ContinuationPrompt
|
||||
if t == "" {
|
||||
t = ans.fmt_ctx.Yellow(">") + " "
|
||||
}
|
||||
}
|
||||
ans.continuation_prompt = ans.make_prompt(t, true)
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Readline) HistoryCompleter(before_cursor, after_cursor string) *cli.Completions {
|
||||
return self.history_completer(before_cursor, after_cursor)
|
||||
}
|
||||
|
||||
func (self *Readline) SetPrompt(prompt string) {
|
||||
self.prompt = self.make_prompt(prompt, false)
|
||||
}
|
||||
|
||||
func (self *Readline) Shutdown() {
|
||||
self.history.Shutdown()
|
||||
}
|
||||
|
||||
func (self *Readline) AddHistoryItem(hi HistoryItem) {
|
||||
self.history.merge_items(hi)
|
||||
}
|
||||
|
||||
func (self *Readline) ResetText() {
|
||||
self.input_state = InputState{lines: []string{""}}
|
||||
self.last_action = ActionNil
|
||||
self.keyboard_state = KeyboardState{}
|
||||
self.history_search = nil
|
||||
self.completions.current = completion{}
|
||||
self.cursor_y = 0
|
||||
}
|
||||
|
||||
func (self *Readline) ChangeLoopAndResetText(lp *loop.Loop) {
|
||||
self.loop = lp
|
||||
self.ResetText()
|
||||
}
|
||||
|
||||
func (self *Readline) Start() {
|
||||
self.loop.SetCursorShape(loop.BAR_CURSOR, true)
|
||||
self.loop.StartBracketedPaste()
|
||||
self.Redraw()
|
||||
}
|
||||
|
||||
func (self *Readline) End() {
|
||||
self.loop.SetCursorShape(loop.BLOCK_CURSOR, true)
|
||||
self.loop.EndBracketedPaste()
|
||||
self.loop.QueueWriteString("\r\n")
|
||||
if self.mark_prompts {
|
||||
self.loop.QueueWriteString(PROMPT_MARK + "C" + ST)
|
||||
}
|
||||
}
|
||||
|
||||
func MarkOutputStart() string {
|
||||
return PROMPT_MARK + "C" + ST
|
||||
}
|
||||
|
||||
func (self *Readline) Redraw() {
|
||||
self.loop.StartAtomicUpdate()
|
||||
self.RedrawNonAtomic()
|
||||
self.loop.EndAtomicUpdate()
|
||||
}
|
||||
|
||||
func (self *Readline) RedrawNonAtomic() {
|
||||
self.redraw()
|
||||
}
|
||||
|
||||
func (self *Readline) OnKeyEvent(event *loop.KeyEvent) error {
|
||||
err := self.handle_key_event(event)
|
||||
if err == ErrCouldNotPerformAction {
|
||||
err = nil
|
||||
self.loop.Beep()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *Readline) OnText(text string, from_key_event bool, in_bracketed_paste bool) error {
|
||||
if in_bracketed_paste {
|
||||
self.bracketed_paste_buffer.WriteString(text)
|
||||
return nil
|
||||
}
|
||||
if self.bracketed_paste_buffer.Len() > 0 {
|
||||
self.bracketed_paste_buffer.WriteString(text)
|
||||
text = self.bracketed_paste_buffer.String()
|
||||
self.bracketed_paste_buffer.Reset()
|
||||
}
|
||||
self.text_to_be_added = text
|
||||
return self.dispatch_key_action(ActionAddText)
|
||||
}
|
||||
|
||||
func (self *Readline) TextBeforeCursor() string {
|
||||
return self.text_upto_cursor_pos()
|
||||
}
|
||||
|
||||
func (self *Readline) TextAfterCursor() string {
|
||||
return self.text_after_cursor_pos()
|
||||
}
|
||||
|
||||
func (self *Readline) AllText() string {
|
||||
return self.all_text()
|
||||
}
|
||||
|
||||
func (self *Readline) SetText(text string) {
|
||||
self.set_text(text)
|
||||
}
|
||||
|
||||
func (self *Readline) MoveCursorToEnd() bool {
|
||||
return self.move_to_end()
|
||||
}
|
||||
|
||||
// PerformAction runs the specified editing Action directly, without going through
|
||||
// key resolution. Useful for callers that want to bind their own keys to a
|
||||
// specific line-editing operation, bypassing this package's own default keymap.
|
||||
func (self *Readline) PerformAction(ac Action, repeat_count uint) error {
|
||||
if repeat_count == 0 {
|
||||
repeat_count = 1
|
||||
}
|
||||
err := self.perform_action(ac, repeat_count)
|
||||
if err == ErrCouldNotPerformAction {
|
||||
self.loop.Beep()
|
||||
err = nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (self *Readline) CursorAtEndOfLine() bool {
|
||||
return self.input_state.cursor.X >= len(self.input_state.lines[self.input_state.cursor.Y])
|
||||
}
|
||||
|
||||
func (self *Readline) ClearCachedScreenSize() {
|
||||
self.screen_width, self.screen_height = 0, 0
|
||||
}
|
||||
|
||||
func (self *Readline) OnResize(old_size loop.ScreenSize, new_size loop.ScreenSize) error {
|
||||
self.ClearCachedScreenSize()
|
||||
self.Redraw()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package readline
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type completion struct {
|
||||
before_cursor, after_cursor string
|
||||
results *cli.Completions
|
||||
results_displayed, forwards bool
|
||||
num_of_matches, current_match int
|
||||
rendered_at_screen_width int
|
||||
rendered_lines []string
|
||||
last_rendered_above bool
|
||||
}
|
||||
|
||||
func (self *completion) initialize() {
|
||||
self.num_of_matches = 0
|
||||
if self.results != nil {
|
||||
for _, g := range self.results.Groups {
|
||||
self.num_of_matches += len(g.Matches)
|
||||
}
|
||||
}
|
||||
self.current_match = -1
|
||||
if !self.forwards {
|
||||
self.current_match = self.num_of_matches
|
||||
}
|
||||
if self.num_of_matches == 1 {
|
||||
self.current_match = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (self *completion) current_match_text() string {
|
||||
if self.results != nil {
|
||||
i := 0
|
||||
for _, g := range self.results.Groups {
|
||||
for _, m := range g.Matches {
|
||||
if i == self.current_match {
|
||||
t := m.Word
|
||||
if !g.NoTrailingSpace && t != "" {
|
||||
t += " "
|
||||
}
|
||||
return t
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type completions struct {
|
||||
completer CompleterFunction
|
||||
current completion
|
||||
}
|
||||
|
||||
func (self *Readline) complete(forwards bool, repeat_count uint) bool {
|
||||
c := &self.completions
|
||||
if c.completer == nil {
|
||||
return false
|
||||
}
|
||||
if self.last_action == ActionCompleteForward || self.last_action == ActionCompleteBackward {
|
||||
if c.current.num_of_matches == 0 {
|
||||
return false
|
||||
}
|
||||
delta := -1
|
||||
if forwards {
|
||||
delta = 1
|
||||
}
|
||||
repeat_count %= uint(c.current.num_of_matches)
|
||||
delta *= int(repeat_count)
|
||||
c.current.current_match = (c.current.current_match + delta + c.current.num_of_matches) % c.current.num_of_matches
|
||||
repeat_count = 0
|
||||
} else {
|
||||
before, after := self.text_upto_cursor_pos(), self.text_after_cursor_pos()
|
||||
c.current = completion{before_cursor: before, after_cursor: after, forwards: forwards, results: c.completer(before, after)}
|
||||
c.current.initialize()
|
||||
if repeat_count > 0 {
|
||||
repeat_count--
|
||||
}
|
||||
if c.current.current_match != 0 {
|
||||
if self.loop != nil {
|
||||
self.loop.Beep()
|
||||
}
|
||||
}
|
||||
}
|
||||
c.current.forwards = forwards
|
||||
if c.current.results == nil {
|
||||
return false
|
||||
}
|
||||
ct := c.current.current_match_text()
|
||||
if ct != "" {
|
||||
all_text_before_completion := self.AllText()
|
||||
before := c.current.before_cursor[:c.current.results.CurrentWordIdx] + ct
|
||||
after := c.current.after_cursor
|
||||
self.input_state.lines = utils.Splitlines(before)
|
||||
if len(self.input_state.lines) == 0 {
|
||||
self.input_state.lines = []string{""}
|
||||
}
|
||||
self.input_state.cursor.Y = len(self.input_state.lines) - 1
|
||||
self.input_state.cursor.X = len(self.input_state.lines[self.input_state.cursor.Y])
|
||||
al := utils.Splitlines(after)
|
||||
if len(al) > 0 {
|
||||
self.input_state.lines[self.input_state.cursor.Y] += al[0]
|
||||
self.input_state.lines = append(self.input_state.lines, al[1:]...)
|
||||
}
|
||||
if c.current.num_of_matches == 1 && self.AllText() == all_text_before_completion && repeat_count > 0 {
|
||||
// when there is only a single match and it has already been inserted there is no point iterating over current completions
|
||||
orig := self.last_action
|
||||
self.last_action = ActionNil
|
||||
self.complete(true, 1)
|
||||
self.last_action = orig
|
||||
}
|
||||
}
|
||||
if repeat_count > 0 {
|
||||
self.complete(forwards, repeat_count)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) screen_lines_for_match_group_with_descriptions(g *cli.MatchGroup, lines []string) []string {
|
||||
maxw := 0
|
||||
for _, m := range g.Matches {
|
||||
l := wcswidth.Stringwidth(m.Word)
|
||||
if l > 16 {
|
||||
maxw = 16
|
||||
break
|
||||
}
|
||||
if l > maxw {
|
||||
maxw = l
|
||||
}
|
||||
}
|
||||
for _, m := range g.Matches {
|
||||
lines = append(lines, utils.Splitlines(m.FormatForCompletionList(maxw, self.fmt_ctx, self.screen_width))...)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
type cell struct {
|
||||
text string
|
||||
length int
|
||||
}
|
||||
|
||||
func (self cell) whitespace(desired_length int) string {
|
||||
return strings.Repeat(" ", max(0, desired_length-self.length))
|
||||
}
|
||||
|
||||
type column struct {
|
||||
cells []cell
|
||||
length int
|
||||
is_last bool
|
||||
}
|
||||
|
||||
func (self *column) update_length() int {
|
||||
self.length = 0
|
||||
for _, c := range self.cells {
|
||||
if c.length > self.length {
|
||||
self.length = c.length
|
||||
}
|
||||
}
|
||||
if !self.is_last {
|
||||
self.length++
|
||||
}
|
||||
return self.length
|
||||
}
|
||||
|
||||
func layout_words_in_table(words []string, lengths map[string]int, num_cols int) ([]column, int) {
|
||||
cols := make([]column, num_cols)
|
||||
for i, col := range cols {
|
||||
col.cells = make([]cell, 0, len(words))
|
||||
if i == len(cols)-1 {
|
||||
col.is_last = true
|
||||
}
|
||||
}
|
||||
c := 0
|
||||
for _, word := range words {
|
||||
cols[c].cells = append(cols[c].cells, cell{word, lengths[word]})
|
||||
c++
|
||||
if c >= num_cols {
|
||||
c = 0
|
||||
}
|
||||
}
|
||||
total_length := 0
|
||||
for i := range cols {
|
||||
if d := len(cols[0].cells) - len(cols[i].cells); d > 0 {
|
||||
cols[i].cells = append(cols[i].cells, make([]cell, d)...)
|
||||
}
|
||||
total_length += cols[i].update_length()
|
||||
}
|
||||
return cols, total_length
|
||||
}
|
||||
|
||||
func (self *Readline) screen_lines_for_match_group_without_descriptions(g *cli.MatchGroup, lines []string) []string {
|
||||
words := make([]string, len(g.Matches))
|
||||
lengths := make(map[string]int, len(words))
|
||||
max_length := 0
|
||||
for i, m := range g.Matches {
|
||||
words[i] = m.Word
|
||||
l := wcswidth.Stringwidth(words[i])
|
||||
lengths[words[i]] = l
|
||||
if l > max_length {
|
||||
max_length = l
|
||||
}
|
||||
}
|
||||
var ans []column
|
||||
ncols := max(1, self.screen_width/(max_length+1))
|
||||
for {
|
||||
cols, total_length := layout_words_in_table(words, lengths, ncols)
|
||||
if total_length > self.screen_width {
|
||||
break
|
||||
}
|
||||
ans = cols
|
||||
ncols++
|
||||
}
|
||||
if ans == nil {
|
||||
for _, w := range words {
|
||||
if lengths[w] > self.screen_width {
|
||||
lines = append(lines, wcswidth.TruncateToVisualLength(w, self.screen_width))
|
||||
} else {
|
||||
lines = append(lines, w)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for r := 0; r < len(ans[0].cells); r++ {
|
||||
w := strings.Builder{}
|
||||
w.Grow(self.screen_width)
|
||||
for c := 0; c < len(ans); c++ {
|
||||
cell := ans[c].cells[r]
|
||||
w.WriteString(cell.text)
|
||||
if !ans[c].is_last {
|
||||
w.WriteString(cell.whitespace(ans[c].length))
|
||||
}
|
||||
}
|
||||
lines = append(lines, w.String())
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func (self *Readline) completion_screen_lines() ([]string, bool) {
|
||||
if self.completions.current.results == nil || self.completions.current.num_of_matches < 2 {
|
||||
return []string{}, false
|
||||
}
|
||||
if len(self.completions.current.rendered_lines) > 0 && self.completions.current.rendered_at_screen_width == self.screen_width {
|
||||
return self.completions.current.rendered_lines, true
|
||||
}
|
||||
lines := make([]string, 0, self.completions.current.num_of_matches)
|
||||
for _, g := range self.completions.current.results.Groups {
|
||||
if len(g.Matches) == 0 {
|
||||
continue
|
||||
}
|
||||
if g.Title != "" {
|
||||
lines = append(lines, self.fmt_ctx.Title(g.Title))
|
||||
}
|
||||
has_descriptions := false
|
||||
for _, m := range g.Matches {
|
||||
if m.Description != "" {
|
||||
has_descriptions = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if has_descriptions {
|
||||
lines = self.screen_lines_for_match_group_with_descriptions(g, lines)
|
||||
} else {
|
||||
lines = self.screen_lines_for_match_group_without_descriptions(g, lines)
|
||||
}
|
||||
}
|
||||
self.completions.current.rendered_lines = lines
|
||||
self.completions.current.rendered_at_screen_width = self.screen_width
|
||||
return lines, false
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package readline
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func (self *Readline) update_current_screen_size() {
|
||||
var screen_size loop.ScreenSize
|
||||
var err error
|
||||
if self.loop != nil {
|
||||
screen_size, err = self.loop.ScreenSize()
|
||||
if err != nil {
|
||||
screen_size.WidthCells = 80
|
||||
screen_size.HeightCells = 24
|
||||
}
|
||||
} else {
|
||||
screen_size.WidthCells = 80
|
||||
screen_size.HeightCells = 24
|
||||
}
|
||||
self.screen_width = max(1, int(screen_size.WidthCells))
|
||||
self.screen_height = max(1, int(screen_size.HeightCells))
|
||||
}
|
||||
|
||||
type ScreenLine struct {
|
||||
ParentLineNumber, OffsetInParentLine int
|
||||
Prompt Prompt
|
||||
TextLengthInCells, CursorCell, CursorTextPos int
|
||||
Text string
|
||||
AfterLineBreak bool
|
||||
}
|
||||
|
||||
func (self *Readline) format_arg_prompt(cna string) string {
|
||||
return fmt.Sprintf("(arg: %s) ", self.fmt_ctx.Yellow(cna))
|
||||
}
|
||||
|
||||
func (self *Readline) prompt_for_line_number(i int) Prompt {
|
||||
is_line_with_cursor := i == self.input_state.cursor.Y
|
||||
if is_line_with_cursor && self.keyboard_state.current_numeric_argument != "" {
|
||||
return self.make_prompt(self.format_arg_prompt(self.keyboard_state.current_numeric_argument), i > 0)
|
||||
}
|
||||
if i == 0 {
|
||||
if self.history_search != nil {
|
||||
return self.make_prompt(self.history_search_prompt(), i > 0)
|
||||
}
|
||||
return self.prompt
|
||||
}
|
||||
return self.continuation_prompt
|
||||
}
|
||||
|
||||
func (self *Readline) apply_syntax_highlighting() (lines []string, cursor Position) {
|
||||
highlighter := self.syntax_highlighted.highlighter
|
||||
highlighter_name := "default"
|
||||
if self.history_search != nil {
|
||||
highlighter = self.history_search_highlighter
|
||||
highlighter_name = "## history ##"
|
||||
}
|
||||
if highlighter == nil {
|
||||
return self.input_state.lines, self.input_state.cursor
|
||||
}
|
||||
src := strings.Join(self.input_state.lines, "\n")
|
||||
if len(self.syntax_highlighted.lines) > 0 && self.syntax_highlighted.last_highlighter_name == highlighter_name && self.syntax_highlighted.src_for_last_highlight == src {
|
||||
lines = self.syntax_highlighted.lines
|
||||
} else {
|
||||
if src == "" {
|
||||
lines = []string{""}
|
||||
} else {
|
||||
text := highlighter(src, self.input_state.cursor.X, self.input_state.cursor.Y)
|
||||
lines = utils.Splitlines(text)
|
||||
for len(lines) < len(self.input_state.lines) {
|
||||
lines = append(lines, "syntax highlighter malfunctioned")
|
||||
}
|
||||
}
|
||||
}
|
||||
line := lines[self.input_state.cursor.Y]
|
||||
w := wcswidth.Stringwidth(self.input_state.lines[self.input_state.cursor.Y][:self.input_state.cursor.X])
|
||||
x := len(wcswidth.TruncateToVisualLength(line, w))
|
||||
return lines, Position{X: x, Y: self.input_state.cursor.Y}
|
||||
}
|
||||
|
||||
func (self *Readline) get_screen_lines() []*ScreenLine {
|
||||
if self.screen_width == 0 || self.screen_height == 0 {
|
||||
self.update_current_screen_size()
|
||||
}
|
||||
lines, cursor := self.apply_syntax_highlighting()
|
||||
ans := make([]*ScreenLine, 0, len(lines))
|
||||
found_cursor := false
|
||||
cursor_at_start_of_next_line := false
|
||||
for i, line := range lines {
|
||||
prompt := self.prompt_for_line_number(i)
|
||||
offset := 0
|
||||
has_cursor := i == cursor.Y
|
||||
for is_first := true; is_first || offset < len(line); is_first = false {
|
||||
l, width := wcswidth.TruncateToVisualLengthWithWidth(line[offset:], self.screen_width-prompt.Length)
|
||||
sl := ScreenLine{
|
||||
ParentLineNumber: i, OffsetInParentLine: offset,
|
||||
Prompt: prompt, TextLengthInCells: width,
|
||||
CursorCell: -1, Text: l, CursorTextPos: -1, AfterLineBreak: is_first,
|
||||
}
|
||||
if cursor_at_start_of_next_line {
|
||||
cursor_at_start_of_next_line = false
|
||||
sl.CursorCell = prompt.Length
|
||||
sl.CursorTextPos = 0
|
||||
found_cursor = true
|
||||
}
|
||||
ans = append(ans, &sl)
|
||||
if has_cursor && !found_cursor && offset <= cursor.X && cursor.X <= offset+len(l) {
|
||||
found_cursor = true
|
||||
ctpos := cursor.X - offset
|
||||
ccell := prompt.Length + wcswidth.Stringwidth(l[:ctpos])
|
||||
if ccell >= self.screen_width {
|
||||
if offset+len(l) < len(line) || i < len(lines)-1 {
|
||||
cursor_at_start_of_next_line = true
|
||||
} else {
|
||||
ans = append(ans, &ScreenLine{ParentLineNumber: i, OffsetInParentLine: len(line)})
|
||||
}
|
||||
} else {
|
||||
sl.CursorTextPos = ctpos
|
||||
sl.CursorCell = ccell
|
||||
}
|
||||
}
|
||||
prompt = Prompt{}
|
||||
offset += len(l)
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func (self *Readline) redraw() {
|
||||
if self.screen_width == 0 || self.screen_height == 0 {
|
||||
self.update_current_screen_size()
|
||||
}
|
||||
if self.screen_width < 4 {
|
||||
return
|
||||
}
|
||||
if self.cursor_y > 0 {
|
||||
self.loop.MoveCursorVertically(-self.cursor_y)
|
||||
}
|
||||
self.loop.QueueWriteString("\r")
|
||||
self.loop.ClearToEndOfScreen()
|
||||
prompt_lines := self.get_screen_lines()
|
||||
csl, csl_cached := self.completion_screen_lines()
|
||||
render_completion_above := len(csl)+len(prompt_lines) > self.screen_height
|
||||
completion_needs_render := len(csl) > 0 && (!render_completion_above || !self.completions.current.last_rendered_above || !csl_cached)
|
||||
final_cursor_x := -1
|
||||
cursor_y := 0
|
||||
move_cursor_up_by := 0
|
||||
|
||||
render_completion_lines := func() int {
|
||||
if completion_needs_render {
|
||||
if render_completion_above {
|
||||
self.loop.QueueWriteString("\r")
|
||||
} else {
|
||||
self.loop.QueueWriteString("\r\n")
|
||||
}
|
||||
for i, cl := range csl {
|
||||
self.loop.QueueWriteString(cl)
|
||||
if i < len(csl)-1 || render_completion_above {
|
||||
self.loop.QueueWriteString("\n\r")
|
||||
}
|
||||
|
||||
}
|
||||
return len(csl)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
self.loop.AllowLineWrapping(false)
|
||||
if render_completion_above {
|
||||
render_completion_lines()
|
||||
}
|
||||
self.loop.AllowLineWrapping(true)
|
||||
self.loop.QueueWriteString("\r")
|
||||
text_length := 0
|
||||
|
||||
for i, sl := range prompt_lines {
|
||||
cursor_moved_down := false
|
||||
if i > 0 && sl.AfterLineBreak {
|
||||
self.loop.QueueWriteString("\r\n")
|
||||
cursor_moved_down = true
|
||||
text_length = 0
|
||||
}
|
||||
if sl.Prompt.Length > 0 {
|
||||
p := self.prompt_for_line_number(i)
|
||||
self.loop.QueueWriteString(p.Text)
|
||||
text_length += p.Length
|
||||
}
|
||||
self.loop.QueueWriteString(sl.Text)
|
||||
text_length += sl.TextLengthInCells
|
||||
if text_length == self.screen_width && sl.Text == "" && i == len(prompt_lines)-1 {
|
||||
self.loop.QueueWriteString("\r\n")
|
||||
cursor_moved_down = true
|
||||
text_length = 0
|
||||
}
|
||||
if text_length > self.screen_width {
|
||||
cursor_moved_down = true
|
||||
text_length -= self.screen_width
|
||||
}
|
||||
if sl.CursorCell > -1 {
|
||||
final_cursor_x = sl.CursorCell
|
||||
} else if final_cursor_x > -1 {
|
||||
if cursor_moved_down {
|
||||
move_cursor_up_by++
|
||||
}
|
||||
}
|
||||
if cursor_moved_down {
|
||||
cursor_y++
|
||||
}
|
||||
}
|
||||
if !render_completion_above {
|
||||
move_cursor_up_by += render_completion_lines()
|
||||
}
|
||||
self.loop.MoveCursorVertically(-move_cursor_up_by)
|
||||
self.loop.QueueWriteString("\r")
|
||||
self.loop.MoveCursorHorizontally(final_cursor_x)
|
||||
self.cursor_y = 0
|
||||
cursor_y -= move_cursor_up_by
|
||||
if cursor_y > 0 {
|
||||
self.cursor_y = cursor_y
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package readline
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type HistoryItem struct {
|
||||
Cmd string `json:"cmd"`
|
||||
Cwd string `json:"cwd,omitempty"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Duration time.Duration `json:"duration,omitempty"`
|
||||
ExitCode int `json:"exit_code"`
|
||||
}
|
||||
|
||||
type HistoryMatches struct {
|
||||
items []HistoryItem
|
||||
prefix string
|
||||
current_idx int
|
||||
original_input_state InputState
|
||||
}
|
||||
|
||||
type HistorySearch struct {
|
||||
query string
|
||||
tokens []string
|
||||
items []*HistoryItem
|
||||
current_idx int
|
||||
backwards bool
|
||||
original_input_state InputState
|
||||
}
|
||||
|
||||
type History struct {
|
||||
file_path string
|
||||
file *os.File
|
||||
max_items int
|
||||
items []HistoryItem
|
||||
cmd_map map[string]int
|
||||
}
|
||||
|
||||
func map_from_items(items []HistoryItem) map[string]int {
|
||||
pmap := make(map[string]int, len(items))
|
||||
for i, hi := range items {
|
||||
pmap[hi.Cmd] = i
|
||||
}
|
||||
return pmap
|
||||
}
|
||||
|
||||
func (self *History) add_item(x HistoryItem) bool {
|
||||
existing, found := self.cmd_map[x.Cmd]
|
||||
if found {
|
||||
if self.items[existing].Timestamp.Before(x.Timestamp) {
|
||||
self.items[existing] = x
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
self.cmd_map[x.Cmd] = len(self.items)
|
||||
self.items = append(self.items, x)
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *History) merge_items(items ...HistoryItem) {
|
||||
if len(self.items) == 0 {
|
||||
self.items = items
|
||||
self.cmd_map = map_from_items(self.items)
|
||||
return
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return
|
||||
}
|
||||
changed := false
|
||||
for _, x := range items {
|
||||
if self.add_item(x) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return
|
||||
}
|
||||
self.items = utils.StableSort(self.items, func(a, b HistoryItem) int {
|
||||
return a.Timestamp.Compare(b.Timestamp)
|
||||
})
|
||||
if len(self.items) > self.max_items {
|
||||
self.items = self.items[len(self.items)-self.max_items:]
|
||||
}
|
||||
self.cmd_map = map_from_items(self.items)
|
||||
}
|
||||
|
||||
func (self *History) Write() {
|
||||
if self.file == nil {
|
||||
return
|
||||
}
|
||||
self.file.Seek(0, 0)
|
||||
utils.LockFileExclusive(self.file)
|
||||
defer utils.UnlockFile(self.file)
|
||||
data, err := io.ReadAll(self.file)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var items []HistoryItem
|
||||
err = json.Unmarshal(data, &items)
|
||||
if err != nil {
|
||||
self.merge_items(items...)
|
||||
}
|
||||
ndata, err := json.MarshalIndent(self.items, "", " ")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
self.file.Truncate(int64(len(ndata)))
|
||||
self.file.Seek(0, 0)
|
||||
self.file.Write(ndata)
|
||||
}
|
||||
|
||||
func (self *History) Read() {
|
||||
if self.file == nil {
|
||||
return
|
||||
}
|
||||
self.file.Seek(0, 0)
|
||||
utils.LockFileShared(self.file)
|
||||
data, err := io.ReadAll(self.file)
|
||||
utils.UnlockFile(self.file)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var items []HistoryItem
|
||||
err = json.Unmarshal(data, &items)
|
||||
if err == nil {
|
||||
self.merge_items(items...)
|
||||
}
|
||||
}
|
||||
|
||||
func (self *History) AddItem(cmd string, duration time.Duration) {
|
||||
self.merge_items(HistoryItem{Cmd: cmd, Duration: duration, Timestamp: time.Now()})
|
||||
}
|
||||
|
||||
func (self *History) Shutdown() {
|
||||
if self.file != nil {
|
||||
self.Write()
|
||||
self.file.Close()
|
||||
self.file = nil
|
||||
}
|
||||
}
|
||||
|
||||
func NewHistory(path string, max_items int) *History {
|
||||
ans := History{items: []HistoryItem{}, cmd_map: map[string]int{}, max_items: max_items}
|
||||
if path != "" {
|
||||
ans.file_path = path
|
||||
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600)
|
||||
if err == nil {
|
||||
ans.file = f
|
||||
} else {
|
||||
fmt.Fprintln(os.Stderr, "Failed to open history file at:", path, "with error:", err)
|
||||
}
|
||||
}
|
||||
ans.Read()
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *History) find_prefix_matches(prefix, current_command string, input_state InputState) *HistoryMatches {
|
||||
ans := HistoryMatches{items: make([]HistoryItem, 0, len(self.items)+1), prefix: prefix, original_input_state: input_state}
|
||||
if prefix == "" {
|
||||
ans.items = ans.items[:len(self.items)]
|
||||
copy(ans.items, self.items)
|
||||
} else {
|
||||
for _, x := range self.items {
|
||||
if strings.HasPrefix(x.Cmd, prefix) {
|
||||
ans.items = append(ans.items, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
ans.items = append(ans.items, HistoryItem{Cmd: current_command})
|
||||
ans.current_idx = len(ans.items) - 1
|
||||
return &ans
|
||||
}
|
||||
|
||||
func (self *Readline) create_history_matches() {
|
||||
if self.last_action_was_history_movement() && self.history_matches != nil {
|
||||
return
|
||||
}
|
||||
prefix := self.text_upto_cursor_pos()
|
||||
self.history_matches = self.history.find_prefix_matches(prefix, self.AllText(), self.input_state.copy())
|
||||
}
|
||||
|
||||
func (self *Readline) last_action_was_history_movement() bool {
|
||||
switch self.last_action {
|
||||
case ActionHistoryLast, ActionHistoryFirst, ActionHistoryNext, ActionHistoryPrevious:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (self *HistoryMatches) apply(rl *Readline) bool {
|
||||
if self.current_idx >= len(self.items) || self.current_idx < 0 {
|
||||
return false
|
||||
}
|
||||
if self.current_idx == len(self.items)-1 {
|
||||
rl.input_state = self.original_input_state.copy()
|
||||
} else {
|
||||
item := self.items[self.current_idx]
|
||||
rl.input_state.lines = utils.Splitlines(item.Cmd)
|
||||
if len(rl.input_state.lines) == 0 {
|
||||
rl.input_state.lines = []string{""}
|
||||
}
|
||||
idx := len(rl.input_state.lines) - 1
|
||||
rl.input_state.cursor = Position{Y: idx, X: len(rl.input_state.lines[idx])}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *HistoryMatches) first(rl *Readline) bool {
|
||||
self.current_idx = 0
|
||||
return self.apply(rl)
|
||||
}
|
||||
|
||||
func (self *HistoryMatches) last(rl *Readline) bool {
|
||||
self.current_idx = max(0, len(self.items)-1)
|
||||
return self.apply(rl)
|
||||
}
|
||||
|
||||
func (self *HistoryMatches) previous(num uint, rl *Readline) bool {
|
||||
if self.current_idx > 0 {
|
||||
self.current_idx = max(0, self.current_idx-int(num))
|
||||
return self.apply(rl)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *HistoryMatches) next(num uint, rl *Readline) bool {
|
||||
if self.current_idx+1 < len(self.items) {
|
||||
self.current_idx = min(len(self.items)-1, self.current_idx+int(num))
|
||||
return self.apply(rl)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (self *Readline) create_history_search(backwards bool, num uint) {
|
||||
self.history_search = &HistorySearch{backwards: backwards, original_input_state: self.input_state.copy()}
|
||||
self.push_keyboard_map(history_search_shortcuts())
|
||||
self.markup_history_search()
|
||||
}
|
||||
|
||||
func (self *Readline) end_history_search(accept bool) {
|
||||
if accept && self.history_search.current_idx < len(self.history_search.items) {
|
||||
self.input_state.lines = utils.Splitlines(self.history_search.items[self.history_search.current_idx].Cmd)
|
||||
self.input_state.cursor.Y = len(self.input_state.lines) - 1
|
||||
self.input_state.cursor.X = len(self.input_state.lines[self.input_state.cursor.Y])
|
||||
} else {
|
||||
self.input_state = self.history_search.original_input_state
|
||||
}
|
||||
self.input_state.cursor = *self.ensure_position_in_bounds(&self.input_state.cursor)
|
||||
self.pop_keyboard_map()
|
||||
self.history_search = nil
|
||||
}
|
||||
|
||||
func (self *Readline) markup_history_search() {
|
||||
if len(self.history_search.items) == 0 {
|
||||
if len(self.history_search.tokens) == 0 {
|
||||
self.input_state.lines = []string{""}
|
||||
} else {
|
||||
self.input_state.lines = []string{"No matches for: " + self.history_search.query}
|
||||
}
|
||||
self.input_state.cursor = Position{X: wcswidth.Stringwidth(self.input_state.lines[0])}
|
||||
return
|
||||
}
|
||||
lines := utils.Splitlines(self.history_search.items[self.history_search.current_idx].Cmd)
|
||||
cursor := Position{Y: len(lines)}
|
||||
for _, tok := range self.history_search.tokens {
|
||||
for i, line := range lines {
|
||||
if idx := strings.Index(line, tok); idx > -1 {
|
||||
q := Position{Y: i, X: idx}
|
||||
if q.Less(cursor) {
|
||||
cursor = q
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
self.input_state.lines = lines
|
||||
self.input_state.cursor = *self.ensure_position_in_bounds(&cursor)
|
||||
}
|
||||
|
||||
func (self *Readline) remove_text_from_history_search(num uint) uint {
|
||||
l := len(self.history_search.query)
|
||||
nl := max(0, l-int(num))
|
||||
self.history_search.query = self.history_search.query[:nl]
|
||||
num_removed := uint(l - nl)
|
||||
self.add_text_to_history_search("") // update the search results
|
||||
return num_removed
|
||||
}
|
||||
|
||||
func (self *Readline) history_search_highlighter(text string, x, y int) string {
|
||||
if len(self.history_search.items) == 0 {
|
||||
return text
|
||||
}
|
||||
lines := utils.Splitlines(text)
|
||||
for _, tok := range self.history_search.tokens {
|
||||
for i, line := range lines {
|
||||
if before, after, ok := strings.Cut(line, tok); ok {
|
||||
lines[i] = before + self.fmt_ctx.Green(tok) + after
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func (self *Readline) add_text_to_history_search(text string) {
|
||||
self.history_search.query += text
|
||||
tokens, err := shlex.Split(self.history_search.query)
|
||||
if err != nil {
|
||||
tokens = strings.Split(self.history_search.query, " ")
|
||||
}
|
||||
self.history_search.tokens = tokens
|
||||
var current_item *HistoryItem
|
||||
if len(self.history_search.items) > 0 {
|
||||
current_item = self.history_search.items[self.history_search.current_idx]
|
||||
}
|
||||
if len(self.history_search.tokens) == 0 {
|
||||
self.history_search.items = []*HistoryItem{}
|
||||
} else {
|
||||
items := make([]*HistoryItem, len(self.history.items))
|
||||
for i := range self.history.items {
|
||||
items[i] = &self.history.items[i]
|
||||
}
|
||||
for _, token := range self.history_search.tokens {
|
||||
matches := make([]*HistoryItem, 0, len(items))
|
||||
for _, item := range items {
|
||||
if strings.Contains(item.Cmd, token) {
|
||||
matches = append(matches, item)
|
||||
}
|
||||
}
|
||||
items = matches
|
||||
}
|
||||
self.history_search.items = items
|
||||
}
|
||||
idx := -1
|
||||
for i, item := range self.history_search.items {
|
||||
if item == current_item {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if idx == -1 {
|
||||
if self.history_search.backwards {
|
||||
idx = len(self.history_search.items) - 1
|
||||
} else {
|
||||
idx = 0
|
||||
}
|
||||
}
|
||||
self.history_search.current_idx = max(0, idx)
|
||||
self.markup_history_search()
|
||||
}
|
||||
|
||||
func (self *Readline) next_history_search(backwards bool, num uint) bool {
|
||||
ni := self.history_search.current_idx
|
||||
self.history_search.backwards = backwards
|
||||
if len(self.history_search.items) == 0 {
|
||||
return false
|
||||
}
|
||||
if backwards {
|
||||
ni = max(0, ni-int(num))
|
||||
} else {
|
||||
ni = min(ni+int(num), len(self.history_search.items)-1)
|
||||
}
|
||||
if ni == self.history_search.current_idx {
|
||||
return false
|
||||
}
|
||||
self.history_search.current_idx = ni
|
||||
self.markup_history_search()
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Readline) history_search_prompt() string {
|
||||
ans := "↑"
|
||||
if !self.history_search.backwards {
|
||||
ans = "↓"
|
||||
}
|
||||
failed := len(self.history_search.tokens) > 0 && len(self.history_search.items) == 0
|
||||
if failed {
|
||||
ans = self.fmt_ctx.BrightRed(ans)
|
||||
} else {
|
||||
ans = self.fmt_ctx.Green(ans)
|
||||
}
|
||||
return fmt.Sprintf("history %s: ", ans)
|
||||
}
|
||||
|
||||
func (self *Readline) history_completer(before_cursor, after_cursor string) (ans *cli.Completions) {
|
||||
ans = cli.NewCompletions()
|
||||
if before_cursor != "" {
|
||||
var words_before_cursor []string
|
||||
words_before_cursor, ans.CurrentWordIdx = shlex.SplitForCompletion(before_cursor)
|
||||
idx := len(words_before_cursor)
|
||||
if idx > 0 {
|
||||
idx--
|
||||
}
|
||||
seen := utils.NewSet[string](16)
|
||||
mg := ans.AddMatchGroup("History")
|
||||
for _, x := range self.history.items {
|
||||
if strings.HasPrefix(x.Cmd, before_cursor) {
|
||||
words, _ := shlex.SplitForCompletion(x.Cmd)
|
||||
if idx < len(words) {
|
||||
word := words[idx]
|
||||
desc := ""
|
||||
if !seen.Has(word) {
|
||||
if word != x.Cmd {
|
||||
desc = x.Cmd
|
||||
}
|
||||
mg.AddMatch(word, desc)
|
||||
seen.Add(word)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package readline
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/shortcuts"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type ShortcutMap = shortcuts.ShortcutMap[Action]
|
||||
|
||||
type KeyboardState struct {
|
||||
active_shortcut_maps []*ShortcutMap
|
||||
current_pending_keys []string
|
||||
current_numeric_argument string
|
||||
}
|
||||
|
||||
var _default_shortcuts *ShortcutMap
|
||||
|
||||
func default_shortcuts() *ShortcutMap {
|
||||
if _default_shortcuts == nil {
|
||||
sm := shortcuts.New[Action]()
|
||||
sm.AddOrPanic(ActionBackspace, "backspace")
|
||||
sm.AddOrPanic(ActionBackspace, "shift+backspace")
|
||||
sm.AddOrPanic(ActionBackspace, "ctrl+h")
|
||||
sm.AddOrPanic(ActionDelete, "delete")
|
||||
|
||||
sm.AddOrPanic(ActionMoveToStartOfLine, "home")
|
||||
sm.AddOrPanic(ActionMoveToStartOfLine, "ctrl+a")
|
||||
|
||||
sm.AddOrPanic(ActionMoveToEndOfLine, "end")
|
||||
sm.AddOrPanic(ActionMoveToEndOfLine, "ctrl+e")
|
||||
|
||||
sm.AddOrPanic(ActionMoveToStartOfDocument, "ctrl+home")
|
||||
sm.AddOrPanic(ActionMoveToEndOfDocument, "ctrl+end")
|
||||
|
||||
sm.AddOrPanic(ActionMoveToEndOfWord, "alt+f")
|
||||
sm.AddOrPanic(ActionMoveToEndOfWord, "ctrl+right")
|
||||
sm.AddOrPanic(ActionMoveToEndOfWord, "alt+right")
|
||||
sm.AddOrPanic(ActionMoveToStartOfWord, "ctrl+left")
|
||||
sm.AddOrPanic(ActionMoveToStartOfWord, "alt+left")
|
||||
sm.AddOrPanic(ActionMoveToStartOfWord, "alt+b")
|
||||
|
||||
sm.AddOrPanic(ActionCursorLeft, "left")
|
||||
sm.AddOrPanic(ActionCursorLeft, "ctrl+b")
|
||||
sm.AddOrPanic(ActionCursorRight, "right")
|
||||
sm.AddOrPanic(ActionCursorRight, "ctrl+f")
|
||||
|
||||
sm.AddOrPanic(ActionClearScreen, "ctrl+l")
|
||||
sm.AddOrPanic(ActionAbortCurrentLine, "ctrl+c")
|
||||
sm.AddOrPanic(ActionAbortCurrentLine, "ctrl+g")
|
||||
|
||||
sm.AddOrPanic(ActionEndInput, "ctrl+d")
|
||||
sm.AddOrPanic(ActionAcceptInput, "enter")
|
||||
|
||||
sm.AddOrPanic(ActionKillToEndOfLine, "ctrl+k")
|
||||
sm.AddOrPanic(ActionKillToStartOfLine, "ctrl+x")
|
||||
sm.AddOrPanic(ActionKillToStartOfLine, "ctrl+u")
|
||||
sm.AddOrPanic(ActionKillNextWord, "alt+d")
|
||||
sm.AddOrPanic(ActionKillPreviousWord, "alt+backspace")
|
||||
sm.AddOrPanic(ActionKillPreviousWord, "ctrl+backspace")
|
||||
sm.AddOrPanic(ActionKillPreviousSpaceDelimitedWord, "ctrl+w")
|
||||
sm.AddOrPanic(ActionYank, "ctrl+y")
|
||||
sm.AddOrPanic(ActionPopYank, "alt+y")
|
||||
|
||||
sm.AddOrPanic(ActionHistoryPreviousOrCursorUp, "up")
|
||||
sm.AddOrPanic(ActionHistoryNextOrCursorDown, "down")
|
||||
sm.AddOrPanic(ActionHistoryPrevious, "ctrl+p")
|
||||
sm.AddOrPanic(ActionHistoryNext, "ctrl+n")
|
||||
sm.AddOrPanic(ActionHistoryFirst, "alt+<")
|
||||
sm.AddOrPanic(ActionHistoryLast, "alt+>")
|
||||
sm.AddOrPanic(ActionHistoryIncrementalSearchBackwards, "ctrl+r")
|
||||
sm.AddOrPanic(ActionHistoryIncrementalSearchBackwards, "ctrl+?")
|
||||
sm.AddOrPanic(ActionHistoryIncrementalSearchForwards, "ctrl+s")
|
||||
sm.AddOrPanic(ActionHistoryIncrementalSearchForwards, "ctrl+/")
|
||||
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit0, "alt+0")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit1, "alt+1")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit2, "alt+2")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit3, "alt+3")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit4, "alt+4")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit5, "alt+5")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit6, "alt+6")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit7, "alt+7")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit8, "alt+8")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigit9, "alt+9")
|
||||
sm.AddOrPanic(ActionNumericArgumentDigitMinus, "alt+-")
|
||||
|
||||
sm.AddOrPanic(ActionCompleteForward, "Tab")
|
||||
sm.AddOrPanic(ActionCompleteBackward, "Shift+Tab")
|
||||
_default_shortcuts = sm
|
||||
}
|
||||
return _default_shortcuts
|
||||
}
|
||||
|
||||
var _history_search_shortcuts *shortcuts.ShortcutMap[Action]
|
||||
|
||||
func history_search_shortcuts() *shortcuts.ShortcutMap[Action] {
|
||||
if _history_search_shortcuts == nil {
|
||||
sm := shortcuts.New[Action]()
|
||||
sm.AddOrPanic(ActionBackspace, "backspace")
|
||||
sm.AddOrPanic(ActionBackspace, "ctrl+h")
|
||||
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "home")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+a")
|
||||
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "end")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+e")
|
||||
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+home")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+end")
|
||||
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "alt+f")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+right")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+left")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "alt+b")
|
||||
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "left")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+b")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "right")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+f")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "up")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "down")
|
||||
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+c")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "ctrl+g")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndRestore, "escape")
|
||||
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndApply, "ctrl+d")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndApply, "enter")
|
||||
sm.AddOrPanic(ActionTerminateHistorySearchAndApply, "ctrl+j")
|
||||
|
||||
_history_search_shortcuts = sm
|
||||
}
|
||||
return _history_search_shortcuts
|
||||
}
|
||||
|
||||
var ErrCouldNotPerformAction = errors.New("Could not perform the specified action")
|
||||
var ErrAcceptInput = errors.New("Accept input")
|
||||
|
||||
func (self *Readline) push_keyboard_map(m *ShortcutMap) {
|
||||
maps := self.keyboard_state.active_shortcut_maps
|
||||
self.keyboard_state = KeyboardState{}
|
||||
if maps == nil {
|
||||
maps = make([]*ShortcutMap, 0, 2)
|
||||
}
|
||||
self.keyboard_state.active_shortcut_maps = append(maps, m)
|
||||
}
|
||||
|
||||
func (self *Readline) pop_keyboard_map() {
|
||||
maps := self.keyboard_state.active_shortcut_maps
|
||||
self.keyboard_state = KeyboardState{}
|
||||
if len(maps) > 0 {
|
||||
maps = maps[:len(maps)-1]
|
||||
self.keyboard_state.active_shortcut_maps = maps
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Readline) handle_numeric_arg(ac Action) {
|
||||
t := "-"
|
||||
num := int(ac - ActionNumericArgumentDigit0)
|
||||
if num < 10 {
|
||||
t = strconv.Itoa(num)
|
||||
}
|
||||
cna := self.keyboard_state.current_numeric_argument
|
||||
if (cna == "" && t == "0") || (cna != "" && t == "-") {
|
||||
self.add_text(t)
|
||||
self.keyboard_state.current_numeric_argument = ""
|
||||
self.last_action = ActionAddText
|
||||
} else {
|
||||
self.keyboard_state.current_numeric_argument += t
|
||||
self.last_action = ac
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Readline) dispatch_key_action(ac Action) error {
|
||||
self.keyboard_state.current_pending_keys = nil
|
||||
if ActionNumericArgumentDigit0 <= ac && ac <= ActionNumericArgumentDigitMinus {
|
||||
if self.history_search != nil {
|
||||
return ErrCouldNotPerformAction
|
||||
}
|
||||
self.handle_numeric_arg(ac)
|
||||
return nil
|
||||
}
|
||||
cna := self.keyboard_state.current_numeric_argument
|
||||
self.keyboard_state.current_numeric_argument = ""
|
||||
if cna == "" {
|
||||
cna = "1"
|
||||
}
|
||||
repeat_count, err := strconv.Atoi(cna)
|
||||
if err != nil || repeat_count <= 0 {
|
||||
repeat_count = 1
|
||||
}
|
||||
return self.perform_action(ac, uint(repeat_count))
|
||||
}
|
||||
|
||||
func (self *Readline) handle_key_event(event *loop.KeyEvent) error {
|
||||
if event.Text != "" {
|
||||
return nil
|
||||
}
|
||||
sm := default_shortcuts()
|
||||
if len(self.keyboard_state.active_shortcut_maps) > 0 {
|
||||
sm = self.keyboard_state.active_shortcut_maps[len(self.keyboard_state.active_shortcut_maps)-1]
|
||||
}
|
||||
ac, pending := sm.ResolveKeyEvent(event, self.keyboard_state.current_pending_keys...)
|
||||
if pending != "" {
|
||||
event.Handled = true
|
||||
if self.keyboard_state.current_pending_keys == nil {
|
||||
self.keyboard_state.current_pending_keys = []string{}
|
||||
}
|
||||
self.keyboard_state.current_pending_keys = append(self.keyboard_state.current_pending_keys, pending)
|
||||
} else {
|
||||
self.keyboard_state.current_pending_keys = nil
|
||||
if ac != ActionNil {
|
||||
event.Handled = true
|
||||
return self.dispatch_key_action(ac)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"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
|
||||
var _ = utils.Repr
|
||||
|
||||
const KittyInternalHyperlinkProtocol = "kitty-ih"
|
||||
|
||||
func InternalHyperlink(text, id string) string {
|
||||
return fmt.Sprintf("\x1b]8;;%s:%s\x1b\\%s\x1b]8;;\x1b\\", KittyInternalHyperlinkProtocol, id, text)
|
||||
}
|
||||
|
||||
type RenderLines struct {
|
||||
}
|
||||
|
||||
var hyperlink_pat = sync.OnceValue(func() *regexp.Regexp {
|
||||
return regexp.MustCompile("\x1b]8;([^;]*);(.*?)(?:\x1b\\\\|\a)")
|
||||
})
|
||||
|
||||
// Render lines in the specified rectangle. If width > 0 then lines are wrapped
|
||||
// to fit in the width. A string containing rendered lines with escape codes to
|
||||
// move cursor is returned. Any internal hyperlinks are added to the
|
||||
// MouseState.
|
||||
func (r RenderLines) InRectangle(
|
||||
lines []string, start_x, start_y, width, height int, mouse_state *MouseState, on_click ...func(id string) error,
|
||||
) (all_rendered bool, y_after_last_line int, ans string) {
|
||||
end_y := start_y + height - 1
|
||||
if end_y < start_y {
|
||||
return len(lines) == 0, start_y + 1, ""
|
||||
}
|
||||
x, y := start_x, start_y
|
||||
buf := strings.Builder{}
|
||||
buf.Grow(len(lines) * max(1, width) * 3)
|
||||
move_cursor := func(x, y int) { buf.WriteString(fmt.Sprintf(loop.MoveCursorToTemplate, y+1, x+1)) }
|
||||
var hyperlink_state struct {
|
||||
action string
|
||||
start_x, start_y int
|
||||
}
|
||||
|
||||
start_hyperlink := func(action string) {
|
||||
hyperlink_state.action = action
|
||||
hyperlink_state.start_x, hyperlink_state.start_y = x, y
|
||||
}
|
||||
|
||||
add_chunk := func(text string) {
|
||||
if text != "" {
|
||||
buf.WriteString(text)
|
||||
x += wcswidth.Stringwidth(text)
|
||||
}
|
||||
}
|
||||
|
||||
commit_hyperlink := func() bool {
|
||||
if hyperlink_state.action == "" {
|
||||
return false
|
||||
}
|
||||
if y == hyperlink_state.start_y && x <= hyperlink_state.start_x {
|
||||
return false
|
||||
}
|
||||
mouse_state.AddCellRegion(hyperlink_state.action, hyperlink_state.start_x, hyperlink_state.start_y, max(0, x-1), y, on_click...)
|
||||
hyperlink_state.action = ``
|
||||
return true
|
||||
}
|
||||
|
||||
add_hyperlink := func(id, url string) {
|
||||
is_closer := id == "" && url == ""
|
||||
if is_closer {
|
||||
if !commit_hyperlink() {
|
||||
buf.WriteString("\x1b]8;;\x1b\\")
|
||||
}
|
||||
} else {
|
||||
commit_hyperlink()
|
||||
if strings.HasPrefix(url, KittyInternalHyperlinkProtocol+":") {
|
||||
start_hyperlink(url[len(KittyInternalHyperlinkProtocol)+1:])
|
||||
} else {
|
||||
buf.WriteString(fmt.Sprintf("\x1b]8;%s;%s\x1b\\", id, url))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
add_line := func(line string) {
|
||||
x = start_x
|
||||
indices := hyperlink_pat().FindAllStringSubmatchIndex(line, -1)
|
||||
start := 0
|
||||
for _, index := range indices {
|
||||
full_hyperlink_start, full_hyperlink_end := index[0], index[1]
|
||||
add_chunk(line[start:full_hyperlink_start])
|
||||
start = full_hyperlink_end
|
||||
add_hyperlink(line[index[2]:index[3]], line[index[4]:index[5]])
|
||||
}
|
||||
add_chunk(line[start:])
|
||||
}
|
||||
|
||||
all_rendered = true
|
||||
wo := style.WrapOptions{Trim_whitespace: true}
|
||||
for _, line := range lines {
|
||||
wrapped_lines := []string{line}
|
||||
if width > 0 {
|
||||
wrapped_lines = style.WrapTextAsLines(line, width, wo)
|
||||
}
|
||||
for _, line := range wrapped_lines {
|
||||
move_cursor(start_x, y)
|
||||
add_line(line)
|
||||
y += 1
|
||||
if y > end_y {
|
||||
all_rendered = false
|
||||
goto end
|
||||
}
|
||||
}
|
||||
}
|
||||
end:
|
||||
commit_hyperlink()
|
||||
return all_rendered, y, buf.String()
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/shirou/gopsutil/v4/process"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/config"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/shell_integration"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/shlex"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type KittyOpts struct {
|
||||
Shell, Shell_integration string
|
||||
}
|
||||
|
||||
func read_relevant_kitty_opts() KittyOpts {
|
||||
ans := KittyOpts{Shell: kitty.KittyConfigDefaults.Shell, Shell_integration: kitty.KittyConfigDefaults.Shell_integration}
|
||||
handle_line := func(key, val string) error {
|
||||
switch key {
|
||||
case "shell":
|
||||
ans.Shell = strings.TrimSpace(val)
|
||||
case "shell_integration":
|
||||
ans.Shell_integration = strings.TrimSpace(val)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config.ReadKittyConfig(handle_line)
|
||||
if ans.Shell == "" {
|
||||
ans.Shell = kitty.KittyConfigDefaults.Shell
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func get_effective_ksi_env_var(x string) string {
|
||||
parts := strings.Split(strings.TrimSpace(strings.ToLower(x)), " ")
|
||||
current := utils.NewSetWithItems(parts...)
|
||||
if current.Has("disabled") {
|
||||
return ""
|
||||
}
|
||||
allowed := utils.NewSetWithItems(kitty.AllowedShellIntegrationValues...)
|
||||
if !current.IsSubsetOf(allowed) {
|
||||
return relevant_kitty_opts().Shell_integration
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
var relevant_kitty_opts = sync.OnceValue(func() KittyOpts {
|
||||
return read_relevant_kitty_opts()
|
||||
})
|
||||
|
||||
func get_shell_from_kitty_conf() (shell string) {
|
||||
shell = relevant_kitty_opts().Shell
|
||||
if shell == "." {
|
||||
s, e := utils.LoginShellForCurrentUser()
|
||||
if e != nil {
|
||||
shell = "/bin/sh"
|
||||
} else {
|
||||
shell = s
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func find_shell_parent_process() string {
|
||||
var p *process.Process
|
||||
var err error
|
||||
for {
|
||||
if p == nil {
|
||||
p, err = process.NewProcess(int32(os.Getppid()))
|
||||
} else {
|
||||
p, err = p.Parent()
|
||||
}
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if cmdline, err := p.CmdlineSlice(); err == nil && len(cmdline) > 0 {
|
||||
exe := get_shell_name(filepath.Base(cmdline[0]))
|
||||
if shell_integration.IsSupportedShell(exe) {
|
||||
return exe
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ResolveShell(shell string) []string {
|
||||
switch shell {
|
||||
case "":
|
||||
shell = get_shell_from_kitty_conf()
|
||||
case ".":
|
||||
if shell = find_shell_parent_process(); shell == "" {
|
||||
shell = get_shell_from_kitty_conf()
|
||||
}
|
||||
}
|
||||
shell_cmd, err := shlex.Split(shell)
|
||||
if err != nil {
|
||||
shell_cmd = []string{shell}
|
||||
}
|
||||
exe := utils.FindExe(shell_cmd[0])
|
||||
if unix.Access(exe, unix.X_OK) != nil {
|
||||
shell_cmd = []string{"/bin/sh"}
|
||||
}
|
||||
return shell_cmd
|
||||
}
|
||||
|
||||
func ResolveShellIntegration(shell_integration string) string {
|
||||
if shell_integration == "" {
|
||||
shell_integration = relevant_kitty_opts().Shell_integration
|
||||
}
|
||||
return get_effective_ksi_env_var(shell_integration)
|
||||
}
|
||||
|
||||
func get_shell_name(argv0 string) (ans string) {
|
||||
ans = filepath.Base(argv0)
|
||||
if strings.HasSuffix(strings.ToLower(ans), ".exe") {
|
||||
ans = ans[:len(ans)-4]
|
||||
}
|
||||
return strings.TrimPrefix(ans, "-")
|
||||
}
|
||||
|
||||
func rc_modification_allowed(ksi string) (allowed bool, set_ksi_env_var bool) {
|
||||
allowed = ksi != ""
|
||||
set_ksi_env_var = true
|
||||
for x := range strings.SplitSeq(ksi, " ") {
|
||||
switch x {
|
||||
case "disabled":
|
||||
allowed = false
|
||||
set_ksi_env_var = false
|
||||
case "no-rc":
|
||||
allowed = false
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func copy_os_env_as_dict() map[string]string {
|
||||
oenv := os.Environ()
|
||||
env := make(map[string]string, len(oenv))
|
||||
for _, x := range oenv {
|
||||
if k, v, found := strings.Cut(x, "="); found {
|
||||
env[k] = v
|
||||
}
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func RunShell(shell_cmd []string, shell_integration_env_var_val, cwd string) (err error) {
|
||||
shell_name := get_shell_name(shell_cmd[0])
|
||||
var shell_env map[string]string
|
||||
if shell_integration.IsSupportedShell(shell_name) {
|
||||
rc_mod_allowed, set_ksi_env_var := rc_modification_allowed(shell_integration_env_var_val)
|
||||
if rc_mod_allowed {
|
||||
// KITTY_SHELL_INTEGRATION is always set by this function
|
||||
argv, env, err := shell_integration.Setup(shell_name, shell_integration_env_var_val, shell_cmd, copy_os_env_as_dict())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
shell_cmd = argv
|
||||
shell_env = env
|
||||
} else if set_ksi_env_var {
|
||||
shell_env = copy_os_env_as_dict()
|
||||
shell_env["KITTY_SHELL_INTEGRATION"] = shell_integration_env_var_val
|
||||
}
|
||||
}
|
||||
exe := shell_cmd[0]
|
||||
if runtime.GOOS == "darwin" && (os.Getenv("KITTY_RUNNING_SHELL_INTEGRATION_TEST") != "1" || os.Getenv("KITTY_RUNNING_BASH_INTEGRATION_TEST") != "") {
|
||||
// ensure shell runs in login mode. On macOS lots of people use ~/.bash_profile instead of ~/.bashrc
|
||||
// which means they expect the shell to run in login mode always. Le Sigh.
|
||||
shell_cmd[0] = "-" + filepath.Base(shell_cmd[0])
|
||||
}
|
||||
var env []string
|
||||
if shell_env != nil {
|
||||
env = make([]string, 0, len(shell_env))
|
||||
for k, v := range shell_env {
|
||||
env = append(env, fmt.Sprintf("%s=%s", k, v))
|
||||
}
|
||||
} else {
|
||||
env = os.Environ()
|
||||
}
|
||||
// fmt.Println(fmt.Sprintf("%s %v\n%#v", utils.FindExe(exe), shell_cmd, env))
|
||||
if cwd != "" {
|
||||
_ = os.Chdir(cwd)
|
||||
}
|
||||
return unix.Exec(utils.FindExe(exe), shell_cmd, env)
|
||||
}
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func RunCommandRestoringTerminalToSaneStateAfter(cmd []string) {
|
||||
exe := utils.FindExe(cmd[0])
|
||||
c := exec.Command(exe, cmd[1:]...)
|
||||
c.Stdout = os.Stdout
|
||||
c.Stdin = os.Stdin
|
||||
c.Stderr = os.Stderr
|
||||
term, err := tty.OpenControllingTerm()
|
||||
if err == nil {
|
||||
var state_before unix.Termios
|
||||
if term.Tcgetattr(&state_before) == nil {
|
||||
if _, err = term.WriteString(loop.SAVE_PRIVATE_MODE_VALUES); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "failed to write to controlling terminal with error:", err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
_, _ = term.WriteString(strings.Join([]string{
|
||||
loop.RESTORE_PRIVATE_MODE_VALUES,
|
||||
"\x1b[=u", // reset kitty keyboard protocol to legacy
|
||||
"\x1bP@kitty-restore-cursor-appearance|\a",
|
||||
PROGRAM_STATUS_PROCESS_EXITED,
|
||||
}, ""))
|
||||
_ = term.Tcsetattr(tty.TCSANOW, &state_before)
|
||||
term.Close()
|
||||
}()
|
||||
} else {
|
||||
defer term.Close()
|
||||
}
|
||||
}
|
||||
// Ignore SIGINT as the kernel tends to send it to us as well as the
|
||||
// subprocess on Ctrl+C. We cant use signal.Ignore as it doesnt reset
|
||||
// sigprocmask so subsequent unix.Exec will inherit blocked SIGINT
|
||||
ignore_sigint_channel := make(chan os.Signal, 512)
|
||||
if err = c.Start(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, cmd[0], "failed to start with error:", err)
|
||||
return
|
||||
}
|
||||
signal.Notify(ignore_sigint_channel, os.Interrupt)
|
||||
err = c.Wait()
|
||||
signal.Reset(os.Interrupt)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, cmd[0], "failed with error:", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package sgr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/style"
|
||||
"github.com/kovidgoyal/kitty/tools/wcswidth"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type UnderlineStyle uint8
|
||||
|
||||
const (
|
||||
No_underline UnderlineStyle = iota
|
||||
Straight_underline
|
||||
Double_underline
|
||||
Curly_underline
|
||||
Dotted_underline
|
||||
Dashed_underline
|
||||
)
|
||||
|
||||
type Color struct {
|
||||
Red, Green, Blue uint8
|
||||
Is_numbered bool
|
||||
}
|
||||
|
||||
func (self *Color) Set(val any) (err error) {
|
||||
switch v := val.(type) {
|
||||
case int:
|
||||
self.Is_numbered = true
|
||||
self.Red = uint8(v)
|
||||
case style.RGBA:
|
||||
self.Is_numbered = false
|
||||
self.Red, self.Green, self.Blue = v.Red, v.Green, v.Blue
|
||||
case string:
|
||||
rgba, err := style.ParseColor(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
self.Is_numbered = false
|
||||
self.Red, self.Green, self.Blue = rgba.Red, rgba.Green, rgba.Blue
|
||||
default:
|
||||
return fmt.Errorf("Unknown type to set color from: %T", v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (self Color) AsCSI(base int) string {
|
||||
if self.Is_numbered && base < 50 {
|
||||
if self.Red < 8 {
|
||||
return strconv.Itoa(base + int(self.Red))
|
||||
}
|
||||
if self.Red < 16 {
|
||||
return strconv.Itoa(base + 52 + int(self.Red))
|
||||
}
|
||||
return fmt.Sprintf("%d:5:%d", base+8, self.Red)
|
||||
}
|
||||
return fmt.Sprintf("%d:2:%d:%d:%d", base+8, self.Red, self.Green, self.Blue)
|
||||
}
|
||||
|
||||
func (self *Color) FromNumber(n uint8) {
|
||||
self.Is_numbered, self.Red = true, n
|
||||
}
|
||||
|
||||
func as_uint8(x int) uint8 {
|
||||
return uint8(uint(x) & 0xff)
|
||||
}
|
||||
|
||||
func (self *Color) FromExtended(nums ...int) bool {
|
||||
switch nums[0] {
|
||||
case 5:
|
||||
if len(nums) > 1 {
|
||||
self.Red = as_uint8(nums[1])
|
||||
self.Is_numbered = true
|
||||
return true
|
||||
}
|
||||
case 2:
|
||||
if len(nums) > 3 {
|
||||
self.Is_numbered = false
|
||||
self.Red, self.Green, self.Blue = as_uint8(nums[1]), as_uint8(nums[2]), as_uint8(nums[3])
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type BoolVal struct{ Is_set, Val bool }
|
||||
|
||||
type UnderlineStyleVal struct {
|
||||
Is_set bool
|
||||
Val UnderlineStyle
|
||||
}
|
||||
type ColorVal struct {
|
||||
Is_set, Is_default bool
|
||||
Val Color
|
||||
}
|
||||
|
||||
type SGR struct {
|
||||
Italic, Reverse, Bold, Dim, Strikethrough BoolVal
|
||||
Underline_style UnderlineStyleVal
|
||||
Foreground, Background, Underline_color ColorVal
|
||||
}
|
||||
|
||||
func (self *BoolVal) AsCSI(set, reset string) string {
|
||||
if !self.Is_set {
|
||||
return ""
|
||||
}
|
||||
if self.Val {
|
||||
return set
|
||||
}
|
||||
return reset
|
||||
}
|
||||
|
||||
func (self *UnderlineStyleVal) AsCSI() string {
|
||||
if !self.Is_set {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("4:%d;", self.Val)
|
||||
}
|
||||
|
||||
func (self *ColorVal) AsCSI(base int) string {
|
||||
if !self.Is_set {
|
||||
return ""
|
||||
}
|
||||
if self.Is_default {
|
||||
return strconv.Itoa(base + 9)
|
||||
}
|
||||
return self.Val.AsCSI(base)
|
||||
}
|
||||
|
||||
func (self *SGR) AsCSI() string {
|
||||
ans := make([]byte, 0, 16)
|
||||
w := func(x string) {
|
||||
if x != "" {
|
||||
ans = append(ans, x...)
|
||||
ans = append(ans, ';')
|
||||
}
|
||||
}
|
||||
w(self.Bold.AsCSI("1", "221"))
|
||||
w(self.Dim.AsCSI("2", "222"))
|
||||
w(self.Italic.AsCSI("3", "23"))
|
||||
w(self.Reverse.AsCSI("7", "27"))
|
||||
w(self.Strikethrough.AsCSI("9", "29"))
|
||||
w(self.Underline_style.AsCSI())
|
||||
w(self.Foreground.AsCSI(30))
|
||||
w(self.Background.AsCSI(40))
|
||||
w(self.Underline_color.AsCSI(50))
|
||||
|
||||
if len(ans) > 0 {
|
||||
ans = ans[:len(ans)-1]
|
||||
ans = append(ans, 'm')
|
||||
}
|
||||
return utils.UnsafeBytesToString(ans)
|
||||
}
|
||||
|
||||
func (self *SGR) IsEmpty() bool {
|
||||
return !(self.Foreground.Is_set || self.Background.Is_set || self.Underline_color.Is_set || self.Underline_style.Is_set || self.Italic.Is_set || self.Bold.Is_set || self.Reverse.Is_set || self.Dim.Is_set || self.Strikethrough.Is_set)
|
||||
}
|
||||
|
||||
func (self *SGR) ApplyMask(other SGR) {
|
||||
if other.Italic.Is_set {
|
||||
self.Italic.Is_set = false
|
||||
}
|
||||
if other.Reverse.Is_set {
|
||||
self.Reverse.Is_set = false
|
||||
}
|
||||
if other.Bold.Is_set {
|
||||
self.Bold.Is_set = false
|
||||
}
|
||||
if other.Dim.Is_set {
|
||||
self.Dim.Is_set = false
|
||||
}
|
||||
if other.Strikethrough.Is_set {
|
||||
self.Strikethrough.Is_set = false
|
||||
}
|
||||
if other.Underline_style.Is_set {
|
||||
self.Underline_style.Is_set = false
|
||||
}
|
||||
if other.Foreground.Is_set {
|
||||
self.Foreground.Is_set = false
|
||||
}
|
||||
if other.Background.Is_set {
|
||||
self.Background.Is_set = false
|
||||
}
|
||||
if other.Underline_color.Is_set {
|
||||
self.Underline_color.Is_set = false
|
||||
}
|
||||
}
|
||||
|
||||
func (self *SGR) ApplySGR(other SGR) {
|
||||
if other.Italic.Is_set {
|
||||
self.Italic = other.Italic
|
||||
}
|
||||
if other.Reverse.Is_set {
|
||||
self.Reverse = other.Reverse
|
||||
}
|
||||
if other.Bold.Is_set {
|
||||
self.Bold = other.Bold
|
||||
}
|
||||
if other.Dim.Is_set {
|
||||
self.Dim = other.Dim
|
||||
}
|
||||
if other.Strikethrough.Is_set {
|
||||
self.Strikethrough = other.Strikethrough
|
||||
}
|
||||
if other.Underline_style.Is_set {
|
||||
self.Underline_style = other.Underline_style
|
||||
}
|
||||
if other.Foreground.Is_set {
|
||||
self.Foreground = other.Foreground
|
||||
}
|
||||
if other.Background.Is_set {
|
||||
self.Background = other.Background
|
||||
}
|
||||
if other.Underline_color.Is_set {
|
||||
self.Underline_color = other.Underline_color
|
||||
}
|
||||
}
|
||||
|
||||
func SGRFromCSI(csi string) (ans SGR) {
|
||||
if !strings.HasSuffix(csi, "m") {
|
||||
return
|
||||
}
|
||||
csi = csi[:len(csi)-1]
|
||||
if csi == "" {
|
||||
csi = "0"
|
||||
}
|
||||
parts := strings.Split(csi, ";")
|
||||
nums := make([]int, 0, 8)
|
||||
for _, part := range parts {
|
||||
subparts := strings.Split(part, ":")
|
||||
nums = nums[:0]
|
||||
for _, b := range subparts {
|
||||
q, err := strconv.Atoi(b)
|
||||
if err == nil {
|
||||
nums = append(nums, q)
|
||||
}
|
||||
}
|
||||
if len(nums) == 0 {
|
||||
continue
|
||||
}
|
||||
switch nums[0] {
|
||||
case 0:
|
||||
ans = SGR{}
|
||||
case 1:
|
||||
ans.Bold.Val, ans.Bold.Is_set = true, true
|
||||
case 221:
|
||||
ans.Bold.Val, ans.Bold.Is_set = false, true
|
||||
case 2:
|
||||
ans.Dim.Val, ans.Dim.Is_set = true, true
|
||||
case 222:
|
||||
ans.Dim.Val, ans.Dim.Is_set = false, true
|
||||
case 22:
|
||||
ans.Dim.Val, ans.Bold.Val = false, false
|
||||
ans.Dim.Is_set, ans.Bold.Is_set = true, true
|
||||
case 3:
|
||||
ans.Italic.Is_set, ans.Italic.Val = true, true
|
||||
case 23:
|
||||
ans.Italic.Is_set, ans.Italic.Val = true, false
|
||||
case 7:
|
||||
ans.Reverse.Is_set, ans.Reverse.Val = true, true
|
||||
case 27:
|
||||
ans.Reverse.Is_set, ans.Reverse.Val = true, false
|
||||
case 9:
|
||||
ans.Strikethrough.Is_set, ans.Strikethrough.Val = true, true
|
||||
case 29:
|
||||
ans.Strikethrough.Is_set, ans.Strikethrough.Val = true, false
|
||||
case 24:
|
||||
ans.Underline_style.Is_set, ans.Underline_style.Val = true, No_underline
|
||||
case 4:
|
||||
us := 1
|
||||
if len(nums) > 1 {
|
||||
us = nums[1]
|
||||
}
|
||||
switch us {
|
||||
case 0:
|
||||
ans.Underline_style.Is_set, ans.Underline_style.Val = true, No_underline
|
||||
case 1:
|
||||
ans.Underline_style.Is_set, ans.Underline_style.Val = true, Straight_underline
|
||||
case 2:
|
||||
ans.Underline_style.Is_set, ans.Underline_style.Val = true, Double_underline
|
||||
case 3:
|
||||
ans.Underline_style.Is_set, ans.Underline_style.Val = true, Curly_underline
|
||||
case 4:
|
||||
ans.Underline_style.Is_set, ans.Underline_style.Val = true, Dotted_underline
|
||||
case 5:
|
||||
ans.Underline_style.Is_set, ans.Underline_style.Val = true, Dashed_underline
|
||||
}
|
||||
case 30, 31, 32, 33, 34, 35, 36, 37:
|
||||
ans.Foreground.Is_set, ans.Foreground.Is_default = true, false
|
||||
ans.Foreground.Val.FromNumber(uint8(nums[0] - 30))
|
||||
case 90, 91, 92, 93, 94, 95, 96, 97:
|
||||
ans.Foreground.Is_set, ans.Foreground.Is_default = true, false
|
||||
ans.Foreground.Val.FromNumber(uint8(nums[0] - 82))
|
||||
case 38:
|
||||
if ans.Foreground.Val.FromExtended(nums[1:]...) {
|
||||
ans.Foreground.Is_set, ans.Foreground.Is_default = true, false
|
||||
}
|
||||
case 39:
|
||||
ans.Foreground.Is_set, ans.Foreground.Is_default = true, true
|
||||
case 40, 41, 42, 43, 44, 45, 46, 47:
|
||||
ans.Background.Is_set, ans.Background.Is_default = true, false
|
||||
ans.Background.Val.FromNumber(uint8(nums[0] - 40))
|
||||
case 100, 101, 102, 103, 104, 105, 106, 107:
|
||||
ans.Background.Is_set, ans.Background.Is_default = true, false
|
||||
ans.Background.Val.FromNumber(uint8(nums[0] - 92))
|
||||
case 48:
|
||||
if ans.Background.Val.FromExtended(nums[1:]...) {
|
||||
ans.Background.Is_set, ans.Background.Is_default = true, false
|
||||
}
|
||||
case 49:
|
||||
ans.Background.Is_set, ans.Background.Is_default = true, true
|
||||
case 58:
|
||||
if ans.Underline_color.Val.FromExtended(nums[1:]...) {
|
||||
ans.Underline_color.Is_set, ans.Underline_color.Is_default = true, false
|
||||
}
|
||||
case 59:
|
||||
ans.Underline_color.Is_set, ans.Underline_color.Is_default = true, true
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
type Span struct {
|
||||
Offset, Size int // in bytes
|
||||
opening_sgr, closing_sgr SGR
|
||||
}
|
||||
|
||||
func NewSpan(offset, size int) *Span {
|
||||
return &Span{Offset: offset, Size: size}
|
||||
}
|
||||
|
||||
func (self *BoolVal) Set(val bool) {
|
||||
self.Is_set = true
|
||||
self.Val = val
|
||||
}
|
||||
|
||||
func (self *ColorVal) Set(val any) {
|
||||
self.Is_set = true
|
||||
if val == nil {
|
||||
self.Is_default = true
|
||||
} else {
|
||||
self.Is_default = false
|
||||
if err := self.Val.Set(val); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (self *Span) SetForeground(val any) *Span {
|
||||
self.opening_sgr.Foreground.Set(val)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetBackground(val any) *Span {
|
||||
self.opening_sgr.Background.Set(val)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetUnderlineColor(val any) *Span {
|
||||
self.opening_sgr.Underline_color.Set(val)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetItalic(val bool) *Span {
|
||||
self.opening_sgr.Italic.Set(val)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetBold(val bool) *Span {
|
||||
self.opening_sgr.Bold.Set(val)
|
||||
return self
|
||||
}
|
||||
func (self *Span) SetReverse(val bool) *Span {
|
||||
self.opening_sgr.Reverse.Set(val)
|
||||
return self
|
||||
}
|
||||
func (self *Span) SetDim(val bool) *Span {
|
||||
self.opening_sgr.Dim.Set(val)
|
||||
return self
|
||||
}
|
||||
func (self *Span) SetStrikethrough(val bool) *Span {
|
||||
self.opening_sgr.Strikethrough.Set(val)
|
||||
return self
|
||||
}
|
||||
func (self *Span) SetUnderlineStyle(val UnderlineStyle) *Span {
|
||||
self.opening_sgr.Underline_style.Is_set = true
|
||||
self.opening_sgr.Underline_style.Val = val
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetClosingForeground(val any) *Span {
|
||||
self.closing_sgr.Foreground.Set(val)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetClosingBackground(val any) *Span {
|
||||
self.closing_sgr.Background.Set(val)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetClosingUnderlineColor(val any) *Span {
|
||||
self.closing_sgr.Underline_color.Set(val)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetClosingItalic(val bool) *Span {
|
||||
self.closing_sgr.Italic.Set(val)
|
||||
return self
|
||||
}
|
||||
|
||||
func (self *Span) SetClosingBold(val bool) *Span {
|
||||
self.closing_sgr.Bold.Set(val)
|
||||
return self
|
||||
}
|
||||
func (self *Span) SetClosingReverse(val bool) *Span {
|
||||
self.closing_sgr.Reverse.Set(val)
|
||||
return self
|
||||
}
|
||||
func (self *Span) SetClosingDim(val bool) *Span {
|
||||
self.closing_sgr.Dim.Set(val)
|
||||
return self
|
||||
}
|
||||
func (self *Span) SetClosingStrikethrough(val bool) *Span {
|
||||
self.closing_sgr.Strikethrough.Set(val)
|
||||
return self
|
||||
}
|
||||
func (self *Span) SetClosingUnderlineStyle(val UnderlineStyle) *Span {
|
||||
self.closing_sgr.Underline_style.Is_set = true
|
||||
self.opening_sgr.Underline_style.Val = val
|
||||
return self
|
||||
}
|
||||
|
||||
// Insert formatting into text at the specified offsets, overriding any existing formatting, and restoring
|
||||
// existing formatting after the replaced sections.
|
||||
func InsertFormatting(text string, spans ...*Span) string {
|
||||
spans = utils.Filter(spans, func(s *Span) bool { return !s.opening_sgr.IsEmpty() })
|
||||
if len(spans) == 0 {
|
||||
return text
|
||||
}
|
||||
var in_span *Span
|
||||
ans := make([]byte, 0, 2*len(text))
|
||||
var overall_sgr_state SGR
|
||||
slices.SortFunc(spans, func(a, b *Span) int { return a.Offset - b.Offset })
|
||||
text_len := 0
|
||||
var ep *wcswidth.EscapeCodeParser
|
||||
|
||||
write_csi := func(csi string) {
|
||||
if csi != "" {
|
||||
ans = append(ans, 0x1b, '[')
|
||||
ans = append(ans, csi...)
|
||||
}
|
||||
}
|
||||
open_span := func() {
|
||||
in_span = spans[0]
|
||||
spans = spans[1:]
|
||||
if in_span.Size > 0 {
|
||||
write_csi(in_span.opening_sgr.AsCSI())
|
||||
} else {
|
||||
in_span = nil
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
close_span := func() {
|
||||
write_csi(in_span.closing_sgr.AsCSI())
|
||||
write_csi(overall_sgr_state.AsCSI())
|
||||
in_span = nil
|
||||
}
|
||||
|
||||
ep = &wcswidth.EscapeCodeParser{
|
||||
HandleRune: func(ch rune) error {
|
||||
var rlen int
|
||||
if in_span == nil {
|
||||
if len(spans) > 0 && text_len >= spans[0].Offset {
|
||||
open_span()
|
||||
return ep.HandleRune(ch)
|
||||
}
|
||||
before := len(ans)
|
||||
ans = utf8.AppendRune(ans, ch)
|
||||
rlen = len(ans) - before
|
||||
} else {
|
||||
rlen = utf8.RuneLen(ch)
|
||||
if text_len+rlen > in_span.Offset+in_span.Size {
|
||||
close_span()
|
||||
}
|
||||
ans = utf8.AppendRune(ans, ch)
|
||||
}
|
||||
text_len += rlen
|
||||
return nil
|
||||
},
|
||||
HandleCSI: func(csib []byte) error {
|
||||
csi := utils.UnsafeBytesToString(csib)
|
||||
if len(csi) == 0 || csi[len(csi)-1] != 'm' {
|
||||
write_csi(csi)
|
||||
return nil
|
||||
}
|
||||
sgr := SGRFromCSI(csi)
|
||||
overall_sgr_state.ApplySGR(sgr)
|
||||
if in_span == nil {
|
||||
write_csi(csi)
|
||||
} else {
|
||||
sgr.ApplyMask(in_span.opening_sgr)
|
||||
csi := sgr.AsCSI()
|
||||
write_csi(csi)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
HandleOSC: func(osc []byte) error {
|
||||
ans = append(ans, 0x1b, ']')
|
||||
ans = append(ans, osc...)
|
||||
ans = append(ans, 0x1b, '\\')
|
||||
return nil
|
||||
},
|
||||
}
|
||||
ep.ParseString(text)
|
||||
if in_span != nil {
|
||||
close_span()
|
||||
}
|
||||
return utils.UnsafeBytesToString(ans)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package sgr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestInsertFormatting(t *testing.T) {
|
||||
test := func(src, expected string, spans ...*Span) {
|
||||
actual := InsertFormatting(src, spans...)
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("Failed with %#v:\n%#v != %#v\n%s", src, expected, actual, diff)
|
||||
}
|
||||
}
|
||||
test(
|
||||
"\x1b[44m abcd \x1b[49m",
|
||||
"\x1b[44m a\x1b[33;41mbc\x1b[39;49m\x1b[44md \x1b[49m",
|
||||
NewSpan(2, 2).SetForeground(3).SetBackground(1).SetClosingForeground(nil).SetClosingBackground(nil),
|
||||
)
|
||||
test(
|
||||
"abcd",
|
||||
"a\x1b[92mbcd\x1b[39m",
|
||||
NewSpan(1, 11).SetForeground(10).SetClosingForeground(nil),
|
||||
)
|
||||
test(
|
||||
"AB\x1b[1mC\x1b[221mDE",
|
||||
"A\x1b[37mB\x1b[1mC\x1b[221mDE\x1b[39m\x1b[221m",
|
||||
NewSpan(1, 11).SetForeground(7).SetClosingForeground(nil),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package shell_integration
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/tty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type integration_setup_func = func(shell_integration_dir string, argv []string, env map[string]string) ([]string, map[string]string, error)
|
||||
|
||||
func TerminfoData() string {
|
||||
d := Data()
|
||||
entry := d["terminfo/x/xterm-kitty"]
|
||||
return utils.UnsafeBytesToString(entry.Data)
|
||||
}
|
||||
|
||||
func extract_files(match, dest_dir string) (err error) {
|
||||
d := Data()
|
||||
for _, fname := range d.FilesMatching(match) {
|
||||
entry := d[fname]
|
||||
dest := filepath.Join(dest_dir, fname)
|
||||
ddir := filepath.Dir(dest)
|
||||
if err = os.MkdirAll(ddir, 0o755); err != nil {
|
||||
return
|
||||
}
|
||||
switch entry.Metadata.Typeflag {
|
||||
case tar.TypeDir:
|
||||
if err = os.MkdirAll(dest, 0o755); err != nil {
|
||||
return
|
||||
}
|
||||
case tar.TypeSymlink:
|
||||
if err = os.Symlink(entry.Metadata.Linkname, dest); err != nil {
|
||||
return
|
||||
}
|
||||
case tar.TypeReg:
|
||||
if existing, rerr := os.ReadFile(dest); rerr == nil && bytes.Equal(existing, entry.Data) {
|
||||
continue
|
||||
}
|
||||
if err = utils.AtomicWriteFile(dest, bytes.NewReader(entry.Data), 0o644); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func extract_shell_integration_for(shell_name string, dest_dir string) (err error) {
|
||||
return extract_files("shell-integration/"+shell_name+"/", dest_dir)
|
||||
}
|
||||
|
||||
func extract_terminfo(dest_dir string) (err error) {
|
||||
var s os.FileInfo
|
||||
if s, err = os.Stat(filepath.Join(dest_dir, "terminfo", "x", kitty.DefaultTermName)); err == nil && s.Mode().IsRegular() {
|
||||
if s, err = os.Stat(filepath.Join(dest_dir, "terminfo", "78", kitty.DefaultTermName)); err == nil && s.Mode().IsRegular() {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err = extract_files("terminfo/", dest_dir); err == nil {
|
||||
dest := filepath.Join(dest_dir, "terminfo", "78")
|
||||
err = os.Symlink("x", dest)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func PathToTerminfoDb(term string) (ans string) {
|
||||
// see man terminfo for the algorithm ncurses uses for this
|
||||
|
||||
seen := utils.NewSet[string]()
|
||||
check_dir := func(path string) string {
|
||||
if seen.Has(path) {
|
||||
return ``
|
||||
}
|
||||
seen.Add(path)
|
||||
q := filepath.Join(path, term[:1], term)
|
||||
if s, err := os.Stat(q); err == nil && s.Mode().IsRegular() {
|
||||
return q
|
||||
}
|
||||
if entries, err := os.ReadDir(filepath.Join(path)); err == nil {
|
||||
for _, x := range entries {
|
||||
q := filepath.Join(path, x.Name(), term)
|
||||
if s, err := os.Stat(q); err == nil && s.Mode().IsRegular() {
|
||||
return q
|
||||
}
|
||||
}
|
||||
}
|
||||
return ``
|
||||
}
|
||||
|
||||
if td := os.Getenv("TERMINFO"); td != "" {
|
||||
if ans = check_dir(td); ans != "" {
|
||||
return ans
|
||||
}
|
||||
}
|
||||
|
||||
if ans = check_dir(utils.Expanduser("~/.terminfo")); ans != "" {
|
||||
return ans
|
||||
}
|
||||
if td := os.Getenv("TERMINFO_DIRS"); td != "" {
|
||||
for q := range strings.SplitSeq(td, string(os.PathListSeparator)) {
|
||||
if q == "" {
|
||||
q = "/usr/share/terminfo"
|
||||
}
|
||||
if ans = check_dir(q); ans != "" {
|
||||
return ans
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, q := range []string{"/usr/share/terminfo", "/usr/lib/terminfo", "/usr/share/lib/terminfo"} {
|
||||
if ans = check_dir(q); ans != "" {
|
||||
return ans
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func EnsureTerminfoFiles() (terminfo_dir string, err error) {
|
||||
if kid := os.Getenv("KITTY_INSTALLATION_DIR"); kid != "" {
|
||||
if s, e := os.Stat(kid); e == nil && s.IsDir() {
|
||||
q := filepath.Join(kid, "terminfo")
|
||||
if s, e := os.Stat(q); e == nil && s.IsDir() {
|
||||
return q, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
base := filepath.Join(utils.CacheDir(), "extracted-kti")
|
||||
if err = os.MkdirAll(base, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = extract_terminfo(base); err != nil {
|
||||
return "", fmt.Errorf("Failed to extract terminfo files with error: %w", err)
|
||||
}
|
||||
return filepath.Join(base, "terminfo"), nil
|
||||
}
|
||||
|
||||
func EnsureShellIntegrationFilesFor(shell_name string) (shell_integration_dir_for_shell string, err error) {
|
||||
if kid := os.Getenv("KITTY_INSTALLATION_DIR"); kid != "" {
|
||||
if s, e := os.Stat(kid); e == nil && s.IsDir() {
|
||||
q := filepath.Join(kid, "shell-integration", shell_name)
|
||||
if s, e := os.Stat(q); e == nil && s.IsDir() {
|
||||
return q, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
base := filepath.Join(utils.CacheDir(), "extracted-ksi")
|
||||
if err = os.MkdirAll(base, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = extract_shell_integration_for(shell_name, base); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(base, "shell-integration", shell_name), nil
|
||||
}
|
||||
|
||||
func is_new_zsh_install(env map[string]string, zdotdir string) bool {
|
||||
// if ZDOTDIR is empty, zsh will read user rc files from /
|
||||
// if there aren't any, it'll run zsh-newuser-install
|
||||
// the latter will bail if there are rc files in $HOME
|
||||
if zdotdir == "" {
|
||||
if zdotdir = env[`HOME`]; zdotdir == "" {
|
||||
if q, err := os.UserHomeDir(); err == nil {
|
||||
zdotdir = q
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, q := range []string{`.zshrc`, `.zshenv`, `.zprofile`, `.zlogin`} {
|
||||
if _, e := os.Stat(filepath.Join(zdotdir, q)); e == nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func get_zsh_zdotdir_from_global_zshenv(argv []string, env map[string]string) string {
|
||||
c := exec.Command(utils.FindExe(argv[0]), `--norcs`, `--interactive`, `-c`, `echo -n $ZDOTDIR`)
|
||||
for k, v := range env {
|
||||
c.Env = append(c.Env, k+"="+v)
|
||||
}
|
||||
if raw, err := c.Output(); err == nil {
|
||||
return utils.UnsafeBytesToString(raw)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func zsh_setup_func(shell_integration_dir string, argv []string, env map[string]string) (final_argv []string, final_env map[string]string, err error) {
|
||||
zdotdir := env[`ZDOTDIR`]
|
||||
final_argv, final_env = argv, env
|
||||
if is_new_zsh_install(env, zdotdir) {
|
||||
if zdotdir == "" {
|
||||
// Try to get ZDOTDIR from /etc/zshenv, when all startup files are not present
|
||||
zdotdir = get_zsh_zdotdir_from_global_zshenv(argv, env)
|
||||
if zdotdir == "" || is_new_zsh_install(env, zdotdir) {
|
||||
return final_argv, final_env, nil
|
||||
}
|
||||
} else {
|
||||
// dont prevent zsh-newuser-install from running
|
||||
// zsh-newuser-install never runs as root but we assume that it does
|
||||
return final_argv, final_env, nil
|
||||
}
|
||||
}
|
||||
if zdotdir != "" {
|
||||
env[`KITTY_ORIG_ZDOTDIR`] = zdotdir
|
||||
} else {
|
||||
// KITTY_ORIG_ZDOTDIR can be set at this point if, for example, the global
|
||||
// zshenv overrides ZDOTDIR; we try to limit the damage in this case
|
||||
delete(final_env, `KITTY_ORIG_ZDOTDIR`)
|
||||
}
|
||||
final_env[`ZDOTDIR`] = shell_integration_dir
|
||||
return
|
||||
}
|
||||
|
||||
func fish_setup_func(shell_integration_dir string, argv []string, env map[string]string) (final_argv []string, final_env map[string]string, err error) {
|
||||
shell_integration_dir = filepath.Dir(shell_integration_dir)
|
||||
val := env[`XDG_DATA_DIRS`]
|
||||
env[`KITTY_FISH_XDG_DATA_DIR`] = shell_integration_dir
|
||||
if val == "" {
|
||||
env[`XDG_DATA_DIRS`] = shell_integration_dir
|
||||
} else {
|
||||
dirs := utils.Filter(strings.Split(val, string(filepath.ListSeparator)), func(x string) bool { return x != "" })
|
||||
dirs = append([]string{shell_integration_dir}, dirs...)
|
||||
env[`XDG_DATA_DIRS`] = strings.Join(dirs, string(filepath.ListSeparator))
|
||||
}
|
||||
return argv, env, nil
|
||||
}
|
||||
|
||||
var debugprintln = tty.DebugPrintln
|
||||
var _ = debugprintln
|
||||
|
||||
func bash_setup_func(shell_integration_dir string, argv []string, env map[string]string) ([]string, map[string]string, error) {
|
||||
inject := utils.NewSetWithItems(`1`)
|
||||
var posix_env, rcfile string
|
||||
remove_args := utils.NewSet[int](8)
|
||||
expecting_multi_chars_opt := true
|
||||
var expecting_option_arg, interactive_opt, expecting_file_arg, file_arg_set bool
|
||||
|
||||
for i := 1; i < len(argv); i++ {
|
||||
arg := argv[i]
|
||||
if expecting_file_arg {
|
||||
file_arg_set = true
|
||||
break
|
||||
}
|
||||
if expecting_option_arg {
|
||||
expecting_option_arg = false
|
||||
continue
|
||||
}
|
||||
if arg == `-` || arg == `--` {
|
||||
if !expecting_file_arg {
|
||||
expecting_file_arg = true
|
||||
}
|
||||
continue
|
||||
} else if len(arg) > 1 && arg[1] != '-' && (arg[0] == '-' || strings.HasPrefix(arg, `+O`)) {
|
||||
expecting_multi_chars_opt = false
|
||||
options := strings.TrimLeft(arg, `-+`)
|
||||
// shopt option
|
||||
if a, b, found := strings.Cut(options, `O`); found {
|
||||
if b == "" {
|
||||
expecting_option_arg = true
|
||||
}
|
||||
options = a
|
||||
}
|
||||
// command string
|
||||
if strings.ContainsRune(options, 'c') {
|
||||
// non-interactive shell
|
||||
// also skip `bash -ic` interactive mode with command string
|
||||
return argv, env, nil
|
||||
}
|
||||
// read from stdin and follow with args
|
||||
if strings.ContainsRune(options, 's') {
|
||||
break
|
||||
}
|
||||
// interactive option
|
||||
if strings.ContainsRune(options, 'i') {
|
||||
interactive_opt = true
|
||||
}
|
||||
} else if strings.HasPrefix(arg, `--`) && expecting_multi_chars_opt {
|
||||
if arg == `--posix` {
|
||||
inject.Add(`posix`)
|
||||
posix_env = env[`ENV`]
|
||||
remove_args.Add(i)
|
||||
} else if arg == `--norc` {
|
||||
inject.Add(`no-rc`)
|
||||
remove_args.Add(i)
|
||||
} else if arg == `--noprofile` {
|
||||
inject.Add(`no-profile`)
|
||||
remove_args.Add(i)
|
||||
} else if (arg == `--rcfile` || arg == `--init-file`) && i+1 < len(argv) {
|
||||
expecting_option_arg = true
|
||||
rcfile = argv[i+1]
|
||||
remove_args.AddItems(i, i+1)
|
||||
}
|
||||
} else {
|
||||
file_arg_set = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if file_arg_set && !interactive_opt {
|
||||
// non-interactive shell
|
||||
return argv, env, nil
|
||||
}
|
||||
env[`ENV`] = filepath.Join(shell_integration_dir, `kitty.bash`)
|
||||
env[`KITTY_BASH_INJECT`] = strings.Join(inject.AsSlice(), " ")
|
||||
if posix_env != "" {
|
||||
env[`KITTY_BASH_POSIX_ENV`] = posix_env
|
||||
}
|
||||
if rcfile != "" {
|
||||
env[`KITTY_BASH_RCFILE`] = rcfile
|
||||
}
|
||||
sorted := remove_args.AsSlice()
|
||||
slices.Sort(sorted)
|
||||
for _, i := range utils.Reverse(sorted) {
|
||||
argv = slices.Delete(argv, i, i+1)
|
||||
}
|
||||
if env[`HISTFILE`] == "" && !inject.Has(`posix`) {
|
||||
// In POSIX mode the default history file is ~/.sh_history instead of ~/.bash_history
|
||||
env[`HISTFILE`] = utils.Expanduser(`~/.bash_history`)
|
||||
env[`KITTY_BASH_UNEXPORT_HISTFILE`] = `1`
|
||||
}
|
||||
argv = slices.Insert(argv, 1, `--posix`)
|
||||
|
||||
if bashrc := os.Getenv(`KITTY_RUNNING_BASH_INTEGRATION_TEST`); bashrc != `` && os.Getenv("KITTY_RUNNING_SHELL_INTEGRATION_TEST") == "1" {
|
||||
// prevent bash from sourcing /etc/profile which is not under our control
|
||||
env[`KITTY_BASH_INJECT`] += ` posix`
|
||||
env[`KITTY_BASH_POSIX_ENV`] = bashrc
|
||||
}
|
||||
|
||||
return argv, env, nil
|
||||
}
|
||||
|
||||
func setup_func_for_shell(shell_name string) integration_setup_func {
|
||||
switch shell_name {
|
||||
case "zsh":
|
||||
return zsh_setup_func
|
||||
case "fish":
|
||||
return fish_setup_func
|
||||
case "bash":
|
||||
return bash_setup_func
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func IsSupportedShell(shell_name string) bool { return setup_func_for_shell(shell_name) != nil }
|
||||
|
||||
func Setup(shell_name string, ksi_var string, argv []string, env map[string]string) ([]string, map[string]string, error) {
|
||||
ksi_dir, err := EnsureShellIntegrationFilesFor(shell_name)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
argv, env, err = setup_func_for_shell(shell_name)(ksi_dir, slices.Clone(argv), maps.Clone(env))
|
||||
if err == nil {
|
||||
env[`KITTY_SHELL_INTEGRATION`] = ksi_var
|
||||
}
|
||||
return argv, env, err
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package shell_integration
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestExtractShellIntegration(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
if err := extract_shell_integration_for("zsh", tdir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kzsh := filepath.Join(tdir, "shell-integration", "zsh", "kitty.zsh")
|
||||
if _, err := os.Stat(kzsh); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tdir, "shell-integration", "zsh", "completions", "_kitty")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
orig, err := os.ReadFile(kzsh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = os.WriteFile(kzsh, []byte("changed"), 0o644)
|
||||
if err := extract_shell_integration_for("zsh", tdir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
changed, err := os.ReadFile(kzsh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(changed, orig) {
|
||||
t.Fatalf("Failed to update shell integration file")
|
||||
}
|
||||
|
||||
if err = extract_terminfo(tdir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(tdir, "terminfo", "78", kitty.DefaultTermName)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
TerminfoData()
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package shell_integration
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
//go:embed data_generated.bin
|
||||
var embedded_data string
|
||||
|
||||
type Entry struct {
|
||||
Metadata *tar.Header
|
||||
Data []byte
|
||||
}
|
||||
|
||||
type Container map[string]Entry
|
||||
|
||||
var Data = sync.OnceValue(func() Container {
|
||||
tr := tar.NewReader(utils.ReaderForCompressedEmbeddedData(embedded_data))
|
||||
ans := make(Container, 64)
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
data, err := utils.ReadAll(tr, int(hdr.Size))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ans[hdr.Name] = Entry{hdr, data}
|
||||
}
|
||||
return ans
|
||||
})
|
||||
|
||||
func (self Container) FilesMatching(prefix string, exclude_patterns ...string) []string {
|
||||
ans := make([]string, 0, len(self))
|
||||
patterns := make([]*regexp.Regexp, len(exclude_patterns))
|
||||
for i, exp := range exclude_patterns {
|
||||
patterns[i] = regexp.MustCompile(exp)
|
||||
}
|
||||
for name := range self {
|
||||
if strings.HasPrefix(name, prefix) {
|
||||
excluded := false
|
||||
for _, pat := range patterns {
|
||||
if matched := pat.FindString(name); matched != "" {
|
||||
excluded = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !excluded {
|
||||
ans = append(ans, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package shortcuts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type ShortcutMap[T comparable] struct {
|
||||
leaves map[string]T
|
||||
children map[string]*ShortcutMap[T]
|
||||
}
|
||||
|
||||
func (self *ShortcutMap[T]) ResolveKeyEvent(k *loop.KeyEvent, pending_keys ...string) (ac T, pending string) {
|
||||
q := self
|
||||
for _, pk := range pending_keys {
|
||||
q = self.children[pk]
|
||||
if q == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
for c, ans := range q.leaves {
|
||||
if k.MatchesPressOrRepeat(c) {
|
||||
ac = ans
|
||||
return
|
||||
}
|
||||
}
|
||||
for c := range q.children {
|
||||
if k.MatchesPressOrRepeat(c) {
|
||||
pending = c
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *ShortcutMap[T]) Add(ac T, keys ...string) (conflict T) {
|
||||
return self.add(ac, keys)
|
||||
}
|
||||
|
||||
func (self *ShortcutMap[T]) AddOrPanic(ac T, keys ...string) {
|
||||
var zero T
|
||||
c := self.add(ac, keys)
|
||||
if c != zero {
|
||||
panic(fmt.Sprintf("The shortcut for %#v (%s) conflicted with the shortcut for %#v (%s)",
|
||||
ac, strings.Join(keys, " "), c, strings.Join(self.shortcut_for(c), " ")))
|
||||
}
|
||||
}
|
||||
|
||||
func New[T comparable]() *ShortcutMap[T] {
|
||||
return &ShortcutMap[T]{leaves: make(map[string]T), children: make(map[string]*ShortcutMap[T])}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package shortcuts
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func (self *ShortcutMap[T]) first_action() (ans T) {
|
||||
for _, ac := range self.leaves {
|
||||
return ac
|
||||
}
|
||||
for _, child := range self.children {
|
||||
return child.first_action()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *ShortcutMap[T]) shortcut_for(ac T) (keys []string) {
|
||||
keys = []string{}
|
||||
for key, q := range self.leaves {
|
||||
if ac == q {
|
||||
return append(keys, key)
|
||||
}
|
||||
}
|
||||
for key, child := range self.children {
|
||||
ckeys := child.shortcut_for(ac)
|
||||
if len(ckeys) > 0 {
|
||||
return append(append(keys, key), ckeys...)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (self *ShortcutMap[T]) add(ac T, keys []string) (conflict T) {
|
||||
sm := self
|
||||
last := len(keys) - 1
|
||||
for i, key := range keys {
|
||||
if i == last {
|
||||
if c, found := sm.leaves[key]; found {
|
||||
conflict = c
|
||||
}
|
||||
sm.leaves[key] = ac
|
||||
if c, found := sm.children[key]; found {
|
||||
conflict = c.first_action()
|
||||
delete(sm.children, key)
|
||||
}
|
||||
} else {
|
||||
if c, found := sm.leaves[key]; found {
|
||||
conflict = c
|
||||
delete(sm.leaves, key)
|
||||
}
|
||||
q := sm.children[key]
|
||||
if q == nil {
|
||||
q = &ShortcutMap[T]{leaves: map[string]T{}, children: map[string]*ShortcutMap[T]{}}
|
||||
sm.children[key] = q
|
||||
}
|
||||
sm = q
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Spinner struct {
|
||||
Name string
|
||||
interval time.Duration
|
||||
frames []string
|
||||
current_frame int
|
||||
last_change_at time.Time
|
||||
}
|
||||
|
||||
func (self Spinner) Interval() time.Duration {
|
||||
return self.interval
|
||||
}
|
||||
|
||||
func (self *Spinner) Tick() string {
|
||||
now := time.Now()
|
||||
if now.Sub(self.last_change_at) >= self.interval {
|
||||
self.last_change_at = now
|
||||
self.current_frame = (self.current_frame + 1) % len(self.frames)
|
||||
}
|
||||
return self.frames[self.current_frame]
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package subseq
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/go-parallel"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
const (
|
||||
LEVEL1 = "/"
|
||||
LEVEL2 = "-_0123456789"
|
||||
LEVEL3 = "."
|
||||
)
|
||||
|
||||
type resolved_options_type struct {
|
||||
level1, level2, level3 []rune
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Level1, Level2, Level3 string
|
||||
NumberOfThreads int
|
||||
}
|
||||
|
||||
type Match struct {
|
||||
Positions []int
|
||||
Score float64
|
||||
idx int
|
||||
Text string
|
||||
}
|
||||
|
||||
func level_factor_for(current_lcase, last_lcase, current_cased, last_cased rune, opts *resolved_options_type) int {
|
||||
switch {
|
||||
case slices.Contains(opts.level1, last_lcase):
|
||||
return 90
|
||||
case slices.Contains(opts.level2, last_lcase):
|
||||
return 80
|
||||
case last_lcase == last_cased && current_lcase != current_cased: // camelCase
|
||||
return 80
|
||||
case slices.Contains(opts.level3, last_lcase):
|
||||
return 70
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
type workspace_type struct {
|
||||
positions [][]int // positions of each needle char in haystack
|
||||
level_factors []int
|
||||
best []float64 // highest score of a match ending at each position of each needle char, flattened
|
||||
prev []int // index into the positions of the previous needle char for that match
|
||||
max_score_per_char float64
|
||||
}
|
||||
|
||||
func (w *workspace_type) initialize(haystack_sz, needle_sz int) {
|
||||
if cap(w.positions) < needle_sz {
|
||||
w.positions = make([][]int, needle_sz)
|
||||
} else {
|
||||
w.positions = w.positions[:needle_sz]
|
||||
}
|
||||
if cap(w.level_factors) < haystack_sz {
|
||||
w.level_factors = make([]int, 2*haystack_sz)
|
||||
} else {
|
||||
w.level_factors = w.level_factors[:haystack_sz]
|
||||
}
|
||||
for i, s := range w.positions {
|
||||
if cap(s) < haystack_sz {
|
||||
w.positions[i] = make([]int, 0, 2*haystack_sz)
|
||||
} else {
|
||||
w.positions[i] = w.positions[i][:0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *workspace_type) char_score(pos, distance int) float64 {
|
||||
if w.level_factors[pos] > 0 {
|
||||
return (100.0 * w.max_score_per_char) / float64(w.level_factors[pos]) // at a special location
|
||||
}
|
||||
return (0.75 * w.max_score_per_char) / float64(distance)
|
||||
}
|
||||
|
||||
func has_atleast_one_match(w *workspace_type) (found bool) {
|
||||
p := -1
|
||||
for i := range len(w.positions) {
|
||||
if len(w.positions[i]) == 0 { // all chars of needle not in haystack
|
||||
return false
|
||||
}
|
||||
found = false
|
||||
for _, pos := range w.positions[i] {
|
||||
if pos > p {
|
||||
p = pos
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found { // chars of needle not present in sequence in haystack
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func score_item(item string, idx int, needle []rune, opts *resolved_options_type, w *workspace_type) *Match {
|
||||
ans := &Match{idx: idx, Text: item, Positions: make([]int, len(needle))}
|
||||
haystack := []rune(strings.ToLower(item))
|
||||
orig_haystack := []rune(item)
|
||||
w.initialize(len(orig_haystack), len(needle))
|
||||
for i := range len(haystack) {
|
||||
level_factor_calculated := false
|
||||
for j := range len(needle) {
|
||||
if needle[j] == haystack[i] {
|
||||
if !level_factor_calculated {
|
||||
level_factor_calculated = true
|
||||
if i > 0 {
|
||||
w.level_factors[i] = level_factor_for(haystack[i], haystack[i-1], orig_haystack[i], orig_haystack[i-1], opts)
|
||||
}
|
||||
}
|
||||
w.positions[j] = append(w.positions[j], i)
|
||||
}
|
||||
}
|
||||
}
|
||||
w.max_score_per_char = (1.0/float64(len(orig_haystack)) + 1.0/float64(len(needle))) / 2.0
|
||||
if !has_atleast_one_match(w) {
|
||||
return ans
|
||||
}
|
||||
// Find the highest scoring monotonic positions one needle char at a time
|
||||
n := 0
|
||||
for _, positions := range w.positions {
|
||||
n += len(positions)
|
||||
}
|
||||
if cap(w.best) < n {
|
||||
w.best, w.prev = make([]float64, 2*n), make([]int, 2*n)
|
||||
}
|
||||
for k, pos := range w.positions[0] {
|
||||
w.best[k] = w.char_score(pos, pos+1)
|
||||
}
|
||||
off := 0 // offset of the entries for the previous needle char in best
|
||||
for j := 1; j < len(w.positions); j++ {
|
||||
prev_positions, next_off := w.positions[j-1], off+len(w.positions[j-1])
|
||||
for k, pos := range w.positions[j] {
|
||||
score, from := 0.0, 0
|
||||
for i := 0; i < len(prev_positions) && prev_positions[i] < pos; i++ {
|
||||
s := w.best[off+i]
|
||||
if s == 0 { // no match ends here, all scores are > 0
|
||||
continue
|
||||
}
|
||||
if distance := pos - prev_positions[i]; distance < 2 {
|
||||
s += w.max_score_per_char // consecutive chars
|
||||
} else {
|
||||
s += w.char_score(pos, distance)
|
||||
}
|
||||
if s > score {
|
||||
score, from = s, i
|
||||
}
|
||||
}
|
||||
w.best[next_off+k], w.prev[next_off+k] = score, from
|
||||
}
|
||||
off = next_off
|
||||
}
|
||||
last, k := len(w.positions)-1, 0
|
||||
for i := range len(w.positions[last]) {
|
||||
if w.best[off+i] > ans.Score {
|
||||
ans.Score, k = w.best[off+i], i
|
||||
}
|
||||
}
|
||||
for j := last; j > 0; j-- {
|
||||
ans.Positions[j] = w.positions[j][k]
|
||||
k = w.prev[off+k]
|
||||
off -= len(w.positions[j-1])
|
||||
}
|
||||
ans.Positions[0] = w.positions[0][k]
|
||||
if ans.Score > 0 {
|
||||
adjust := utils.RuneOffsetsToByteOffsets(item)
|
||||
for i := range ans.Positions {
|
||||
ans.Positions[i] = adjust(ans.Positions[i])
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
|
||||
func ScoreItems(query string, items []string, opts Options) []*Match {
|
||||
ans := make([]*Match, len(items))
|
||||
nr := []rune(strings.ToLower(query))
|
||||
if opts.Level1 == "" {
|
||||
opts.Level1 = LEVEL1
|
||||
}
|
||||
if opts.Level2 == "" {
|
||||
opts.Level2 = LEVEL2
|
||||
}
|
||||
if opts.Level3 == "" {
|
||||
opts.Level3 = LEVEL3
|
||||
}
|
||||
ropts := resolved_options_type{
|
||||
level1: []rune(opts.Level1), level2: []rune(opts.Level2), level3: []rune(opts.Level3),
|
||||
}
|
||||
parallel.Run_in_parallel_over_range(opts.NumberOfThreads, func(start, limit int) {
|
||||
w := workspace_type{}
|
||||
for i := start; i < limit; i++ {
|
||||
ans[i] = score_item(items[i], i, nr, &ropts, &w)
|
||||
}
|
||||
}, 0, len(items))
|
||||
return ans
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package subseq
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"math/rand"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestSubseq(t *testing.T) {
|
||||
var positions [][]int
|
||||
sort_by_score := false
|
||||
|
||||
simple := func(items, query string, expected ...string) {
|
||||
matches := ScoreItems(query, utils.Splitlines(items), Options{})
|
||||
if sort_by_score {
|
||||
matches = utils.StableSort(matches, func(a, b *Match) int {
|
||||
if b.Score < a.Score {
|
||||
return -1
|
||||
}
|
||||
if b.Score > a.Score {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
}
|
||||
actual := make([]string, 0, len(matches))
|
||||
actual_positions := make([][]int, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
if m.Score > 0 {
|
||||
actual = append(actual, m.Text)
|
||||
actual_positions = append(actual_positions, m.Positions)
|
||||
}
|
||||
}
|
||||
if expected == nil {
|
||||
expected = []string{}
|
||||
}
|
||||
if diff := cmp.Diff(expected, actual); diff != "" {
|
||||
t.Fatalf("Failed for items: %v\nMatches: %#v\n%s", utils.Splitlines(items), matches, diff)
|
||||
}
|
||||
if positions != nil {
|
||||
if diff := cmp.Diff(positions, actual_positions); diff != "" {
|
||||
t.Fatalf("Failed positions for items: %v\n%s", utils.Splitlines(items), diff)
|
||||
}
|
||||
positions = nil
|
||||
}
|
||||
}
|
||||
simple("test\nxyz", "te", "test")
|
||||
simple("abc\nxyz", "ba")
|
||||
simple("abc\n123", "abc", "abc")
|
||||
simple("test\nxyz", "Te", "test")
|
||||
simple("test\nxyz", "XY", "xyz")
|
||||
simple("test\nXYZ", "xy", "XYZ")
|
||||
simple("test\nXYZ", "mn")
|
||||
|
||||
positions = [][]int{{0, 2}, {0, 1}}
|
||||
simple("abc\nac", "ac", "abc", "ac")
|
||||
positions = [][]int{{0}}
|
||||
simple("abc\nv", "a", "abc")
|
||||
positions = [][]int{{len("汉"), 7}}
|
||||
simple("汉a字b\nxyz", "ab", "汉a字b")
|
||||
|
||||
sort_by_score = true
|
||||
// Match at start
|
||||
simple("archer\nelementary", "e", "elementary", "archer")
|
||||
// Match at level factor
|
||||
simple("xxxy\nxx/y", "y", "xx/y", "xxxy")
|
||||
// CamelCase
|
||||
simple("xxxy\nxxxY", "y", "xxxY", "xxxy")
|
||||
// Total length
|
||||
simple("xxxya\nxxxy", "y", "xxxy", "xxxya")
|
||||
// Distance
|
||||
simple("abbc\nabc", "ac", "abc", "abbc")
|
||||
// Extreme chars
|
||||
simple("xxa\naxx", "a", "axx", "xxa")
|
||||
// Highest score
|
||||
positions = [][]int{{3}}
|
||||
simple("xa/a", "a", "xa/a")
|
||||
|
||||
sort_by_score = false
|
||||
items := make([]string, 256)
|
||||
for i := range items {
|
||||
items[i] = strconv.Itoa(i)
|
||||
}
|
||||
expected := make([]string, 0, len(items))
|
||||
for _, x := range items {
|
||||
if strings.ContainsRune(x, rune('2')) {
|
||||
expected = append(expected, x)
|
||||
}
|
||||
}
|
||||
simple(strings.Join(items, "\n"), "2", expected...)
|
||||
}
|
||||
|
||||
var theme_names = []string{
|
||||
"1984 Dark", "Adwaita darker", "Aquarium Light", "Atelier Plateau Dark", "Ayu Mirage", "Base2Tone Heath Dark",
|
||||
"Base2Tone Sea Dark", "Base4Tone_Modern_W Dark", "Bluloco Dark", "C64", "Catppuccin-Latte", "Chalkboard",
|
||||
"Copland OS", "Darkside", "Doom Vibrant", "Earthsong", "Everforest Light Hard", "Flexoki (Dark)",
|
||||
"GitHub Dark Colorblind", "GitHub Light High Contrast", "Gnome-ish gray-on-black", "Gruvbox Light Soft",
|
||||
"Gruvbox Material Light Medium", "HardHacker", "IC Green PPL", "Kanagawa_dragon", "Kibble", "Linh", "Mayukai",
|
||||
"Modus Vivendi", "N0tch2k", "Nord", "One Half Dark", "Pastel EGA", "Red Alert", "Ryoccino", "Selenized White",
|
||||
"Serendipity Sunset", "Soft Server", "Solarized Dark Higher Contrast", "Sonokai Sushia", "Spring", "Teerb",
|
||||
"Tokyo Night", "Tomorrow", "Tomorrow Night Eighties", "Ubuntu", "Wez", "Yorumi Kraken", "ferra", "pink lavender",
|
||||
"zenbones_light",
|
||||
}
|
||||
|
||||
func score_positions(w *workspace_type, positions []int) (ans float64) {
|
||||
for i, pos := range positions {
|
||||
distance := pos + 1
|
||||
if i > 0 {
|
||||
distance = pos - positions[i-1]
|
||||
if distance < 2 {
|
||||
ans += w.max_score_per_char
|
||||
continue
|
||||
}
|
||||
}
|
||||
if w.level_factors[pos] > 0 {
|
||||
ans += (100.0 * w.max_score_per_char) / float64(w.level_factors[pos])
|
||||
} else {
|
||||
ans += (0.75 * w.max_score_per_char) / float64(distance)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Try every monotonic set of positions for the item last scored with w
|
||||
func brute_force(w *workspace_type) (best float64) {
|
||||
positions := make([]int, len(w.positions))
|
||||
var recurse func(j int)
|
||||
recurse = func(j int) {
|
||||
if j == len(positions) {
|
||||
best = max(best, score_positions(w, positions))
|
||||
return
|
||||
}
|
||||
for _, pos := range w.positions[j] {
|
||||
if j == 0 || pos > positions[j-1] {
|
||||
positions[j] = pos
|
||||
recurse(j + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
recurse(0)
|
||||
return
|
||||
}
|
||||
|
||||
func TestSubseqBruteForce(t *testing.T) {
|
||||
opts := resolved_options_type{level1: []rune(" "), level2: []rune(LEVEL2), level3: []rune(LEVEL3)}
|
||||
w := workspace_type{}
|
||||
r := rand.New(rand.NewSource(1))
|
||||
for range 200 {
|
||||
name := []rune(strings.ToLower(theme_names[r.Intn(len(theme_names))]))
|
||||
idx := r.Perm(len(name))[:1+r.Intn(min(6, len(name)))]
|
||||
slices.Sort(idx)
|
||||
needle := make([]rune, len(idx))
|
||||
for i, x := range idx {
|
||||
needle[i] = name[x]
|
||||
}
|
||||
for _, item := range theme_names {
|
||||
m := score_item(item, 0, needle, &opts, &w)
|
||||
if expected := brute_force(&w); m.Score != expected {
|
||||
t.Fatalf("Score for %#v in %#v: %v != %v", string(needle), item, m.Score, expected)
|
||||
}
|
||||
if m.Score > 0 {
|
||||
ok := score_positions(&w, m.Positions) == m.Score
|
||||
for i, pos := range m.Positions {
|
||||
ok = ok && strings.ToLower(item)[pos] == byte(needle[i]) && (i == 0 || pos > m.Positions[i-1])
|
||||
}
|
||||
if !ok {
|
||||
t.Fatalf("Positions for %#v in %#v: %v do not give the score %v", string(needle), item, m.Positions, m.Score)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// the old code tried every combination of positions here, which never finishes
|
||||
m := ScoreItems(strings.Repeat("a", 100), []string{strings.Repeat("a", 200)}, Options{})[0]
|
||||
expected := make([]int, 100)
|
||||
for i := range expected {
|
||||
expected[i] = i
|
||||
}
|
||||
if diff := cmp.Diff(expected, m.Positions); diff != "" {
|
||||
t.Fatalf("Failed positions for long needle:\n%s", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkScoreItems(b *testing.B) {
|
||||
for _, query := range []string{"dark", "tokyo night", "solarized dark higher contrast"} {
|
||||
b.Run(query, func(b *testing.B) {
|
||||
for b.Loop() {
|
||||
for i := range len(query) { // as if typed one char at a time
|
||||
ScoreItems(query[:i+1], theme_names, Options{Level1: " "})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/shirou/gopsutil/v4/process"
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var TmuxExe = sync.OnceValue(func() string {
|
||||
return utils.FindExe("tmux")
|
||||
})
|
||||
|
||||
func tmux_socket_address() (socket string) {
|
||||
socket = os.Getenv("TMUX")
|
||||
if socket == "" {
|
||||
return ""
|
||||
}
|
||||
addr, pid_str, found := strings.Cut(socket, ",")
|
||||
if !found {
|
||||
return ""
|
||||
}
|
||||
if unix.Access(addr, unix.R_OK|unix.W_OK) != nil {
|
||||
return ""
|
||||
}
|
||||
pid_str, _, _ = strings.Cut(pid_str, ",")
|
||||
pid, err := strconv.ParseInt(pid_str, 10, 32)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
p, err := process.NewProcess(int32(pid))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
cmd, err := p.CmdlineSlice()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if len(cmd) > 0 && strings.ToLower(filepath.Base(cmd[0])) != "tmux" {
|
||||
return ""
|
||||
}
|
||||
return socket
|
||||
}
|
||||
|
||||
var TmuxSocketAddress = sync.OnceValue(tmux_socket_address)
|
||||
|
||||
func tmux_command(args ...string) (c *exec.Cmd, stderr *strings.Builder) {
|
||||
c = exec.Command(TmuxExe(), args...)
|
||||
stderr = &strings.Builder{}
|
||||
c.Stderr = stderr
|
||||
return c, stderr
|
||||
}
|
||||
|
||||
func tmux_allow_passthrough() error {
|
||||
c, stderr := tmux_command("show", "-Ap", "allow-passthrough")
|
||||
allowed, not_allowed := errors.New("allowed"), errors.New("not allowed")
|
||||
get_result := make(chan error)
|
||||
go func() {
|
||||
output, err := c.Output()
|
||||
if err != nil {
|
||||
get_result <- fmt.Errorf("Running %#v failed with error: %w. STDERR: %s", c.Args, err, stderr.String())
|
||||
} else {
|
||||
q := strings.TrimSpace(utils.UnsafeBytesToString(output))
|
||||
if strings.HasSuffix(q, " on") || strings.HasSuffix(q, " all") {
|
||||
get_result <- allowed
|
||||
} else {
|
||||
get_result <- not_allowed
|
||||
}
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case r := <-get_result:
|
||||
if r == allowed {
|
||||
return nil
|
||||
}
|
||||
if r != not_allowed {
|
||||
return r
|
||||
}
|
||||
c, stderr = tmux_command("set", "-p", "allow-passthrough", "on")
|
||||
err := c.Run()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Running %#v failed with error: %w. STDERR: %s", c.Args, err, stderr.String())
|
||||
}
|
||||
return err
|
||||
case <-time.After(2 * time.Second):
|
||||
return fmt.Errorf("Tmux command timed out. This often happens when the version of tmux on your PATH is older than the version of the running tmux server")
|
||||
}
|
||||
}
|
||||
|
||||
var TmuxAllowPassthrough = sync.OnceValue(tmux_allow_passthrough)
|
||||
@@ -0,0 +1,85 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/base85"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var RunningAsUI = sync.OnceValue(func() bool {
|
||||
defer func() { os.Unsetenv("KITTEN_RUNNING_AS_UI") }()
|
||||
return os.Getenv("KITTEN_RUNNING_AS_UI") != ""
|
||||
})
|
||||
|
||||
type BasicColors struct {
|
||||
Foreground uint32 `json:"foreground"`
|
||||
Background uint32 `json:"background"`
|
||||
Color0 uint32 `json:"color0"`
|
||||
Color1 uint32 `json:"color1"`
|
||||
Color2 uint32 `json:"color2"`
|
||||
Color3 uint32 `json:"color3"`
|
||||
Color4 uint32 `json:"color4"`
|
||||
Color5 uint32 `json:"color5"`
|
||||
Color6 uint32 `json:"color6"`
|
||||
Color7 uint32 `json:"color7"`
|
||||
Color8 uint32 `json:"color8"`
|
||||
Color9 uint32 `json:"color9"`
|
||||
Color10 uint32 `json:"color10"`
|
||||
Color11 uint32 `json:"color11"`
|
||||
Color12 uint32 `json:"color12"`
|
||||
Color13 uint32 `json:"color13"`
|
||||
Color14 uint32 `json:"color14"`
|
||||
Color15 uint32 `json:"color15"`
|
||||
}
|
||||
|
||||
func ReadBasicColors() (ans BasicColors, err error) {
|
||||
q := os.Getenv("KITTY_BASIC_COLORS")
|
||||
if q == "" {
|
||||
err = fmt.Errorf("No KITTY_BASIC_COLORS env var")
|
||||
} else {
|
||||
err = json.Unmarshal(utils.UnsafeStringToBytes(q), &ans)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func PrepareRootCmd(root *cli.Command) {
|
||||
if RunningAsUI() {
|
||||
root.CallbackOnError = func(cmd *cli.Command, err error, during_parsing bool, exit_code int) int {
|
||||
cli.ShowError(err)
|
||||
os.Stdout.WriteString("\x1bP@kitty-overlay-ready|\x1b\\")
|
||||
HoldTillEnter(true)
|
||||
return exit_code
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func KittenOutputSerializer() func(any) (string, error) {
|
||||
if RunningAsUI() {
|
||||
return func(what any) (string, error) {
|
||||
data, err := json.Marshal(what)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "\x1bP@kitty-kitten-result|" + base85.EncodeToString(data) + "\x1b\\", nil
|
||||
}
|
||||
}
|
||||
return func(what any) (string, error) {
|
||||
if sval, ok := what.(string); ok {
|
||||
return sval, nil
|
||||
}
|
||||
data, err := json.MarshalIndent(what, "", " ")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return utils.UnsafeBytesToString(data), nil
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user