package uv

import (
	
	
	
	
	
	
	
	
	
	

	
	
	xwindows 
	
)

// Flags to control the behavior of the parser.
const (
	// When this flag is set, the driver will treat both Ctrl+Space and Ctrl+@
	// as the same key sequence.
	//
	// Historically, the ANSI specs generate NUL (0x00) on both the Ctrl+Space
	// and Ctrl+@ key sequences. This flag allows the driver to treat both as
	// the same key sequence.
	flagCtrlAt = 1 << iota

	// When this flag is set, the driver will treat the Tab key and Ctrl+I as
	// the same key sequence.
	//
	// Historically, the ANSI specs generate HT (0x09) on both the Tab key and
	// Ctrl+I. This flag allows the driver to treat both as the same key
	// sequence.
	flagCtrlI

	// When this flag is set, the driver will treat the Enter key and Ctrl+M as
	// the same key sequence.
	//
	// Historically, the ANSI specs generate CR (0x0D) on both the Enter key
	// and Ctrl+M. This flag allows the driver to treat both as the same key.
	flagCtrlM

	// When this flag is set, the driver will treat Escape and Ctrl+[ as
	// the same key sequence.
	//
	// Historically, the ANSI specs generate ESC (0x1B) on both the Escape key
	// and Ctrl+[. This flag allows the driver to treat both as the same key
	// sequence.
	flagCtrlOpenBracket

	// When this flag is set, the driver will send a BS (0x08 byte) character
	// instead of a DEL (0x7F byte) character when the Backspace key is
	// pressed.
	//
	// The VT100 terminal has both a Backspace and a Delete key. The VT220
	// terminal dropped the Backspace key and replaced it with the Delete key.
	// Both terminals send a DEL character when the Delete key is pressed.
	// Modern terminals and PCs later readded the Delete key but used a
	// different key sequence, and the Backspace key was standardized to send a
	// DEL character.
	flagBackspace

	// When this flag is set, the driver will recognize the Find key instead of
	// treating it as a Home key.
	//
	// The Find key was part of the VT220 keyboard, and is no longer used in
	// modern day PCs.
	flagFind

	// When this flag is set, the driver will recognize the Select key instead
	// of treating it as a End key.
	//
	// The Symbol key was part of the VT220 keyboard, and is no longer used in
	// modern day PCs.
	flagSelect

	// When this flag is set, the driver will preserve function keys (F13-F63)
	// as symbols.
	//
	// Since these keys are not part of today's standard 20th century keyboard,
	// we treat them as F1-F12 modifier keys i.e. ctrl/shift/alt + Fn combos.
	// Key definitions come from Terminfo, this flag is only useful when
	// FlagTerminfo is not set.
	flagFKeys
)

// LegacyKeyEncoding is a set of flags that control the behavior of legacy
// terminal key encodings. Historically, ctrl+<key> input events produce
// control characters (0x00-0x1F) that collide with some special keys like Tab,
// Enter, and Escape. This controls the expected behavior of encoding these
// keys.
//
// This type has the following default values:
//   - CtrlAt maps 0x00 [ansi.NUL] to ctrl+space instead of ctrl+@.
//   - CtrlI maps 0x09 [ansi.HT] to the tab key instead of ctrl+i.
//   - CtrlM maps 0x0D [ansi.CR] to the enter key instead of ctrl+m.
//   - CtrlOpenBracket maps 0x1B [ansi.ESC] to the escape key instead of ctrl+[.
//   - Backspace maps the backspace key to 0x08 [ansi.BS] instead of 0x7F [ansi.DEL].
//   - Find maps the legacy find key to the home key.
//   - Select maps the legacy select key to the end key.
//   - FKeys maps high function keys instead of treating them as Function+<modifiers>.
type LegacyKeyEncoding uint32

// CtrlAt returns a [LegacyKeyEncoding] with whether [ansi.NUL] (0x00)
// is mapped to ctrl+at instead of ctrl+space.
func ( LegacyKeyEncoding) ( bool) LegacyKeyEncoding {
	if  {
		 |= flagCtrlAt
	} else {
		 &^= flagCtrlAt
	}
	return 
}

// CtrlI returns a [LegacyKeyEncoding] with whether [ansi.HT] (0x09)
// is mapped to ctrl+i instead of the tab key.
func ( LegacyKeyEncoding) ( bool) LegacyKeyEncoding {
	if  {
		 |= flagCtrlI
	} else {
		 &^= flagCtrlI
	}
	return 
}

// CtrlM returns a [LegacyKeyEncoding] with whether [ansi.CR] (0x0D)
// is mapped to ctrl+m instead of the enter key.
func ( LegacyKeyEncoding) ( bool) LegacyKeyEncoding {
	if  {
		 |= flagCtrlM
	} else {
		 &^= flagCtrlM
	}
	return 
}

// CtrlOpenBracket returns a [LegacyKeyEncoding] with whether [ansi.ESC] (0x1B)
// is mapped to ctrl+[ instead of the escape key.
func ( LegacyKeyEncoding) ( bool) LegacyKeyEncoding {
	if  {
		 |= flagCtrlOpenBracket
	} else {
		 &^= flagCtrlOpenBracket
	}
	return 
}

// Backspace returns a [LegacyKeyEncoding] with whether the backspace key is
// mapped to [ansi.BS] (0x08) instead of [ansi.DEL] (0x7F).
func ( LegacyKeyEncoding) ( bool) LegacyKeyEncoding {
	if  {
		 |= flagBackspace
	} else {
		 &^= flagBackspace
	}
	return 
}

// Find returns a [LegacyKeyEncoding] with whether the legacy find key
// is mapped to the home key.
func ( LegacyKeyEncoding) ( bool) LegacyKeyEncoding {
	if  {
		 |= flagFind
	} else {
		 &^= flagFind
	}
	return 
}

// Select returns a [LegacyKeyEncoding] with whether the legacy select key
// is mapped to the end key.
func ( LegacyKeyEncoding) ( bool) LegacyKeyEncoding {
	if  {
		 |= flagSelect
	} else {
		 &^= flagSelect
	}
	return 
}

// FKeys returns a [LegacyKeyEncoding] with whether high function keys are
// mapped to high function keys (beyond F20) instead of treating them as
// Function+<modifiers> keys.
func ( LegacyKeyEncoding) ( bool) LegacyKeyEncoding {
	if  {
		 |= flagFKeys
	} else {
		 &^= flagFKeys
	}
	return 
}

// EventDecoder decodes terminal input events from a byte buffer. Terminal
// input events are typically encoded as Unicode or ASCII characters, control
// codes, or ANSI escape sequences.
type EventDecoder struct {
	// Legacy is the legacy key encoding flags. These flags control the
	// behavior of legacy terminal key encodings. See [LegacyKeyEncoding] for
	// more details.
	Legacy LegacyKeyEncoding
	// UseTerminfo is a flag that controls whether to use the terminal type
	// Terminfo database to map escape sequences to key events. This will
	// override the default key sequences handled by the parser.
	UseTerminfo bool

	lastCks uint32 // the last control key state for the previous key event record.
}

