chore: import official kitty sources from upstream

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

No files matched your search

+758
View File
@@ -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})
}
+34
View File
@@ -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
}
+464
View File
@@ -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
}
}
+189
View File
@@ -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")
}
}
+291
View File
@@ -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
}
}
+155
View File
@@ -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):
}
}
+683
View File
@@ -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
}
+38
View File
@@ -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)
}
}
+209
View File
@@ -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)
}
+85
View File
@@ -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) })
}
+299
View File
@@ -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
}
}
}