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

View File
Whitespace-only changes.
+384
View File
@@ -0,0 +1,384 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os
import stat
from collections.abc import Generator
from contextlib import suppress
DEFAULT_DIRCOLORS = r"""# {{{
# Configuration file for dircolors, a utility to help you set the
# LS_COLORS environment variable used by GNU ls with the --color option.
# Copyright (C) 1996-2019 Free Software Foundation, Inc.
# Copying and distribution of this file, with or without modification,
# are permitted provided the copyright notice and this notice are preserved.
# The keywords COLOR, OPTIONS, and EIGHTBIT (honored by the
# slackware version of dircolors) are recognized but ignored.
# Below are TERM entries, which can be a glob patterns, to match
# against the TERM environment variable to determine if it is colorizable.
TERM Eterm
TERM ansi
TERM *color*
TERM con[0-9]*x[0-9]*
TERM cons25
TERM console
TERM cygwin
TERM dtterm
TERM gnome
TERM hurd
TERM jfbterm
TERM konsole
TERM kterm
TERM linux
TERM linux-c
TERM mlterm
TERM putty
TERM rxvt*
TERM screen*
TERM st
TERM terminator
TERM tmux*
TERM vt100
TERM xterm*
# Below are the color init strings for the basic file types.
# One can use codes for 256 or more colors supported by modern terminals.
# The default color codes use the capabilities of an 8 color terminal
# with some additional attributes as per the following codes:
# Attribute codes:
# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes:
# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
#NORMAL 00 # no color code at all
#FILE 00 # regular file: use no color at all
RESET 0 # reset to "normal" color
DIR 01;34 # directory
LINK 01;36 # symbolic link. (If you set this to 'target' instead of a
# numerical value, the color is as for the file pointed to.)
MULTIHARDLINK 00 # regular file with more than one link
FIFO 40;33 # pipe
SOCK 01;35 # socket
DOOR 01;35 # door
BLK 40;33;01 # block device driver
CHR 40;33;01 # character device driver
ORPHAN 40;31;01 # symlink to nonexistent file, or non-stat'able file ...
MISSING 00 # ... and the files they point to
SETUID 37;41 # file that is setuid (u+s)
SETGID 30;43 # file that is setgid (g+s)
CAPABILITY 30;41 # file with capability
STICKY_OTHER_WRITABLE 30;42 # dir that is sticky and other-writable (+t,o+w)
OTHER_WRITABLE 34;42 # dir that is other-writable (o+w) and not sticky
STICKY 37;44 # dir with the sticky bit set (+t) and not other-writable
# This is for files with execute permission:
EXEC 01;32
# List any file extensions like '.gz' or '.tar' that you would like ls
# to colorize below. Put the extension, a space, and the color init string.
# (and any comments you want to add after a '#')
# If you use DOS-style suffixes, you may want to uncomment the following:
#.cmd 01;32 # executables (bright green)
#.exe 01;32
#.com 01;32
#.btm 01;32
#.bat 01;32
# Or if you want to colorize scripts even if they do not have the
# executable bit actually set.
#.sh 01;32
#.csh 01;32
# archives or compressed (bright red)
.tar 01;31
.tgz 01;31
.arc 01;31
.arj 01;31
.taz 01;31
.lha 01;31
.lz4 01;31
.lzh 01;31
.lzma 01;31
.tlz 01;31
.txz 01;31
.tzo 01;31
.t7z 01;31
.zip 01;31
.z 01;31
.dz 01;31
.gz 01;31
.lrz 01;31
.lz 01;31
.lzo 01;31
.xz 01;31
.zst 01;31
.tzst 01;31
.bz2 01;31
.bz 01;31
.tbz 01;31
.tbz2 01;31
.tz 01;31
.deb 01;31
.rpm 01;31
.jar 01;31
.war 01;31
.ear 01;31
.sar 01;31
.rar 01;31
.alz 01;31
.ace 01;31
.zoo 01;31
.cpio 01;31
.7z 01;31
.rz 01;31
.cab 01;31
.wim 01;31
.swm 01;31
.dwm 01;31
.esd 01;31
# image formats
.jpg 01;35
.jpeg 01;35
.mjpg 01;35
.mjpeg 01;35
.gif 01;35
.bmp 01;35
.pbm 01;35
.pgm 01;35
.ppm 01;35
.tga 01;35
.xbm 01;35
.xpm 01;35
.tif 01;35
.tiff 01;35
.png 01;35
.svg 01;35
.svgz 01;35
.mng 01;35
.pcx 01;35
.mov 01;35
.mpg 01;35
.mpeg 01;35
.m2v 01;35
.mkv 01;35
.webm 01;35
.ogm 01;35
.mp4 01;35
.m4v 01;35
.mp4v 01;35
.vob 01;35
.qt 01;35
.nuv 01;35
.wmv 01;35
.asf 01;35
.rm 01;35
.rmvb 01;35
.flc 01;35
.avi 01;35
.fli 01;35
.flv 01;35
.gl 01;35
.dl 01;35
.xcf 01;35
.xwd 01;35
.yuv 01;35
.cgm 01;35
.emf 01;35
# https://wiki.xiph.org/MIME_Types_and_File_Extensions
.ogv 01;35
.ogx 01;35
# audio formats
.aac 00;36
.au 00;36
.flac 00;36
.m4a 00;36
.mid 00;36
.midi 00;36
.mka 00;36
.mp3 00;36
.mpc 00;36
.ogg 00;36
.ra 00;36
.wav 00;36
# https://wiki.xiph.org/MIME_Types_and_File_Extensions
.oga 00;36
.opus 00;36
.spx 00;36
.xspf 00;36
""" # }}}
# special file?
special_types = (
(stat.S_IFLNK, 'ln'), # symlink
(stat.S_IFIFO, 'pi'), # pipe (FIFO)
(stat.S_IFSOCK, 'so'), # socket
(stat.S_IFBLK, 'bd'), # block device
(stat.S_IFCHR, 'cd'), # character device
(stat.S_ISUID, 'su'), # setuid
(stat.S_ISGID, 'sg'), # setgid
)
CODE_MAP = {
'RESET': 'rs',
'DIR': 'di',
'LINK': 'ln',
'MULTIHARDLINK': 'mh',
'FIFO': 'pi',
'SOCK': 'so',
'DOOR': 'do',
'BLK': 'bd',
'CHR': 'cd',
'ORPHAN': 'or',
'MISSING': 'mi',
'SETUID': 'su',
'SETGID': 'sg',
'CAPABILITY': 'ca',
'STICKY_OTHER_WRITABLE': 'tw',
'OTHER_WRITABLE': 'ow',
'STICKY': 'st',
'EXEC': 'ex',
}
def stat_at(file: str, cwd: int | str | None = None, follow_symlinks: bool = False) -> os.stat_result:
dirfd: int | None = None
need_to_close = False
if isinstance(cwd, str):
dirfd = os.open(cwd, os.O_RDONLY | getattr(os, 'O_CLOEXEC', 0))
need_to_close = True
elif isinstance(cwd, int):
dirfd = cwd
try:
return os.stat(file, dir_fd=dirfd, follow_symlinks=follow_symlinks)
finally:
if need_to_close and dirfd is not None:
os.close(dirfd)
class Dircolors:
def __init__(self) -> None:
self.codes: dict[str, str] = {}
self.extensions: dict[str, str] = {}
if not self.load_from_environ() and not self.load_from_file():
self.load_defaults()
def clear(self) -> None:
self.codes.clear()
self.extensions.clear()
def load_from_file(self) -> bool:
for candidate in (os.path.expanduser('~/.dir_colors'), '/etc/DIR_COLORS'):
with suppress(Exception):
with open(candidate) as f:
return self.load_from_dircolors(f.read())
return False
def load_from_lscolors(self, lscolors: str) -> bool:
self.clear()
if not lscolors:
return False
for item in lscolors.split(':'):
try:
code, color = item.split('=', 1)
except ValueError:
continue
if code.startswith('*.'):
self.extensions[code[1:]] = color
else:
self.codes[code] = color
return bool(self.codes or self.extensions)
def load_from_environ(self, envvar: str = 'LS_COLORS') -> bool:
return self.load_from_lscolors(os.environ.get(envvar) or '')
def load_from_dircolors(self, database: str, strict: bool = False) -> bool:
self.clear()
for line in database.splitlines():
line = line.split('#')[0].strip()
if not line:
continue
split = line.split()
if len(split) != 2:
if strict:
raise ValueError(f'Warning: unable to parse dircolors line "{line}"')
continue
key, val = split
if key == 'TERM':
continue
if key in CODE_MAP:
self.codes[CODE_MAP[key]] = val
elif key.startswith('.'):
self.extensions[key] = val
elif strict:
raise ValueError(f'Warning: unable to parse dircolors line "{line}"')
return bool(self.codes or self.extensions)
def load_defaults(self) -> bool:
self.clear()
return self.load_from_dircolors(DEFAULT_DIRCOLORS, True)
def generate_lscolors(self) -> str:
"""Output the database in the format used by the LS_COLORS environment variable."""
def gen_pairs() -> Generator[tuple[str, str], None, None]:
for pair in self.codes.items():
yield pair
for pair in self.extensions.items():
# change .xyz to *.xyz
yield '*' + pair[0], pair[1]
return ':'.join('{}={}'.format(*pair) for pair in gen_pairs())
def _format_code(self, text: str, code: str) -> str:
val = self.codes.get(code)
return '\033[{}m{}\033[{}m'.format(val, text, self.codes.get('rs', '0')) if val else text
def _format_ext(self, text: str, ext: str) -> str:
val = self.extensions.get(ext, '0')
return '\033[{}m{}\033[{}m'.format(val, text, self.codes.get('rs', '0')) if val else text
def format_mode(self, text: str, sr: os.stat_result) -> str:
mode = sr.st_mode
if stat.S_ISDIR(mode):
if (mode & (stat.S_ISVTX | stat.S_IWOTH)) == (stat.S_ISVTX | stat.S_IWOTH):
# sticky and world-writable
return self._format_code(text, 'tw')
if mode & stat.S_ISVTX:
# sticky but not world-writable
return self._format_code(text, 'st')
if mode & stat.S_IWOTH:
# world-writable but not sticky
return self._format_code(text, 'ow')
# normal directory
return self._format_code(text, 'di')
for mask, code in special_types:
if (mode & mask) == mask:
return self._format_code(text, code)
# executable file?
if mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH):
return self._format_code(text, 'ex')
# regular file, format according to its extension
ext = os.path.splitext(text)[1]
if ext:
return self._format_ext(text, ext)
return text
def __call__(self, path: str, text: str, cwd: int | str | None = None) -> str:
follow_symlinks = self.codes.get('ln') == 'target'
try:
sr = stat_at(path, cwd, follow_symlinks)
except OSError:
return text
return self.format_mode(text, sr)
def develop() -> None:
import sys
print(Dircolors()(sys.argv[-1], sys.argv[-1]))
+354
View File
@@ -0,0 +1,354 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
from collections import deque
from collections.abc import Callable, Sequence
from contextlib import suppress
from types import TracebackType
from typing import TYPE_CHECKING, Any, ContextManager, Deque, NamedTuple, Optional, cast
from kitty.constants import kitten_exe, running_in_kitty
from kitty.fast_data_types import monotonic, safe_pipe
from kitty.types import DecoratedFunc, ParsedShortcut
from kitty.typing_compat import (
AbstractEventLoop,
BossType,
Debug,
ImageManagerType,
KeyActionType,
KeyEventType,
LoopType,
MouseButton,
MouseEvent,
ScreenSize,
TermManagerType,
WindowType,
)
from .operations import MouseTracking, pending_update
if TYPE_CHECKING:
from kitty.file_transmission import FileTransmissionCommand
OpenUrlHandler = Optional[Callable[[BossType, WindowType, str, int, str], bool]]
class ButtonEvent(NamedTuple):
mouse_event: MouseEvent
timestamp: float
def is_click(a: ButtonEvent, b: ButtonEvent) -> bool:
from .loop import EventType
if a.mouse_event.type is not EventType.PRESS or b.mouse_event.type is not EventType.RELEASE:
return False
x = a.mouse_event.cell_x - b.mouse_event.cell_x
y = a.mouse_event.cell_y - b.mouse_event.cell_y
return x * x + y * y <= 4
class KittenUI:
allow_remote_control: bool = False
remote_control_password: bool | str = False
def __init__(self, func: Callable[[list[str]], str], allow_remote_control: bool, remote_control_password: bool | str):
self.func = func
self.allow_remote_control = allow_remote_control
self.remote_control_password = remote_control_password
self.password = self.to = ''
self.rc_fd = -1
self.initialized = False
def initialize(self) -> None:
if self.initialized:
return
self.initialized = True
if running_in_kitty():
return
if self.allow_remote_control:
self.to = os.environ.get('KITTY_LISTEN_ON', '')
if not self.to:
raise ValueError('Remote control not enabled, this kitten should be run via a map in kitty.conf, not from the command line')
self.rc_fd = int(self.to.partition(':')[-1])
os.set_inheritable(self.rc_fd, False)
if (self.remote_control_password or self.remote_control_password == '') and not self.password:
import socket
with socket.fromfd(self.rc_fd, socket.AF_UNIX, socket.SOCK_STREAM) as s:
data = s.recv(256)
if not data.endswith(b'\n'):
raise Exception(f'The remote control password was invalid: {data!r}')
self.password = data.strip().decode()
def __call__(self, args: list[str]) -> str:
self.initialize()
return self.func(args)
def allow_indiscriminate_remote_control(self, enable: bool = True) -> None:
if self.rc_fd > -1:
if enable:
os.set_inheritable(self.rc_fd, True)
if self.password:
os.environ['KITTY_RC_PASSWORD'] = self.password
else:
os.set_inheritable(self.rc_fd, False)
if self.password:
os.environ.pop('KITTY_RC_PASSWORD', None)
def remote_control(self, cmd: str | Sequence[str], **kw: Any) -> Any:
if not self.allow_remote_control:
raise ValueError('Remote control is not enabled, remember to use allow_remote_control=True')
prefix = [kitten_exe(), '@']
r = -1
pass_fds = list(kw.get('pass_fds') or [])
try:
if self.rc_fd > -1:
pass_fds.append(self.rc_fd)
if self.password and self.rc_fd > -1:
r, w = safe_pipe(False)
os.write(w, self.password.encode())
os.close(w)
prefix += ['--password-file', f'fd:{r}', '--use-password', 'always']
pass_fds.append(r)
if pass_fds:
kw['pass_fds'] = tuple(pass_fds)
if isinstance(cmd, str):
cmd = ' '.join(prefix)
else:
cmd = prefix + list(cmd)
import subprocess
if self.rc_fd > -1:
is_inheritable = os.get_inheritable(self.rc_fd)
if not is_inheritable:
os.set_inheritable(self.rc_fd, True)
try:
return subprocess.run(cmd, **kw)
finally:
if self.rc_fd > -1 and not is_inheritable:
os.set_inheritable(self.rc_fd, False)
finally:
if r > -1:
os.close(r)
def kitten_ui(
allow_remote_control: bool = KittenUI.allow_remote_control,
remote_control_password: bool | str = KittenUI.allow_remote_control,
) -> Callable[[Callable[[list[str]], str]], KittenUI]:
def wrapper(impl: Callable[..., Any]) -> KittenUI:
return KittenUI(impl, allow_remote_control, remote_control_password)
return wrapper
class Handler:
image_manager_class: type[ImageManagerType] | None = None
use_alternate_screen = True
mouse_tracking = MouseTracking.none
terminal_io_ended = False
overlay_ready_report_needed = False
def _initialize(
self,
screen_size: ScreenSize,
term_manager: TermManagerType,
schedule_write: Callable[[bytes], None],
tui_loop: LoopType,
debug: Debug,
image_manager: ImageManagerType | None = None,
) -> None:
from .operations import commander
self.screen_size = screen_size
self._term_manager = term_manager
self._tui_loop = tui_loop
self._schedule_write = schedule_write
self.debug = debug
self.cmd = commander(self)
self._image_manager = image_manager
self._button_events: dict[MouseButton, Deque[ButtonEvent]] = {}
@property
def image_manager(self) -> ImageManagerType:
assert self._image_manager is not None
return self._image_manager
@property
def asyncio_loop(self) -> AbstractEventLoop:
return self._tui_loop.asyncio_loop
def add_shortcut(self, action: KeyActionType, spec: str | ParsedShortcut) -> None:
if not hasattr(self, '_key_shortcuts'):
self._key_shortcuts: dict[ParsedShortcut, KeyActionType] = {}
if isinstance(spec, str):
from kitty.key_encoding import parse_shortcut
spec = parse_shortcut(spec)
self._key_shortcuts[spec] = action
def shortcut_action(self, key_event: KeyEventType) -> KeyActionType | None:
for sc, action in self._key_shortcuts.items():
if key_event.matches(sc):
return action
return None
def __enter__(self) -> None:
if self._image_manager is not None:
self._image_manager.__enter__()
self.debug.fobj = self
self.initialize()
def __exit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, tb: TracebackType | None) -> bool | None:
del self.debug.fobj
with suppress(Exception):
self.finalize()
if self._image_manager is not None:
self._image_manager.__exit__(exc_type, exc_val, tb)
return None
def initialize(self) -> None:
pass
def finalize(self) -> None:
pass
def on_resize(self, new_size: ScreenSize) -> None:
self.screen_size = new_size
def quit_loop(self, return_code: int | None = None) -> None:
self._tui_loop.quit(return_code)
def on_term(self) -> None:
self._tui_loop.quit(1)
def on_hup(self) -> None:
self.terminal_io_ended = True
self._tui_loop.quit(1)
def on_key_event(self, key_event: KeyEventType, in_bracketed_paste: bool = False) -> None:
"Override this method and perform_default_key_action() to handle all key events"
if key_event.text:
self.on_text(key_event.text, in_bracketed_paste)
else:
self.on_key(key_event)
def perform_default_key_action(self, key_event: KeyEventType) -> bool:
"Override in sub-class if you want to handle these key events yourself"
if key_event.matches('ctrl+c'):
self.on_interrupt()
return True
if key_event.matches('ctrl+d'):
self.on_eot()
return True
return False
def on_text(self, text: str, in_bracketed_paste: bool = False) -> None:
pass
def on_key(self, key_event: KeyEventType) -> None:
pass
def on_mouse_event(self, mouse_event: MouseEvent) -> None:
from .loop import EventType
if mouse_event.type is EventType.MOVE:
self.on_mouse_move(mouse_event)
elif mouse_event.type is EventType.PRESS:
q = self._button_events.setdefault(mouse_event.buttons, deque())
q.append(ButtonEvent(mouse_event, monotonic()))
if len(q) > 5:
q.popleft()
elif mouse_event.type is EventType.RELEASE:
q = self._button_events.setdefault(mouse_event.buttons, deque())
q.append(ButtonEvent(mouse_event, monotonic()))
if len(q) > 5:
q.popleft()
if len(q) > 1 and is_click(q[-2], q[-1]):
self.on_click(mouse_event)
def on_mouse_move(self, mouse_event: MouseEvent) -> None:
pass
def on_click(self, mouse_event: MouseEvent) -> None:
pass
def on_interrupt(self) -> None:
pass
def on_eot(self) -> None:
pass
def on_writing_finished(self) -> None:
pass
def on_kitty_cmd_response(self, response: dict[str, Any]) -> None:
pass
def on_clipboard_response(self, text: str, from_primary: bool = False) -> None:
pass
def on_file_transfer_response(self, ftc: 'FileTransmissionCommand') -> None:
pass
def on_capability_response(self, name: str, val: str) -> None:
pass
def write(self, data: bytes | str) -> None:
if isinstance(data, str):
data = data.encode('utf-8')
self._schedule_write(data)
def flush(self) -> None:
pass
def print(self, *args: object, sep: str = ' ', end: str = '\r\n') -> None:
data = sep.join(map(str, args)) + end
self.write(data)
def suspend(self) -> ContextManager[TermManagerType]:
return self._term_manager.suspend()
@classmethod
def atomic_update(cls, func: DecoratedFunc) -> DecoratedFunc:
from functools import wraps
@wraps(func)
def f(*a: Any, **kw: Any) -> Any:
with pending_update(a[0].write):
return func(*a, **kw)
return cast(DecoratedFunc, f)
class HandleResult:
type_of_input: str | None = None
no_ui: bool = False
def __init__(self, impl: Callable[..., Any], type_of_input: str | None, no_ui: bool, has_ready_notification: bool, open_url_handler: OpenUrlHandler):
self.impl = impl
self.no_ui = no_ui
self.type_of_input = type_of_input
self.has_ready_notification = has_ready_notification
self.open_url_handler = open_url_handler
def __call__(self, args: Sequence[str], data: Any, target_window_id: int, boss: BossType) -> Any:
return self.impl(args, data, target_window_id, boss)
def result_handler(
type_of_input: str | None = None,
no_ui: bool = False,
has_ready_notification: bool = Handler.overlay_ready_report_needed,
open_url_handler: OpenUrlHandler = None,
) -> Callable[[Callable[..., Any]], HandleResult]:
def wrapper(impl: Callable[..., Any]) -> HandleResult:
return HandleResult(impl, type_of_input, no_ui, has_ready_notification, open_url_handler)
return wrapper
+611
View File
@@ -0,0 +1,611 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import codecs
import os
import sys
from base64 import standard_b64encode
from collections import defaultdict, deque
from collections.abc import Callable, Iterator, Sequence
from contextlib import suppress
from enum import IntEnum
from itertools import count
from typing import Any, ClassVar, DefaultDict, Deque, Generic, Optional, TypeVar, Union, cast, final
from kitty.conf.utils import positive_float, positive_int
from kitty.fast_data_types import create_canvas
from kitty.typing_compat import CompletedProcess, GRT_f, GRT_o, HandlerType
from kitty.utils import ScreenSize, fit_image, which
from .operations import cursor
try:
fsenc = sys.getfilesystemencoding() or 'utf-8'
codecs.lookup(fsenc)
except Exception:
fsenc = 'utf-8'
class Dispose(IntEnum):
undefined = 0
none = 1
background = 2
previous = 3
class Frame:
gap: int # milliseconds
canvas_width: int
canvas_height: int
width: int
height: int
index: int
xdpi: float
ydpi: float
canvas_x: int
canvas_y: int
mode: str
needs_blend: bool
dimensions_swapped: bool
dispose: Dispose
path: str = ''
def __init__(self, identify_data: Union['Frame', dict[str, str]]):
if isinstance(identify_data, Frame):
for k in Frame.__annotations__:
setattr(self, k, getattr(identify_data, k))
else:
self.gap = max(0, int(identify_data['gap']) * 10)
sz, pos = identify_data['canvas'].split('+', 1)
self.canvas_width, self.canvas_height = map(positive_int, sz.split('x', 1))
self.canvas_x, self.canvas_y = map(int, pos.split('+', 1))
self.width, self.height = map(positive_int, identify_data['size'].split('x', 1))
self.xdpi, self.ydpi = map(positive_float, identify_data['dpi'].split('x', 1))
self.index = positive_int(identify_data['index'])
q = identify_data['transparency'].lower()
self.mode = 'rgba' if q in ('blend', 'true') else 'rgb'
self.needs_blend = q == 'blend'
self.dispose = getattr(Dispose, identify_data['dispose'].lower())
self.dimensions_swapped = identify_data.get('orientation') in ('5', '6', '7', '8')
if self.dimensions_swapped:
self.canvas_width, self.canvas_height = self.canvas_height, self.canvas_width
self.width, self.height = self.height, self.width
def __repr__(self) -> str:
canvas = f'{self.canvas_width}x{self.canvas_height}:{self.canvas_x}+{self.canvas_y}'
geom = f'{self.width}x{self.height}'
return f'Frame(index={self.index}, gap={self.gap}, geom={geom}, canvas={canvas}, dispose={self.dispose.name})'
class ImageData:
def __init__(self, fmt: str, width: int, height: int, mode: str, frames: list[Frame]):
self.width, self.height, self.fmt, self.mode = width, height, fmt, mode
self.transmit_fmt: GRT_f = 24 if self.mode == 'rgb' else 32
self.frames = frames
def __len__(self) -> int:
return len(self.frames)
def __iter__(self) -> Iterator[Frame]:
yield from self.frames
def __repr__(self) -> str:
frames = '\n '.join(map(repr, self.frames))
return f'Image(fmt={self.fmt}, mode={self.mode},\n {frames}\n)'
class OpenFailed(ValueError):
def __init__(self, path: str, message: str):
ValueError.__init__(self, f'Failed to open image: {path} with error: {message}')
self.path = path
class ConvertFailed(ValueError):
def __init__(self, path: str, message: str):
ValueError.__init__(self, f'Failed to convert image: {path} with error: {message}')
self.path = path
class NoImageMagick(Exception):
pass
class OutdatedImageMagick(ValueError):
def __init__(self, detailed_error: str):
super().__init__('ImageMagick on this system is too old ImageMagick 7+ required which was first released in 2016')
self.detailed_error = detailed_error
last_imagemagick_cmd: Sequence[str] = ()
def run_imagemagick(path: str, cmd: Sequence[str], keep_stdout: bool = True) -> 'CompletedProcess[bytes]':
global last_imagemagick_cmd
import subprocess
last_imagemagick_cmd = cmd
try:
p = subprocess.run(cmd, stdout=subprocess.PIPE if keep_stdout else subprocess.DEVNULL, stderr=subprocess.PIPE)
except FileNotFoundError:
raise NoImageMagick('ImageMagick is required to process images')
if p.returncode != 0:
raise OpenFailed(path, p.stderr.decode('utf-8'))
return p
def identify(path: str) -> ImageData:
import json
q = (
'{"fmt":"%m","canvas":"%g","transparency":"%A","gap":"%T","index":"%p","size":"%wx%h",'
'"dpi":"%xx%y","dispose":"%D","orientation":"%[EXIF:Orientation]"},'
)
exe = which('magick')
if exe:
cmd = [exe, 'identify']
else:
cmd = ['identify']
p = run_imagemagick(path, cmd + ['-format', q, '--', path])
raw = p.stdout.rstrip(b',')
data = json.loads(b'[' + raw + b']')
first = data[0]
frames = list(map(Frame, data))
image_fmt = first['fmt'].lower()
if image_fmt == 'gif' and not any(f.gap > 0 for f in frames):
# Some broken GIF images have all zero gaps, browsers with their usual
# idiot ideas render these with a default 100ms gap https://bugzilla.mozilla.org/show_bug.cgi?id=125137
# Browsers actually force a 100ms gap at any zero gap frame, but that
# just means it is impossible to deliberately use zero gap frames for
# sophisticated blending, so we dont do that.
for f in frames:
f.gap = 100
mode = 'rgb'
for f in frames:
if f.mode == 'rgba':
mode = 'rgba'
break
return ImageData(image_fmt, frames[0].canvas_width, frames[0].canvas_height, mode, frames)
class RenderedImage(ImageData):
def __init__(self, fmt: str, width: int, height: int, mode: str):
super().__init__(fmt, width, height, mode, [])
def render_image(
path: str,
output_prefix: str,
m: ImageData,
available_width: int,
available_height: int,
scale_up: bool,
only_first_frame: bool = False,
remove_alpha: str = '',
flip: bool = False,
flop: bool = False,
) -> RenderedImage:
import tempfile
has_multiple_frames = len(m) > 1
get_multiple_frames = has_multiple_frames and not only_first_frame
exe = which('magick')
if exe:
cmd = [exe, 'convert']
else:
exe = which('convert')
if exe is None:
raise OSError('Failed to find the ImageMagick convert executable, make sure it is present in PATH')
cmd = [exe]
if remove_alpha:
cmd += ['-background', remove_alpha, '-alpha', 'remove']
else:
cmd += ['-background', 'none']
if flip:
cmd.append('-flip')
if flop:
cmd.append('-flop')
cmd += ['--', path]
if only_first_frame and has_multiple_frames:
cmd[-1] += '[0]'
cmd.append('-auto-orient')
scaled = False
width, height = m.width, m.height
if scale_up:
if width < available_width:
r = available_width / width
width, height = available_width, int(height * r)
scaled = True
if scaled or width > available_width or height > available_height:
width, height = fit_image(width, height, available_width, available_height)
resize_cmd = ['-resize', f'{width}x{height}!']
if get_multiple_frames:
# we have to coalesce, resize and de-coalesce all frames
resize_cmd = ['-coalesce'] + resize_cmd + ['-deconstruct']
cmd += resize_cmd
cmd += ['-depth', '8', '-set', 'filename:f', '%w-%h-%g-%p']
ans = RenderedImage(m.fmt, width, height, m.mode)
if only_first_frame:
ans.frames = [Frame(m.frames[0])]
else:
ans.frames = list(map(Frame, m.frames))
bytes_per_pixel = 3 if m.mode == 'rgb' else 4
def check_resize(frame: Frame) -> None:
# ImageMagick sometimes generates RGBA images smaller than the specified
# size. See https://github.com/kovidgoyal/kitty/issues/276 for examples
sz = os.path.getsize(frame.path)
expected_size = bytes_per_pixel * frame.width * frame.height
if sz < expected_size:
missing = expected_size - sz
if missing % (bytes_per_pixel * width) != 0:
raise ConvertFailed(
path,
'ImageMagick failed to convert {} correctly, it generated {} < {} of data (w={}, h={}, bpp={})'.format(
path, sz, expected_size, frame.width, frame.height, bytes_per_pixel
),
)
frame.height -= missing // (bytes_per_pixel * frame.width)
if frame.index == 0:
ans.height = frame.height
ans.width = frame.width
with tempfile.TemporaryDirectory(dir=os.path.dirname(output_prefix)) as tdir:
output_template = os.path.join(tdir, f'im-%[filename:f].{m.mode}')
if get_multiple_frames:
cmd.append('+adjoin')
run_imagemagick(path, cmd + [output_template])
unseen = {x.index for x in m}
for x in os.listdir(tdir):
try:
parts = x.split('.', 1)[0].split('-')
index = int(parts[-1])
unseen.discard(index)
f = ans.frames[index]
f.width, f.height = map(positive_int, parts[1:3])
sz, pos = parts[3].split('+', 1)
f.canvas_width, f.canvas_height = map(positive_int, sz.split('x', 1))
f.canvas_x, f.canvas_y = map(int, pos.split('+', 1))
except Exception:
raise OutdatedImageMagick(f'Unexpected output filename: {x!r} produced by ImageMagick command: {last_imagemagick_cmd}')
f.path = output_prefix + f'-{index}.{m.mode}'
os.rename(os.path.join(tdir, x), f.path)
check_resize(f)
f = ans.frames[0]
if f.width != ans.width or f.height != ans.height:
with open(f.path, 'r+b') as ff:
data = ff.read()
ff.seek(0)
ff.truncate()
cd = create_canvas(data, f.width, f.canvas_x, f.canvas_y, ans.width, ans.height, 3 if ans.mode == 'rgb' else 4)
ff.write(cd)
if get_multiple_frames:
if unseen:
raise ConvertFailed(path, f'Failed to render {len(unseen)} out of {len(m)} frames of animation')
elif not ans.frames[0].path:
raise ConvertFailed(path, 'Failed to render image')
return ans
def render_as_single_image(
path: str,
m: ImageData,
available_width: int,
available_height: int,
scale_up: bool,
tdir: str | None = None,
remove_alpha: str = '',
flip: bool = False,
flop: bool = False,
) -> tuple[str, int, int]:
import tempfile
fd, output = tempfile.mkstemp(prefix='tty-graphics-protocol-', suffix=f'.{m.mode}', dir=tdir)
os.close(fd)
result = render_image(path, output, m, available_width, available_height, scale_up, only_first_frame=True, remove_alpha=remove_alpha, flip=flip, flop=flop)
os.rename(result.frames[0].path, output)
return output, result.width, result.height
def can_display_images() -> bool:
ans: bool | None = getattr(can_display_images, 'ans', None)
if ans is None:
ans = which('convert') is not None
setattr(can_display_images, 'ans', ans)
return ans
ImageKey = tuple[str, int, int]
SentImageKey = tuple[int, int, int]
T = TypeVar('T')
class Alias(Generic[T]):
currently_processing: ClassVar[str] = ''
def __init__(self, defval: T) -> None:
self.name = ''
self.defval = defval
def __get__(self, instance: Optional['GraphicsCommand'], cls: type['GraphicsCommand'] | None = None) -> T:
if instance is None:
return self.defval
return cast(T, instance._actual_values.get(self.name, self.defval))
def __set__(self, instance: 'GraphicsCommand', val: T) -> None:
if val == self.defval:
instance._actual_values.pop(self.name, None)
else:
instance._actual_values[self.name] = val
def __set_name__(self, owner: type['GraphicsCommand'], name: str) -> None:
if len(name) == 1:
Alias.currently_processing = name
self.name = Alias.currently_processing
@final
class GraphicsCommand:
a = action = Alias('t')
q = quiet = Alias(0)
f = format = Alias(32)
t = transmission_type = Alias('d')
s = data_width = animation_state = Alias(0)
v = data_height = loop_count = Alias(0)
S = data_size = Alias(0)
O = data_offset = Alias(0) # noqa
i = image_id = Alias(0)
I = image_number = Alias(0) # noqa
p = placement_id = Alias(0)
o = compression = Alias(cast(Optional[GRT_o], None))
m = more = Alias(0)
x = left_edge = Alias(0)
y = top_edge = Alias(0)
w = width = Alias(0)
h = height = Alias(0)
X = cell_x_offset = blend_mode = Alias(0)
Y = cell_y_offset = bgcolor = Alias(0)
c = columns = other_frame_number = dest_frame = Alias(0)
r = rows = frame_number = source_frame = Alias(0)
z = z_index = gap = Alias(0)
C = cursor_movement = compose_mode = Alias(0)
d = delete_action = Alias('a')
def __init__(self) -> None:
self._actual_values: dict[str, Any] = {}
def __repr__(self) -> str:
return self.serialize().decode('ascii').replace('\033', '^]')
def clone(self) -> 'GraphicsCommand':
ans = GraphicsCommand()
ans._actual_values = self._actual_values.copy()
return ans
def serialize(self, payload: bytes | memoryview | str = b'') -> bytes:
items = []
for k, val in self._actual_values.items():
items.append(f'{k}={val}')
ans: list[bytes | memoryview] = []
w = ans.append
w(b'\033_G')
w(','.join(items).encode('ascii'))
if payload:
w(b';')
if isinstance(payload, str):
payload = standard_b64encode(payload.encode('utf-8'))
w(payload)
w(b'\033\\')
return b''.join(ans)
def clear(self) -> None:
self._actual_values = {}
def iter_transmission_chunks(self, data: bytes | None = None, level: int = -1, compression_threshold: int = 1024) -> Iterator[bytes]:
if data is None:
yield self.serialize()
return
gc = self.clone()
gc.S = len(data)
if level and len(data) >= compression_threshold:
import zlib
compressed = zlib.compress(data, level)
if len(compressed) < len(data):
gc.o = 'z'
data = compressed
gc.S = len(data)
data = standard_b64encode(data)
while data:
chunk, data = data[:4096], data[4096:]
gc.m = 1 if data else 0
yield gc.serialize(chunk)
gc.clear()
class Placement:
cmd: GraphicsCommand
x: int = 0
y: int = 0
def __init__(self, cmd: GraphicsCommand, x: int = 0, y: int = 0):
self.cmd = cmd
self.x = x
self.y = y
class ImageManager:
def __init__(self, handler: HandlerType):
self.image_id_counter = count()
self.handler = handler
self.filesystem_ok: bool | None = None
self.image_data: dict[str, ImageData] = {}
self.failed_images: dict[str, Exception] = {}
self.converted_images: dict[ImageKey, ImageKey] = {}
self.sent_images: dict[ImageKey, int] = {}
self.image_id_to_image_data: dict[int, ImageData] = {}
self.image_id_to_converted_data: dict[int, ImageKey] = {}
self.transmission_status: dict[int, str | int] = {}
self.placements_in_flight: DefaultDict[int, Deque[Placement]] = defaultdict(deque)
self.update_image_placement_for_resend: Callable[[int, Placement], bool] | None
@property
def next_image_id(self) -> int:
return next(self.image_id_counter) + 2
@property
def screen_size(self) -> ScreenSize:
return self.handler.screen_size
def __enter__(self) -> None:
import tempfile
self.tdir = tempfile.mkdtemp(prefix='kitten-images-')
with tempfile.NamedTemporaryFile(dir=self.tdir, delete=False) as f:
f.write(b'abcd')
gc = GraphicsCommand()
gc.a = 'q'
gc.s = gc.v = gc.i = 1
gc.t = 'f'
self.handler.cmd.gr_command(gc, standard_b64encode(f.name.encode(fsenc)))
def __exit__(self, *a: Any) -> bool | None:
import shutil
shutil.rmtree(self.tdir, ignore_errors=True)
self.handler.cmd.clear_images_on_screen(delete_data=True)
self.delete_all_sent_images()
del self.handler
return None
def delete_all_sent_images(self) -> None:
gc = GraphicsCommand()
gc.a = 'd'
for img_id in self.transmission_status:
gc.i = img_id
self.handler.cmd.gr_command(gc)
self.transmission_status.clear()
def handle_response(self, apc: str) -> None:
cdata, payload = apc[1:].partition(';')[::2]
control = {}
for x in cdata.split(','):
k, v = x.partition('=')[::2]
control[k] = v
try:
image_id = int(control.get('i', '0'))
except Exception:
image_id = 0
if image_id == 1:
self.filesystem_ok = payload == 'OK'
return
if not image_id:
return
if not self.transmission_status.get(image_id):
self.transmission_status[image_id] = payload
else:
in_flight = self.placements_in_flight[image_id]
if in_flight:
pl = in_flight.popleft()
if payload.startswith('ENOENT:'):
with suppress(Exception):
self.resend_image(image_id, pl)
if not in_flight:
self.placements_in_flight.pop(image_id, None)
def resend_image(self, image_id: int, pl: Placement) -> None:
if self.update_image_placement_for_resend is not None and not self.update_image_placement_for_resend(image_id, pl):
return
image_data = self.image_id_to_image_data[image_id]
skey = self.image_id_to_converted_data[image_id]
self.transmit_image(image_data, image_id, *skey)
with cursor(self.handler.write):
self.handler.cmd.set_cursor_position(pl.x, pl.y)
self.handler.cmd.gr_command(pl.cmd)
def send_image(self, path: str, max_cols: int | None = None, max_rows: int | None = None, scale_up: bool = False) -> SentImageKey:
path = os.path.abspath(path)
if path in self.failed_images:
raise self.failed_images[path]
if path not in self.image_data:
try:
self.image_data[path] = identify(path)
except Exception as e:
self.failed_images[path] = e
raise
m = self.image_data[path]
ss = self.screen_size
if max_cols is None:
max_cols = ss.cols
if max_rows is None:
max_rows = ss.rows
available_width = max_cols * ss.cell_width
available_height = max_rows * ss.cell_height
key = path, available_width, available_height
skey = self.converted_images.get(key)
if skey is None:
try:
self.converted_images[key] = skey = self.convert_image(path, available_width, available_height, m, scale_up)
except Exception as e:
self.failed_images[path] = e
raise
final_width, final_height = skey[1:]
if final_width == 0:
return 0, 0, 0
image_id = self.sent_images.get(skey)
if image_id is None:
image_id = self.next_image_id
self.transmit_image(m, image_id, *skey)
self.sent_images[skey] = image_id
self.image_id_to_converted_data[image_id] = skey
self.image_id_to_image_data[image_id] = m
return image_id, skey[1], skey[2]
def hide_image(self, image_id: int) -> None:
gc = GraphicsCommand()
gc.a = 'd'
gc.i = image_id
self.handler.cmd.gr_command(gc)
def show_image(self, image_id: int, x: int, y: int, src_rect: tuple[int, int, int, int] | None = None) -> None:
gc = GraphicsCommand()
gc.a = 'p'
gc.i = image_id
if src_rect is not None:
gc.x, gc.y, gc.w, gc.h = map(int, src_rect)
self.placements_in_flight[image_id].append(Placement(gc, x, y))
with cursor(self.handler.write):
self.handler.cmd.set_cursor_position(x, y)
self.handler.cmd.gr_command(gc)
def convert_image(self, path: str, available_width: int, available_height: int, image_data: ImageData, scale_up: bool = False) -> ImageKey:
rgba_path, width, height = render_as_single_image(path, image_data, available_width, available_height, scale_up, tdir=self.tdir)
return rgba_path, width, height
def transmit_image(self, image_data: ImageData, image_id: int, rgba_path: str, width: int, height: int) -> int:
self.transmission_status[image_id] = 0
gc = GraphicsCommand()
gc.a = 't'
gc.f = image_data.transmit_fmt
gc.s = width
gc.v = height
gc.i = image_id
if self.filesystem_ok:
gc.t = 'f'
self.handler.cmd.gr_command(gc, standard_b64encode(rgba_path.encode(fsenc)))
else:
import zlib
with open(rgba_path, 'rb') as f:
data = f.read()
gc.S = len(data)
data = zlib.compress(data)
gc.o = 'z'
data = standard_b64encode(data)
while data:
chunk, data = data[:4096], data[4096:]
gc.m = 1 if data else 0
self.handler.cmd.gr_command(gc, chunk)
gc.clear()
return image_id
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
from collections.abc import Callable
from kitty.fast_data_types import truncate_point_for_length, wcswidth
from kitty.key_encoding import EventType, KeyEvent
from .operations import RESTORE_CURSOR, SAVE_CURSOR, move_cursor_by, set_cursor_shape
class LineEdit:
def __init__(self, is_password: bool = False) -> None:
self.clear()
self.is_password = is_password
def clear(self) -> None:
self.current_input = ''
self.cursor_pos = 0
self.pending_bell = False
def split_at_cursor(self, delta: int = 0) -> tuple[str, str]:
pos = max(0, self.cursor_pos + delta)
x = truncate_point_for_length(self.current_input, pos) if pos else 0
before, after = self.current_input[:x], self.current_input[x:]
return before, after
def write(self, write: Callable[[str], None], prompt: str = '', screen_cols: int = 0) -> None:
if self.pending_bell:
write('\a')
self.pending_bell = False
ci = self.current_input
if self.is_password:
ci = '*' * wcswidth(ci)
text = prompt + ci
cursor_pos = self.cursor_pos + wcswidth(prompt)
if screen_cols:
write(SAVE_CURSOR + text + RESTORE_CURSOR)
used_lines, last_line_cursor_pos = divmod(cursor_pos, screen_cols)
if used_lines == 0:
if last_line_cursor_pos:
write(move_cursor_by(last_line_cursor_pos, 'right'))
else:
if used_lines:
write(move_cursor_by(used_lines, 'down'))
if last_line_cursor_pos:
write(move_cursor_by(last_line_cursor_pos, 'right'))
else:
write(text)
write('\r')
if cursor_pos:
write(move_cursor_by(cursor_pos, 'right'))
write(set_cursor_shape('beam'))
def add_text(self, text: str) -> None:
if self.current_input:
x = truncate_point_for_length(self.current_input, self.cursor_pos) if self.cursor_pos else 0
self.current_input = self.current_input[:x] + text + self.current_input[x:]
else:
self.current_input = text
self.cursor_pos += wcswidth(text)
def on_text(self, text: str, in_bracketed_paste: bool) -> None:
self.add_text(text)
def backspace(self, num: int = 1) -> bool:
before, after = self.split_at_cursor()
nbefore = before[:-num]
if nbefore != before:
self.current_input = nbefore + after
self.cursor_pos = wcswidth(nbefore)
return True
self.pending_bell = True
return False
def delete(self, num: int = 1) -> bool:
before, after = self.split_at_cursor()
nafter = after[num:]
if nafter != after:
self.current_input = before + nafter
self.cursor_pos = wcswidth(before)
return True
self.pending_bell = True
return False
def _left(self) -> None:
if not self.current_input:
self.cursor_pos = 0
return
if self.cursor_pos:
before, after = self.split_at_cursor(-1)
self.cursor_pos = wcswidth(before)
def _right(self) -> None:
if not self.current_input:
self.cursor_pos = 0
return
max_pos = wcswidth(self.current_input)
if self.cursor_pos >= max_pos:
self.cursor_pos = max_pos
return
before, after = self.split_at_cursor(1)
self.cursor_pos += 1 + int(wcswidth(before) == self.cursor_pos)
def _move_loop(self, func: Callable[[], None], num: int) -> bool:
before = self.cursor_pos
changed = False
while num > 0:
func()
changed = self.cursor_pos != before
if not changed:
break
num -= 1
if not changed:
self.pending_bell = True
return changed
def left(self, num: int = 1) -> bool:
return self._move_loop(self._left, num)
def right(self, num: int = 1) -> bool:
return self._move_loop(self._right, num)
def home(self) -> bool:
if self.cursor_pos:
self.cursor_pos = 0
return True
return False
def end(self) -> bool:
orig = self.cursor_pos
self.cursor_pos = wcswidth(self.current_input)
return self.cursor_pos != orig
def on_key(self, key_event: KeyEvent) -> bool:
if key_event.type is EventType.RELEASE:
return False
if key_event.matches('home') or key_event.matches('ctrl+a'):
return self.home()
if key_event.matches('end') or key_event.matches('ctrl+e'):
return self.end()
if key_event.matches('backspace'):
self.backspace()
return True
if key_event.matches('delete') or key_event.matches('ctrl+d'):
self.delete()
return True
if key_event.matches('left') or key_event.matches('ctrl+b'):
self.left()
return True
if key_event.matches('right') or key_event.matches('ctrl+f'):
self.right()
return True
return False
+464
View File
@@ -0,0 +1,464 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import asyncio
import codecs
import io
import os
import re
import selectors
import signal
import sys
import termios
from collections.abc import Callable, Generator
from contextlib import contextmanager, suppress
from enum import Enum, IntFlag, auto
from functools import partial
from typing import Any, NamedTuple
from kitty.constants import is_macos
from kitty.fast_data_types import FILE_TRANSFER_CODE, close_tty, normal_tty, open_tty, parse_input_from_terminal, raw_tty
from kitty.key_encoding import ALT, CTRL, SHIFT, backspace_key, decode_key_event, enter_key
from kitty.typing_compat import ImageManagerType, KeyEventType, Protocol
from kitty.utils import ScreenSize, ScreenSizeGetter, screen_size_function, write_all
from .handler import Handler
from .operations import MouseTracking, init_state, reset_state
class BinaryWrite(Protocol):
def write(self, data: bytes) -> None:
pass
def flush(self) -> None:
pass
def debug_write(*a: Any, **kw: Any) -> None:
from base64 import standard_b64encode
fobj = kw.pop('file', sys.stderr.buffer)
buf = io.StringIO()
kw['file'] = buf
print(*a, **kw)
stext = buf.getvalue()
for i in range(0, len(stext), 256):
chunk = stext[i : i + 256]
text = b'\x1bP@kitty-print|' + standard_b64encode(chunk.encode('utf-8')) + b'\x1b\\'
fobj.write(text)
fobj.flush()
class Debug:
fobj: BinaryWrite | None = None
def __call__(self, *a: Any, **kw: Any) -> None:
kw['file'] = self.fobj or sys.stdout.buffer
debug_write(*a, **kw)
debug = Debug()
ftc_code = str(FILE_TRANSFER_CODE)
class TermManager:
def __init__(self, optional_actions: int = termios.TCSANOW, use_alternate_screen: bool = True, mouse_tracking: MouseTracking = MouseTracking.none) -> None:
self.extra_finalize: str | None = None
self.optional_actions = optional_actions
self.use_alternate_screen = use_alternate_screen
self.mouse_tracking = mouse_tracking
def set_state_for_loop(self, set_raw: bool = True) -> None:
if set_raw:
raw_tty(self.tty_fd, self.original_termios)
write_all(self.tty_fd, init_state(self.use_alternate_screen, self.mouse_tracking))
def reset_state_to_original(self) -> None:
normal_tty(self.tty_fd, self.original_termios)
if self.extra_finalize:
write_all(self.tty_fd, self.extra_finalize)
write_all(self.tty_fd, reset_state(self.use_alternate_screen))
@contextmanager
def suspend(self) -> Generator['TermManager', None, None]:
self.reset_state_to_original()
yield self
self.set_state_for_loop()
def __enter__(self) -> 'TermManager':
self.tty_fd, self.original_termios = open_tty(False, self.optional_actions)
self.set_state_for_loop(set_raw=False)
return self
def __exit__(self, *a: object) -> None:
with suppress(Exception):
self.reset_state_to_original()
close_tty(self.tty_fd, self.original_termios)
del self.tty_fd, self.original_termios
class MouseButton(IntFlag):
NONE, LEFT, MIDDLE, RIGHT, FOURTH, FIFTH, SIXTH, SEVENTH = 0, 1, 2, 4, 8, 16, 32, 64
WHEEL_UP, WHEEL_DOWN, WHEEL_LEFT, WHEEL_RIGHT = -1, -2, -4, -8
bmap = MouseButton.LEFT, MouseButton.MIDDLE, MouseButton.RIGHT
ebmap = MouseButton.FOURTH, MouseButton.FIFTH, MouseButton.SIXTH, MouseButton.SEVENTH
wbmap = MouseButton.WHEEL_UP, MouseButton.WHEEL_DOWN, MouseButton.WHEEL_LEFT, MouseButton.WHEEL_RIGHT
SHIFT_INDICATOR = 1 << 2
ALT_INDICATOR = 1 << 3
CTRL_INDICATOR = 1 << 4
MOTION_INDICATOR = 1 << 5
class EventType(Enum):
PRESS = auto()
RELEASE = auto()
MOVE = auto()
class MouseEvent(NamedTuple):
cell_x: int
cell_y: int
pixel_x: int
pixel_y: int
type: EventType
buttons: MouseButton
mods: int
def pixel_to_cell(px: int, length: int, cell_length: int) -> int:
px = max(0, min(px, length - 1))
return px // cell_length
def decode_sgr_mouse(text: str, screen_size: ScreenSize) -> MouseEvent:
cb_, x_, y_ = text.split(';')
m, y_ = y_[-1], y_[:-1]
cb, x, y = map(int, (cb_, x_, y_))
typ = EventType.RELEASE if m == 'm' else (EventType.MOVE if cb & MOTION_INDICATOR else EventType.PRESS)
buttons: MouseButton = MouseButton.NONE
cb3 = cb & 3
if cb >= 128:
buttons |= ebmap[cb3]
elif cb >= 64:
buttons |= wbmap[cb3]
elif cb3 < 3:
buttons |= bmap[cb3]
mods = 0
if cb & SHIFT_INDICATOR:
mods |= SHIFT
if cb & ALT_INDICATOR:
mods |= ALT
if cb & CTRL_INDICATOR:
mods |= CTRL
return MouseEvent(
pixel_to_cell(x, screen_size.width, screen_size.cell_width), pixel_to_cell(y, screen_size.height, screen_size.cell_height), x, y, typ, buttons, mods
)
class UnhandledException(Handler):
def __init__(self, tb: str) -> None:
self.tb = tb
def initialize(self) -> None:
self.cmd.clear_screen()
self.cmd.set_scrolling_region()
self.cmd.set_cursor_visible(True)
self.cmd.set_default_colors()
self.write(self.tb.replace('\n', '\r\n'))
self.write('\r\n')
self.write('Press Enter to quit')
def on_key(self, key_event: KeyEventType) -> None:
if key_event.key == 'ENTER':
self.quit_loop(1)
def on_interrupt(self) -> None:
self.quit_loop(1)
on_eot = on_term = on_interrupt
class SignalManager:
def __init__(
self,
loop: asyncio.AbstractEventLoop,
on_winch: Callable[[], None],
on_interrupt: Callable[[], None],
on_term: Callable[[], None],
on_hup: Callable[[], None],
) -> None:
self.asyncio_loop = loop
self.on_winch, self.on_interrupt, self.on_term = on_winch, on_interrupt, on_term
self.on_hup = on_hup
def __enter__(self) -> None:
self.asyncio_loop.add_signal_handler(signal.SIGWINCH, self.on_winch)
self.asyncio_loop.add_signal_handler(signal.SIGINT, self.on_interrupt)
self.asyncio_loop.add_signal_handler(signal.SIGTERM, self.on_term)
self.asyncio_loop.add_signal_handler(signal.SIGHUP, self.on_hup)
def __exit__(self, *a: Any) -> None:
tuple(map(self.asyncio_loop.remove_signal_handler, (signal.SIGWINCH, signal.SIGINT, signal.SIGTERM, signal.SIGHUP)))
sanitize_bracketed_paste: str = '[\x03\x04\x0e\x0f\r\x07\x7f\x8d\x8e\x8f\x90\x9b\x9d\x9e\x9f]'
class Loop:
def __init__(self, sanitize_bracketed_paste: str = sanitize_bracketed_paste, optional_actions: int = termios.TCSADRAIN):
if is_macos:
# On macOS PTY devices are not supported by the KqueueSelector and
# the PollSelector is broken, causes 100% CPU usage
self.asyncio_loop: asyncio.AbstractEventLoop = asyncio.SelectorEventLoop(selectors.SelectSelector())
asyncio.set_event_loop(self.asyncio_loop)
else:
try:
self.asyncio_loop = asyncio.get_event_loop()
except RuntimeError:
self.asyncio_loop = asyncio.new_event_loop()
self.return_code = 0
self.overlay_ready_reported = False
self.optional_actions = optional_actions
self.read_buf = ''
self.decoder = codecs.getincrementaldecoder('utf-8')('ignore')
try:
self.iov_limit = max(os.sysconf('SC_IOV_MAX') - 1, 255)
except Exception:
self.iov_limit = 255
self.parse_input_from_terminal = partial(parse_input_from_terminal, self._on_text, self._on_dcs, self._on_csi, self._on_osc, self._on_pm, self._on_apc)
self.ebs_pat = re.compile('([\177\r\x03\x04])')
self.in_bracketed_paste = False
self.sanitize_bracketed_paste = bool(sanitize_bracketed_paste)
if self.sanitize_bracketed_paste:
self.sanitize_ibp_pat = re.compile(sanitize_bracketed_paste)
def _read_ready(self, handler: Handler, fd: int) -> None:
try:
bdata = os.read(fd, io.DEFAULT_BUFFER_SIZE)
except BlockingIOError:
return
if not bdata:
handler.terminal_io_ended = True
self.quit(1)
return
data = self.decoder.decode(bdata)
if self.read_buf:
data = self.read_buf + data
self.read_buf = data
self.handler = handler
try:
self.read_buf = self.parse_input_from_terminal(self.read_buf, self.in_bracketed_paste)
except Exception:
self.read_buf = ''
raise
finally:
del self.handler
# terminal input callbacks {{{
def _on_text(self, text: str) -> None:
if self.in_bracketed_paste and self.sanitize_bracketed_paste:
text = self.sanitize_ibp_pat.sub('', text)
for chunk in self.ebs_pat.split(text):
if len(chunk) == 1:
if chunk == '\r':
self.handler.on_key(enter_key)
elif chunk == '\177':
self.handler.on_key(backspace_key)
elif chunk == '\x03':
self.handler.on_interrupt()
elif chunk == '\x04':
self.handler.on_eot()
else:
self.handler.on_text(chunk, self.in_bracketed_paste)
elif chunk:
self.handler.on_text(chunk, self.in_bracketed_paste)
def _on_dcs(self, dcs: str) -> None:
if dcs.startswith('@kitty-cmd'):
import json
self.handler.on_kitty_cmd_response(json.loads(dcs[len('@kitty-cmd') :]))
elif dcs.startswith('1+r'):
from binascii import unhexlify
vals = dcs[3:].split(';')
for q in vals:
parts = q.split('=', 1)
try:
name, val = parts[0], unhexlify(parts[1]).decode('utf-8', 'replace')
except Exception:
continue
self.handler.on_capability_response(name, val)
def _on_csi(self, csi: str) -> None:
q = csi[-1]
if q in 'mM':
if csi.startswith('<'):
# SGR mouse event
try:
ev = decode_sgr_mouse(csi[1:], self.handler.screen_size)
except Exception:
pass
else:
self.handler.on_mouse_event(ev)
elif q in 'u~ABCDEHFPQRS':
if csi == '200~':
self.in_bracketed_paste = True
return
elif csi == '201~':
self.in_bracketed_paste = False
return
try:
k = decode_key_event(csi[:-1], q)
except Exception:
pass
else:
if not self.handler.perform_default_key_action(k):
self.handler.on_key_event(k)
def _on_pm(self, pm: str) -> None:
pass
def _on_osc(self, osc: str) -> None:
idx = osc.find(';')
if idx <= 0:
return
q = osc[:idx]
if q == '52':
widx = osc.find(';', idx + 1)
if widx < idx:
from_primary = osc.find('p', idx + 1) > -1
payload = ''
else:
from base64 import standard_b64decode
from_primary = osc.find('p', idx + 1, widx) > -1
data = memoryview(osc.encode('ascii'))
payload = standard_b64decode(data[widx + 1 :]).decode('utf-8')
self.handler.on_clipboard_response(payload, from_primary)
elif q == ftc_code:
from kitty.file_transmission import FileTransmissionCommand
data = memoryview(osc.encode('ascii'))
self.handler.on_file_transfer_response(FileTransmissionCommand.deserialize(data[idx + 1 :]))
def _on_apc(self, apc: str) -> None:
if apc.startswith('G'):
if self.handler.image_manager is not None:
self.handler.image_manager.handle_response(apc)
# }}}
@property
def total_pending_bytes_to_write(self) -> int:
return sum(map(len, self.write_buf))
def _write_ready(self, handler: Handler, fd: int) -> None:
if len(self.write_buf) > self.iov_limit:
self.write_buf[self.iov_limit - 1] = b''.join(self.write_buf[self.iov_limit - 1 :])
del self.write_buf[self.iov_limit :]
total_size = self.total_pending_bytes_to_write
if total_size:
try:
written = os.writev(fd, self.write_buf)
except BlockingIOError:
return
if not written:
handler.terminal_io_ended = True
self.quit(1)
return
else:
written = 0
if written >= total_size:
self.write_buf: list[bytes] = []
self.asyncio_loop.remove_writer(fd)
self.waiting_for_writes = False
handler.on_writing_finished()
else:
consumed = 0
for i, buf in enumerate(self.write_buf):
if not written:
break
if len(buf) <= written:
written -= len(buf)
consumed += 1
continue
self.write_buf[i] = buf[written:]
break
del self.write_buf[:consumed]
def quit(self, return_code: int | None = None) -> None:
if return_code is not None:
self.return_code = return_code
self.asyncio_loop.stop()
def loop_impl(self, handler: Handler, term_manager: TermManager, image_manager: ImageManagerType | None = None) -> str | None:
self.write_buf = []
tty_fd = term_manager.tty_fd
tb = None
self.waiting_for_writes = True
def schedule_write(data: bytes) -> None:
self.write_buf.append(data)
if not self.waiting_for_writes:
self.asyncio_loop.add_writer(tty_fd, self._write_ready, handler, tty_fd)
self.waiting_for_writes = True
def handle_exception(loop: asyncio.AbstractEventLoop, context: dict[str, Any]) -> None:
nonlocal tb
loop.stop()
tb = context['message']
exc = context.get('exception')
if exc is not None:
import traceback
tb += '\n' + ''.join(traceback.format_exception(exc.__class__, exc, exc.__traceback__))
self.asyncio_loop.set_exception_handler(handle_exception)
handler._initialize(self._get_screen_size(), term_manager, schedule_write, self, debug, image_manager)
with handler:
if handler.overlay_ready_report_needed:
handler.cmd.overlay_ready()
self.asyncio_loop.add_reader(tty_fd, self._read_ready, handler, tty_fd)
self.asyncio_loop.add_writer(tty_fd, self._write_ready, handler, tty_fd)
self.asyncio_loop.run_forever()
self.asyncio_loop.remove_reader(tty_fd)
if self.waiting_for_writes:
self.asyncio_loop.remove_writer(tty_fd)
return tb
def loop(self, handler: Handler) -> None:
tb: str | None = None
def _on_sigwinch() -> None:
self._get_screen_size.changed = True
handler.screen_size = self._get_screen_size()
handler.on_resize(handler.screen_size)
signal_manager = SignalManager(self.asyncio_loop, _on_sigwinch, handler.on_interrupt, handler.on_term, handler.on_hup)
with TermManager(self.optional_actions, handler.use_alternate_screen, handler.mouse_tracking) as term_manager, signal_manager:
self._get_screen_size: ScreenSizeGetter = screen_size_function(term_manager.tty_fd)
image_manager = None
if handler.image_manager_class is not None:
image_manager = handler.image_manager_class(handler)
try:
tb = self.loop_impl(handler, term_manager, image_manager)
except Exception:
import traceback
tb = traceback.format_exc()
term_manager.extra_finalize = b''.join(self.write_buf).decode('utf-8')
if tb is not None:
report_overlay_ready = handler.overlay_ready_report_needed and not self.overlay_ready_reported
self.return_code = 1
if not handler.terminal_io_ended:
self._report_error_loop(tb, term_manager, report_overlay_ready)
def _report_error_loop(self, tb: str, term_manager: TermManager, overlay_ready_report_needed: bool) -> None:
handler = UnhandledException(tb)
handler.overlay_ready_report_needed = overlay_ready_report_needed
self.loop_impl(handler, term_manager)
+490
View File
@@ -0,0 +1,490 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
import sys
from collections.abc import Callable, Generator
from contextlib import contextmanager
from enum import Enum, auto
from functools import wraps
from typing import Any, Optional, TypeVar, Union
from kitty.fast_data_types import Color
from kitty.rgb import color_as_sharp, to_color
from kitty.typing_compat import GraphicsCommandType, HandlerType, ScreenSize, UnderlineLiteral
from .operations_stub import CMD
GraphicsCommandType, ScreenSize # needed for stub generation
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'
F = TypeVar('F')
all_cmds: dict[str, Callable[..., Any]] = {}
class Mode(Enum):
LNM = 20, ''
IRM = 4, ''
DECKM = 1, '?'
DECSCNM = 5, '?'
DECOM = 6, '?'
DECAWM = 7, '?'
DECARM = 8, '?'
DECTCEM = 25, '?'
MOUSE_BUTTON_TRACKING = 1000, '?'
MOUSE_MOTION_TRACKING = 1002, '?'
MOUSE_MOVE_TRACKING = 1003, '?'
FOCUS_TRACKING = 1004, '?'
MOUSE_UTF8_MODE = 1005, '?'
MOUSE_SGR_MODE = 1006, '?'
MOUSE_URXVT_MODE = 1015, '?'
MOUSE_SGR_PIXEL_MODE = 1016, '?'
ALTERNATE_SCREEN = 1049, '?'
BRACKETED_PASTE = 2004, '?'
PENDING_UPDATE = 2026, '?'
HANDLE_TERMIOS_SIGNALS = 19997, '?'
def cmd(f: F) -> F:
all_cmds[f.__name__] = f # type: ignore
return f
@cmd
def set_mode(which: Mode) -> str:
num, private = which.value
return f'\033[{private}{num}h'
@cmd
def reset_mode(which: Mode) -> str:
num, private = which.value
return f'\033[{private}{num}l'
@cmd
def clear_screen() -> str:
return '\033[H\033[2J'
@cmd
def clear_to_end_of_screen() -> str:
return '\033[J'
@cmd
def clear_to_eol() -> str:
return '\033[K'
@cmd
def reset_terminal() -> str:
return '\033]\033\\\033c'
@cmd
def bell() -> str:
return '\a'
@cmd
def beep() -> str:
return '\a'
@cmd
def set_window_title(value: str) -> str:
return '\033]2;' + value.replace('\033', '').replace('\x9c', '') + '\033\\'
@cmd
def set_line_wrapping(yes_or_no: bool) -> str:
return set_mode(Mode.DECAWM) if yes_or_no else reset_mode(Mode.DECAWM)
@contextmanager
def without_line_wrap(write: Callable[[str], None]) -> Generator[None, None, None]:
write(set_line_wrapping(False))
try:
yield
finally:
write(set_line_wrapping(True))
@cmd
def repeat(char: str, count: int) -> str:
if count > 5:
return f'{char}\x1b[{count - 1}b'
return char * count
@cmd
def set_cursor_visible(yes_or_no: bool) -> str:
return set_mode(Mode.DECTCEM) if yes_or_no else reset_mode(Mode.DECTCEM)
@cmd
def set_cursor_position(x: int = 0, y: int = 0) -> str: # (0, 0) is top left
return f'\033[{y + 1};{x + 1}H'
@cmd
def move_cursor_by(amt: int, direction: str) -> str:
suffix = {'up': 'A', 'down': 'B', 'right': 'C', 'left': 'D'}[direction]
return f'\033[{amt}{suffix}'
@cmd
def set_cursor_shape(shape: str = 'block', blink: bool = True) -> str:
val = {'block': 1, 'underline': 3, 'beam': 5}.get(shape, 1)
if not blink:
val += 1
return f'\033[{val} q'
@cmd
def set_scrolling_region(screen_size: Optional['ScreenSize'] = None, top: int | None = None, bottom: int | None = None) -> str:
if screen_size is None:
return '\033[r'
if top is None:
top = 0
if bottom is None:
bottom = screen_size.rows - 1
if bottom < 0:
bottom = screen_size.rows - 1 + bottom
else:
bottom += 1
return f'\033[{top + 1};{bottom + 1}r'
@cmd
def scroll_screen(amt: int = 1) -> str:
return f'\033[{abs(amt)}{"T" if amt < 0 else "S"}'
STANDARD_COLORS = {'black': 0, 'red': 1, 'green': 2, 'yellow': 3, 'blue': 4, 'magenta': 5, 'cyan': 6, 'gray': 7, 'white': 7}
UNDERLINE_STYLES = {'straight': 1, 'double': 2, 'curly': 3, 'dotted': 4, 'dashed': 5}
ColorSpec = Union[int, str, Color]
def color_code(color: ColorSpec, intense: bool = False, base: int = 30) -> str:
if isinstance(color, str):
e = str((base + 60 if intense else base) + STANDARD_COLORS[color])
elif isinstance(color, int):
e = f'{base + 8}:5:{max(0, min(color, 255))}'
else:
e = f'{base + 8}{color.as_sgr}'
return e
@cmd
def sgr(*parts: str) -> str:
return '\033[{}m'.format(';'.join(parts))
@cmd
def colored(text: str, color: ColorSpec, intense: bool = False, reset_to: ColorSpec | None = None, reset_to_intense: bool = False) -> str:
e = color_code(color, intense)
return f'\033[{e}m{text}\033[{39 if reset_to is None else color_code(reset_to, reset_to_intense)}m'
@cmd
def faint(text: str) -> str:
return colored(text, 'black', True)
@cmd
def styled(
text: str,
fg: ColorSpec | None = None,
bg: ColorSpec | None = None,
fg_intense: bool = False,
bg_intense: bool = False,
italic: bool | None = None,
bold: bool | None = None,
underline: UnderlineLiteral | None = None,
underline_color: ColorSpec | None = None,
reverse: bool | None = None,
dim: bool | None = None,
) -> str:
start, end = [], []
if fg is not None:
start.append(color_code(fg, fg_intense))
end.append('39')
if bg is not None:
start.append(color_code(bg, bg_intense, 40))
end.append('49')
if underline_color is not None:
if isinstance(underline_color, str):
underline_color = STANDARD_COLORS[underline_color]
start.append(color_code(underline_color, base=50))
end.append('59')
if underline is not None:
start.append(f'4:{UNDERLINE_STYLES[underline]}')
end.append('4:0')
if italic is not None:
s, e = (start, end) if italic else (end, start)
s.append('3')
e.append('23')
if bold is not None:
s, e = (start, end) if bold else (end, start)
s.append('1')
e.append('22')
if dim is not None:
s, e = (start, end) if dim else (end, start)
s.append('2')
e.append('22')
if reverse is not None:
s, e = (start, end) if reverse else (end, start)
s.append('7')
e.append('27')
if not start:
return text
return '\033[{}m{}\033[{}m'.format(';'.join(start), text, ';'.join(end))
def serialize_gr_command(cmd: dict[str, int | str], payload: bytes | None = None) -> bytes:
from .images import GraphicsCommand
gc = GraphicsCommand()
for k, v in cmd.items():
setattr(gc, k, v)
return gc.serialize(payload or b'')
@cmd
def gr_command(cmd: Union[dict[str, int | str], 'GraphicsCommandType'], payload: bytes | None = None) -> str:
if isinstance(cmd, dict):
raw = serialize_gr_command(cmd, payload)
else:
raw = cmd.serialize(payload or b'')
return raw.decode('ascii')
@cmd
def clear_images_on_screen(delete_data: bool = False) -> str:
from .images import GraphicsCommand
gc = GraphicsCommand()
gc.a = 'd'
gc.d = 'A' if delete_data else 'a'
return gc.serialize().decode('ascii')
class MouseTracking(Enum):
none = auto()
buttons_only = auto()
buttons_and_drag = auto()
full = auto()
def init_state(alternate_screen: bool = True, mouse_tracking: MouseTracking = MouseTracking.none, kitty_keyboard_mode: bool = True) -> str:
sc = SAVE_CURSOR if alternate_screen else ''
ans = (
sc
+ SAVE_PRIVATE_MODE_VALUES
+ reset_mode(Mode.LNM)
+ reset_mode(Mode.IRM)
+ reset_mode(Mode.DECKM)
+ reset_mode(Mode.DECSCNM)
+ set_mode(Mode.DECARM)
+ set_mode(Mode.DECAWM)
+ set_mode(Mode.DECTCEM)
+ reset_mode(Mode.MOUSE_BUTTON_TRACKING)
+ reset_mode(Mode.MOUSE_MOTION_TRACKING)
+ reset_mode(Mode.MOUSE_MOVE_TRACKING)
+ reset_mode(Mode.FOCUS_TRACKING)
+ reset_mode(Mode.MOUSE_UTF8_MODE)
+ reset_mode(Mode.MOUSE_SGR_MODE)
+ set_mode(Mode.BRACKETED_PASTE)
+ SAVE_COLORS
+ '\033[*x' # reset DECSACE to default region select
)
if alternate_screen:
ans += set_mode(Mode.ALTERNATE_SCREEN) + reset_mode(Mode.DECOM)
ans += clear_screen()
if mouse_tracking is not MouseTracking.none:
ans += set_mode(Mode.MOUSE_SGR_PIXEL_MODE)
if mouse_tracking is MouseTracking.buttons_only:
ans += set_mode(Mode.MOUSE_BUTTON_TRACKING)
elif mouse_tracking is MouseTracking.buttons_and_drag:
ans += set_mode(Mode.MOUSE_MOTION_TRACKING)
elif mouse_tracking is MouseTracking.full:
ans += set_mode(Mode.MOUSE_MOVE_TRACKING)
if kitty_keyboard_mode:
ans += '\033[>31u' # extended keyboard mode
else:
ans += '\033[>u' # legacy keyboard mode
return ans
def reset_state(normal_screen: bool = True) -> str:
ans = '\033[<u' # restore keyboard mode
if normal_screen:
ans += reset_mode(Mode.ALTERNATE_SCREEN)
else:
ans += SAVE_CURSOR
ans += RESTORE_PRIVATE_MODE_VALUES
ans += RESTORE_CURSOR
ans += RESTORE_COLORS
return ans
@contextmanager
def pending_update(write: Callable[[str], None]) -> Generator[None, None, None]:
write(set_mode(Mode.PENDING_UPDATE))
try:
yield
finally:
write(reset_mode(Mode.PENDING_UPDATE))
@contextmanager
def cursor(write: Callable[[str], None]) -> Generator[None, None, None]:
write(SAVE_CURSOR)
try:
yield
finally:
write(RESTORE_CURSOR)
@contextmanager
def alternate_screen() -> Generator[None, None, None]:
with open(os.ctermid(), 'w') as f:
print(set_mode(Mode.ALTERNATE_SCREEN), end='', file=f, flush=True)
try:
yield
finally:
print(reset_mode(Mode.ALTERNATE_SCREEN), end='', file=f, flush=True)
@contextmanager
def raw_mode(fd: int | None = None) -> Generator[None, None, None]:
import termios
import tty
if fd is None:
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
yield
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
@cmd
def set_default_colors(
fg: Color | str | None = None,
bg: Color | str | None = None,
cursor: Color | str | None = None,
select_bg: Color | str | None = None,
select_fg: Color | str | None = None,
) -> str:
ans = ''
def item(which: Color | str | None, num: int) -> None:
nonlocal ans
if which is None:
ans += f'\x1b]1{num}\x1b\\'
else:
if isinstance(which, Color):
q = color_as_sharp(which)
else:
x = to_color(which)
assert x is not None
q = color_as_sharp(x)
ans += f'\x1b]{num};{q}\x1b\\'
item(fg, 10)
item(bg, 11)
item(cursor, 12)
item(select_bg, 17)
item(select_fg, 19)
return ans
@cmd
def save_colors() -> str:
return '\x1b[#P'
@cmd
def restore_colors() -> str:
return '\x1b[#Q'
@cmd
def overlay_ready() -> str:
return '\x1bP@kitty-overlay-ready|\x1b\\'
@cmd
def write_to_clipboard(data: str | bytes, use_primary: bool = False) -> str:
from base64 import standard_b64encode
fmt = 'p' if use_primary else 'c'
if isinstance(data, str):
data = data.encode('utf-8')
payload = standard_b64encode(data).decode('ascii')
return f'\x1b]52;{fmt};{payload}\a'
@cmd
def request_from_clipboard(use_primary: bool = False) -> str:
return '\x1b]52;{};?\a'.format('p' if use_primary else 'c')
# Boilerplate to make operations available via Handler.cmd {{{
def writer(handler: HandlerType, func: Callable[..., bytes | str]) -> Callable[..., None]:
@wraps(func)
def f(*a: Any, **kw: Any) -> None:
handler.write(func(*a, **kw))
return f
def commander(handler: HandlerType) -> CMD:
ans = CMD()
for name, func in all_cmds.items():
setattr(ans, name, writer(handler, func))
return ans
def func_sig(func: Callable[..., Any]) -> Generator[str, None, None]:
import inspect
import re
s = inspect.signature(func)
for val in s.parameters.values():
yield re.sub(r'ForwardRef\([\'"](\w+?)[\'"]\)', r'\1', str(val).replace('NoneType', 'None'))
def as_type_stub() -> str:
ans = [
'from typing import * # noqa',
'from kitty.typing_compat import GraphicsCommandType, ScreenSize',
'from kitty.fast_data_types import Color',
'import kitty.rgb',
'import kittens.tui.operations',
]
methods = []
for name, func in all_cmds.items():
args = ', '.join(func_sig(func))
if args:
args = f', {args}'
methods.append(f' def {name}(self{args}) -> str: pass')
ans += ['', '', 'class CMD:'] + methods
return '\n'.join(ans) + '\n\n\n'
# }}}
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
class CMD:
pass
def generate_stub() -> None:
from kittens.tui.operations import as_type_stub
from kitty.conf.utils import save_type_stub
text = as_type_stub()
save_type_stub(text, __file__)
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os
from collections.abc import Callable, Generator, Sequence
from typing import Any
from kitty.fast_data_types import wcswidth
from kitty.utils import ScreenSize, screen_size_function
from .operations import styled
def directory_completions(path: str, qpath: str, prefix: str = '') -> Generator[str, None, None]:
try:
entries = os.scandir(qpath)
except OSError:
return
for x in entries:
try:
is_dir = x.is_dir()
except OSError:
is_dir = False
name = x.name + (os.sep if is_dir else '')
if not prefix or name.startswith(prefix):
if path:
yield os.path.join(path, name)
else:
yield name
def expand_path(path: str) -> str:
return os.path.abspath(os.path.expandvars(os.path.expanduser(path)))
def find_completions(path: str) -> Generator[str, None, None]:
if path and path[0] == '~':
if path == '~':
yield '~' + os.sep
return
if os.sep not in path:
qpath = os.path.expanduser(path)
if qpath != path:
yield path + os.sep
return
qpath = expand_path(path)
if not path or path.endswith(os.sep):
yield from directory_completions(path, qpath)
else:
yield from directory_completions(os.path.dirname(path), os.path.dirname(qpath), os.path.basename(qpath))
def print_table(items: Sequence[str], screen_size: ScreenSize, dir_colors: Callable[[str, str], str]) -> None:
max_width = 0
item_widths = {}
for item in items:
item_widths[item] = w = wcswidth(item)
max_width = max(w, max_width)
col_width = max_width + 2
num_of_cols = max(1, screen_size.cols // col_width)
cr = 0
at_start = False
for item in items:
w = item_widths[item]
left = col_width - w
print(dir_colors(expand_path(item), item), ' ' * left, sep='', end='')
at_start = False
cr = (cr + 1) % num_of_cols
if not cr:
print()
at_start = True
if not at_start:
print()
class PathCompleter:
def __init__(self, prompt: str = '> '):
self.prompt = prompt
self.prompt_len = wcswidth(self.prompt)
def __enter__(self) -> 'PathCompleter':
import readline
from .dircolors import Dircolors
if 'libedit' in getattr(readline, '__doc__', '') or '': # ty: ignore[redundant-condition]
readline.parse_and_bind('bind -e')
readline.parse_and_bind("bind '\t' rl_complete")
else:
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set colored-stats on')
readline.set_completer_delims(' \t\n`!@#$%^&*()-=+[{]}\\|;:\'",<>?')
readline.set_completion_display_matches_hook(self.format_completions)
self.original_completer = readline.get_completer()
readline.set_completer(self)
self.cache: dict[str, tuple[str, ...]] = {}
self.dircolors = Dircolors()
return self
def format_completions(self, substitution: str, matches: Sequence[str], longest_match_length: int) -> None:
import readline
print()
files, dirs = [], []
for m in matches:
if m.endswith('/'):
if len(m) > 1:
m = m[:-1]
dirs.append(m)
else:
files.append(m)
ss = screen_size_function()()
if dirs:
print(styled('Directories', bold=True, fg_intense=True))
print_table(dirs, ss, self.dircolors)
if files:
print(styled('Files', bold=True, fg_intense=True))
print_table(files, ss, self.dircolors)
buf = readline.get_line_buffer()
x = readline.get_endidx()
buflen = wcswidth(buf)
print(self.prompt, buf, sep='', end='')
if x < buflen:
pos = x + self.prompt_len
print(f'\r\033[{pos}C', end='')
print(sep='', end='', flush=True)
def __call__(self, text: str, state: int) -> str | None:
options = self.cache.get(text)
if options is None:
options = self.cache[text] = tuple(find_completions(text))
if options and state < len(options):
return options[state]
return None
def __exit__(self, *a: Any) -> bool:
import readline
del self.cache
readline.set_completer(self.original_completer)
readline.set_completion_display_matches_hook()
return True
def input(self) -> str:
with self:
return input(self.prompt)
return ''
def get_path(prompt: str = '> ') -> str:
return PathCompleter(prompt).input()
def develop() -> None:
PathCompleter().input()
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from .operations import repeat, styled
def render_progress_bar(frac: float, width: int = 80) -> str:
if frac >= 1:
return styled('🬋' * width, fg='green')
if frac <= 0:
return styled('🬋' * width, dim=True)
w = frac * width
fl = int(w)
overhang = w - fl
filled = repeat('🬋', fl)
if overhang < 0.2:
needs_break = True
elif overhang < 0.8:
filled += '🬃'
fl += 1
needs_break = False
else:
if fl < width - 1:
filled += '🬋'
fl += 1
needs_break = True
else:
filled += '🬃'
fl += 1
needs_break = False
ans = styled(filled, fg='blue')
unfilled = '🬇' if width > fl and needs_break else ''
filler = width - fl - len(unfilled)
if filler > 0:
unfilled += repeat('🬋', filler)
if unfilled:
ans += styled(unfilled, dim=True)
return ans
+687
View File
@@ -0,0 +1,687 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from collections.abc import Sequence
from kitty.fast_data_types import monotonic
from kitty.typing_compat import TypedDict
class SpinnerDef(TypedDict):
interval: int
frames: Sequence[str]
# Spinner definitions are from
# https://raw.githubusercontent.com/sindresorhus/cli-spinners/main/spinners.json
spinners: dict[str, SpinnerDef] = { # {{{
'dots': {'interval': 80, 'frames': ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']},
'dots2': {'interval': 80, 'frames': ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']},
'dots3': {'interval': 80, 'frames': ['⠋', '⠙', '⠚', '⠞', '⠖', '⠦', '⠴', '⠲', '⠳', '⠓']},
'dots4': {'interval': 80, 'frames': ['⠄', '⠆', '⠇', '⠋', '⠙', '⠸', '⠰', '⠠', '⠰', '⠸', '⠙', '⠋', '⠇', '⠆']},
'dots5': {'interval': 80, 'frames': ['⠋', '⠙', '⠚', '⠒', '⠂', '⠂', '⠒', '⠲', '⠴', '⠦', '⠖', '⠒', '⠐', '⠐', '⠒', '⠓', '⠋']},
'dots6': {
'interval': 80,
'frames': ['⠁', '⠉', '⠙', '⠚', '⠒', '⠂', '⠂', '⠒', '⠲', '⠴', '⠤', '⠄', '⠄', '⠤', '⠴', '⠲', '⠒', '⠂', '⠂', '⠒', '⠚', '⠙', '⠉', '⠁'],
},
'dots7': {
'interval': 80,
'frames': ['⠈', '⠉', '⠋', '⠓', '⠒', '⠐', '⠐', '⠒', '⠖', '⠦', '⠤', '⠠', '⠠', '⠤', '⠦', '⠖', '⠒', '⠐', '⠐', '⠒', '⠓', '⠋', '⠉', '⠈'],
},
'dots8': {
'interval': 80,
'frames': [
'⠁',
'⠁',
'⠉',
'⠙',
'⠚',
'⠒',
'⠂',
'⠂',
'⠒',
'⠲',
'⠴',
'⠤',
'⠄',
'⠄',
'⠤',
'⠠',
'⠠',
'⠤',
'⠦',
'⠖',
'⠒',
'⠐',
'⠐',
'⠒',
'⠓',
'⠋',
'⠉',
'⠈',
'⠈',
],
},
'dots9': {'interval': 80, 'frames': ['⢹', '⢺', '⢼', '⣸', '⣇', '⡧', '⡗', '⡏']},
'dots10': {'interval': 80, 'frames': ['⢄', '⢂', '⢁', '⡁', '⡈', '⡐', '⡠']},
'dots11': {'interval': 100, 'frames': ['⠁', '⠂', '⠄', '⡀', '⢀', '⠠', '⠐', '⠈']},
'dots12': {
'interval': 80,
'frames': [
'⢀⠀',
'⡀⠀',
'⠄⠀',
'⢂⠀',
'⡂⠀',
'⠅⠀',
'⢃⠀',
'⡃⠀',
'⠍⠀',
'⢋⠀',
'⡋⠀',
'⠍⠁',
'⢋⠁',
'⡋⠁',
'⠍⠉',
'⠋⠉',
'⠋⠉',
'⠉⠙',
'⠉⠙',
'⠉⠩',
'⠈⢙',
'⠈⡙',
'⢈⠩',
'⡀⢙',
'⠄⡙',
'⢂⠩',
'⡂⢘',
'⠅⡘',
'⢃⠨',
'⡃⢐',
'⠍⡐',
'⢋⠠',
'⡋⢀',
'⠍⡁',
'⢋⠁',
'⡋⠁',
'⠍⠉',
'⠋⠉',
'⠋⠉',
'⠉⠙',
'⠉⠙',
'⠉⠩',
'⠈⢙',
'⠈⡙',
'⠈⠩',
'⠀⢙',
'⠀⡙',
'⠀⠩',
'⠀⢘',
'⠀⡘',
'⠀⠨',
'⠀⢐',
'⠀⡐',
'⠀⠠',
'⠀⢀',
'⠀⡀',
],
},
'dots8Bit': {
'interval': 80,
'frames': [
'⠀',
'⠁',
'⠂',
'⠃',
'⠄',
'⠅',
'⠆',
'⠇',
'⡀',
'⡁',
'⡂',
'⡃',
'⡄',
'⡅',
'⡆',
'⡇',
'⠈',
'⠉',
'⠊',
'⠋',
'⠌',
'⠍',
'⠎',
'⠏',
'⡈',
'⡉',
'⡊',
'⡋',
'⡌',
'⡍',
'⡎',
'⡏',
'⠐',
'⠑',
'⠒',
'⠓',
'⠔',
'⠕',
'⠖',
'⠗',
'⡐',
'⡑',
'⡒',
'⡓',
'⡔',
'⡕',
'⡖',
'⡗',
'⠘',
'⠙',
'⠚',
'⠛',
'⠜',
'⠝',
'⠞',
'⠟',
'⡘',
'⡙',
'⡚',
'⡛',
'⡜',
'⡝',
'⡞',
'⡟',
'⠠',
'⠡',
'⠢',
'⠣',
'⠤',
'⠥',
'⠦',
'⠧',
'⡠',
'⡡',
'⡢',
'⡣',
'⡤',
'⡥',
'⡦',
'⡧',
'⠨',
'⠩',
'⠪',
'⠫',
'⠬',
'⠭',
'⠮',
'⠯',
'⡨',
'⡩',
'⡪',
'⡫',
'⡬',
'⡭',
'⡮',
'⡯',
'⠰',
'⠱',
'⠲',
'⠳',
'⠴',
'⠵',
'⠶',
'⠷',
'⡰',
'⡱',
'⡲',
'⡳',
'⡴',
'⡵',
'⡶',
'⡷',
'⠸',
'⠹',
'⠺',
'⠻',
'⠼',
'⠽',
'⠾',
'⠿',
'⡸',
'⡹',
'⡺',
'⡻',
'⡼',
'⡽',
'⡾',
'⡿',
'⢀',
'⢁',
'⢂',
'⢃',
'⢄',
'⢅',
'⢆',
'⢇',
'⣀',
'⣁',
'⣂',
'⣃',
'⣄',
'⣅',
'⣆',
'⣇',
'⢈',
'⢉',
'⢊',
'⢋',
'⢌',
'⢍',
'⢎',
'⢏',
'⣈',
'⣉',
'⣊',
'⣋',
'⣌',
'⣍',
'⣎',
'⣏',
'⢐',
'⢑',
'⢒',
'⢓',
'⢔',
'⢕',
'⢖',
'⢗',
'⣐',
'⣑',
'⣒',
'⣓',
'⣔',
'⣕',
'⣖',
'⣗',
'⢘',
'⢙',
'⢚',
'⢛',
'⢜',
'⢝',
'⢞',
'⢟',
'⣘',
'⣙',
'⣚',
'⣛',
'⣜',
'⣝',
'⣞',
'⣟',
'⢠',
'⢡',
'⢢',
'⢣',
'⢤',
'⢥',
'⢦',
'⢧',
'⣠',
'⣡',
'⣢',
'⣣',
'⣤',
'⣥',
'⣦',
'⣧',
'⢨',
'⢩',
'⢪',
'⢫',
'⢬',
'⢭',
'⢮',
'⢯',
'⣨',
'⣩',
'⣪',
'⣫',
'⣬',
'⣭',
'⣮',
'⣯',
'⢰',
'⢱',
'⢲',
'⢳',
'⢴',
'⢵',
'⢶',
'⢷',
'⣰',
'⣱',
'⣲',
'⣳',
'⣴',
'⣵',
'⣶',
'⣷',
'⢸',
'⢹',
'⢺',
'⢻',
'⢼',
'⢽',
'⢾',
'⢿',
'⣸',
'⣹',
'⣺',
'⣻',
'⣼',
'⣽',
'⣾',
'⣿',
],
},
'line': {'interval': 130, 'frames': ['-', '\\', '|', '/']},
'line2': {'interval': 100, 'frames': ['⠂', '-', '–', '—', '–', '-']},
'pipe': {'interval': 100, 'frames': ['┤', '┘', '┴', '└', '├', '┌', '┬', '┐']},
'simpleDots': {'interval': 400, 'frames': ['. ', '.. ', '...', ' ']},
'simpleDotsScrolling': {'interval': 200, 'frames': ['. ', '.. ', '...', ' ..', ' .', ' ']},
'star': {'interval': 70, 'frames': ['✶', '✸', '✹', '✺', '✹', '✷']},
'star2': {'interval': 80, 'frames': ['+', 'x', '*']},
'flip': {'interval': 70, 'frames': ['_', '_', '_', '-', '`', '`', "'", '´', '-', '_', '_', '_']},
'hamburger': {'interval': 100, 'frames': ['☱', '☲', '☴']},
'growVertical': {'interval': 120, 'frames': ['▁', '▃', '▄', '▅', '▆', '▇', '▆', '▅', '▄', '▃']},
'growHorizontal': {'interval': 120, 'frames': ['▏', '▎', '▍', '▌', '▋', '▊', '▉', '▊', '▋', '▌', '▍', '▎']},
'balloon': {'interval': 140, 'frames': [' ', '.', 'o', 'O', '@', '*', ' ']},
'balloon2': {'interval': 120, 'frames': ['.', 'o', 'O', '°', 'O', 'o', '.']},
'noise': {'interval': 100, 'frames': ['▓', '▒', '░']},
'bounce': {'interval': 120, 'frames': ['⠁', '⠂', '⠄', '⠂']},
'boxBounce': {'interval': 120, 'frames': ['▖', '▘', '▝', '▗']},
'boxBounce2': {'interval': 100, 'frames': ['▌', '▀', '▐', '▄']},
'triangle': {'interval': 50, 'frames': ['◢', '◣', '◤', '◥']},
'arc': {'interval': 100, 'frames': ['◜', '◠', '◝', '◞', '◡', '◟']},
'circle': {'interval': 120, 'frames': ['◡', '⊙', '◠']},
'squareCorners': {'interval': 180, 'frames': ['◰', '◳', '◲', '◱']},
'circleQuarters': {'interval': 120, 'frames': ['◴', '◷', '◶', '◵']},
'circleHalves': {'interval': 50, 'frames': ['◐', '◓', '◑', '◒']},
'squish': {'interval': 100, 'frames': ['╫', '╪']},
'toggle': {'interval': 250, 'frames': ['⊶', '⊷']},
'toggle2': {'interval': 80, 'frames': ['▫', '▪']},
'toggle3': {'interval': 120, 'frames': ['□', '■']},
'toggle4': {'interval': 100, 'frames': ['■', '□', '▪', '▫']},
'toggle5': {'interval': 100, 'frames': ['▮', '▯']},
'toggle6': {'interval': 300, 'frames': ['ဝ', '၀']},
'toggle7': {'interval': 80, 'frames': ['⦾', '⦿']},
'toggle8': {'interval': 100, 'frames': ['◍', '◌']},
'toggle9': {'interval': 100, 'frames': ['◉', '◎']},
'toggle10': {'interval': 100, 'frames': ['㊂', '㊀', '㊁']},
'toggle11': {'interval': 50, 'frames': ['⧇', '⧆']},
'toggle12': {'interval': 120, 'frames': ['☗', '☖']},
'toggle13': {'interval': 80, 'frames': ['=', '*', '-']},
'arrow': {'interval': 100, 'frames': ['←', '↖', '↑', '↗', '→', '↘', '↓', '↙']},
'arrow2': {'interval': 80, 'frames': ['⬆️ ', '↗️ ', '➡️ ', '↘️ ', '⬇️ ', '↙️ ', '⬅️ ', '↖️ ']},
'arrow3': {'interval': 120, 'frames': ['▹▹▹▹▹', '▸▹▹▹▹', '▹▸▹▹▹', '▹▹▸▹▹', '▹▹▹▸▹', '▹▹▹▹▸']},
'bouncingBar': {
'interval': 80,
'frames': [
'[ ]',
'[= ]',
'[== ]',
'[=== ]',
'[ ===]',
'[ ==]',
'[ =]',
'[ ]',
'[ =]',
'[ ==]',
'[ ===]',
'[====]',
'[=== ]',
'[== ]',
'[= ]',
],
},
'bouncingBall': {
'interval': 80,
'frames': ['( ● )', '( ● )', '( ● )', '( ● )', '( ●)', '( ● )', '( ● )', '( ● )', '( ● )', '(● )'],
},
'smiley': {'interval': 200, 'frames': ['😄 ', '😝 ']},
'monkey': {'interval': 300, 'frames': ['🙈 ', '🙈 ', '🙉 ', '🙊 ']},
'hearts': {'interval': 100, 'frames': ['💛 ', '💙 ', '💜 ', '💚 ', '❤️ ']},
'clock': {'interval': 100, 'frames': ['🕛 ', '🕐 ', '🕑 ', '🕒 ', '🕓 ', '🕔 ', '🕕 ', '🕖 ', '🕗 ', '🕘 ', '🕙 ', '🕚 ']},
'earth': {'interval': 180, 'frames': ['🌍 ', '🌎 ', '🌏 ']},
'material': {
'interval': 17,
'frames': [
'█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'███████▁▁▁▁▁▁▁▁▁▁▁▁▁',
'████████▁▁▁▁▁▁▁▁▁▁▁▁',
'█████████▁▁▁▁▁▁▁▁▁▁▁',
'█████████▁▁▁▁▁▁▁▁▁▁▁',
'██████████▁▁▁▁▁▁▁▁▁▁',
'███████████▁▁▁▁▁▁▁▁▁',
'█████████████▁▁▁▁▁▁▁',
'██████████████▁▁▁▁▁▁',
'██████████████▁▁▁▁▁▁',
'▁██████████████▁▁▁▁▁',
'▁██████████████▁▁▁▁▁',
'▁██████████████▁▁▁▁▁',
'▁▁██████████████▁▁▁▁',
'▁▁▁██████████████▁▁▁',
'▁▁▁▁█████████████▁▁▁',
'▁▁▁▁██████████████▁▁',
'▁▁▁▁██████████████▁▁',
'▁▁▁▁▁██████████████▁',
'▁▁▁▁▁██████████████▁',
'▁▁▁▁▁██████████████▁',
'▁▁▁▁▁▁██████████████',
'▁▁▁▁▁▁██████████████',
'▁▁▁▁▁▁▁█████████████',
'▁▁▁▁▁▁▁█████████████',
'▁▁▁▁▁▁▁▁████████████',
'▁▁▁▁▁▁▁▁████████████',
'▁▁▁▁▁▁▁▁▁███████████',
'▁▁▁▁▁▁▁▁▁███████████',
'▁▁▁▁▁▁▁▁▁▁██████████',
'▁▁▁▁▁▁▁▁▁▁██████████',
'▁▁▁▁▁▁▁▁▁▁▁▁████████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁███████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████',
'█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████',
'██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███',
'██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███',
'███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███',
'████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██',
'█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█',
'█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█',
'██████▁▁▁▁▁▁▁▁▁▁▁▁▁█',
'████████▁▁▁▁▁▁▁▁▁▁▁▁',
'█████████▁▁▁▁▁▁▁▁▁▁▁',
'█████████▁▁▁▁▁▁▁▁▁▁▁',
'█████████▁▁▁▁▁▁▁▁▁▁▁',
'█████████▁▁▁▁▁▁▁▁▁▁▁',
'███████████▁▁▁▁▁▁▁▁▁',
'████████████▁▁▁▁▁▁▁▁',
'████████████▁▁▁▁▁▁▁▁',
'██████████████▁▁▁▁▁▁',
'██████████████▁▁▁▁▁▁',
'▁██████████████▁▁▁▁▁',
'▁██████████████▁▁▁▁▁',
'▁▁▁█████████████▁▁▁▁',
'▁▁▁▁▁████████████▁▁▁',
'▁▁▁▁▁████████████▁▁▁',
'▁▁▁▁▁▁███████████▁▁▁',
'▁▁▁▁▁▁▁▁█████████▁▁▁',
'▁▁▁▁▁▁▁▁█████████▁▁▁',
'▁▁▁▁▁▁▁▁▁█████████▁▁',
'▁▁▁▁▁▁▁▁▁█████████▁▁',
'▁▁▁▁▁▁▁▁▁▁█████████▁',
'▁▁▁▁▁▁▁▁▁▁▁████████▁',
'▁▁▁▁▁▁▁▁▁▁▁████████▁',
'▁▁▁▁▁▁▁▁▁▁▁▁███████▁',
'▁▁▁▁▁▁▁▁▁▁▁▁███████▁',
'▁▁▁▁▁▁▁▁▁▁▁▁▁███████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁███████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
'▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁',
],
},
'moon': {'interval': 80, 'frames': ['🌑 ', '🌒 ', '🌓 ', '🌔 ', '🌕 ', '🌖 ', '🌗 ', '🌘 ']},
'runner': {'interval': 140, 'frames': ['🚶 ', '🏃 ']},
'pong': {
'interval': 80,
'frames': [
'▐⠂ ▌',
'▐⠈ ▌',
'▐ ⠂ ▌',
'▐ ⠠ ▌',
'▐ ⡀ ▌',
'▐ ⠠ ▌',
'▐ ⠂ ▌',
'▐ ⠈ ▌',
'▐ ⠂ ▌',
'▐ ⠠ ▌',
'▐ ⡀ ▌',
'▐ ⠠ ▌',
'▐ ⠂ ▌',
'▐ ⠈ ▌',
'▐ ⠂▌',
'▐ ⠠▌',
'▐ ⡀▌',
'▐ ⠠ ▌',
'▐ ⠂ ▌',
'▐ ⠈ ▌',
'▐ ⠂ ▌',
'▐ ⠠ ▌',
'▐ ⡀ ▌',
'▐ ⠠ ▌',
'▐ ⠂ ▌',
'▐ ⠈ ▌',
'▐ ⠂ ▌',
'▐ ⠠ ▌',
'▐ ⡀ ▌',
'▐⠠ ▌',
],
},
'shark': {
'interval': 120,
'frames': [
'▐|\\____________▌',
'▐_|\\___________▌',
'▐__|\\__________▌',
'▐___|\\_________▌',
'▐____|\\________▌',
'▐_____|\\_______▌',
'▐______|\\______▌',
'▐_______|\\_____▌',
'▐________|\\____▌',
'▐_________|\\___▌',
'▐__________|\\__▌',
'▐___________|\\_▌',
'▐____________|\\▌',
'▐____________/|▌',
'▐___________/|_▌',
'▐__________/|__▌',
'▐_________/|___▌',
'▐________/|____▌',
'▐_______/|_____▌',
'▐______/|______▌',
'▐_____/|_______▌',
'▐____/|________▌',
'▐___/|_________▌',
'▐__/|__________▌',
'▐_/|___________▌',
'▐/|____________▌',
],
},
'dqpb': {'interval': 100, 'frames': ['d', 'q', 'p', 'b']},
'weather': {
'interval': 100,
'frames': ['☀️ ', '☀️ ', '☀️ ', '🌤 ', '⛅️ ', '🌥 ', '☁️ ', '🌧 ', '🌨 ', '🌧 ', '🌨 ', '🌧 ', '🌨 ', '⛈ ', '🌨 ', '🌧 ', '🌨 ', '☁️ ', '🌥 ', '⛅️ ', '🌤 ', '☀️ ', '☀️ '],
},
'christmas': {'interval': 400, 'frames': ['🌲', '🎄']},
'grenade': {'interval': 80, 'frames': ['، ', '′ ', ' ´ ', ' ‾ ', ' ⸌', ' ⸊', ' |', ' ⁎', ' ⁕', ' ෴ ', ' ⁓', ' ', ' ', ' ']},
'point': {'interval': 125, 'frames': ['∙∙∙', '●∙∙', '∙●∙', '∙∙●', '∙∙∙']},
'layer': {'interval': 150, 'frames': ['-', '=', '≡']},
'betaWave': {'interval': 80, 'frames': ['ρββββββ', 'βρβββββ', 'ββρββββ', 'βββρβββ', 'ββββρββ', 'βββββρβ', 'ββββββρ']},
'fingerDance': {'interval': 160, 'frames': ['🤘 ', '🤟 ', '🖖 ', '✋ ', '🤚 ', '👆 ']},
'fistBump': {
'interval': 80,
'frames': [
'🤜\u3000\u3000\u3000\u3000🤛 ',
'🤜\u3000\u3000\u3000\u3000🤛 ',
'🤜\u3000\u3000\u3000\u3000🤛 ',
'\u3000🤜\u3000\u3000🤛\u3000 ',
'\u3000\u3000🤜🤛\u3000\u3000 ',
'\u3000🤜✨🤛\u3000\u3000 ',
'🤜\u3000✨\u3000🤛\u3000 ',
],
},
'soccerHeader': {
'interval': 80,
'frames': [
' 🧑⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
'🧑 ⚽️ 🧑 ',
],
},
'mindblown': {'interval': 160, 'frames': ['😐 ', '😐 ', '😮 ', '😮 ', '😦 ', '😦 ', '😧 ', '😧 ', '🤯 ', '💥 ', '✨ ', '\u3000 ', '\u3000 ', '\u3000 ']},
'speaker': {'interval': 160, 'frames': ['🔈 ', '🔉 ', '🔊 ', '🔉 ']},
'orangePulse': {'interval': 100, 'frames': ['🔸 ', '🔶 ', '🟠 ', '🟠 ', '🔶 ']},
'bluePulse': {'interval': 100, 'frames': ['🔹 ', '🔷 ', '🔵 ', '🔵 ', '🔷 ']},
'orangeBluePulse': {'interval': 100, 'frames': ['🔸 ', '🔶 ', '🟠 ', '🟠 ', '🔶 ', '🔹 ', '🔷 ', '🔵 ', '🔵 ', '🔷 ']},
'timeTravel': {'interval': 100, 'frames': ['🕛 ', '🕚 ', '🕙 ', '🕘 ', '🕗 ', '🕖 ', '🕕 ', '🕔 ', '🕓 ', '🕒 ', '🕑 ', '🕐 ']},
'aesthetic': {'interval': 80, 'frames': ['▰▱▱▱▱▱▱', '▰▰▱▱▱▱▱', '▰▰▰▱▱▱▱', '▰▰▰▰▱▱▱', '▰▰▰▰▰▱▱', '▰▰▰▰▰▰▱', '▰▰▰▰▰▰▰', '▰▱▱▱▱▱▱']},
} # }}}
class Spinner:
def __init__(self, name: str = 'dots'):
definition = spinners[name]
self.interval = definition['interval'] / 1000
self.frames = definition['frames']
self.current_frame = -1
self.last_change_at = -self.interval
def __call__(self) -> str:
now = monotonic()
if now - self.last_change_at >= self.interval:
self.last_change_at = now
self.current_frame = (self.current_frame + 1) % len(self.frames)
return self.frames[self.current_frame]
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os
import sys
from collections.abc import Sequence
from contextlib import suppress
from typing import TYPE_CHECKING, Optional, cast
from kitty.types import run_once
from .operations import raw_mode, set_cursor_visible
if TYPE_CHECKING:
from kitty.options.types import Options
def get_key_press(allowed: str, default: str) -> str:
response = default
with raw_mode():
print(set_cursor_visible(False), end='', flush=True)
try:
while True:
q = sys.stdin.buffer.read(1)
if q:
if q in b'\x1b\x03':
break
with suppress(Exception):
response = q.decode('utf-8').lower()
if response in allowed:
break
except (KeyboardInterrupt, EOFError):
pass
finally:
print(set_cursor_visible(True), end='', flush=True)
return response
def format_number(val: float, max_num_of_decimals: int = 2) -> str:
ans = str(val)
pos = ans.find('.')
if pos > -1:
ans = ans[: pos + max_num_of_decimals + 1]
return ans.rstrip('0').rstrip('.')
def human_size(size: int, sep: str = ' ', max_num_of_decimals: int = 2, unit_list: tuple[str, ...] = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB')) -> str:
"""Convert a size in bytes into a human readable form"""
if size < 2:
return f'{size}{sep}{unit_list[0]}'
from math import log
exponent = min(int(log(size, 1024)), len(unit_list) - 1)
return format_number(size / 1024**exponent, max_num_of_decimals) + sep + unit_list[exponent]
def kitty_opts() -> 'Options':
from kitty.fast_data_types import get_options, set_options
try:
ans = cast(Optional['Options'], get_options())
except RuntimeError:
ans = None
if ans is None:
from kitty.cli import create_default_opts
from kitty.utils import suppress_error_logging
with suppress_error_logging():
ans = create_default_opts()
set_options(ans)
return ans
def set_kitty_opts(paths: Sequence[str], overrides: Sequence[str] = ()) -> 'Options':
from kitty.config import load_config
from kitty.fast_data_types import set_options
from kitty.utils import suppress_error_logging
with suppress_error_logging():
opts = load_config(*paths, overrides=overrides or None)
set_options(opts)
return opts
def report_error(msg: str = '', return_code: int = 1, print_exc: bool = False) -> None:
"Report an error also sending the overlay ready message to ensure kitten is visible"
from .operations import overlay_ready
print(end=overlay_ready())
if msg:
print(msg, file=sys.stderr)
if print_exc:
cls, e, tb = sys.exc_info()
if e and not isinstance(e, (SystemExit, KeyboardInterrupt)):
import traceback
traceback.print_exc()
with suppress(KeyboardInterrupt, EOFError):
input('Press Enter to quit')
raise SystemExit(return_code)
def report_unhandled_error(msg: str = '') -> None:
"Report an unhandled exception with the overlay ready message"
return report_error(msg, print_exc=True)
@run_once
def running_in_tmux() -> str:
socket = os.environ.get('TMUX')
if not socket:
return ''
parts = socket.split(',')
if len(parts) < 2:
return ''
try:
if not os.access(parts[0], os.R_OK | os.W_OK):
return ''
except OSError:
return ''
from kitty.child import cmdline_of_pid
c = cmdline_of_pid(int(parts[1]))
if not c:
return ''
exe = os.path.basename(c[0])
if exe.lower() == 'tmux':
return exe
return ''