// Decode finds the first recognized event sequence and returns it along
// with its length.
//
// It will return zero and nil no sequence is recognized or when the buffer is
// empty. If a sequence is not supported, an [UnknownEvent] is returned.
//
// Example:
//
//	```go
//	var decoder EventDecoder
//	var events []Event
//	buf := []byte("\x00" + // Ctrl+Space
//	    "\x1b[A" + // Up arrow
//	    "Hello") // Text input
//	for len(buf) > 0 {
//	    n, ev := decoder.Decode(buf)
//	    if ev != nil {
//	        events = append(events, ev)
//	    }
//	    buf = buf[n:]
//	}
//	```
func ( *EventDecoder) ( []byte) ( int,  Event) {
	if len() == 0 {
		return 0, nil
	}

	switch  := [0];  {
	case ansi.ESC:
		if len() == 1 {
			// Escape key
			return 1, KeyPressEvent{Code: KeyEscape}
		}

		switch  := [1];  {
		case 'O': // Esc-prefixed SS3
			return .parseSs3()
		case 'P': // Esc-prefixed DCS
			return .parseDcs()
		case '[': // Esc-prefixed CSI
			return .parseCsi()
		case ']': // Esc-prefixed OSC
			return .parseOsc()
		case '_': // Esc-prefixed APC
			return .parseApc()
		case '^': // Esc-prefixed PM
			return .parseStTerminated(ansi.PM, '^', nil)()
		case 'X': // Esc-prefixed SOS
			return .parseStTerminated(ansi.SOS, 'X', nil)()
		default:
			,  := .([1:])
			if ,  := .(KeyPressEvent);  {
				.Text = ""
				.Mod |= ModAlt
				return  + 1, 
			}

			// Not a key sequence, nor an alt modified key sequence. In that
			// case, just report a single escape key.
			return 1, KeyPressEvent{Code: KeyEscape}
		}
	case ansi.SS3:
		return .parseSs3()
	case ansi.DCS:
		return .parseDcs()
	case ansi.CSI:
		return .parseCsi()
	case ansi.OSC:
		return .parseOsc()
	case ansi.APC:
		return .parseApc()
	case ansi.PM:
		return .parseStTerminated(ansi.PM, '^', nil)()
	case ansi.SOS:
		return .parseStTerminated(ansi.SOS, 'X', nil)()
	default:
		if  <= ansi.US ||  == ansi.DEL ||  == ansi.SP {
			return 1, .parseControl()
		} else if  >= ansi.PAD &&  <= ansi.APC {
			// C1 control code
			// UTF-8 never starts with a C1 control code
			// Encode these as Ctrl+Alt+<code - 0x40>
			 := rune() - 0x40
			return 1, KeyPressEvent{Code: , Mod: ModCtrl | ModAlt}
		}
		return .parseUtf8()
	}
}

func ( *EventDecoder) ( []byte) (int, Event) {
	if len() == 2 && [0] == ansi.ESC {
		// short cut if this is an alt+[ key
		return 2, KeyPressEvent{Code: rune([1]), Mod: ModAlt}
	}

	var  ansi.Cmd
	var  [parser.MaxParamsSize]ansi.Param
	var  int

	var  int
	if [] == ansi.CSI || [] == ansi.ESC {
		++
	}
	if  < len() && [-1] == ansi.ESC && [] == '[' {
		++
	}

	// Initial CSI byte
	if  < len() && [] >= '<' && [] <= '?' {
		 |= ansi.Cmd([]) << parser.PrefixShift
	}

	// Scan parameter bytes in the range 0x30-0x3F
	var  int
	for  = 0;  < len() &&  < len() && [] >= 0x30 && [] <= 0x3F; ,  = +1, +1 {
		if [] >= '0' && [] <= '9' {
			if [] == parser.MissingParam {
				[] = 0
			}
			[] *= 10
			[] += ansi.Param([]) - '0'
		}
		if [] == ':' {
			[] |= parser.HasMoreFlag
		}
		if [] == ';' || [] == ':' {
			++
			if  < len() {
				// Don't overflow the params slice
				[] = parser.MissingParam
			}
		}
	}

	if  > 0 &&  < len() {
		// has parameters
		++
	}

	// Scan intermediate bytes in the range 0x20-0x2F
	var  byte
	for ;  < len() && [] >= 0x20 && [] <= 0x2F; ++ {
		 = []
	}

	// Set the intermediate byte
	 |= ansi.Cmd() << parser.IntermedShift

	// Scan final byte in the range 0x40-0x7E
	if  >= len() || [] < 0x40 || [] > 0x7E {
		// Special case for URxvt keys
		// CSI <number> $ is an invalid sequence, but URxvt uses it for
		// shift modified keys.
		if  == '$' && [-1] == '$' {
			 := slices.Clone([:-1])
			,  := .(append(, '~'))
			if ,  := .(KeyPressEvent);  {
				.Mod |= ModShift
				return , 
			}
		}
		return , UnknownEvent([:])
	}

	// Add the final byte
	 |= ansi.Cmd([])
	++

	 := ansi.Params([:])
	switch  {
	case 'y' | '?'<<parser.PrefixShift | '$'<<parser.IntermedShift:
		// Report Mode (DECRPM)
		, ,  := .Param(0, -1)
		if ! ||  == -1 {
			break
		}
		, ,  := .Param(1, 0)
		if ! {
			break
		}
		return , ModeReportEvent{Mode: ansi.DECMode(), Value: ansi.ModeSetting()}
	case 'c' | '?'<<parser.PrefixShift:
		// Primary Device Attributes
		return , parsePrimaryDevAttrs()
	case 'c' | '>'<<parser.PrefixShift:
		// Secondary Device Attributes
		return , parseSecondaryDevAttrs()
	case 'u' | '?'<<parser.PrefixShift:
		// Kitty keyboard flags
		, ,  := .Param(0, -1)
		return , KeyboardEnhancementsEvent{}
	case 'R' | '?'<<parser.PrefixShift:
		// This report may return a third parameter representing the page
		// number, but we don't really need it.
		, ,  := .Param(0, 1)
		, ,  := .Param(1, 1)
		if ! {
			break
		}
		return , CursorPositionEvent{Y:  - 1, X:  - 1}
	case 'm' | '<'<<parser.PrefixShift, 'M' | '<'<<parser.PrefixShift:
		// Handle SGR mouse
		if  == 3 {
			return , parseSGRMouseEvent(, )
		}
	case 'm' | '>'<<parser.PrefixShift:
		// XTerm modifyOtherKeys
		, ,  := .Param(0, 0)
		if ! ||  != 4 {
			break
		}
		, ,  := .Param(1, -1)
		if ! ||  == -1 {
			break
		}
		return , ModifyOtherKeysEvent{}
	case 'n' | '?'<<parser.PrefixShift:
		, ,  := .Param(0, -1)
		, ,  := .Param(1, -1)
		switch  {
		case 997: // [ansi.LightDarkReport]
			switch  {
			case 1:
				return , DarkColorSchemeEvent{}
			case 2:
				return , LightColorSchemeEvent{}
			}
		}
	case 'I':
		return , FocusEvent{}
	case 'O':
		return , BlurEvent{}
	case 'R':
		// Cursor position report OR modified F3
		, ,  := .Param(0, 1)
		, ,  := .Param(1, 1)
		if  == 2 &&  &&  {
			 := CursorPositionEvent{Y:  - 1, X:  - 1}
			if  == 1 && -1 <= int(ModMeta|ModShift|ModAlt|ModCtrl) {
				// XXX: We cannot differentiate between cursor position report and
				// CSI 1 ; <mod> R (which is modified F3) when the cursor is at the
				// row 1. In this case, we report both messages.
				//
				// For a non ambiguous cursor position report, use
				// [ansi.RequestExtendedCursorPosition] (DECXCPR) instead.
				return , MultiEvent{KeyPressEvent{Code: KeyF3, Mod: KeyMod( - 1)}, }
			}

			return , 
		}

		if  != 0 {
			break
		}

		// Unmodified key F3 (CSI R)
		fallthrough
	case 'a', 'b', 'c', 'd', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'S', 'Z':
		var  KeyPressEvent
		switch  {
		case 'a', 'b', 'c', 'd':
			 = KeyPressEvent{Code: KeyUp + rune(-'a'), Mod: ModShift}
		case 'A', 'B', 'C', 'D':
			 = KeyPressEvent{Code: KeyUp + rune(-'A')}
		case 'E':
			 = KeyPressEvent{Code: KeyBegin}
		case 'F':
			 = KeyPressEvent{Code: KeyEnd}
		case 'H':
			 = KeyPressEvent{Code: KeyHome}
		case 'P', 'Q', 'R', 'S':
			 = KeyPressEvent{Code: KeyF1 + rune(-'P')}
		case 'Z':
			 = KeyPressEvent{Code: KeyTab, Mod: ModShift}
		}
		, ,  := .Param(0, 1)
		, ,  := .Param(1, 1)
		if  > 2 && ![1].HasMore() ||  != 1 {
			break
		}
		if  > 1 &&  == 1 &&  != -1 {
			// CSI 1 ; <modifiers> A
			.Mod |= KeyMod( - 1)
		}
		// Don't forget to handle Kitty keyboard protocol
		return , parseKittyKeyboardExt(, )
	case 'M':
		// Handle X10 mouse
		if +3 > len() {
			return , UnknownCsiEvent([:])
		}
		return  + 3, parseX10MouseEvent(append([:], [:+3]...))
	case 'y' | '$'<<parser.IntermedShift:
		// Report Mode (DECRPM)
		, ,  := .Param(0, -1)
		if ! ||  == -1 {
			break
		}
		, ,  := .Param(1, 0)
		if ! {
			break
		}
		return , ModeReportEvent{Mode: ansi.ANSIMode(), Value: ansi.ModeSetting()}
	case 'u':
		// Kitty keyboard protocol & CSI u (fixterms)
		if  == 0 {
			return , UnknownCsiEvent([:])
		}
		return , parseKittyKeyboard()
	case '_':
		// Win32 Input Mode
		if  != 6 {
			return , UnknownCsiEvent([:])
		}

		, ,  := .Param(0, 0)
		, ,  := .Param(1, 0)
		, ,  := .Param(2, 0)
		, ,  := .Param(3, 0)
		, ,  := .Param(4, 0)
		, ,  := .Param(5, 0)
		 := .parseWin32InputKeyEvent(
			uint16(),         //nolint:gosec // Vk wVirtualKeyCode
			uint16(),         //nolint:gosec // Sc wVirtualScanCode
			rune(),           // Uc UnicodeChar
			 == 1,            // Kd bKeyDown
			uint32(),         //nolint:gosec // Cs dwControlKeyState
			max(1, uint16()), //nolint:gosec // Rc wRepeatCount
		)

		return , 
	case '@', '^', '~':
		if  == 0 {
			return , UnknownCsiEvent([:])
		}

		, ,  := .Param(0, 0)
		switch  {
		case '~':
			switch  {
			case 27:
				// XTerm modifyOtherKeys 2
				if  != 3 {
					return , UnknownCsiEvent([:])
				}
				return , parseXTermModifyOtherKeys()
			case 200:
				// bracketed-paste start
				return , PasteStartEvent{}
			case 201:
				// bracketed-paste end
				return , PasteEndEvent{}
			}
		}

		switch  {
		case 1, 2, 3, 4, 5, 6, 7, 8,
			11, 12, 13, 14, 15,
			17, 18, 19, 20, 21,
			23, 24, 25, 26,
			28, 29, 31, 32, 33, 34:
			var  KeyPressEvent
			switch  {
			case 1:
				if .Legacy&flagFind != 0 {
					 = KeyPressEvent{Code: KeyFind}
				} else {
					 = KeyPressEvent{Code: KeyHome}
				}
			case 2:
				 = KeyPressEvent{Code: KeyInsert}
			case 3:
				 = KeyPressEvent{Code: KeyDelete}
			case 4:
				if .Legacy&flagSelect != 0 {
					 = KeyPressEvent{Code: KeySelect}
				} else {
					 = KeyPressEvent{Code: KeyEnd}
				}
			case 5:
				 = KeyPressEvent{Code: KeyPgUp}
			case 6:
				 = KeyPressEvent{Code: KeyPgDown}
			case 7:
				 = KeyPressEvent{Code: KeyHome}
			case 8:
				 = KeyPressEvent{Code: KeyEnd}
			case 11, 12, 13, 14, 15:
				 = KeyPressEvent{Code: KeyF1 + rune(-11)}
			case 17, 18, 19, 20, 21:
				 = KeyPressEvent{Code: KeyF6 + rune(-17)}
			case 23, 24, 25, 26:
				 = KeyPressEvent{Code: KeyF11 + rune(-23)}
			case 28, 29:
				 = KeyPressEvent{Code: KeyF15 + rune(-28)}
			case 31, 32, 33, 34:
				 = KeyPressEvent{Code: KeyF17 + rune(-31)}
			}

			// modifiers
			, ,  := .Param(1, -1)
			if  > 1 &&  != -1 {
				.Mod |= KeyMod( - 1)
			}

			// Handle URxvt weird keys
			switch  {
			case '~':
				// Don't forget to handle Kitty keyboard protocol
				return , parseKittyKeyboardExt(, )
			case '^':
				.Mod |= ModCtrl
			case '@':
				.Mod |= ModCtrl | ModShift
			}

			return , 
		}

	case 't':
		, ,  := .Param(0, 0)
		if ! {
			break
		}

		switch  {
		case 4: // Report Terminal window size in pixels.
			if  == 3 {
				, ,  := .Param(1, 0)
				, ,  := .Param(2, 0)
				if ! || ! {
					break
				}
				return , PixelSizeEvent{Width: , Height: }
			}
		case 6: // Report Terminal character cell size.
			if  == 3 {
				, ,  := .Param(1, 0)
				, ,  := .Param(2, 0)
				if ! || ! {
					break
				}
				return , CellSizeEvent{Width: , Height: }
			}
		case 8: // Report Terminal Window size in cells.
			if  == 3 {
				, ,  := .Param(1, 0)
				, ,  := .Param(2, 0)
				if ! || ! {
					break
				}
				return , WindowSizeEvent{Width: , Height: }
			}
		case 48: // In band terminal size report.
			if  == 5 {
				, ,  := .Param(1, 0)
				, ,  := .Param(2, 0)
				, ,  := .Param(3, 0)
				, ,  := .Param(4, 0)
				if ! || ! || ! || ! {
					break
				}
				return , MultiEvent{
					WindowSizeEvent{Width: , Height: },
					PixelSizeEvent{Width: , Height: },
				}
			}
		}

		// Any other window operation event.

		var  WindowOpEvent
		.Op = 
		for  := 1;  < ; ++ {
			, ,  := .Param(, 0)
			if  {
				.Args = append(.Args, )
			}
		}

		return , 
	}
	return , UnknownCsiEvent([:])
}

// parseSs3 parses a SS3 sequence.
// See https://vt100.net/docs/vt220-rm/chapter4.html#S4.4.4.2
func ( *EventDecoder) ( []byte) (int, Event) {
	if len() == 2 && [0] == ansi.ESC {
		// short cut if this is an alt+O key
		return 2, KeyPressEvent{Code: unicode.ToLower(rune([1])), Mod: ModShift | ModAlt}
	}

	var  int
	if [] == ansi.SS3 || [] == ansi.ESC {
		++
	}
	if  < len() && [-1] == ansi.ESC && [] == 'O' {
		++
	}

	// Scan numbers from 0-9
	var  int
	for ;  < len() && [] >= '0' && [] <= '9'; ++ {
		 *= 10
		 += int([]) - '0'
	}

	// Scan a GL character
	// A GL character is a single byte in the range 0x21-0x7E
	// See https://vt100.net/docs/vt220-rm/chapter2.html#S2.3.2
	if  >= len() || [] < 0x21 || [] > 0x7E {
		return , UnknownEvent([:])
	}

	// GL character(s)
	 := []
	++

	var  KeyPressEvent
	switch  {
	case 'a', 'b', 'c', 'd':
		 = KeyPressEvent{Code: KeyUp + rune(-'a'), Mod: ModCtrl}
	case 'A', 'B', 'C', 'D':
		 = KeyPressEvent{Code: KeyUp + rune(-'A')}
	case 'E':
		 = KeyPressEvent{Code: KeyBegin}
	case 'F':
		 = KeyPressEvent{Code: KeyEnd}
	case 'H':
		 = KeyPressEvent{Code: KeyHome}
	case 'P', 'Q', 'R', 'S':
		 = KeyPressEvent{Code: KeyF1 + rune(-'P')}
	case 'M':
		 = KeyPressEvent{Code: KeyKpEnter}
	case 'X':
		 = KeyPressEvent{Code: KeyKpEqual}
	case 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y':
		 = KeyPressEvent{Code: KeyKpMultiply + rune(-'j')}
	default:
		return , UnknownSs3Event([:])
	}

	// Handle weird SS3 <modifier> Func
	if  > 0 {
		.Mod |= KeyMod( - 1)
	}

	return , 
}

func ( *EventDecoder) ( []byte) (int, Event) {
	 := func() KeyPressEvent {
		return KeyPressEvent{Code: rune([1]), Mod: ModAlt}
	}
	if len() == 2 && [0] == ansi.ESC {
		// short cut if this is an alt+] key
		return 2, ()
	}

	var  int
	if [] == ansi.OSC || [] == ansi.ESC {
		++
	}
	if  < len() && [-1] == ansi.ESC && [] == ']' {
		++
	}

	// Parse OSC command
	// An OSC sequence is terminated by a BEL, ESC, or ST character
	var ,  int
	 := -1
	for ;  < len() && [] >= '0' && [] <= '9'; ++ {
		if  == -1 {
			 = 0
		} else {
			 *= 10
		}
		 += int([]) - '0'
	}

	if  < len() && [] == ';' {
		// mark the start of the sequence data
		++
		 = 
	}

	for ;  < len(); ++ {
		// advance to the end of the sequence
		if slices.Contains([]byte{ansi.BEL, ansi.ESC, ansi.ST, ansi.CAN, ansi.SUB}, []) {
			break
		}
	}

	if  >= len() {
		return , UnknownEvent([:])
	}

	 =  // end of the sequence data
	++

	// Check 7-bit ST (string terminator) character
	switch [-1] {
	case ansi.CAN, ansi.SUB:
		return , ignoredEvent([:])
	case ansi.ESC:
		if  >= len() || [] != '\\' {
			if  == -1 || ( == 0 &&  == 2) {
				return 2, ()
			}

			// If we don't have a valid ST terminator, then this is a
			// cancelled sequence and should be ignored.
			return , ignoredEvent([:])
		}

		++
	}

	if  <=  {
		return , UnknownEvent([:])
	}

	 := string([:])
	switch  {
	case 10:
		return , ForegroundColorEvent{ansi.XParseColor()}
	case 11:
		return , BackgroundColorEvent{ansi.XParseColor()}
	case 12:
		return , CursorColorEvent{ansi.XParseColor()}
	case 52:
		 := strings.Split(, ";")
		if len() != 2 || len([0]) < 1 {
			return , ClipboardEvent{}
		}

		 := [1]
		,  := base64.StdEncoding.DecodeString()
		if  != nil {
			return , ClipboardEvent{Content: [1]}
		}

		 := ClipboardSelection([0][0]) //nolint:unconvert
		return , ClipboardEvent{Selection: , Content: string()}
	}

	return , UnknownOscEvent([:])
}

// parseStTerminated parses a control sequence that gets terminated by a ST character.
func ( *EventDecoder) (,  byte,  func([]byte) Event) func([]byte) (int, Event) {
	 := func( []byte) (int, Event) {
		switch  {
		case ansi.SOS:
			return 2, KeyPressEvent{Code: unicode.ToLower(rune([1])), Mod: ModShift | ModAlt}
		case ansi.PM, ansi.APC:
			return 2, KeyPressEvent{Code: rune([1]), Mod: ModAlt}
		}
		return 0, nil
	}
	return func( []byte) (int, Event) {
		if len() == 2 && [0] == ansi.ESC {
			return ()
		}

		var  int
		if [] ==  || [] == ansi.ESC {
			++
		}
		if  < len() && [-1] == ansi.ESC && [] ==  {
			++
		}

		// Scan control sequence
		// Most common control sequence is terminated by a ST character
		// ST is a 7-bit string terminator character is (ESC \)
		 := 
		for ;  < len(); ++ {
			if slices.Contains([]byte{ansi.ESC, ansi.ST, ansi.CAN, ansi.SUB}, []) {
				break
			}
		}

		if  >= len() {
			return , UnknownEvent([:])
		}

		 :=  // end of the sequence data
		++

		// Check 7-bit ST (string terminator) character
		switch [-1] {
		case ansi.CAN, ansi.SUB:
			return , ignoredEvent([:])
		case ansi.ESC:
			if  >= len() || [] != '\\' {
				if  ==  {
					return ()
				}

				// If we don't have a valid ST terminator, then this is a
				// cancelled sequence and should be ignored.
				return , ignoredEvent([:])
			}

			++
		}

		// Call the function to parse the sequence and return the result
		if  != nil {
			if  := ([:]);  != nil {
				return , 
			}
		}

		switch  {
		case ansi.PM:
			return , UnknownPmEvent([:])
		case ansi.SOS:
			return , UnknownSosEvent([:])
		case ansi.APC:
			return , UnknownApcEvent([:])
		default:
			return , UnknownEvent([:])
		}
	}
}

func ( *EventDecoder) ( []byte) (int, Event) {
	if len() == 2 && [0] == ansi.ESC {
		// short cut if this is an alt+P key
		return 2, KeyPressEvent{Code: unicode.ToLower(rune([1])), Mod: ModShift | ModAlt}
	}

	var  [16]ansi.Param
	var  int
	var  ansi.Cmd

	// DCS sequences are introduced by DCS (0x90) or ESC P (0x1b 0x50)
	var  int
	if [] == ansi.DCS || [] == ansi.ESC {
		++
	}
	if  < len() && [-1] == ansi.ESC && [] == 'P' {
		++
	}

	// initial DCS byte
	if  < len() && [] >= '<' && [] <= '?' {
		 |= ansi.Cmd([]) << parser.PrefixShift
	}

	// Scan parameter bytes in the range 0x30-0x3F
	var  int
	for  = 0;  < len() &&  < len() && [] >= 0x30 && [] <= 0x3F; ,  = +1, +1 {
		if [] >= '0' && [] <= '9' {
			if [] == parser.MissingParam {
				[] = 0
			}
			[] *= 10
			[] += ansi.Param([]) - '0'
		}
		if [] == ':' {
			[] |= parser.HasMoreFlag
		}
		if [] == ';' || [] == ':' {
			++
			if  < len() {
				// Don't overflow the params slice
				[] = parser.MissingParam
			}
		}
	}

	if  > 0 &&  < len() {
		// has parameters
		++
	}

	// Scan intermediate bytes in the range 0x20-0x2F
	var  byte
	for  := 0;  < len() && [] >= 0x20 && [] <= 0x2F; ,  = +1, +1 {
		 = []
	}

	// set intermediate byte
	 |= ansi.Cmd() << parser.IntermedShift

	// Scan final byte in the range 0x40-0x7E
	if  >= len() || [] < 0x40 || [] > 0x7E {
		return , UnknownEvent([:])
	}

	// Add the final byte
	 |= ansi.Cmd([])
	++

	 :=  // start of the sequence data
	for ;  < len(); ++ {
		if [] == ansi.ST || [] == ansi.ESC {
			break
		}
	}

	if  >= len() {
		return , UnknownEvent([:])
	}

	 :=  // end of the sequence data
	++

	// Check 7-bit ST (string terminator) character
	if  < len() && [-1] == ansi.ESC && [] == '\\' {
		++
	}

	 := ansi.Params([:])
	switch  {
	case 'r' | '+'<<parser.IntermedShift:
		// XTGETTCAP responses
		, ,  := .Param(0, 0)
		switch  {
		case 1: // 1 means valid response, 0 means invalid response
			 := parseTermcap([:])
			// XXX: some terminals like KiTTY report invalid responses with
			// their queries i.e. sending a query for "Tc" using "\x1bP+q5463\x1b\\"
			// returns "\x1bP0+r5463\x1b\\".
			// The specs says that invalid responses should be in the form of
			// DCS 0 + r ST "\x1bP0+r\x1b\\"
			// We ignore invalid responses and only send valid ones to the program.
			//
			// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands
			return , 
		}
	case '|' | '>'<<parser.PrefixShift:
		// XTVersion response
		return , TerminalVersionEvent{string([:])}
	case '|' | '!'<<parser.IntermedShift:
		// Teritary Device Attributes
		return , parseTertiaryDevAttrs([:])
	}

	return , UnknownDcsEvent([:])
}

func ( *EventDecoder) ( []byte) (int, Event) {
	if len() == 2 && [0] == ansi.ESC {
		// short cut if this is an alt+_ key
		return 2, KeyPressEvent{Code: rune([1]), Mod: ModAlt}
	}

	// APC sequences are introduced by APC (0x9f) or ESC _ (0x1b 0x5f)
	return .parseStTerminated(ansi.APC, '_', func( []byte) Event {
		if len() == 0 {
			return nil
		}

		switch [0] {
		case 'G': // Kitty Graphics Protocol
			var  KittyGraphicsEvent
			 := bytes.Split([1:], []byte{';'})
			.Options.UnmarshalText([0]) //nolint:errcheck,gosec
			if len() > 1 {
				.Payload = [1]
			}
			return 
		}

		return nil
	})()
}

func ( *EventDecoder) ( []byte) (int, Event) {
	if len() == 0 {
		return 0, nil
	}

	 := [0]
	if  <= ansi.US ||  == ansi.DEL {
		// Control codes get handled by parseControl
		return 1, .parseControl()
	} else if  > ansi.US &&  < ansi.DEL {
		// ASCII printable characters
		 := rune()
		 := KeyPressEvent{Code: , Text: string()}
		if unicode.IsUpper() {
			// Convert upper case letters to lower case + shift modifier
			.Code = unicode.ToLower()
			.ShiftedCode = 
			.Mod |= ModShift
		}

		return 1, 
	}

	,  := utf8.DecodeRune()
	if  == utf8.RuneError {
		return 1, UnknownEvent([0])
	}

	, , ,  := uniseg.FirstGraphemeCluster(, -1)
	 := string()
	for  := range  {
		if  > 0 {
			// Use [KeyExtended] for multi-rune graphemes
			 = KeyExtended
			break
		}
	}

	return len(), KeyPressEvent{Code: , Text: }
}

func ( *EventDecoder) ( byte) Event {
	switch  {
	case ansi.NUL:
		if .Legacy&flagCtrlAt != 0 {
			return KeyPressEvent{Code: '@', Mod: ModCtrl}
		}
		return KeyPressEvent{Code: KeySpace, Mod: ModCtrl}
	case ansi.BS:
		return KeyPressEvent{Code: 'h', Mod: ModCtrl}
	case ansi.HT:
		if .Legacy&flagCtrlI != 0 {
			return KeyPressEvent{Code: 'i', Mod: ModCtrl}
		}
		return KeyPressEvent{Code: KeyTab}
	case ansi.CR:
		if .Legacy&flagCtrlM != 0 {
			return KeyPressEvent{Code: 'm', Mod: ModCtrl}
		}
		return KeyPressEvent{Code: KeyEnter}
	case ansi.ESC:
		if .Legacy&flagCtrlOpenBracket != 0 {
			return KeyPressEvent{Code: '[', Mod: ModCtrl}
		}
		return KeyPressEvent{Code: KeyEscape}
	case ansi.DEL:
		if .Legacy&flagBackspace != 0 {
			return KeyPressEvent{Code: KeyDelete}
		}
		return KeyPressEvent{Code: KeyBackspace}
	case ansi.SP:
		return KeyPressEvent{Code: KeySpace, Text: " "}
	default:
		if  >= ansi.SOH &&  <= ansi.SUB {
			// Use lower case letters for control codes
			 := rune( + 0x60)
			return KeyPressEvent{Code: , Mod: ModCtrl}
		} else if  >= ansi.FS &&  <= ansi.US {
			 := rune( + 0x40)
			return KeyPressEvent{Code: , Mod: ModCtrl}
		}
		return UnknownEvent()
	}
}

func ( ansi.Params) Event {
	// XTerm modify other keys starts with ESC [ 27 ; <modifier> ; <code> ~
	, ,  := .Param(1, 1)
	, ,  := .Param(2, 1)
	 := KeyMod( - 1)
	 := rune()

	switch  {
	case ansi.BS:
		return KeyPressEvent{Mod: , Code: KeyBackspace}
	case ansi.HT:
		return KeyPressEvent{Mod: , Code: KeyTab}
	case ansi.CR:
		return KeyPressEvent{Mod: , Code: KeyEnter}
	case ansi.ESC:
		return KeyPressEvent{Mod: , Code: KeyEscape}
	case ansi.DEL:
		return KeyPressEvent{Mod: , Code: KeyBackspace}
	}

	// CSI 27 ; <modifier> ; <code> ~ keys defined in XTerm modifyOtherKeys
	 := KeyPressEvent{Code: , Mod: }
	if .Mod <= ModShift {
		.Text = string()
	}

	return 
}

// Kitty Clipboard Control Sequences.
var kittyKeyMap = map[int]Key{
	ansi.BS:  {Code: KeyBackspace},
	ansi.HT:  {Code: KeyTab},
	ansi.CR:  {Code: KeyEnter},
	ansi.ESC: {Code: KeyEscape},
	ansi.DEL: {Code: KeyBackspace},

	57344: {Code: KeyEscape},
	57345: {Code: KeyEnter},
	57346: {Code: KeyTab},
	57347: {Code: KeyBackspace},
	57348: {Code: KeyInsert},
	57349: {Code: KeyDelete},
	57350: {Code: KeyLeft},
	57351: {Code: KeyRight},
	57352: {Code: KeyUp},
	57353: {Code: KeyDown},
	57354: {Code: KeyPgUp},
	57355: {Code: KeyPgDown},
	57356: {Code: KeyHome},
	57357: {Code: KeyEnd},
	57358: {Code: KeyCapsLock},
	57359: {Code: KeyScrollLock},
	57360: {Code: KeyNumLock},
	57361: {Code: KeyPrintScreen},
	57362: {Code: KeyPause},
	57363: {Code: KeyMenu},
	57364: {Code: KeyF1},
	57365: {Code: KeyF2},
	57366: {Code: KeyF3},
	57367: {Code: KeyF4},
	57368: {Code: KeyF5},
	57369: {Code: KeyF6},
	57370: {Code: KeyF7},
	57371: {Code: KeyF8},
	57372: {Code: KeyF9},
	57373: {Code: KeyF10},
	57374: {Code: KeyF11},
	57375: {Code: KeyF12},
	57376: {Code: KeyF13},
	57377: {Code: KeyF14},
	57378: {Code: KeyF15},
	57379: {Code: KeyF16},
	57380: {Code: KeyF17},
	57381: {Code: KeyF18},
	57382: {Code: KeyF19},
	57383: {Code: KeyF20},
	57384: {Code: KeyF21},
	57385: {Code: KeyF22},
	57386: {Code: KeyF23},
	57387: {Code: KeyF24},
	57388: {Code: KeyF25},
	57389: {Code: KeyF26},
	57390: {Code: KeyF27},
	57391: {Code: KeyF28},
	57392: {Code: KeyF29},
	57393: {Code: KeyF30},
	57394: {Code: KeyF31},
	57395: {Code: KeyF32},
	57396: {Code: KeyF33},
	57397: {Code: KeyF34},
	57398: {Code: KeyF35},
	57399: {Code: KeyKp0},
	57400: {Code: KeyKp1},
	57401: {Code: KeyKp2},
	57402: {Code: KeyKp3},
	57403: {Code: KeyKp4},
	57404: {Code: KeyKp5},
	57405: {Code: KeyKp6},
	57406: {Code: KeyKp7},
	57407: {Code: KeyKp8},
	57408: {Code: KeyKp9},
	57409: {Code: KeyKpDecimal},
	57410: {Code: KeyKpDivide},
	57411: {Code: KeyKpMultiply},
	57412: {Code: KeyKpMinus},
	57413: {Code: KeyKpPlus},
	57414: {Code: KeyKpEnter},
	57415: {Code: KeyKpEqual},
	57416: {Code: KeyKpSep},
	57417: {Code: KeyKpLeft},
	57418: {Code: KeyKpRight},
	57419: {Code: KeyKpUp},
	57420: {Code: KeyKpDown},
	57421: {Code: KeyKpPgUp},
	57422: {Code: KeyKpPgDown},
	57423: {Code: KeyKpHome},
	57424: {Code: KeyKpEnd},
	57425: {Code: KeyKpInsert},
	57426: {Code: KeyKpDelete},
	57427: {Code: KeyKpBegin},
	57428: {Code: KeyMediaPlay},
	57429: {Code: KeyMediaPause},
	57430: {Code: KeyMediaPlayPause},
	57431: {Code: KeyMediaReverse},
	57432: {Code: KeyMediaStop},
	57433: {Code: KeyMediaFastForward},
	57434: {Code: KeyMediaRewind},
	57435: {Code: KeyMediaNext},
	57436: {Code: KeyMediaPrev},
	57437: {Code: KeyMediaRecord},
	57438: {Code: KeyLowerVol},
	57439: {Code: KeyRaiseVol},
	57440: {Code: KeyMute},
	57441: {Code: KeyLeftShift},
	57442: {Code: KeyLeftCtrl},
	57443: {Code: KeyLeftAlt},
	57444: {Code: KeyLeftSuper},
	57445: {Code: KeyLeftHyper},
	57446: {Code: KeyLeftMeta},
	57447: {Code: KeyRightShift},
	57448: {Code: KeyRightCtrl},
	57449: {Code: KeyRightAlt},
	57450: {Code: KeyRightSuper},
	57451: {Code: KeyRightHyper},
	57452: {Code: KeyRightMeta},
	57453: {Code: KeyIsoLevel3Shift},
	57454: {Code: KeyIsoLevel5Shift},
}

func () {
	// These are some faulty C0 mappings some terminals such as WezTerm have
	// and doesn't follow the specs.
	kittyKeyMap[ansi.NUL] = Key{Code: KeySpace, Mod: ModCtrl}
	for  := ansi.SOH;  <= ansi.SUB; ++ {
		if ,  := kittyKeyMap[]; ! {
			kittyKeyMap[] = Key{Code: rune( + 0x60), Mod: ModCtrl}
		}
	}
	for  := ansi.FS;  <= ansi.US; ++ {
		if ,  := kittyKeyMap[]; ! {
			kittyKeyMap[] = Key{Code: rune( + 0x40), Mod: ModCtrl}
		}
	}
}

const (
	kittyShift = 1 << iota
	kittyAlt
	kittyCtrl
	kittySuper
	kittyHyper
	kittyMeta
	kittyCapsLock
	kittyNumLock
)

func ( int) KeyMod {
	var  KeyMod
	if &kittyShift != 0 {
		 |= ModShift
	}
	if &kittyAlt != 0 {
		 |= ModAlt
	}
	if &kittyCtrl != 0 {
		 |= ModCtrl
	}
	if &kittySuper != 0 {
		 |= ModSuper
	}
	if &kittyHyper != 0 {
		 |= ModHyper
	}
	if &kittyMeta != 0 {
		 |= ModMeta
	}
	if &kittyCapsLock != 0 {
		 |= ModCapsLock
	}
	if &kittyNumLock != 0 {
		 |= ModNumLock
	}
	return 
}

// parseKittyKeyboard parses a Kitty Keyboard Protocol sequence.
//
// In `CSI u`, this is parsed as:
//
//	CSI codepoint ; modifiers u
//	codepoint: ASCII Dec value
//
// The Kitty Keyboard Protocol extends this with optional components that can be
// enabled progressively. The full sequence is parsed as:
//
//	CSI unicode-key-code:alternate-key-codes ; modifiers:event-type ; text-as-codepoints u
//
// See https://sw.kovidgoyal.net/kitty/keyboard-protocol/
func ( ansi.Params) ( Event) {
	var  bool
	var  Key

	// The index of parameters separated by semicolons ';'. Sub parameters are
	// separated by colons ':'.
	var  int
	var  int // The sub parameter index
	for ,  := range  {
		// Kitty Keyboard Protocol has 3 optional components.
		switch  {
		case 0:
			switch  {
			case 0:
				var  bool
				 := .Param(1) // CSI u has a default value of 1
				,  = kittyKeyMap[]
				if ! {
					 := rune()
					if !utf8.ValidRune() {
						 = utf8.RuneError
					}

					.Code = 
				}

			case 2:
				// shifted key + base key
				if  := rune(.Param(1)); unicode.IsPrint() {
					// XXX: When alternate key reporting is enabled, the protocol
					// can return 3 things, the unicode codepoint of the key,
					// the shifted codepoint of the key, and the standard
					// PC-101 key layout codepoint.
					// This is useful to create an unambiguous mapping of keys
					// when using a different language layout.
					.BaseCode = 
				}
				fallthrough

			case 1:
				// shifted key
				if  := rune(.Param(1)); unicode.IsPrint() {
					// XXX: We swap keys here because we want the shifted key
					// to be the Rune that is returned by the event.
					// For example, shift+a should produce "A" not "a".
					// In such a case, we set AltRune to the original key "a"
					// and Rune to "A".
					.ShiftedCode = 
				}
			}
		case 1:
			switch  {
			case 0:
				 := .Param(1)
				if  > 1 {
					.Mod = fromKittyMod( - 1)
					if .Mod > ModShift {
						// XXX: We need to clear the text if we have a modifier key
						// other than a [ModShift] key.
						.Text = ""
					}
				}

			case 1:
				switch .Param(1) {
				case 2:
					.IsRepeat = true
				case 3:
					 = true
				}
			case 2:
			}
		case 2:
			if  := .Param(0);  != 0 {
				.Text += string(rune())
			}
		}

		++
		if !.HasMore() {
			++
			 = 0
		}
	}

	 := .Mod

	// Remove these lock modifiers from now on since they don't affect the text.
	 &^= ModNumLock
	// keyMod &^= ModScrollLock // Kitty doesn't support scroll lock

	 :=  <= ModShift ||  == ModCapsLock ||  == (ModShift|ModCapsLock)
	 := .Code >= KeyKpEqual && .Code <= KeyKpSep
	if len(.Text) == 0 &&  &&  {
		switch {
		case .Code >= KeyKp0 && .Code <= KeyKp9:
			.Text = string('0' + .Code - KeyKp0)
		case .Code == KeyKpEqual:
			.Text = "="
		case .Code == KeyKpMultiply:
			.Text = "*"
		case .Code == KeyKpPlus:
			.Text = "+"
		case .Code == KeyKpMinus:
			.Text = "-"
		case .Code == KeyKpDecimal:
			.Text = "."
		case .Code == KeyKpDivide:
			.Text = "/"
		case .Code == KeyKpSep:
			.Text = ","
		}
	}

	//nolint:nestif
	if len(.Text) == 0 && unicode.IsPrint(.Code) &&  {
		if  == 0 {
			.Text = string(.Code)
		} else {
			 := unicode.ToLower
			if .Contains(ModShift) || .Contains(ModCapsLock) {
				 = unicode.ToUpper
			}
			if .ShiftedCode != 0 {
				.Text = string(.ShiftedCode)
			} else {
				.Text = string((.Code))
			}
		}
	}

	if  {
		return KeyReleaseEvent()
	}

	return KeyPressEvent()
}

// parseKittyKeyboardExt parses a Kitty Keyboard Protocol sequence extensions
// for non CSI u sequences. This includes things like CSI A, SS3 A and others,
// and CSI ~.
func ( ansi.Params,  KeyPressEvent) Event {
	// Handle Kitty keyboard protocol
	if len() > 2 && // We have at least 3 parameters
		[1].HasMore() { // The second parameter is a subparameter (separated by a ":")
		switch [2].Param(1) { // The third parameter is the event type (defaults to 1)
		case 2:
			.IsRepeat = true
		case 3:
			return KeyReleaseEvent()
		}
	}
	return 
}

func ( ansi.Params) Event {
	// Primary Device Attributes
	 := make(PrimaryDeviceAttributesEvent, len())
	for ,  := range  {
		if !.HasMore() {
			[] = .Param(0)
		}
	}
	return 
}

func ( ansi.Params) Event {
	// Secondary Device Attributes
	 := make(SecondaryDeviceAttributesEvent, len())
	for ,  := range  {
		if !.HasMore() {
			[] = .Param(0)
		}
	}
	return 
}

func ( []byte) Event {
	// Tertiary Device Attributes
	// The response is a 4-digit hexadecimal number.
	,  := hex.DecodeString(string())
	if  != nil {
		return UnknownDcsEvent(fmt.Sprintf("\x1bP!|%s\x1b\\", ))
	}
	return TertiaryDeviceAttributesEvent()
}

// Parse SGR-encoded mouse events; SGR extended mouse events. SGR mouse events
// look like:
//
//	ESC [ < Cb ; Cx ; Cy (M or m)
//
// where:
//
//	Cb is the encoded button code
//	Cx is the x-coordinate of the mouse
//	Cy is the y-coordinate of the mouse
//	M is for button press, m is for button release
//
// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates
func ( ansi.Cmd,  ansi.Params) Event {
	, ,  := .Param(1, 1)
	if ! {
		 = 1
	}
	, ,  := .Param(2, 1)
	if ! {
		 = 1
	}
	 := .Final() == 'm'
	, ,  := .Param(0, 0)
	, , ,  := parseMouseButton()

	// (1,1) is the upper left. We subtract 1 to normalize it to (0,0).
	--
	--

	 := Mouse{X: , Y: , Button: , Mod: }

	// Wheel buttons don't have release events
	// Motion can be reported as a release event in some terminals (Windows Terminal)
	if isWheel(.Button) {
		return MouseWheelEvent()
	} else if ! &&  {
		return MouseReleaseEvent()
	} else if  {
		return MouseMotionEvent()
	}
	return MouseClickEvent()
}

const x10MouseByteOffset = 32

// Parse X10-encoded mouse events; the simplest kind. The last release of X10
// was December 1986, by the way. The original X10 mouse protocol limits the Cx
// and Cy coordinates to 223 (=255-032).
//
// X10 mouse events look like:
//
//	ESC [M Cb Cx Cy
//
// See: http://www.xfree86.org/current/ctlseqs.html#Mouse%20Tracking
func ( []byte) Event {
	 := [3:6]
	 := int([0])
	if  >= x10MouseByteOffset {
		// XXX: b < 32 should be impossible, but we're being defensive.
		 -= x10MouseByteOffset
	}

	, , ,  := parseMouseButton()

	// (1,1) is the upper left. We subtract 1 to normalize it to (0,0).
	 := int([1]) - x10MouseByteOffset - 1
	 := int([2]) - x10MouseByteOffset - 1

	 := Mouse{X: , Y: , Button: , Mod: }
	if isWheel(.Button) {
		return MouseWheelEvent()
	} else if  {
		return MouseMotionEvent()
	} else if  {
		return MouseReleaseEvent()
	}
	return MouseClickEvent()
}

// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates
func ( int) ( KeyMod,  MouseButton,  bool,  bool) {
	// mouse bit shifts
	const (
		  = 0b0000_0100
		    = 0b0000_1000
		   = 0b0001_0000
		 = 0b0010_0000
		  = 0b0100_0000
		    = 0b1000_0000 // additional buttons 8-11

		 = 0b0000_0011
	)

	// Modifiers
	if & != 0 {
		 |= ModAlt
	}
	if & != 0 {
		 |= ModCtrl
	}
	if & != 0 {
		 |= ModShift
	}

	if & != 0 {
		 = MouseBackward + MouseButton(&)
	} else if & != 0 {
		 = MouseWheelUp + MouseButton(&)
	} else {
		 = MouseLeft + MouseButton(&)
		// X10 reports a button release as 0b0000_0011 (3)
		if & ==  {
			 = MouseNone
			 = true
		}
	}

	// Motion bit doesn't get reported for wheel events.
	if & != 0 && !isWheel() {
		 = true
	}

	return //nolint:nakedret
}

// isWheel returns true if the mouse event is a wheel event.
func ( MouseButton) bool {
	return  >= MouseWheelUp &&  <= MouseWheelRight
}

type shiftable interface {
	~uint | ~uint16 | ~uint32 | ~uint64
}

func [ shiftable]( )  {
	if  > 0xff {
		 >>= 8
	}
	return 
}

func ( color.Color) string {
	if  == nil {
		return ""
	}
	, , ,  := .RGBA()
	return fmt.Sprintf("#%02x%02x%02x", shift(), shift(), shift())
}

func (, ,  float64) (,  float64) {
	if  >  {
		 = 
		 = 
	} else {
		 = 
		 = 
	}
	if  >  {
		 = 
	} else if  <  {
		 = 
	}
	return , 
}

func ( float64) float64 {
	return math.Round(*1000) / 1000
}

// rgbToHSL converts an RGB triple to an HSL triple.
func (, ,  uint8) (, ,  float64) {
	// convert uint32 pre-multiplied value to uint8
	// The r,g,b values are divided by 255 to change the range from 0..255 to 0..1:
	 := float64() / 255
	 := float64() / 255
	 := float64() / 255
	,  := getMaxMin(, , )
	 :=  - 
	// Lightness calculation:
	 = ( + ) / 2
	// Hue and Saturation Calculation:
	if  == 0 {
		 = 0
		 = 0
	} else {
		switch  {
		case :
			 = 60 * (math.Mod((-)/, 6))
		case :
			 = 60 * ((( - ) / ) + 2)
		case :
			 = 60 * ((( - ) / ) + 4)
		}
		if  < 0 {
			 += 360
		}

		 =  / (1 - math.Abs((2*)-1))
	}

	return , round(), round()
}

// isDarkColor returns whether the given color is dark.
func ( color.Color) bool {
	if  == nil {
		return true
	}

	, , ,  := .RGBA()
	, ,  := rgbToHSL(uint8(>>8), uint8(>>8), uint8(>>8)) //nolint:gosec
	return  < 0.5
}

func ( []byte) CapabilityEvent {
	// XTGETTCAP
	if len() == 0 {
		return CapabilityEvent{""}
	}

	var  strings.Builder
	 := bytes.Split(, []byte{';'})
	for ,  := range  {
		 := bytes.SplitN(, []byte{'='}, 2)
		if len() == 0 {
			return CapabilityEvent{""}
		}

		,  := hex.DecodeString(string([0]))
		if  != nil || len() == 0 {
			continue
		}

		var  []byte
		if len() > 1 {
			,  = hex.DecodeString(string([1]))
			if  != nil {
				continue
			}
		}

		if .Len() > 0 {
			.WriteByte(';')
		}
		.WriteString(string())
		if len() > 0 {
			.WriteByte('=')
			.WriteString(string())
		}
	}

	return CapabilityEvent{.String()}
}

// parseWin32InputKeyEvent converts a Windows Input Record Key Event into a
// KeyPressEvent, KeyReleaseEvent, or MultiEvent including multiple of the
// former type.
// A special case is when the key is either part of VtInputMode which produces
// vkc == 0, or when a key is a UTF-16 surrogate pair.  In both of these cases,
// we need to handle key encoding and properly parse the key event.
func ( *EventDecoder) ( uint16,  uint16,  rune,  bool,  uint32,  uint16) ( Event) {
	defer func() {
		// Respect the repeat count.
		if  > 1 {
			var  MultiEvent
			for  := 0;  < int(); ++ {
				 = append(, )
			}
			 = 
		}
	}()
	defer func() {
		if  != 0 {
			.lastCks = 
		}
	}()

	var  Key
	switch {
	case  == 0:
		// This is either a UTF-16 encoded pair, or an escape sequence waiting
		// to be decoded.
		if  {
			return KeyPressEvent{Code: 0, BaseCode: , Mod: translateControlKeyState()}
		}
		return KeyReleaseEvent{Code: 0, BaseCode: , Mod: translateControlKeyState()}
	case  == xwindows.VK_BACK:
		.BaseCode = KeyBackspace
	case  == xwindows.VK_TAB:
		.BaseCode = KeyTab
	case  == xwindows.VK_RETURN:
		.BaseCode = KeyEnter
	case  == xwindows.VK_SHIFT:
		//nolint:nestif
		if &xwindows.SHIFT_PRESSED != 0 {
			if &xwindows.ENHANCED_KEY != 0 {
				.BaseCode = KeyRightShift
			} else {
				.BaseCode = KeyLeftShift
			}
		} else if .lastCks&xwindows.SHIFT_PRESSED != 0 {
			if .lastCks&xwindows.ENHANCED_KEY != 0 {
				.BaseCode = KeyRightShift
			} else {
				.BaseCode = KeyLeftShift
			}
		}
	case  == xwindows.VK_CONTROL:
		if &xwindows.LEFT_CTRL_PRESSED != 0 {
			.BaseCode = KeyLeftCtrl
		} else if &xwindows.RIGHT_CTRL_PRESSED != 0 {
			.BaseCode = KeyRightCtrl
		} else if .lastCks&xwindows.LEFT_CTRL_PRESSED != 0 {
			.BaseCode = KeyLeftCtrl
		} else if .lastCks&xwindows.RIGHT_CTRL_PRESSED != 0 {
			.BaseCode = KeyRightCtrl
		}
	case  == xwindows.VK_MENU:
		if &xwindows.LEFT_ALT_PRESSED != 0 {
			.BaseCode = KeyLeftAlt
		} else if &xwindows.RIGHT_ALT_PRESSED != 0 {
			.BaseCode = KeyRightAlt
		} else if .lastCks&xwindows.LEFT_ALT_PRESSED != 0 {
			.BaseCode = KeyLeftAlt
		} else if .lastCks&xwindows.RIGHT_ALT_PRESSED != 0 {
			.BaseCode = KeyRightAlt
		}
	case  == xwindows.VK_PAUSE:
		.BaseCode = KeyPause
	case  == xwindows.VK_CAPITAL:
		.BaseCode = KeyCapsLock
	case  == xwindows.VK_ESCAPE:
		.BaseCode = KeyEscape
	case  == xwindows.VK_SPACE:
		.BaseCode = KeySpace
	case  == xwindows.VK_PRIOR:
		.BaseCode = KeyPgUp
	case  == xwindows.VK_NEXT:
		.BaseCode = KeyPgDown
	case  == xwindows.VK_END:
		.BaseCode = KeyEnd
	case  == xwindows.VK_HOME:
		.BaseCode = KeyHome
	case  == xwindows.VK_LEFT:
		.BaseCode = KeyLeft
	case  == xwindows.VK_UP:
		.BaseCode = KeyUp
	case  == xwindows.VK_RIGHT:
		.BaseCode = KeyRight
	case  == xwindows.VK_DOWN:
		.BaseCode = KeyDown
	case  == xwindows.VK_SELECT:
		.BaseCode = KeySelect
	case  == xwindows.VK_SNAPSHOT:
		.BaseCode = KeyPrintScreen
	case  == xwindows.VK_INSERT:
		.BaseCode = KeyInsert
	case  == xwindows.VK_DELETE:
		.BaseCode = KeyDelete
	case  >= '0' &&  <= '9':
		.BaseCode = rune()
	case  >= 'A' &&  <= 'Z':
		// Convert to lowercase.
		.BaseCode = rune() + 32
	case  == xwindows.VK_LWIN:
		.BaseCode = KeyLeftSuper
	case  == xwindows.VK_RWIN:
		.BaseCode = KeyRightSuper
	case  == xwindows.VK_APPS:
		.BaseCode = KeyMenu
	case  >= xwindows.VK_NUMPAD0 &&  <= xwindows.VK_NUMPAD9:
		.BaseCode = rune(-xwindows.VK_NUMPAD0) + KeyKp0
		.Text = string('0' + (rune() - xwindows.VK_NUMPAD0))
	case  == xwindows.VK_MULTIPLY:
		.BaseCode = KeyKpMultiply
		.Text = "*"
	case  == xwindows.VK_ADD:
		.BaseCode = KeyKpPlus
		.Text = "+"
	case  == xwindows.VK_SEPARATOR:
		.BaseCode = KeyKpComma
		.Text = ","
	case  == xwindows.VK_SUBTRACT:
		.BaseCode = KeyKpMinus
		.Text = "-"
	case  == xwindows.VK_DECIMAL:
		.BaseCode = KeyKpDecimal
		.Text = "."
	case  == xwindows.VK_DIVIDE:
		.BaseCode = KeyKpDivide
		.Text = "/"
	case  >= xwindows.VK_F1 &&  <= xwindows.VK_F24:
		.BaseCode = rune(-xwindows.VK_F1) + KeyF1
	case  == xwindows.VK_NUMLOCK:
		.BaseCode = KeyNumLock
	case  == xwindows.VK_SCROLL:
		.BaseCode = KeyScrollLock
	case  == xwindows.VK_LSHIFT:
		.BaseCode = KeyLeftShift
	case  == xwindows.VK_RSHIFT:
		.BaseCode = KeyRightShift
	case  == xwindows.VK_LCONTROL:
		.BaseCode = KeyLeftCtrl
	case  == xwindows.VK_RCONTROL:
		.BaseCode = KeyRightCtrl
	case  == xwindows.VK_LMENU:
		.BaseCode = KeyLeftAlt
	case  == xwindows.VK_RMENU:
		.BaseCode = KeyRightAlt
	case  == xwindows.VK_VOLUME_MUTE:
		.BaseCode = KeyMute
	case  == xwindows.VK_VOLUME_DOWN:
		.BaseCode = KeyLowerVol
	case  == xwindows.VK_VOLUME_UP:
		.BaseCode = KeyRaiseVol
	case  == xwindows.VK_MEDIA_NEXT_TRACK:
		.BaseCode = KeyMediaNext
	case  == xwindows.VK_MEDIA_PREV_TRACK:
		.BaseCode = KeyMediaPrev
	case  == xwindows.VK_MEDIA_STOP:
		.BaseCode = KeyMediaStop
	case  == xwindows.VK_MEDIA_PLAY_PAUSE:
		.BaseCode = KeyMediaPlayPause
	case  == xwindows.VK_OEM_1:
		.BaseCode = ';'
	case  == xwindows.VK_OEM_PLUS:
		.BaseCode = '+'
	case  == xwindows.VK_OEM_COMMA:
		.BaseCode = ','
	case  == xwindows.VK_OEM_MINUS:
		.BaseCode = '-'
	case  == xwindows.VK_OEM_PERIOD:
		.BaseCode = '.'
	case  == xwindows.VK_OEM_2:
		.BaseCode = '/'
	case  == xwindows.VK_OEM_3:
		.BaseCode = '`'
	case  == xwindows.VK_OEM_4:
		.BaseCode = '['
	case  == xwindows.VK_OEM_5:
		.BaseCode = '\\'
	case  == xwindows.VK_OEM_6:
		.BaseCode = ']'
	case  == xwindows.VK_OEM_7:
		.BaseCode = '\''
	}

	// AltGr is left ctrl + right alt. On non-US keyboards, this is used to type
	// special characters and produce printable events.
	// XXX: Should this be a KeyMod?
	const  = xwindows.LEFT_CTRL_PRESSED | xwindows.RIGHT_ALT_PRESSED
	 := & == 

	// Remove these lock keys from the control key state from now on.
	 &^= xwindows.NUMLOCK_ON
	 &^= xwindows.SCROLLLOCK_ON
	.Code = .BaseCode
	if !unicode.IsControl() {
		.Code = 
		if unicode.IsPrint(.Code) && ( == 0 || // no modifiers pressed
			 == xwindows.SHIFT_PRESSED || // shift pressed
			 == xwindows.CAPSLOCK_ON || // caps lock on
			 == (xwindows.SHIFT_PRESSED|xwindows.CAPSLOCK_ON) || // Shift + caps lock pressed
			) { // AltGr pressed
			// If the control key state is 0, shift is pressed, or caps lock
			// then the key event is a printable event i.e. [text] is not empty.
			.Text = string(.Code)
		}
	}

	.Mod = translateControlKeyState()
	 = ensureKeyCase(, )
	if  {
		return KeyPressEvent()
	}

	return KeyReleaseEvent()
}

// ensureKeyCase ensures that the key's text is in the correct case based on the
// control key state.
func ( Key,  uint32) Key {
	if len(.Text) == 0 {
		return 
	}

	 := &xwindows.SHIFT_PRESSED != 0
	 := &xwindows.CAPSLOCK_ON != 0
	if  ||  {
		if unicode.IsLower(.Code) {
			.ShiftedCode = unicode.ToUpper(.Code)
			.Text = string(.ShiftedCode)
		}
	} else {
		if unicode.IsUpper(.Code) {
			.ShiftedCode = unicode.ToLower(.Code)
			.Text = string(.ShiftedCode)
		}
	}

	return 
}

// translateControlKeyState translates the control key state from the Windows
// Console API into a Mod bitmask.
func ( uint32) ( KeyMod) {
	if &xwindows.LEFT_CTRL_PRESSED != 0 || &xwindows.RIGHT_CTRL_PRESSED != 0 {
		 |= ModCtrl
	}
	if &xwindows.LEFT_ALT_PRESSED != 0 || &xwindows.RIGHT_ALT_PRESSED != 0 {
		 |= ModAlt
	}
	if &xwindows.SHIFT_PRESSED != 0 {
		 |= ModShift
	}
	if &xwindows.CAPSLOCK_ON != 0 {
		 |= ModCapsLock
	}
	if &xwindows.NUMLOCK_ON != 0 {
		 |= ModNumLock
	}
	if &xwindows.SCROLLLOCK_ON != 0 {
		 |= ModScrollLock
	}
	return
}