chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
1134 files changed
+433629
No files matched your search
Binary file not shown.
Binary file not shown.
Binary file not shown.
Generated
+5237
File diff suppressed because it is too large.
Load diff
Binary file not shown.
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
|
||||
is_ci = os.environ.get('CI') == 'true'
|
||||
|
||||
|
||||
def in_isolated_test_env() -> bool:
|
||||
"""Whether HOME and the XDG dirs point at the throwaway directory created by env_for_python_tests()."""
|
||||
return 'KT_ORIGINAL_HOME' in os.environ
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2025, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import os
|
||||
import select
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from kitty.constants import kitten_exe, kitty_exe
|
||||
from kitty.shm import SharedMemory
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class Atexit(BaseTest):
|
||||
def setUp(self):
|
||||
self.tdir = tempfile.mkdtemp()
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.tdir)
|
||||
|
||||
def test_go_atexit(self):
|
||||
cp = subprocess.run([kitten_exe(), '__atexit__', 'test'], cwd=self.tdir)
|
||||
self.ae(cp.returncode, 0)
|
||||
self.assertFalse(os.listdir(self.tdir))
|
||||
|
||||
def test_atexit(self):
|
||||
|
||||
def r(action='close'):
|
||||
p = subprocess.Popen(
|
||||
[
|
||||
kitty_exe(),
|
||||
'+runpy',
|
||||
f"""\
|
||||
import subprocess
|
||||
p = subprocess.Popen(['{kitten_exe()}', '__atexit__'])
|
||||
print(p.pid, flush=True)
|
||||
raise SystemExit(p.wait())
|
||||
""",
|
||||
],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
)
|
||||
readers = [p.stdout.fileno()]
|
||||
|
||||
def read():
|
||||
r, _, _ = select.select(readers, [], [], 10)
|
||||
if not r:
|
||||
raise TimeoutError('Timed out waiting for read from child')
|
||||
return p.stdout.readline().rstrip().decode()
|
||||
|
||||
atexit_pid = int(read())
|
||||
for i in range(2):
|
||||
with open(os.path.join(self.tdir, str(i)), 'w') as f:
|
||||
p.stdin.write(f'unlink {f.name}\n'.encode())
|
||||
p.stdin.flush()
|
||||
select.select(readers, [], [], 10)
|
||||
self.ae(read(), str(i + 1))
|
||||
sdir = os.path.join(self.tdir, 'd')
|
||||
os.mkdir(sdir)
|
||||
p.stdin.write(f'rmtree {sdir}\n'.encode())
|
||||
p.stdin.flush()
|
||||
open(os.path.join(sdir, 'f'), 'w').close()
|
||||
select.select(readers, [], [], 10)
|
||||
self.ae(read(), str(i + 2))
|
||||
shm = SharedMemory(size=64)
|
||||
shm.write(b'1' * 64)
|
||||
shm.flush()
|
||||
p.stdin.write(f'shm_unlink {shm.name}\n'.encode())
|
||||
p.stdin.flush()
|
||||
self.ae(read(), str(i + 3))
|
||||
|
||||
self.assertTrue(os.listdir(self.tdir))
|
||||
shm2 = SharedMemory(shm.name)
|
||||
self.ae(shm2.read()[:64], b'1' * 64)
|
||||
|
||||
# Ensure child is ignoring signals
|
||||
os.kill(atexit_pid, signal.SIGINT)
|
||||
os.kill(atexit_pid, signal.SIGTERM)
|
||||
if action == 'close':
|
||||
p.stdin.close()
|
||||
elif action == 'terminate':
|
||||
p.terminate()
|
||||
else:
|
||||
p.kill()
|
||||
p.wait(10)
|
||||
if action != 'close':
|
||||
p.stdin.close()
|
||||
select.select(readers, [], [], 10)
|
||||
self.assertFalse(read())
|
||||
p.stdout.close()
|
||||
self.assertFalse(os.listdir(self.tdir))
|
||||
try:
|
||||
os.waitpid(atexit_pid, 0)
|
||||
except ChildProcessError:
|
||||
pass
|
||||
self.assertRaises(FileNotFoundError, lambda: SharedMemory(shm.name))
|
||||
|
||||
r('close')
|
||||
r('terminate')
|
||||
r('kill')
|
||||
@@ -0,0 +1,608 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import fcntl
|
||||
import io
|
||||
import os
|
||||
import select
|
||||
import shlex
|
||||
import shutil
|
||||
import signal
|
||||
import struct
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
from contextlib import contextmanager, suppress
|
||||
from functools import wraps
|
||||
from unittest import TestCase
|
||||
|
||||
from kitty.config import finalize_keys, finalize_mouse_mappings
|
||||
from kitty.fast_data_types import TEXT_SIZE_CODE, Cursor, HistoryBuf, LineBuf, Screen, get_options, monotonic, set_options
|
||||
from kitty.options.parse import merge_result_dicts
|
||||
from kitty.options.types import Options, defaults
|
||||
from kitty.options.utils import mouse_wheel_buttons
|
||||
from kitty.rgb import to_color
|
||||
from kitty.types import MouseEvent
|
||||
from kitty.window import da1, decode_cmdline, process_remote_print, process_title_from_child
|
||||
|
||||
from . import is_ci
|
||||
|
||||
|
||||
def parse_bytes(screen, data, dump_callback=None):
|
||||
data = memoryview(data)
|
||||
while data:
|
||||
dest = screen.test_create_write_buffer()
|
||||
s = screen.test_commit_write_buffer(data, dest)
|
||||
data = data[s:]
|
||||
screen.test_parse_written_data(dump_callback)
|
||||
|
||||
|
||||
def draw_multicell(
|
||||
screen: Screen, text: str, width: int = 0, scale: int = 1, subscale_n: int = 0, subscale_d: int = 0, vertical_align: int = 0, horizontal_align: int = 0
|
||||
) -> None:
|
||||
cmd = f'\x1b]{TEXT_SIZE_CODE};w={width}:s={scale}:n={subscale_n}:d={subscale_d}:v={vertical_align}:h={horizontal_align};{text}\a'
|
||||
parse_bytes(screen, cmd.encode())
|
||||
|
||||
|
||||
class Callbacks:
|
||||
def __init__(self, pty=None) -> None:
|
||||
self.clear()
|
||||
self.pty = pty
|
||||
self.ftc = None
|
||||
self.set_pointer_shape = lambda data: None
|
||||
self.last_cmd_at = 0
|
||||
self.last_cmd_cmdline = ''
|
||||
self.last_cmd_exit_status = sys.maxsize
|
||||
|
||||
def write(self, data) -> None:
|
||||
self.wtcbuf += bytes(data)
|
||||
|
||||
def notify_child_of_resize(self):
|
||||
self.num_of_resize_events += 1
|
||||
|
||||
def on_reset(self, is_hard_reset: bool = True) -> None:
|
||||
if self.pty is not None:
|
||||
self.pty.reset_termios_state()
|
||||
|
||||
def color_control(self, code, data) -> None:
|
||||
from kitty.fast_data_types import base64_decode
|
||||
from kitty.window import color_control
|
||||
|
||||
response = color_control(self.color_profile, code, data)
|
||||
if response:
|
||||
|
||||
def p(x):
|
||||
if '@' in x:
|
||||
return (to_color(x.partition('@')[0]), int(255 * float(x.partition('@')[2])))
|
||||
ans = to_color(x)
|
||||
if ans is None:
|
||||
ans = x
|
||||
return ans
|
||||
|
||||
parts = {}
|
||||
for x in response.split(';')[1:]:
|
||||
k, _, v = x.partition('=')
|
||||
if k == 'unknown':
|
||||
# unknown field names are base64 encoded, collect the decoded names in a list
|
||||
parts.setdefault('unknown', []).append(base64_decode(v).decode('ascii'))
|
||||
else:
|
||||
parts[k] = p(v)
|
||||
self.color_control_responses.append(parts)
|
||||
|
||||
def title_changed(self, data, is_base64=False) -> None:
|
||||
self.titlebuf.append(process_title_from_child(data, is_base64, ''))
|
||||
|
||||
def osc_context(self, data):
|
||||
pass
|
||||
|
||||
def program_status_report(self, data):
|
||||
self.program_status_reports.append(str(data, 'utf-8'))
|
||||
|
||||
def icon_changed(self, data) -> None:
|
||||
self.iconbuf += str(data, 'utf-8')
|
||||
|
||||
def set_dynamic_color(self, code, data='') -> None:
|
||||
if code == 22:
|
||||
self.set_pointer_shape(data)
|
||||
else:
|
||||
self.colorbuf += str(data or b'', 'utf-8')
|
||||
|
||||
def set_color_table_color(self, code, data='') -> None:
|
||||
self.ctbuf += ''
|
||||
|
||||
def color_profile_popped(self, x) -> None:
|
||||
pass
|
||||
|
||||
def cmd_output_marking(self, is_start: bool | None, data: str = '') -> None:
|
||||
if is_start:
|
||||
self.last_cmd_at = monotonic()
|
||||
self.last_cmd_cmdline = decode_cmdline(data) if data else data
|
||||
else:
|
||||
if self.last_cmd_at != 0:
|
||||
self.last_cmd_at = 0
|
||||
with suppress(Exception):
|
||||
self.last_cmd_exit_status = int(data)
|
||||
|
||||
def request_capabilities(self, q) -> None:
|
||||
from kitty.terminfo import get_capabilities
|
||||
|
||||
for c in get_capabilities(q, None):
|
||||
self.write(c.encode('ascii'))
|
||||
|
||||
def desktop_notify(self, osc_code: int, raw_data: memoryview) -> None:
|
||||
self.notifications.append((osc_code, str(raw_data, 'utf-8')))
|
||||
|
||||
def open_url(self, url: str, hyperlink_id: int) -> None:
|
||||
self.open_urls.append((url, hyperlink_id))
|
||||
|
||||
def clipboard_control(self, data: memoryview, is_partial: bool = False) -> None:
|
||||
self.cc_buf.append((str(data, 'utf-8'), is_partial))
|
||||
|
||||
def clear(self) -> None:
|
||||
self.wtcbuf = b''
|
||||
self.iconbuf = self.colorbuf = self.ctbuf = ''
|
||||
self.titlebuf = []
|
||||
self.printbuf = []
|
||||
self.color_control_responses = []
|
||||
self.notifications = []
|
||||
self.program_status_reports = []
|
||||
self.open_urls = []
|
||||
self.cc_buf = []
|
||||
self.bell_count = 0
|
||||
self.clone_cmds = []
|
||||
self.current_clone_data = ''
|
||||
self.last_cmd_exit_status = sys.maxsize
|
||||
self.last_cmd_cmdline = ''
|
||||
self.last_cmd_at = 0
|
||||
self.num_of_resize_events = 0
|
||||
self.da1 = []
|
||||
|
||||
def on_bell(self) -> None:
|
||||
self.bell_count += 1
|
||||
|
||||
def on_da1(self) -> None:
|
||||
opts = None
|
||||
with suppress(RuntimeError):
|
||||
opts = get_options()
|
||||
if opts is None:
|
||||
opts = defaults
|
||||
payload = da1(opts)
|
||||
self.da1.append(payload)
|
||||
if self.pty and self.pty.needs_da1:
|
||||
self.pty.send_da1_response(payload)
|
||||
|
||||
def on_activity_since_last_focus(self) -> None:
|
||||
pass
|
||||
|
||||
def finish_scroll_animation(self) -> None:
|
||||
pass
|
||||
|
||||
def on_mouse_event(self, event):
|
||||
steps = 1
|
||||
if event['button'] in mouse_wheel_buttons: # repeat_count is the number of wheel steps
|
||||
steps, event['repeat_count'] = event['repeat_count'], 1
|
||||
ev = MouseEvent(**event)
|
||||
opts = get_options()
|
||||
action_def = opts.mousemap.get(ev)
|
||||
if not action_def:
|
||||
return False
|
||||
self.current_mouse_button = ev.button
|
||||
for _ in range(steps):
|
||||
for action in opts.alias_map.resolve_aliases(action_def, 'mouse_map'):
|
||||
getattr(self, action.func)(*action.args)
|
||||
self.current_mouse_button = 0
|
||||
return True
|
||||
|
||||
def handle_remote_print(self, msg):
|
||||
text = process_remote_print(msg)
|
||||
self.printbuf.append(text)
|
||||
|
||||
def handle_remote_cmd(self, msg):
|
||||
pass
|
||||
|
||||
def handle_remote_clone(self, msg):
|
||||
msg = str(msg, 'utf-8')
|
||||
if not msg:
|
||||
if self.current_clone_data:
|
||||
cdata, self.current_clone_data = self.current_clone_data, ''
|
||||
from kitty.launch import CloneCmd
|
||||
|
||||
self.clone_cmds.append(CloneCmd(cdata))
|
||||
self.current_clone_data = ''
|
||||
return
|
||||
num, rest = msg.split(':', 1)
|
||||
if num == '0' or len(self.current_clone_data) > 1024 * 1024:
|
||||
self.current_clone_data = ''
|
||||
self.current_clone_data += rest
|
||||
|
||||
def handle_remote_ssh(self, msg):
|
||||
from kittens.ssh.utils import get_ssh_data
|
||||
|
||||
if self.pty:
|
||||
for line in get_ssh_data(msg, 'testing'):
|
||||
self.pty.write_to_child(line)
|
||||
|
||||
def handle_remote_echo(self, msg):
|
||||
from base64 import standard_b64decode
|
||||
|
||||
if self.pty:
|
||||
data = standard_b64decode(msg)
|
||||
self.pty.write_to_child(data)
|
||||
|
||||
def file_transmission(self, data):
|
||||
if self.ftc:
|
||||
self.ftc.handle_serialized_command(data)
|
||||
|
||||
|
||||
def filled_line_buf(ynum=5, xnum=5, cursor=Cursor()):
|
||||
ans = LineBuf(ynum, xnum)
|
||||
cursor.x = 0
|
||||
for i in range(ynum):
|
||||
t = (f'{i}') * xnum
|
||||
ans.line(i).set_text(t, 0, xnum, cursor)
|
||||
return ans
|
||||
|
||||
|
||||
def filled_cursor():
|
||||
ans = Cursor()
|
||||
ans.bold = ans.italic = ans.reverse = ans.strikethrough = ans.dim = True
|
||||
ans.fg = 0x101
|
||||
ans.bg = 0x201
|
||||
ans.decoration_fg = 0x301
|
||||
return ans
|
||||
|
||||
|
||||
def filled_history_buf(ynum=5, xnum=5, cursor=Cursor()):
|
||||
lb = filled_line_buf(ynum, xnum, cursor)
|
||||
ans = HistoryBuf(ynum, xnum)
|
||||
for i in range(ynum):
|
||||
ans.push(lb.line(i))
|
||||
return ans
|
||||
|
||||
|
||||
max_attempts = 4 if is_ci else 2
|
||||
sleep_duration = 4 if is_ci else 2
|
||||
|
||||
|
||||
def retry_on_failure(max_attempts=max_attempts, sleep_duration=sleep_duration):
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
for attempt in range(max_attempts):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Exception:
|
||||
if attempt < max_attempts - 1: # Don't sleep on the last attempt
|
||||
time.sleep(sleep_duration)
|
||||
print(f'{func.__name__} failed, retrying in {sleep_duration} seconds', file=sys.stderr)
|
||||
else:
|
||||
raise # Re-raise the last exception
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class BaseTest(TestCase):
|
||||
ae = TestCase.assertEqual
|
||||
maxDiff = 2048
|
||||
is_ci = is_ci
|
||||
|
||||
def rmtree_ignoring_errors(self, tdir):
|
||||
try:
|
||||
shutil.rmtree(tdir)
|
||||
except FileNotFoundError as err:
|
||||
print('Failed to delete the directory:', tdir, 'with error:', err, file=sys.stderr)
|
||||
|
||||
def tearDown(self):
|
||||
set_options(None)
|
||||
|
||||
def set_options(self, options=None):
|
||||
final_options = {'scrollback_pager_history_size': 1024, 'click_interval': 0.5}
|
||||
if options:
|
||||
final_options.update(options)
|
||||
options = Options(merge_result_dicts(defaults._asdict(), final_options))
|
||||
finalize_keys(options, {})
|
||||
finalize_mouse_mappings(options, {})
|
||||
set_options(options)
|
||||
return options
|
||||
|
||||
def cmd_to_run_python_code(self, code):
|
||||
from kitty.constants import kitty_exe
|
||||
|
||||
return [kitty_exe(), '+runpy', code]
|
||||
|
||||
def create_screen(self, cols=5, lines=5, scrollback=5, cell_width=10, cell_height=20, options=None):
|
||||
self.set_options(options)
|
||||
c = Callbacks()
|
||||
s = Screen(c, lines, cols, scrollback, cell_width, cell_height, 0, c)
|
||||
c.color_profile = s.color_profile
|
||||
return s
|
||||
|
||||
def create_pty(
|
||||
self,
|
||||
argv=None,
|
||||
cols=80,
|
||||
lines=100,
|
||||
scrollback=100,
|
||||
cell_width=10,
|
||||
cell_height=20,
|
||||
options=None,
|
||||
cwd=None,
|
||||
env=None,
|
||||
stdin_fd=None,
|
||||
needs_da1=False,
|
||||
):
|
||||
self.set_options(options)
|
||||
return PTY(
|
||||
argv,
|
||||
lines,
|
||||
cols,
|
||||
scrollback,
|
||||
cell_width,
|
||||
cell_height,
|
||||
cwd,
|
||||
env,
|
||||
stdin_fd=stdin_fd,
|
||||
needs_da1=needs_da1,
|
||||
)
|
||||
|
||||
def assertEqualAttributes(self, c1, c2):
|
||||
x1, y1, c1.x, c1.y = c1.x, c1.y, 0, 0
|
||||
x2, y2, c2.x, c2.y = c2.x, c2.y, 0, 0
|
||||
try:
|
||||
self.assertEqual(c1, c2)
|
||||
finally:
|
||||
c1.x, c1.y, c2.x, c2.y = x1, y1, x2, y2
|
||||
|
||||
|
||||
debug_stdout = debug_stderr = -1
|
||||
|
||||
|
||||
@contextmanager
|
||||
def forwardable_stdio():
|
||||
global debug_stderr, debug_stdout
|
||||
debug_stdout = fd = os.dup(sys.stdout.fileno())
|
||||
os.set_inheritable(fd, True)
|
||||
debug_stderr = fd = os.dup(sys.stderr.fileno())
|
||||
os.set_inheritable(fd, True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.close(debug_stderr)
|
||||
os.close(debug_stdout)
|
||||
debug_stderr = debug_stdout = -1
|
||||
|
||||
|
||||
class PTY:
|
||||
def __init__(
|
||||
self,
|
||||
argv=None,
|
||||
rows=25,
|
||||
columns=80,
|
||||
scrollback=100,
|
||||
cell_width=10,
|
||||
cell_height=20,
|
||||
cwd=None,
|
||||
env=None,
|
||||
stdin_fd=None,
|
||||
needs_da1=True,
|
||||
window_id=0,
|
||||
log_data_flow=False,
|
||||
):
|
||||
self.log_data_flow = log_data_flow
|
||||
if isinstance(argv, str):
|
||||
argv = shlex.split(argv)
|
||||
self.write_buf = b''
|
||||
self.child_pid = 0
|
||||
self.child_waited_for = False
|
||||
self.cell_width = cell_width
|
||||
self.cell_height = cell_height
|
||||
if argv is None:
|
||||
from kitty.child import openpty
|
||||
|
||||
self.master_fd, self.slave_fd = openpty()
|
||||
self.initial_termios_state = termios.tcgetattr(self.master_fd)
|
||||
else:
|
||||
self.child_pid, self.master_fd = self.spawn_child(argv, rows, columns, cwd, env, stdin_fd)
|
||||
if stdin_fd is not None:
|
||||
os.close(stdin_fd)
|
||||
os.set_blocking(self.master_fd, False)
|
||||
self.set_window_size(rows=rows, columns=columns)
|
||||
self.needs_da1 = needs_da1
|
||||
self.callbacks = Callbacks(self)
|
||||
self.screen = Screen(self.callbacks, rows, columns, scrollback, cell_width, cell_height, window_id, self.callbacks)
|
||||
self.received_bytes = b''
|
||||
|
||||
def spawn_child(self, argv, rows, columns, cwd, env, stdin_fd):
|
||||
# Do not use pty.fork() as that runs Python code in the forked child
|
||||
# before exec(), and macOS (since Tahoe 26.2) sometimes kills processes
|
||||
# that do anything non-trivial between fork() and exec() with SIGKILL.
|
||||
# spawn() does all the child setup in C using only async-signal-safe
|
||||
# functions. The window size is set before spawning so that the child
|
||||
# sees the correct size from the start.
|
||||
from kitty.child import openpty
|
||||
from kitty.constants import kitten_exe
|
||||
from kitty.fast_data_types import spawn
|
||||
|
||||
master, slave = openpty()
|
||||
try:
|
||||
s = struct.pack('HHHH', rows, columns, columns * self.cell_width, rows * self.cell_height)
|
||||
fcntl.ioctl(master, termios.TIOCSWINSZ, s)
|
||||
env = dict(os.environ if env is None else env)
|
||||
pass_fds: tuple[int, ...] = ()
|
||||
if debug_stdout > -1:
|
||||
env['KITTY_STDIO_FORWARDED'] = str(debug_stdout)
|
||||
pass_fds = (debug_stdout, debug_stderr)
|
||||
ready_read_fd, ready_write_fd = os.pipe()
|
||||
try:
|
||||
pid = spawn(
|
||||
argv[0],
|
||||
cwd or os.getcwd(),
|
||||
tuple(argv),
|
||||
tuple(f'{k}={v}' for k, v in env.items()),
|
||||
master,
|
||||
slave,
|
||||
-1 if stdin_fd is None else stdin_fd,
|
||||
-1,
|
||||
ready_read_fd,
|
||||
ready_write_fd,
|
||||
(),
|
||||
kitten_exe(),
|
||||
False,
|
||||
pass_fds,
|
||||
)
|
||||
finally:
|
||||
os.close(ready_read_fd)
|
||||
# Closing the write end tells the child it can exec
|
||||
os.close(ready_write_fd)
|
||||
except BaseException:
|
||||
os.close(master)
|
||||
raise
|
||||
finally:
|
||||
os.close(slave)
|
||||
return pid, master
|
||||
|
||||
def reset_termios_state(self):
|
||||
if s := getattr(self, 'initial_termios_state', None):
|
||||
termios.tcsetattr(self.master_fd, termios.TCSANOW, s)
|
||||
|
||||
def turn_off_echo(self):
|
||||
s = termios.tcgetattr(self.master_fd)
|
||||
s[3] &= ~termios.ECHO
|
||||
termios.tcsetattr(self.master_fd, termios.TCSANOW, s)
|
||||
|
||||
def is_echo_on(self):
|
||||
s = termios.tcgetattr(self.master_fd)
|
||||
return True if s[3] & termios.ECHO else False
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
self.__del__()
|
||||
|
||||
def __del__(self):
|
||||
if hasattr(self, 'master_fd'):
|
||||
os.close(self.master_fd)
|
||||
del self.master_fd
|
||||
if hasattr(self, 'slave_fd'):
|
||||
os.close(self.slave_fd)
|
||||
del self.slave_fd
|
||||
if getattr(self, 'child_pid', 0) > 0 and not self.child_waited_for:
|
||||
st = time.monotonic()
|
||||
while time.monotonic() - st < 2:
|
||||
pid, ec = os.waitpid(self.child_pid, os.WNOHANG)
|
||||
if pid == self.child_pid:
|
||||
self.child_waited_for = True
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if not self.child_waited_for:
|
||||
os.kill(self.child_pid, signal.SIGKILL)
|
||||
os.waitpid(self.child_pid, 0)
|
||||
self.child_waited_for = True
|
||||
|
||||
def write_to_child(self, data, flush=False):
|
||||
if isinstance(data, str):
|
||||
data = data.encode('utf-8')
|
||||
if self.log_data_flow:
|
||||
print('t -> c:', bytes(data))
|
||||
self.write_buf += data
|
||||
if flush:
|
||||
self.process_input_from_child(0)
|
||||
|
||||
def send_da1_response(self, data: str) -> None:
|
||||
self.write_to_child('\x1b[' + data, flush=False) # ]]]]]]
|
||||
|
||||
def send_cmd_to_child(self, cmd, flush=False):
|
||||
self.callbacks.last_cmd_exit_status = sys.maxsize
|
||||
self.last_cmd = cmd
|
||||
self.write_to_child(cmd + '\r', flush=flush)
|
||||
|
||||
def process_input_from_child(self, timeout=10):
|
||||
rd, wd, _ = select.select([self.master_fd], [self.master_fd] if self.write_buf else [], [], max(0, timeout))
|
||||
if wd:
|
||||
n = os.write(self.master_fd, self.write_buf)
|
||||
self.write_buf = self.write_buf[n:]
|
||||
|
||||
bytes_read = 0
|
||||
if rd:
|
||||
data = os.read(self.master_fd, io.DEFAULT_BUFFER_SIZE)
|
||||
bytes_read += len(data)
|
||||
self.received_bytes += data
|
||||
if self.log_data_flow:
|
||||
print('c -> t:', data)
|
||||
parse_bytes(self.screen, data)
|
||||
return bytes_read
|
||||
|
||||
def wait_till(self, q, timeout=10, timeout_msg=None):
|
||||
end_time = time.monotonic() + timeout
|
||||
while not q() and time.monotonic() <= end_time:
|
||||
try:
|
||||
self.process_input_from_child(timeout=end_time - time.monotonic())
|
||||
except OSError as e:
|
||||
if not q():
|
||||
raise Exception(f'Failed to read from pty with error: {e}. {self.screen_contents_for_error()}') from e
|
||||
return
|
||||
if not q():
|
||||
msg = 'The condition was not met'
|
||||
if timeout_msg is not None:
|
||||
msg = timeout_msg()
|
||||
if not msg.endswith('\n'):
|
||||
msg += '. '
|
||||
raise TimeoutError(f'Timed out after {timeout} seconds: {msg}{self.screen_contents_for_error()}')
|
||||
|
||||
def wait_till_child_exits(self, timeout=30 if BaseTest.is_ci else 10, require_exit_code=None):
|
||||
end_time = time.monotonic() + timeout
|
||||
while time.monotonic() <= end_time:
|
||||
si_pid, status = os.waitpid(self.child_pid, os.WNOHANG)
|
||||
if si_pid == self.child_pid:
|
||||
# The child has been reaped, calling waitpid() on it again
|
||||
# would fail with ECHILD, so handle every kind of termination
|
||||
# here, not just a normal exit.
|
||||
self.child_waited_for = True
|
||||
with suppress(OSError):
|
||||
while self.process_input_from_child(timeout=0):
|
||||
pass
|
||||
if os.WIFSIGNALED(status):
|
||||
sig = os.WTERMSIG(status)
|
||||
try:
|
||||
signame = signal.Signals(sig).name
|
||||
except ValueError:
|
||||
signame = str(sig)
|
||||
raise AssertionError(f'Child was killed by signal: {signame}. {self.screen_contents_for_error()}')
|
||||
ec = os.waitstatus_to_exitcode(status)
|
||||
if require_exit_code is not None and ec != require_exit_code:
|
||||
raise AssertionError(f'Child exited with exit status: {status} code: {ec} != {require_exit_code}. {self.screen_contents_for_error()}')
|
||||
return status
|
||||
with suppress(OSError):
|
||||
self.process_input_from_child(timeout=0.02)
|
||||
raise AssertionError(f'Child did not exit in {timeout} seconds. {self.screen_contents_for_error()}')
|
||||
|
||||
def set_window_size(self, rows=25, columns=80, send_signal=True):
|
||||
if hasattr(self, 'screen'):
|
||||
self.screen.resize(rows, columns)
|
||||
if send_signal:
|
||||
x_pixels = columns * self.cell_width
|
||||
y_pixels = rows * self.cell_height
|
||||
s = struct.pack('HHHH', rows, columns, x_pixels, y_pixels)
|
||||
fcntl.ioctl(self.master_fd, termios.TIOCSWINSZ, s)
|
||||
|
||||
def screen_contents_for_error(self):
|
||||
from kitty.window import as_text
|
||||
|
||||
ans = as_text(self.screen, add_history=True, as_ansi=False)
|
||||
return f'Screen contents as repr:\n{ans!r}\nScreen contents:\n{ans.rstrip()}'
|
||||
|
||||
def screen_contents(self):
|
||||
lines = []
|
||||
for i in range(self.screen.lines):
|
||||
x = str(self.screen.line(i))
|
||||
if x:
|
||||
lines.append(x)
|
||||
return '\n'.join(lines)
|
||||
|
||||
def last_cmd_output(self, as_ansi=False, add_wrap_markers=False):
|
||||
from kitty.window import cmd_output
|
||||
|
||||
return cmd_output(self.screen, as_ansi=as_ansi, add_wrap_markers=add_wrap_markers)
|
||||
@@ -0,0 +1,244 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import unittest
|
||||
from functools import partial
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestBuild(BaseTest):
|
||||
def test_exe(self) -> None:
|
||||
from kitty.constants import kitten_exe, kitty_exe, slangc, str_version
|
||||
|
||||
exe = kitty_exe()
|
||||
self.assertTrue(os.access(exe, os.X_OK))
|
||||
self.assertTrue(os.path.isfile(exe))
|
||||
self.assertIn('kitty', os.path.basename(exe))
|
||||
exe = kitten_exe()
|
||||
self.assertTrue(os.access(exe, os.X_OK))
|
||||
self.assertTrue(os.path.isfile(exe))
|
||||
self.assertIn(str_version, subprocess.check_output([exe, '--version']).decode())
|
||||
self.assertTrue(shutil.which(slangc()[0]), f'slang compiler: {slangc()[0]} not found on PATH: {os.environ["PATH"]}')
|
||||
|
||||
def test_loading_extensions(self) -> None:
|
||||
import kitty.fast_data_types as fdt
|
||||
from kittens.transfer import rsync
|
||||
|
||||
del fdt, rsync
|
||||
|
||||
def test_slang_build(self) -> None:
|
||||
from kitty.shaders.slang import test_slang_build
|
||||
|
||||
test_slang_build()
|
||||
|
||||
def test_macos_dictation_forwarding(self) -> None:
|
||||
from kitty.constants import glfw_path, is_macos
|
||||
|
||||
if not is_macos or not shutil.which('clang'):
|
||||
self.skipTest('Dictation smoke test is macOS only and requires clang')
|
||||
cocoa_module = glfw_path('cocoa')
|
||||
probe = textwrap.dedent("""\
|
||||
#import <AppKit/AppKit.h>
|
||||
#import <dlfcn.h>
|
||||
#import <objc/runtime.h>
|
||||
#import <objc/message.h>
|
||||
|
||||
static int start_calls = 0;
|
||||
static int stop_calls = 0;
|
||||
static id last_sender = nil;
|
||||
|
||||
static void fake_start_dictation(id self, SEL _cmd, id sender) {
|
||||
(void)self; (void)_cmd;
|
||||
start_calls++;
|
||||
last_sender = sender;
|
||||
}
|
||||
|
||||
static void fake_stop_dictation(id self, SEL _cmd, id sender) {
|
||||
(void)self; (void)_cmd;
|
||||
stop_calls++;
|
||||
last_sender = sender;
|
||||
}
|
||||
|
||||
static void require_true(BOOL condition, const char *message) {
|
||||
if (!condition) {
|
||||
fprintf(stderr, "FAIL: %s\\n", message);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
@autoreleasepool {
|
||||
[NSApplication sharedApplication];
|
||||
void *handle = dlopen(@@COCOA_MODULE@@, RTLD_NOW | RTLD_GLOBAL);
|
||||
require_true(handle != NULL, dlerror());
|
||||
|
||||
SEL start = NSSelectorFromString(@"startDictation:");
|
||||
SEL stop = NSSelectorFromString(@"stopDictation:");
|
||||
Method start_method = class_getInstanceMethod([NSApplication class], start);
|
||||
Method stop_method = class_getInstanceMethod([NSApplication class], stop);
|
||||
require_true(start_method != NULL, "NSApplication startDictation: missing");
|
||||
require_true(stop_method != NULL, "NSApplication stopDictation: missing");
|
||||
method_setImplementation(start_method, (IMP)fake_start_dictation);
|
||||
method_setImplementation(stop_method, (IMP)fake_stop_dictation);
|
||||
|
||||
Class view_cls = NSClassFromString(@"GLFWContentView");
|
||||
Class context_cls = NSClassFromString(@"GLFWTextInputContext");
|
||||
require_true(view_cls != Nil, "GLFWContentView class not loaded");
|
||||
require_true(context_cls != Nil, "GLFWTextInputContext class not loaded");
|
||||
|
||||
SEL init_with_glfw_window = NSSelectorFromString(@"initWithGlfwWindow:");
|
||||
id view = ((id (*)(id, SEL, void *)) objc_msgSend)([view_cls alloc], init_with_glfw_window, NULL);
|
||||
require_true(view != nil, "GLFWContentView initWithGlfwWindow: failed");
|
||||
require_true([view respondsToSelector:start], "GLFWContentView does not expose startDictation:");
|
||||
require_true([view respondsToSelector:stop], "GLFWContentView does not expose stopDictation:");
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
|
||||
[view performSelector:start withObject:@"menu sender"];
|
||||
#pragma clang diagnostic pop
|
||||
require_true(start_calls == 1, "startDictation: action was not forwarded to NSApplication");
|
||||
require_true([(id)last_sender isEqual:@"menu sender"], "startDictation: forwarded wrong sender");
|
||||
|
||||
[view doCommandBySelector:start];
|
||||
require_true(start_calls == 2, "doCommandBySelector:startDictation: was swallowed");
|
||||
require_true(last_sender == view, "doCommandBySelector:startDictation: should forward self as sender");
|
||||
|
||||
id context = [view inputContext];
|
||||
require_true(context != nil, "GLFWContentView inputContext missing");
|
||||
require_true([context isKindOfClass:context_cls], "GLFWContentView inputContext has wrong class");
|
||||
[context doCommandBySelector:stop];
|
||||
require_true(stop_calls == 1, "GLFWTextInputContext did not forward stopDictation:");
|
||||
require_true(last_sender == nil, "GLFWTextInputContext should forward nil sender");
|
||||
|
||||
printf("dictation forwarding probe passed\\n");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
""").replace('@@COCOA_MODULE@@', json.dumps(cocoa_module))
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
src = os.path.join(tdir, 'dictation_probe.m')
|
||||
exe = os.path.join(tdir, 'dictation_probe')
|
||||
with open(src, 'w') as f:
|
||||
f.write(probe)
|
||||
nm = subprocess.run(['nm', '-g', cocoa_module], capture_output=True, text=True)
|
||||
asan_flags = ['-fsanitize=address,undefined', '-fno-omit-frame-pointer'] if '__asan_init' in nm.stdout else []
|
||||
cp = subprocess.run(['clang', '-framework', 'AppKit'] + asan_flags + [src, '-o', exe], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
self.assertEqual(cp.returncode, 0, cp.stdout)
|
||||
cp = subprocess.run([exe], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
self.assertEqual(cp.returncode, 0, cp.stdout)
|
||||
self.assertIn('dictation forwarding probe passed', cp.stdout)
|
||||
|
||||
def test_glfw_modules(self) -> None:
|
||||
from kitty.constants import glfw_path, is_macos
|
||||
|
||||
linux_backends = ['x11']
|
||||
if not self.is_ci:
|
||||
linux_backends.append('wayland')
|
||||
modules = ['cocoa'] if is_macos else linux_backends
|
||||
for name in modules:
|
||||
path = glfw_path(name)
|
||||
self.assertTrue(os.path.isfile(path), f'{path} is not a file')
|
||||
self.assertTrue(os.access(path, os.X_OK), f'{path} is not executable')
|
||||
|
||||
def test_all_kitten_names(self) -> None:
|
||||
from kittens.runner import all_kitten_names
|
||||
|
||||
names = all_kitten_names()
|
||||
self.assertIn('diff', names)
|
||||
self.assertIn('hints', names)
|
||||
self.assertGreater(len(names), 8)
|
||||
|
||||
def test_filesystem_locations(self) -> None:
|
||||
from kitty.constants import fonts_dir, local_docs, logo_png_file, shell_integration_dir, terminfo_dir
|
||||
|
||||
zsh = os.path.join(shell_integration_dir, 'zsh')
|
||||
self.assertTrue(os.path.isdir(terminfo_dir), f'Terminfo dir: {terminfo_dir}')
|
||||
self.assertTrue(os.path.exists(logo_png_file), f'Logo file: {logo_png_file}')
|
||||
self.assertTrue(os.path.exists(zsh), f'Shell integration: {zsh}')
|
||||
nsfm = os.path.join(fonts_dir, 'SymbolsNerdFontMono-Regular.ttf')
|
||||
self.assertTrue(os.path.exists(nsfm), f'Logo file: {nsfm}')
|
||||
|
||||
def is_executable(x):
|
||||
mode = os.stat(x).st_mode
|
||||
q = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
|
||||
return mode & q == q
|
||||
|
||||
for x in ('kitty', 'kitten'):
|
||||
x = os.path.join(shell_integration_dir, 'ssh', x)
|
||||
self.assertTrue(is_executable(x), f'{x} is not executable')
|
||||
if getattr(sys, 'frozen', False):
|
||||
self.assertTrue(os.path.isdir(local_docs()), f'Local docs: {local_docs()}')
|
||||
|
||||
def test_ca_certificates(self):
|
||||
import ssl
|
||||
|
||||
if not getattr(sys, 'frozen', False):
|
||||
self.skipTest('CA certificates are only tested on frozen builds')
|
||||
c = ssl.create_default_context()
|
||||
self.assertGreater(c.cert_store_stats()['x509_ca'], 2)
|
||||
|
||||
def test_docs_url(self):
|
||||
from kitty.constants import website_url
|
||||
from kitty.utils import docs_url
|
||||
|
||||
def run_tests(p, base, suffix='.html'):
|
||||
def t(x, e):
|
||||
self.ae(p(x), base + e)
|
||||
|
||||
t('', 'index.html' if suffix == '.html' else '')
|
||||
t('conf', f'conf{suffix}')
|
||||
t('kittens/ssh#frag', f'kittens/ssh{suffix}#frag')
|
||||
t('#ref=confloc', f'conf{suffix}#confloc')
|
||||
t('#ref=conf-kitty-fonts', f'conf{suffix}#conf-kitty-fonts')
|
||||
t('#ref=conf-kitten-ssh-xxx', f'kittens/ssh{suffix}#conf-kitten-ssh-xxx')
|
||||
t('#ref=at_close_tab', f'remote-control{suffix}#at-close-tab')
|
||||
t('#ref=at-close-tab', f'remote-control{suffix}#at-close-tab')
|
||||
t('#ref=action-copy', f'actions{suffix}#copy')
|
||||
t('#ref=doc-/marks', f'marks{suffix}')
|
||||
|
||||
run_tests(partial(docs_url, local_docs_root='/docs'), 'file:///docs/')
|
||||
w = website_url()
|
||||
run_tests(partial(docs_url, local_docs_root=None), w, '/')
|
||||
self.ae(docs_url('#ref=issues-123'), 'https://github.com/kovidgoyal/kitty/issues/123')
|
||||
|
||||
def test_launcher_ensures_stdio(self):
|
||||
import subprocess
|
||||
|
||||
from kitty.constants import kitty_exe
|
||||
|
||||
exe = kitty_exe()
|
||||
cp = subprocess.run(
|
||||
[
|
||||
exe,
|
||||
'+runpy',
|
||||
f"""\
|
||||
import os, sys
|
||||
if sys.stdin:
|
||||
os.close(sys.stdin.fileno())
|
||||
if sys.stdout:
|
||||
os.close(sys.stdout.fileno())
|
||||
if sys.stderr:
|
||||
os.close(sys.stderr.fileno())
|
||||
os.execlp({exe!r}, 'kitty', '+runpy', 'import sys; raise SystemExit(1 if sys.stdout is None or sys.stdin is None or sys.stderr is None else 0)')
|
||||
""",
|
||||
]
|
||||
)
|
||||
self.assertEqual(cp.returncode, 0)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
tests = unittest.defaultTestLoader.loadTestsFromTestCase(TestBuild)
|
||||
r = unittest.TextTestRunner(verbosity=4)
|
||||
result = r.run(tests)
|
||||
if result.errors or result.failures:
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,253 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from kitty.child import Child, KittyWrapper, children_of_process, cmdline_of_pid, cwd_of_process, memory_used_by_process_tree_rooted_at
|
||||
from kitty.constants import is_macos, kitty_exe
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
def spawn_and_wait_for_ready(code: str, what: str) -> subprocess.Popen:
|
||||
# Run code via kitty +runpy and wait for it to print ready. stderr is
|
||||
# captured, as in test workers it is /dev/null, so that the reason the
|
||||
# child failed is reported.
|
||||
p = subprocess.Popen([kitty_exe(), '+runpy', code], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
line = p.stdout.readline().strip()
|
||||
p.stdout.close()
|
||||
if line != b'ready':
|
||||
p.kill()
|
||||
err = p.stderr.read().decode('utf-8', 'replace')
|
||||
p.stderr.close()
|
||||
raise AssertionError(f'Unexpected output from {what}: {line!r} exit code: {p.wait()} stderr:\n{err}')
|
||||
p.stderr.close()
|
||||
return p
|
||||
|
||||
|
||||
class ChildMemoryTest(BaseTest):
|
||||
def _spawn_allocating_child(self, alloc_bytes: int) -> subprocess.Popen:
|
||||
return spawn_and_wait_for_ready(
|
||||
f"""\
|
||||
import sys, time
|
||||
buf = bytearray({alloc_bytes})
|
||||
for i in range(0, {alloc_bytes}, 4096):
|
||||
buf[i] = 1
|
||||
sys.stdout.write("ready\\n")
|
||||
sys.stdout.flush()
|
||||
time.sleep(300)
|
||||
""",
|
||||
'allocating child',
|
||||
)
|
||||
|
||||
def _terminate(self, p: subprocess.Popen) -> None:
|
||||
p.terminate()
|
||||
p.wait()
|
||||
|
||||
def test_memory_returns_positive_for_live_process(self):
|
||||
mem = memory_used_by_process_tree_rooted_at(os.getpid())
|
||||
self.assertGreater(mem, 0)
|
||||
|
||||
def test_memory_returns_minus_one_for_nonexistent_pid(self):
|
||||
self.ae(memory_used_by_process_tree_rooted_at(99999999), -1)
|
||||
|
||||
def test_memory_accounts_for_child_allocation(self):
|
||||
# Verify that a child's known resident allocation shows up in the
|
||||
# measurement. check_if_cgroup_root=True falls back to per-process
|
||||
# tree walk when pid is not the cgroup root (the common case when
|
||||
# running under a shared session cgroup), so this exercises the tree
|
||||
# walk path on Linux and the always-tree-walk path on macOS.
|
||||
alloc = 20 * 1024 * 1024 # 20 MiB
|
||||
child = self._spawn_allocating_child(alloc)
|
||||
try:
|
||||
mem = memory_used_by_process_tree_rooted_at(child.pid, check_if_cgroup_root=True)
|
||||
self.assertGreater(
|
||||
mem,
|
||||
alloc // 2,
|
||||
f'Expected at least {alloc // 2} bytes for a {alloc}-byte allocation, got {mem}',
|
||||
)
|
||||
finally:
|
||||
self._terminate(child)
|
||||
|
||||
def test_memory_of_parent_tree_includes_child(self):
|
||||
# Measuring the current process tree must yield more than measuring
|
||||
# the child alone, because the test runner itself occupies memory.
|
||||
alloc = 20 * 1024 * 1024 # 20 MiB
|
||||
child = self._spawn_allocating_child(alloc)
|
||||
try:
|
||||
mem_child = memory_used_by_process_tree_rooted_at(child.pid, check_if_cgroup_root=True)
|
||||
mem_tree = memory_used_by_process_tree_rooted_at(os.getpid(), check_if_cgroup_root=True)
|
||||
self.assertGreater(
|
||||
mem_tree,
|
||||
mem_child,
|
||||
'Parent tree memory should exceed child-only memory',
|
||||
)
|
||||
finally:
|
||||
self._terminate(child)
|
||||
|
||||
def test_memory_cgroup_path_returns_positive(self):
|
||||
# The fast cgroup path (check_if_cgroup_root=False, the default) must
|
||||
# return a usable value on Linux.
|
||||
if is_macos:
|
||||
self.skipTest('cgroup not available on macOS')
|
||||
mem = memory_used_by_process_tree_rooted_at(os.getpid())
|
||||
self.assertGreater(mem, 0)
|
||||
|
||||
def test_memory_cgroup_and_tree_walk_both_positive(self):
|
||||
# Both the cgroup path and the tree-walk path should give positive
|
||||
# results for a process that is alive.
|
||||
if is_macos:
|
||||
self.skipTest('cgroup path not applicable on macOS')
|
||||
alloc = 10 * 1024 * 1024 # 10 MiB
|
||||
child = self._spawn_allocating_child(alloc)
|
||||
try:
|
||||
mem_cgroup = memory_used_by_process_tree_rooted_at(child.pid, check_if_cgroup_root=False)
|
||||
mem_walk = memory_used_by_process_tree_rooted_at(child.pid, check_if_cgroup_root=True)
|
||||
self.assertGreater(mem_cgroup, 0)
|
||||
self.assertGreater(mem_walk, 0)
|
||||
finally:
|
||||
self._terminate(child)
|
||||
|
||||
|
||||
class ChildRootTest(BaseTest):
|
||||
def _spawn_wrapper(self, child_cwd: str, start_child: bool = True) -> subprocess.Popen:
|
||||
# A process that, like /usr/bin/login, runs a child and waits for it.
|
||||
# The child is started from a non-main thread, as kitten does.
|
||||
code = f"""\
|
||||
import sys, threading, time
|
||||
def run_child(started):
|
||||
import subprocess, sys, time
|
||||
subprocess.Popen(
|
||||
[sys.executable, '-c', 'import time; time.sleep(300)'], cwd={child_cwd!r},
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
started.set()
|
||||
time.sleep(300) # keep the thread alive so the child stays its child
|
||||
if {start_child!r}:
|
||||
started = threading.Event()
|
||||
threading.Thread(target=run_child, args=(started,), daemon=True).start()
|
||||
if not started.wait(10):
|
||||
raise SystemExit('Failed to start child')
|
||||
sys.stdout.write("ready\\n")
|
||||
sys.stdout.flush()
|
||||
time.sleep(300)
|
||||
"""
|
||||
return spawn_and_wait_for_ready(code, 'wrapper')
|
||||
|
||||
def _terminate_tree(self, p: subprocess.Popen) -> None:
|
||||
children = children_of_process(p.pid)
|
||||
p.terminate()
|
||||
p.wait()
|
||||
for c in children:
|
||||
try:
|
||||
os.kill(c, 15)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
def _child_for(self, pid: int, *wrappers: KittyWrapper) -> Child:
|
||||
c = Child(['unused'], '/')
|
||||
c.pid = pid
|
||||
c.kitty_wrappers = wrappers
|
||||
return c
|
||||
|
||||
def test_root_pid(self):
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
tdir = os.path.realpath(tdir)
|
||||
p = self._spawn_wrapper(tdir)
|
||||
try:
|
||||
children = children_of_process(p.pid)
|
||||
self.ae(len(children), 1)
|
||||
inner = children[0]
|
||||
self.ae(cwd_of_process(inner), tdir)
|
||||
self.assertNotEqual(cwd_of_process(p.pid), tdir)
|
||||
# Not launched via a wrapper, the original process is root
|
||||
c = self._child_for(p.pid)
|
||||
self.ae(c.root_pid, p.pid)
|
||||
self.ae(c.current_cwd, cwd_of_process(p.pid))
|
||||
# A wrapper that never replaces itself is always skipped
|
||||
c = self._child_for(p.pid, KittyWrapper(('/usr/bin/login', '-f'), False))
|
||||
self.ae(c.root_pid, inner)
|
||||
self.ae(c.current_cwd, tdir)
|
||||
# A wrapper that replaces itself is skipped only while it is
|
||||
# still running as the wrapper
|
||||
argv = tuple(cmdline_of_pid(p.pid))
|
||||
c = self._child_for(p.pid, KittyWrapper(argv[:2], True))
|
||||
self.ae(c.root_pid, inner)
|
||||
c = self._child_for(p.pid, KittyWrapper(('/some/other/wrapper',), True))
|
||||
self.ae(c.root_pid, p.pid)
|
||||
# Skipping stops at the first process that is not a wrapper
|
||||
c = self._child_for(p.pid, KittyWrapper(argv[:2], True), KittyWrapper(('/some/other/wrapper',), True))
|
||||
self.ae(c.root_pid, inner)
|
||||
finally:
|
||||
self._terminate_tree(p)
|
||||
|
||||
def test_root_pid_caching(self):
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
p = self._spawn_wrapper(tdir)
|
||||
try:
|
||||
inner = children_of_process(p.pid)[0]
|
||||
argv = tuple(cmdline_of_pid(p.pid))
|
||||
# No wrappers, nothing to resolve
|
||||
c = self._child_for(p.pid)
|
||||
self.ae(c.root_pid, p.pid)
|
||||
self.assertIsNone(c.resolved_root_pid)
|
||||
# A wrapper that never replaces itself has a fixed child
|
||||
c = self._child_for(p.pid, KittyWrapper(('/usr/bin/login',), False))
|
||||
self.ae(c.root_pid, inner)
|
||||
self.ae(c.resolved_root_pid, inner)
|
||||
# A wrapper that will replace itself, its child is cached but
|
||||
# not the result
|
||||
wrapping = KittyWrapper(argv[:2], True)
|
||||
c = self._child_for(p.pid, wrapping)
|
||||
self.ae(c.root_pid, inner)
|
||||
self.assertIsNone(c.resolved_root_pid)
|
||||
self.ae(c.wrapper_children, {p.pid: inner})
|
||||
# Once it has replaced itself, the result is final
|
||||
replaced = KittyWrapper(('/not/the/wrapper/anymore',), True)
|
||||
c.kitty_wrappers = (replaced,)
|
||||
self.ae(c.root_pid, p.pid)
|
||||
self.ae(c.resolved_root_pid, p.pid)
|
||||
self.ae(c.wrapper_children, {})
|
||||
# Not looking like the wrapper without ever having looked like
|
||||
# it, means it might not have been exec-ed yet, so dont cache
|
||||
c = self._child_for(p.pid, replaced)
|
||||
self.ae(c.root_pid, p.pid)
|
||||
self.assertIsNone(c.resolved_root_pid)
|
||||
# The original process properties use the root process
|
||||
c = self._child_for(p.pid, KittyWrapper(('/usr/bin/login',), False))
|
||||
self.ae(c.current_cwd, os.path.realpath(tdir))
|
||||
self.ae(c.cmdline, cmdline_of_pid(inner))
|
||||
finally:
|
||||
self._terminate_tree(p)
|
||||
|
||||
def test_descendants_from_threads(self):
|
||||
if is_macos:
|
||||
self.skipTest('Per thread children lists are Linux only')
|
||||
from kitty import child
|
||||
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
p = self._spawn_wrapper(tdir)
|
||||
try:
|
||||
inner = children_of_process(p.pid)
|
||||
self.ae(len(inner), 1)
|
||||
self.ae(child._get_descendants_of(p.pid), set(inner))
|
||||
# Kernels without /proc/<pid>/task/<tid>/children
|
||||
orig = child.proc_children_supported
|
||||
child.proc_children_supported = lambda: False # type: ignore
|
||||
try:
|
||||
self.ae(children_of_process(p.pid), inner)
|
||||
self.ae(child._get_descendants_of(p.pid), set(inner))
|
||||
finally:
|
||||
child.proc_children_supported = orig
|
||||
finally:
|
||||
self._terminate_tree(p)
|
||||
|
||||
def test_root_pid_wrapper_without_child(self):
|
||||
p = self._spawn_wrapper('/', start_child=False)
|
||||
try:
|
||||
self.ae(children_of_process(p.pid), [])
|
||||
c = self._child_for(p.pid, KittyWrapper(('/usr/bin/login',), False))
|
||||
self.ae(c.root_pid, p.pid)
|
||||
finally:
|
||||
self._terminate_tree(p)
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import shlex
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestChooseFiles(BaseTest):
|
||||
def test_format_selection_for_paste(self) -> None:
|
||||
from kittens.choose_files.main import format_selection_for_paste
|
||||
|
||||
paths = ['/work/simple', '/work/a path', '/work/a;command', '/work/*.txt', '/work/~root', '/work/a>output', r'/work/a\b', "/work/it's"]
|
||||
text = format_selection_for_paste(paths, '/work', at_prompt=True)
|
||||
self.assertEqual(shlex.split(text), [path.removeprefix('/work/') for path in paths])
|
||||
self.assertEqual(format_selection_for_paste(paths[:2], '/work', at_prompt=False), 'simple\na path')
|
||||
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from base64 import standard_b64decode, standard_b64encode
|
||||
|
||||
from kitty.clipboard import WriteRequest
|
||||
from kitty.fast_data_types import StreamingBase64Decoder
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestClipboard(BaseTest):
|
||||
def test_clipboard_write_request(self):
|
||||
def t(data, expected):
|
||||
wr = WriteRequest(max_size=64)
|
||||
wr.add_base64_data(data)
|
||||
self.ae(wr.data_for(), expected)
|
||||
|
||||
t('dGl0bGU=', b'title')
|
||||
t('dGl0bGU', b'title')
|
||||
t('dGl0bG', b'titl')
|
||||
t('dGl0bG==', b'titl')
|
||||
t('dGl0b', b'tit')
|
||||
t('bGlnaHQgd29yaw', b'light work')
|
||||
t('bGlnaHQgd29yaw==', b'light work')
|
||||
wr = WriteRequest(max_size=64)
|
||||
wr.add_base64_data('bGlnaHQgd29')
|
||||
for x in b'y', b'a', b'y', b'4', b'=':
|
||||
wr.add_base64_data(x)
|
||||
self.ae(wr.data_for(), b'light work.')
|
||||
wr = WriteRequest(max_size=64)
|
||||
for x in 'bGlnaHQgd29y':
|
||||
wr.add_base64_data(x)
|
||||
self.ae(wr.data_for(), b'light wor')
|
||||
|
||||
def test_base64_streaming_decoder(self):
|
||||
d = StreamingBase64Decoder()
|
||||
c = standard_b64encode(b'abcdef')
|
||||
self.ae(b'abcdef', d.decode(c))
|
||||
self.assertFalse(d.needs_more_data())
|
||||
a = d.decode(c[:4])
|
||||
self.assertFalse(d.needs_more_data())
|
||||
self.ae(b'abcdef', a + d.decode(c[4:]))
|
||||
self.assertFalse(d.needs_more_data())
|
||||
a = d.decode(c[:1])
|
||||
self.assertTrue(d.needs_more_data())
|
||||
self.ae(b'abcdef', a + d.decode(c[1:4]) + d.decode(c[4:]))
|
||||
self.assertFalse(d.needs_more_data())
|
||||
c = standard_b64encode(b'abcd')
|
||||
self.ae(b'abcd', d.decode(c[:2]) + d.decode(c[2:]))
|
||||
c1 = standard_b64encode(b'1' * 4096)
|
||||
c2 = standard_b64encode(b'2' * 4096)
|
||||
self.ae(standard_b64decode(c1) + standard_b64decode(c2), d.decode(c1) + d.decode(c2))
|
||||
self.assertFalse(d.needs_more_data())
|
||||
|
||||
def test_clipboard_write_too_much_data(self):
|
||||
from kitty.clipboard import Clipboard, ClipboardRequestManager, ClipboardType, encode_mime
|
||||
from kitty.fast_data_types import set_boss
|
||||
|
||||
class Window:
|
||||
id = 1
|
||||
|
||||
def __init__(self, screen):
|
||||
self.screen = screen
|
||||
|
||||
class Boss:
|
||||
def __init__(self, window):
|
||||
self.clipboard = Clipboard()
|
||||
self.primary_selection = Clipboard(ClipboardType.primary_selection)
|
||||
self.window_id_map = {window.id: window}
|
||||
|
||||
s = self.create_screen(options={'clipboard_max_size': 16 / (1024 * 1024)})
|
||||
c = s.callbacks
|
||||
w = Window(s)
|
||||
set_boss(Boss(w))
|
||||
try:
|
||||
crm = ClipboardRequestManager(w.id)
|
||||
|
||||
def send(metadata, payload=b''):
|
||||
data = metadata.encode('ascii')
|
||||
if payload:
|
||||
data += b';' + standard_b64encode(payload)
|
||||
crm.parse_osc_5522(memoryview(data))
|
||||
|
||||
mime = f'mime={encode_mime("text/plain")}'
|
||||
send('type=write')
|
||||
send(f'type=wdata:{mime}', b'a' * 16)
|
||||
self.ae(c.wtcbuf, b'')
|
||||
self.assertIsNotNone(crm.in_flight_write_request)
|
||||
send(f'type=wdata:{mime}', b'a' * 4)
|
||||
self.assertIn(b'type=write:status=EFBIG', c.wtcbuf)
|
||||
self.assertIsNone(crm.in_flight_write_request)
|
||||
# further packets for the aborted request must be ignored
|
||||
c.clear()
|
||||
send(f'type=wdata:{mime}', b'a' * 4)
|
||||
send('type=wdata')
|
||||
self.ae(c.wtcbuf, b'')
|
||||
finally:
|
||||
set_boss(None)
|
||||
|
||||
def test_clipboard_invalid_base64(self):
|
||||
from kitty.clipboard import Clipboard, ClipboardRequestManager, ClipboardType, encode_mime
|
||||
from kitty.fast_data_types import set_boss
|
||||
|
||||
class Window:
|
||||
id = 1
|
||||
|
||||
def __init__(self, screen):
|
||||
self.screen = screen
|
||||
|
||||
class Boss:
|
||||
def __init__(self, window):
|
||||
self.clipboard = Clipboard()
|
||||
self.primary_selection = Clipboard(ClipboardType.primary_selection)
|
||||
self.window_id_map = {window.id: window}
|
||||
|
||||
s = self.create_screen()
|
||||
c = s.callbacks
|
||||
w = Window(s)
|
||||
set_boss(Boss(w))
|
||||
try:
|
||||
crm = ClipboardRequestManager(w.id)
|
||||
mime = f'mime={encode_mime("text/plain")}'
|
||||
|
||||
def send(metadata, epayload=b''):
|
||||
data = metadata.encode('ascii')
|
||||
if epayload:
|
||||
data += b';' + epayload
|
||||
crm.parse_osc_5522(memoryview(data))
|
||||
|
||||
def t(*payloads, expected_status=b'EINVAL'):
|
||||
c.clear()
|
||||
send('type=write:id=w1')
|
||||
for payload in payloads:
|
||||
send(f'type=wdata:{mime}', payload)
|
||||
send('type=wdata')
|
||||
self.ae(c.wtcbuf, b'\x1b]5522;type=write:status=' + expected_status + b':id=w1\x1b\\')
|
||||
self.assertIsNone(crm.in_flight_write_request)
|
||||
|
||||
# characters outside the base64 alphabet must be rejected not ignored
|
||||
t(b'!!!')
|
||||
t(b'SGVs!!!bG8=')
|
||||
t(standard_b64encode(b'good'), b'SGVs!!!bG8=')
|
||||
t(b'\n' + standard_b64encode(b'data with a newline in the payload'))
|
||||
# data that is not correctly padded must be rejected
|
||||
t(b'SGVsbG8')
|
||||
t(standard_b64encode(b'good'), b'SGVsbG8')
|
||||
# data split into chunks at non multiple of four boundaries is valid
|
||||
ec = standard_b64encode(b'some data')
|
||||
t(ec[:3], ec[3:7], ec[7:], expected_status=b'DONE')
|
||||
t(*(ec[i : i + 1] for i in range(len(ec))), expected_status=b'DONE')
|
||||
|
||||
# invalid base64 in a metadata value must be rejected
|
||||
c.clear()
|
||||
send('type=write:id=w2')
|
||||
send(f'type=wdata:mime={encode_mime("text/plain")[:-1]}!', standard_b64encode(b'xxx'))
|
||||
self.ae(c.wtcbuf, b'\x1b]5522;type=write:status=EINVAL:id=w2\x1b\\')
|
||||
self.assertIsNone(crm.in_flight_write_request)
|
||||
|
||||
# OSC 52 write requests with invalid base64 must be ignored entirely
|
||||
# as OSC 52 has no way to report errors to the client
|
||||
written = []
|
||||
|
||||
class RecordingRequestManager(ClipboardRequestManager):
|
||||
def handle_write_request(self, wr):
|
||||
written.append(wr)
|
||||
|
||||
rrm = RecordingRequestManager(w.id)
|
||||
rrm.parse_osc_52(memoryview(b'c;' + standard_b64encode(b'new value')))
|
||||
self.ae([x.data_for() for x in written], [b'new value'])
|
||||
written.clear()
|
||||
rrm.parse_osc_52(memoryview(b'c;SGVs!!!bG8='))
|
||||
self.ae(written, [])
|
||||
# including when the invalid data is spread over multiple chunks
|
||||
# (continuation chunks have an empty where field, see continue_osc_52() in vt-parser.c)
|
||||
rrm.parse_osc_52(memoryview(b'c;SGVs'), is_partial=True)
|
||||
rrm.parse_osc_52(memoryview(b';!!!!'), is_partial=True)
|
||||
rrm.parse_osc_52(memoryview(b';bG8='))
|
||||
self.ae(written, [])
|
||||
# unpadded data is however tolerated for OSC 52
|
||||
rrm.parse_osc_52(memoryview(b'c;' + standard_b64encode(b'unpadded').rstrip(b'=')))
|
||||
self.ae([x.data_for() for x in written], [b'unpadded'])
|
||||
finally:
|
||||
set_boss(None)
|
||||
|
||||
def test_clipboard_malformed_write_packets(self):
|
||||
from kitty.clipboard import Clipboard, ClipboardRequestManager, ClipboardType, encode_mime
|
||||
from kitty.fast_data_types import set_boss
|
||||
|
||||
class Window:
|
||||
id = 1
|
||||
|
||||
def __init__(self, screen):
|
||||
self.screen = screen
|
||||
|
||||
class Boss:
|
||||
def __init__(self, window):
|
||||
self.clipboard = Clipboard()
|
||||
self.primary_selection = Clipboard(ClipboardType.primary_selection)
|
||||
self.window_id_map = {window.id: window}
|
||||
|
||||
s = self.create_screen()
|
||||
c = s.callbacks
|
||||
w = Window(s)
|
||||
set_boss(Boss(w))
|
||||
try:
|
||||
crm = ClipboardRequestManager(w.id)
|
||||
|
||||
def send(metadata, epayload=b''):
|
||||
data = metadata.encode('ascii')
|
||||
if epayload:
|
||||
data += b';' + epayload
|
||||
crm.parse_osc_5522(memoryview(data))
|
||||
|
||||
mime = f'mime={encode_mime("text/plain")}'
|
||||
|
||||
def t(*packets):
|
||||
c.clear()
|
||||
send('type=write:id=w1')
|
||||
send(f'type=wdata:{mime}', standard_b64encode(b'xxx'))
|
||||
c.clear()
|
||||
for packet in packets:
|
||||
send(*packet)
|
||||
self.ae(c.wtcbuf, b'\x1b]5522;type=write:status=EINVAL:id=w1\x1b\\')
|
||||
self.assertIsNone(crm.in_flight_write_request)
|
||||
# further packets for the aborted request must be ignored
|
||||
c.clear()
|
||||
send(f'type=wdata:{mime}', standard_b64encode(b'xxx'))
|
||||
send('type=wdata')
|
||||
self.ae(c.wtcbuf, b'')
|
||||
|
||||
# alias payload that is not valid base64
|
||||
t((f'type=walias:{mime}', b'AAA'))
|
||||
# alias payload that is not valid UTF-8
|
||||
t((f'type=walias:{mime}', b'/w=='))
|
||||
# alias packet without a MIME type
|
||||
t(('type=walias', standard_b64encode(b'text/rtf')))
|
||||
# metadata value that is not valid base64
|
||||
t(('type=walias:mime=AAA', standard_b64encode(b'text/rtf')))
|
||||
t(('type=wdata:mime=AAA', standard_b64encode(b'xxx')))
|
||||
# a malformed read packet must not abort the write request
|
||||
c.clear()
|
||||
send('type=write:id=w2')
|
||||
send('type=read:id=r1', b'AAA')
|
||||
self.ae(c.wtcbuf, b'')
|
||||
self.assertIsNotNone(crm.in_flight_write_request)
|
||||
finally:
|
||||
set_boss(None)
|
||||
@@ -0,0 +1,281 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestCommandPalette(BaseTest):
|
||||
def test_collect_keys_data(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
from kitty.actions import groups
|
||||
|
||||
opts = self.set_options()
|
||||
data = collect_keys_data(opts)
|
||||
self.assertIn('modes', data)
|
||||
self.assertIn('mouse', data)
|
||||
self.assertIn('', data['modes'], 'Default keyboard mode should be present')
|
||||
default_mode = data['modes']['']
|
||||
# Should have at least some categories
|
||||
self.assertTrue(len(default_mode) > 0, 'Should have at least one category')
|
||||
# All category names should be from the known groups or special palette sections
|
||||
known_titles = set(groups.values()) | {'Action aliases', 'Kitten aliases', 'Combined actions'}
|
||||
for cat_name in default_mode:
|
||||
self.assertIn(cat_name, known_titles, f'Unknown category: {cat_name}')
|
||||
# Each category should have bindings with required fields
|
||||
for cat_name, bindings in default_mode.items():
|
||||
self.assertIsInstance(bindings, list)
|
||||
for b in bindings:
|
||||
self.assertIn('key', b)
|
||||
self.assertIn('action', b)
|
||||
self.assertIn('action_display', b)
|
||||
self.assertIn('definition', b)
|
||||
self.assertIn('help', b)
|
||||
self.assertIn('long_help', b)
|
||||
self.assertIsInstance(b['key'], str)
|
||||
self.assertIsInstance(b['action'], str)
|
||||
# key may be empty for unmapped actions; action must always be non-empty
|
||||
self.assertTrue(len(b['action']) > 0)
|
||||
# Mouse mappings
|
||||
self.assertIsInstance(data['mouse'], list)
|
||||
for b in data['mouse']:
|
||||
self.assertIn('key', b)
|
||||
self.assertIn('action', b)
|
||||
self.assertIn('action_display', b)
|
||||
|
||||
def test_collect_keys_categories_ordered(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
from kitty.actions import groups
|
||||
|
||||
opts = self.set_options()
|
||||
data = collect_keys_data(opts)
|
||||
default_mode = data['modes']['']
|
||||
cat_names = list(default_mode.keys())
|
||||
group_titles = list(groups.values())
|
||||
# Categories should appear in the same order as defined in groups
|
||||
indices = []
|
||||
for cat in cat_names:
|
||||
if cat in group_titles:
|
||||
indices.append(group_titles.index(cat))
|
||||
self.ae(indices, sorted(indices), 'Categories should be ordered according to groups dict')
|
||||
|
||||
def test_collect_keys_bindings_sorted(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
|
||||
opts = self.set_options()
|
||||
data = collect_keys_data(opts)
|
||||
# Within each category, mapped entries (non-empty key) come first sorted by key,
|
||||
# then unmapped entries (empty key) sorted by action name.
|
||||
for cat_name, bindings in data['modes'][''].items():
|
||||
seen_unmapped = False
|
||||
for b in bindings:
|
||||
if b['key'] == '':
|
||||
seen_unmapped = True
|
||||
elif seen_unmapped:
|
||||
self.fail(f'In category {cat_name!r}, mapped binding {b!r} follows an unmapped one')
|
||||
|
||||
def test_collect_keys_has_help_text(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
|
||||
opts = self.set_options()
|
||||
data = collect_keys_data(opts)
|
||||
# At least some bindings should have help text
|
||||
has_help = False
|
||||
for cat_name, bindings in data['modes'][''].items():
|
||||
for b in bindings:
|
||||
if b['help']:
|
||||
has_help = True
|
||||
break
|
||||
if has_help:
|
||||
break
|
||||
self.assertTrue(has_help, 'At least some bindings should have help text')
|
||||
|
||||
def test_ordering_arrays_present(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
|
||||
opts = self.set_options()
|
||||
data = collect_keys_data(opts)
|
||||
# mode_order should list all modes
|
||||
self.assertIn('mode_order', data)
|
||||
self.assertIsInstance(data['mode_order'], list)
|
||||
self.ae(set(data['mode_order']), set(data['modes'].keys()))
|
||||
# category_order should list categories for each mode
|
||||
self.assertIn('category_order', data)
|
||||
self.assertIsInstance(data['category_order'], dict)
|
||||
for mode_name in data['modes']:
|
||||
self.assertIn(mode_name, data['category_order'])
|
||||
self.ae(
|
||||
set(data['category_order'][mode_name]),
|
||||
set(data['modes'][mode_name].keys()),
|
||||
f'category_order for mode {mode_name!r} should match modes keys',
|
||||
)
|
||||
|
||||
def test_always_includes_unmapped_actions(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
|
||||
opts = self.set_options()
|
||||
data = collect_keys_data(opts)
|
||||
# Unmapped actions (empty key) are always included
|
||||
found_unmapped = False
|
||||
for cats in data['modes'].values():
|
||||
for bindings in cats.values():
|
||||
for b in bindings:
|
||||
if b['key'] == '':
|
||||
found_unmapped = True
|
||||
# Unmapped actions must still have action and definition
|
||||
self.assertTrue(len(b['action']) > 0)
|
||||
self.assertTrue(len(b['definition']) > 0)
|
||||
break
|
||||
self.assertTrue(found_unmapped, 'Expected at least one unmapped action to always be present')
|
||||
|
||||
def test_alias_resolution(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
from kitty.options.utils import ActionAlias, AliasMap, parse_map
|
||||
|
||||
opts = self.set_options()
|
||||
# Set up action aliases: launch_tab (bound) and launch_bg (unbound)
|
||||
alias_map = AliasMap()
|
||||
alias_map.append('launch_tab', ActionAlias('launch_tab', 'launch --type=tab --cwd=current'))
|
||||
alias_map.append('launch_bg', ActionAlias('launch_bg', 'launch --type=background'))
|
||||
opts.alias_map = alias_map
|
||||
# Add a keybinding that uses the launch_tab alias
|
||||
for kd in parse_map('f1 launch_tab vim'):
|
||||
kd = kd.resolve_and_copy(opts.kitty_mod)
|
||||
default_mode = opts.keyboard_modes['']
|
||||
default_mode.keymap.setdefault(kd.trigger, []).append(kd)
|
||||
|
||||
data = collect_keys_data(opts)
|
||||
|
||||
# Aliases should have their own section
|
||||
self.assertIn('Action aliases', data['modes'][''], 'Aliases should have a dedicated section')
|
||||
alias_section = data['modes']['']['Action aliases']
|
||||
|
||||
# Bound alias should appear in the alias section with its key
|
||||
bound = [b for b in alias_section if b.get('alias') == 'launch_tab']
|
||||
self.ae(len(bound), 1, 'Bound alias should appear exactly once')
|
||||
self.ae(bound[0]['action'], 'launch')
|
||||
self.assertTrue(bound[0]['key'] != '', 'Bound alias should have its key')
|
||||
|
||||
# Unbound alias should also appear in the alias section
|
||||
unbound = [b for b in alias_section if b['action_display'] == 'launch_bg']
|
||||
self.ae(len(unbound), 1, 'Unbound alias should appear exactly once')
|
||||
self.ae(unbound[0]['action'], 'launch')
|
||||
self.ae(unbound[0]['key'], '')
|
||||
self.assertTrue(unbound[0]['help'].startswith('Alias for:'))
|
||||
|
||||
# Bound alias should NOT appear in any other category
|
||||
for cat_name, bindings in data['modes'][''].items():
|
||||
if cat_name == 'Action aliases':
|
||||
continue
|
||||
for b in bindings:
|
||||
self.assertNotEqual(b.get('alias'), 'launch_tab', f'Alias binding should not appear in {cat_name!r}')
|
||||
|
||||
def test_alias_sections_come_first(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
from kitty.options.utils import ActionAlias, AliasMap
|
||||
|
||||
opts = self.set_options()
|
||||
alias_map = AliasMap()
|
||||
alias_map.append('launch_bg', ActionAlias('launch_bg', 'launch --type=background'))
|
||||
alias_map.append('kitten', ActionAlias('hints', 'hints --hints-offset=0', replace_second_arg=True))
|
||||
opts.alias_map = alias_map
|
||||
data = collect_keys_data(opts)
|
||||
cat_names = list(data['modes'][''].keys())
|
||||
self.ae(cat_names[:2], ['Action aliases', 'Kitten aliases'])
|
||||
self.ae(data['category_order'][''][:2], ['Action aliases', 'Kitten aliases'])
|
||||
|
||||
# Without aliases there are no alias sections at the top
|
||||
opts = self.set_options()
|
||||
opts.alias_map = AliasMap()
|
||||
data = collect_keys_data(opts)
|
||||
self.assertNotIn('Action aliases', data['modes'][''])
|
||||
self.assertNotIn('Kitten aliases', data['modes'][''])
|
||||
|
||||
def test_alias_entries_display_alias_name(self):
|
||||
# The Go side relies on action_display starting with the alias name
|
||||
# for every entry that has an alias, so that it does not need to add it.
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
from kitty.options.utils import ActionAlias, AliasMap, parse_map
|
||||
|
||||
opts = self.set_options()
|
||||
alias_map = AliasMap()
|
||||
alias_map.append('launch_tab', ActionAlias('launch_tab', 'launch --type=tab --cwd=current'))
|
||||
alias_map.append('launch_bg', ActionAlias('launch_bg', 'launch --type=background'))
|
||||
alias_map.append('kitten', ActionAlias('hints', 'hints --hints-offset=0', replace_second_arg=True))
|
||||
opts.alias_map = alias_map
|
||||
for kd in parse_map('f1 launch_tab vim'):
|
||||
kd = kd.resolve_and_copy(opts.kitty_mod)
|
||||
opts.keyboard_modes[''].keymap.setdefault(kd.trigger, []).append(kd)
|
||||
data = collect_keys_data(opts)
|
||||
alias_entries = [b for cats in data['modes'].values() for bindings in cats.values() for b in bindings if 'alias' in b]
|
||||
self.ae({b['alias'] for b in alias_entries}, {'launch_tab', 'launch_bg', 'kitten hints'})
|
||||
for b in alias_entries:
|
||||
self.assertTrue(b['action_display'].startswith(b['alias']), f'{b["action_display"]!r} does not start with {b["alias"]!r}')
|
||||
|
||||
def test_kitten_alias_section(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
from kitty.options.utils import ActionAlias, AliasMap
|
||||
|
||||
opts = self.set_options()
|
||||
# Set up a kitten alias: kitten hints -> kitten hints --hints-offset=0
|
||||
alias_map = AliasMap()
|
||||
alias_map.append('kitten', ActionAlias('hints', 'hints --hints-offset=0', replace_second_arg=True))
|
||||
opts.alias_map = alias_map
|
||||
|
||||
data = collect_keys_data(opts)
|
||||
self.assertIn('Kitten aliases', data['modes'][''], 'Kitten aliases should have a dedicated section')
|
||||
kitten_section = data['modes']['']['Kitten aliases']
|
||||
found = [b for b in kitten_section if b['action_display'] == 'kitten hints']
|
||||
self.ae(len(found), 1, 'Kitten alias should appear exactly once')
|
||||
self.ae(found[0]['definition'], 'kitten hints --hints-offset=0')
|
||||
self.assertTrue(found[0]['help'].startswith('Alias for:'))
|
||||
|
||||
def test_combine_actions_section(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
from kitty.options.utils import parse_map
|
||||
|
||||
opts = self.set_options()
|
||||
# Add a combine keybinding
|
||||
for kd in parse_map('f2 combine : new_tab : launch vim'):
|
||||
kd = kd.resolve_and_copy(opts.kitty_mod)
|
||||
default_mode = opts.keyboard_modes['']
|
||||
default_mode.keymap.setdefault(kd.trigger, []).append(kd)
|
||||
|
||||
data = collect_keys_data(opts)
|
||||
# Combine bindings should have their own section
|
||||
self.assertIn('Combined actions', data['modes'][''], 'Combine bindings should have a dedicated section')
|
||||
combine_section = data['modes']['']['Combined actions']
|
||||
found = [b for b in combine_section if b['action'] == 'combine']
|
||||
self.assertTrue(len(found) > 0, 'Combine binding should be in the section')
|
||||
self.ae(found[0]['key'], 'f2')
|
||||
|
||||
def test_no_duplicate_alias_entries(self):
|
||||
from kittens.command_palette.main import collect_keys_data
|
||||
from kitty.options.utils import ActionAlias, AliasMap, parse_map
|
||||
|
||||
opts = self.set_options()
|
||||
# Set up aliases, some bound to keys and some not
|
||||
alias_map = AliasMap()
|
||||
alias_map.append('launch_tab', ActionAlias('launch_tab', 'launch --type=tab --cwd=current'))
|
||||
alias_map.append('launch_bg', ActionAlias('launch_bg', 'launch --type=background'))
|
||||
opts.alias_map = alias_map
|
||||
for kd in parse_map('f1 launch_tab vim'):
|
||||
kd = kd.resolve_and_copy(opts.kitty_mod)
|
||||
default_mode = opts.keyboard_modes['']
|
||||
default_mode.keymap.setdefault(kd.trigger, []).append(kd)
|
||||
|
||||
data = collect_keys_data(opts)
|
||||
# Collect all entries that have an alias field across all categories
|
||||
alias_entries: list[tuple[str, str]] = []
|
||||
for cat_name, bindings in data['modes'][''].items():
|
||||
for b in bindings:
|
||||
if 'alias' in b:
|
||||
alias_entries.append((cat_name, b['alias']))
|
||||
# Each alias should appear exactly once
|
||||
seen: set[str] = set()
|
||||
for cat_name, alias_name in alias_entries:
|
||||
self.assertNotIn(alias_name, seen, f'Alias {alias_name!r} appears in multiple places')
|
||||
seen.add(alias_name)
|
||||
|
||||
def test_unmapped_actions_sorted_order(self):
|
||||
# Covered by test_collect_keys_bindings_sorted
|
||||
pass
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from kitty.constants import kitten_exe as kitten
|
||||
from kitty.session import SESSION_FILE_EXTENSIONS
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestCompletion(BaseTest):
|
||||
def test_completion(self):
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
completion(self, tdir)
|
||||
|
||||
|
||||
def get_all_words(result):
|
||||
all_words = set()
|
||||
for group in result.get('groups', ()):
|
||||
for m in group['matches']:
|
||||
all_words.add(m['word'])
|
||||
return all_words
|
||||
|
||||
|
||||
def has_words(*words):
|
||||
def t(self, result):
|
||||
q = set(words)
|
||||
missing = q - get_all_words(result)
|
||||
self.assertFalse(missing, f'Words missing. Command line: {self.current_cmd!r}')
|
||||
|
||||
return t
|
||||
|
||||
|
||||
def does_not_have_words(*words):
|
||||
def t(self, result):
|
||||
q = set(words)
|
||||
all_words = get_all_words(result)
|
||||
self.assertFalse(q & all_words, f'Words unexpectedly present. Command line: {self.current_cmd!r}')
|
||||
|
||||
return t
|
||||
|
||||
|
||||
def all_words(*words):
|
||||
def t(self, result):
|
||||
expected = set(words)
|
||||
actual = get_all_words(result)
|
||||
self.assertEqual(expected, actual, f'Command line: {self.current_cmd!r}')
|
||||
|
||||
return t
|
||||
|
||||
|
||||
def is_delegate(num_to_remove: int = 0, command: str = ''):
|
||||
q = {}
|
||||
if num_to_remove:
|
||||
q['num_to_remove'] = num_to_remove
|
||||
if command:
|
||||
q['command'] = command
|
||||
|
||||
def t(self, result):
|
||||
d = result['delegate']
|
||||
self.assertEqual(d, q, f'Command line: {self.current_cmd!r}')
|
||||
|
||||
return t
|
||||
|
||||
|
||||
def completion(self: TestCompletion, tdir: str):
|
||||
all_cmds = []
|
||||
all_argv = []
|
||||
all_tests = []
|
||||
|
||||
def add(cmdline: str, *tests):
|
||||
all_cmds.append(cmdline)
|
||||
new_word = cmdline.endswith(' ')
|
||||
if new_word:
|
||||
cmdline = cmdline[:-1]
|
||||
all_argv.append(shlex.split(cmdline))
|
||||
if new_word:
|
||||
all_argv[-1].append('')
|
||||
all_tests.append(tests)
|
||||
|
||||
def run_tool():
|
||||
env = os.environ.copy()
|
||||
env['PATH'] = os.path.join(tdir, 'bin')
|
||||
env['HOME'] = os.path.join(tdir, 'sub')
|
||||
env['KITTY_CONFIG_DIRECTORY'] = os.path.join(tdir, 'sub')
|
||||
cp = subprocess.run([kitten(), '__complete__', 'json'], check=True, stdout=subprocess.PIPE, cwd=tdir, input=json.dumps(all_argv).encode(), env=env)
|
||||
self.assertEqual(cp.returncode, 0, f'kitten __complete__ failed with exit code: {cp.returncode}')
|
||||
return json.loads(cp.stdout)
|
||||
|
||||
add('kitty ', has_words('@', '+', '+open'))
|
||||
add('kitty @ l', has_words('ls', 'last-used-layout', 'launch'))
|
||||
add('kitty @ set-o', has_words('set-os-window-title'))
|
||||
|
||||
def make_file(path, mode=None):
|
||||
with open(os.path.join(tdir, path), mode='x') as f:
|
||||
if mode is not None:
|
||||
os.chmod(f.fileno(), mode)
|
||||
|
||||
os.mkdir(os.path.join(tdir, 'bin'))
|
||||
os.mkdir(os.path.join(tdir, 'sub'))
|
||||
make_file('bin/exe1', 0o700)
|
||||
make_file('bin/exe-not1')
|
||||
make_file('exe2', 0o700)
|
||||
make_file('exe-not2.jpeg')
|
||||
make_file('sub/exe3', 0o700)
|
||||
make_file('sub/exe-not3.png')
|
||||
session_files = tuple(f'project.{ext}' for ext in sorted(SESSION_FILE_EXTENSIONS))
|
||||
for path in session_files:
|
||||
make_file(f'sub/{path}')
|
||||
|
||||
add('kitty x', all_words())
|
||||
add('kitty e', all_words('exe1', 'exe2'))
|
||||
add('kitty ./', all_words('./bin/', './sub/', './exe2'))
|
||||
add('kitty ./e', all_words('./exe2'))
|
||||
add('kitty ./s', all_words('./sub/'))
|
||||
add('kitty ~', all_words('~/exe3'))
|
||||
add('kitty ~/', all_words('~/exe3'))
|
||||
add('kitty ~/e', all_words('~/exe3'))
|
||||
|
||||
add('kitty @ goto-layout ', has_words('tall', 'fat'))
|
||||
add('kitty @ goto-layout spli', all_words('splits'))
|
||||
add('kitty @ goto-layout f f', all_words())
|
||||
add('kitty @ set-window-logo ', all_words('exe-not2.jpeg', 'sub/'))
|
||||
add('kitty @ set-window-logo e', all_words('exe-not2.jpeg'))
|
||||
add('kitty @ set-window-logo e e', all_words())
|
||||
add('kitty +ope', has_words('+open'))
|
||||
add('kitty +open -', has_words('-1', '-T'))
|
||||
|
||||
add('kitty -', has_words('-c', '-1', '--'), does_not_have_words('--config', '--single-instance'))
|
||||
add('kitty -c', all_words('-c'))
|
||||
add('kitty --', has_words('--config', '--single-instance', '--'))
|
||||
add('kitty --s', has_words('--session', '--start-as'))
|
||||
add('kitty --session ', all_words(*session_files))
|
||||
add('kitty --start-as', all_words('--start-as'))
|
||||
add('kitty --start-as ', all_words('minimized', 'maximized', 'fullscreen', 'normal', 'hidden'))
|
||||
add('kitty -1 ', does_not_have_words('@ls', '@'))
|
||||
add('kitty --directory ', all_words('bin/', 'sub/'))
|
||||
add('kitty -1d ', all_words('exe1'))
|
||||
add('kitty -1d', all_words('-1d'))
|
||||
add('kitty -o a', has_words('allow_remote_control='))
|
||||
add('kitty --listen-on ', all_words('unix:', 'tcp:'))
|
||||
add('kitty --listen-on unix:b', all_words('unix:bin/'))
|
||||
add('kitty --directory=', all_words('--directory=bin/', '--directory=sub/'))
|
||||
add('kitty --start-as=m', all_words('--start-as=minimized', '--start-as=maximized'))
|
||||
add('kitty @launch --ty', has_words('--type'))
|
||||
add('kitty @launch --type ', has_words('window', 'background', 'overlay'))
|
||||
add('kitty @launch --cwd ', has_words('current', 'oldest', 'last_reported'))
|
||||
add('kitty @launch --logo ', all_words('exe-not3.png'))
|
||||
add('kitty @launch --logo ~', all_words('~/exe-not3.png'))
|
||||
add('kitten ', has_words('@'))
|
||||
add('kitten ', does_not_have_words('__complete__'))
|
||||
add('kitten @launch --ty', has_words('--type'))
|
||||
|
||||
add('kitty + ', has_words('launch', 'kitten'))
|
||||
add('kitty + kitten ', has_words('icat', 'diff'))
|
||||
add('kitty +kitten icat ', has_words('sub/', 'exe-not2.jpeg'))
|
||||
add('kitty + kitten icat --pr', has_words('--print-window-size'))
|
||||
add('kitty + kitten diff ', has_words('exe-not2.jpeg'))
|
||||
add('kitty + kitten themes --', has_words('--cache-age'))
|
||||
add('kitty + kitten themes D', has_words('Default'))
|
||||
add('kitty + kitten hyperlinked_grep ', is_delegate(3, 'rg'))
|
||||
add('kitty +kitten hyperlinked_grep ', is_delegate(2, 'rg'))
|
||||
|
||||
add('clone-in-kitty --ty', has_words('--type'))
|
||||
|
||||
add('kitty bash ', is_delegate(1, 'bash'))
|
||||
add('kitty -1 bash ', is_delegate(2, 'bash'))
|
||||
add('kitty -1 bash --n', is_delegate(2, 'bash'))
|
||||
add('kitty @launch --type tab bash --n', is_delegate(4, 'bash'))
|
||||
add('kitty +kitten hyperlinked_grep --s', is_delegate(2, 'rg'))
|
||||
add('kitty @launch e', all_words('exe1', 'exe2'))
|
||||
|
||||
for cmd, tests, result in zip(all_cmds, all_tests, run_tool()):
|
||||
self.current_cmd = cmd
|
||||
for test in tests:
|
||||
test(self, result)
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
def is_rlimit_memlock_too_low() -> bool:
|
||||
"""On supported systems, return true if the MEMLOCK limit is too low to
|
||||
run the crypto test."""
|
||||
try:
|
||||
import resource
|
||||
except ModuleNotFoundError:
|
||||
return False
|
||||
|
||||
memlock_limit, _ = resource.getrlimit(resource.RLIMIT_MEMLOCK)
|
||||
pagesize = resource.getpagesize()
|
||||
return memlock_limit <= pagesize
|
||||
|
||||
|
||||
class TestCrypto(BaseTest):
|
||||
def test_random_secret(self):
|
||||
if is_rlimit_memlock_too_low():
|
||||
self.skipTest('RLIMIT_MEMLOCK is too low')
|
||||
from kitty.fast_data_types import AES256GCMDecrypt, AES256GCMEncrypt, random_secret
|
||||
|
||||
a, b = random_secret(), random_secret()
|
||||
self.ae((len(a), len(random_secret(64))), (32, 64))
|
||||
self.assertNotEqual(a, b)
|
||||
with self.assertRaises(ValueError):
|
||||
random_secret(0)
|
||||
e = AES256GCMEncrypt(a)
|
||||
ciphertext = e.add_data_to_be_encrypted(b'data', True)
|
||||
self.ae(AES256GCMDecrypt(a, e.iv, e.tag).add_data_to_be_decrypted(ciphertext, True), b'data')
|
||||
|
||||
def test_elliptic_curve_data_exchange(self):
|
||||
if is_rlimit_memlock_too_low():
|
||||
self.skipTest('RLIMIT_MEMLOCK is too low')
|
||||
from kitty.fast_data_types import AES256GCMDecrypt, AES256GCMEncrypt, CryptoError, EllipticCurveKey
|
||||
|
||||
alice = EllipticCurveKey()
|
||||
bob = EllipticCurveKey()
|
||||
alice_secret = alice.derive_secret(bob.public)
|
||||
bob_secret = bob.derive_secret(alice.public)
|
||||
self.assertEqual(len(alice_secret), 32)
|
||||
self.assertEqual(len(bob_secret), 32)
|
||||
self.assertEqual(alice_secret, bob_secret)
|
||||
|
||||
auth_data = os.urandom(213)
|
||||
plaintext = os.urandom(1011)
|
||||
e = AES256GCMEncrypt(alice_secret)
|
||||
e.add_authenticated_but_unencrypted_data(auth_data)
|
||||
ciphertext = e.add_data_to_be_encrypted(plaintext, True)
|
||||
|
||||
d = AES256GCMDecrypt(bob_secret, e.iv, e.tag)
|
||||
d.add_data_to_be_authenticated_but_not_decrypted(auth_data)
|
||||
q = d.add_data_to_be_decrypted(ciphertext, True)
|
||||
self.ae(q, plaintext)
|
||||
|
||||
def corrupt_data(data):
|
||||
b = bytearray(data)
|
||||
b[0] = (b[0] + 13) % 256
|
||||
return bytes(b)
|
||||
|
||||
d = AES256GCMDecrypt(bob_secret, e.iv, corrupt_data(e.tag))
|
||||
d.add_data_to_be_authenticated_but_not_decrypted(auth_data)
|
||||
self.assertRaises(CryptoError, d.add_data_to_be_decrypted, ciphertext, True)
|
||||
|
||||
d = AES256GCMDecrypt(bob_secret, e.iv, e.tag)
|
||||
d.add_data_to_be_authenticated_but_not_decrypted(corrupt_data(auth_data))
|
||||
self.assertRaises(CryptoError, d.add_data_to_be_decrypted, ciphertext, True)
|
||||
|
||||
d = AES256GCMDecrypt(bob_secret, e.iv, e.tag)
|
||||
d.add_data_to_be_authenticated_but_not_decrypted(auth_data)
|
||||
self.assertRaises(CryptoError, d.add_data_to_be_decrypted, corrupt_data(ciphertext), True)
|
||||
|
||||
def test_short_tag_does_not_leak(self):
|
||||
if is_rlimit_memlock_too_low():
|
||||
self.skipTest('RLIMIT_MEMLOCK is too low')
|
||||
from kitty.fast_data_types import AES256GCMDecrypt, EllipticCurveKey
|
||||
|
||||
secret = EllipticCurveKey().derive_secret(EllipticCurveKey().public)
|
||||
iv = os.urandom(12)
|
||||
|
||||
def attempt():
|
||||
with self.assertRaises(ValueError):
|
||||
AES256GCMDecrypt(secret, iv, b'short')
|
||||
|
||||
attempt()
|
||||
before = sys.getallocatedblocks()
|
||||
for i in range(10000):
|
||||
attempt()
|
||||
self.assertLess(sys.getallocatedblocks() - before, 1000)
|
||||
File diff suppressed because it is too large.
Load diff
+3426
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,607 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import errno
|
||||
import fnmatch
|
||||
import itertools
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from base64 import standard_b64encode
|
||||
from functools import partial
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from kitty.constants import kitten_exe
|
||||
from kitty.fast_data_types import (
|
||||
DND_CODE,
|
||||
GLFW_DRAG_OPERATION_COPY,
|
||||
GLFW_DRAG_OPERATION_MOVE,
|
||||
dnd_set_test_write_func,
|
||||
dnd_test_cleanup_fake_window,
|
||||
dnd_test_create_fake_window,
|
||||
dnd_test_drag_finish,
|
||||
dnd_test_drag_get_data,
|
||||
dnd_test_drag_notify,
|
||||
dnd_test_fake_drop_data,
|
||||
dnd_test_fake_drop_event,
|
||||
dnd_test_force_drag_dropped,
|
||||
dnd_test_probe_state,
|
||||
dnd_test_start_drag_offer,
|
||||
)
|
||||
from kitty.utils import as_file_url
|
||||
|
||||
from .base import PTY, BaseTest
|
||||
from .dnd import WriteCapture
|
||||
|
||||
|
||||
class Capture(WriteCapture):
|
||||
def __call__(self, window_id: int, data: bytes) -> None:
|
||||
self.pty.write_to_child(data)
|
||||
|
||||
|
||||
def create_fs(base, include_toplevel_working_symlink=True):
|
||||
join = partial(os.path.join, base)
|
||||
|
||||
def w(sz, *path):
|
||||
if sz == 0:
|
||||
sz = random.randint(5713, 9879)
|
||||
with open(join(*path), 'wb') as f:
|
||||
f.write(b'x' * sz)
|
||||
|
||||
os.makedirs(join('d1', 'sd', 'ssd'))
|
||||
os.mkdir(join('d2'))
|
||||
os.symlink('/' + str(uuid.uuid4()), join('s1')) # non-existent
|
||||
if include_toplevel_working_symlink:
|
||||
os.symlink('d1', join('sd'))
|
||||
os.symlink('/', join('d1', 'sa')) # absolute symlink in sub dir
|
||||
os.symlink('../d1', join('d1', 'sr'))
|
||||
w(4096 * 3 + 113, 'some-image.png')
|
||||
w(0, 'd1', 'f1')
|
||||
w(0, 'd1', 'f2')
|
||||
w(0, 'd1', 'sd', 'f11')
|
||||
w(0, 'd1', 'sd', 'ssd', 'f111')
|
||||
os.symlink('../moose', join('d1', 'sd', 'ssd', 's11'))
|
||||
|
||||
|
||||
class TestDnDKitten(BaseTest):
|
||||
def assert_trees_equal(self, a: str, b: str, ignored='.dnd-kitten-drop-*'):
|
||||
a_name = os.path.relpath(a, self.test_dir)
|
||||
b_name = os.path.relpath(b, self.test_dir)
|
||||
entries_a = list(itertools.filterfalse(lambda x: fnmatch.fnmatch(x, ignored), os.listdir(a)))
|
||||
entries_b = list(itertools.filterfalse(lambda x: fnmatch.fnmatch(x, ignored), os.listdir(b)))
|
||||
self.assertEqual(set(entries_a), set(entries_b), f'readdir() different for {a_name} vs {b_name}')
|
||||
for x in entries_a:
|
||||
ca, cb = os.path.join(a, x), os.path.join(b, x)
|
||||
sta, stb = os.lstat(ca), os.lstat(cb)
|
||||
self.assertEqual(stat.S_IFMT(sta.st_mode), stat.S_IFMT(stb.st_mode), f'type mismatch for {a_name}/{x} vs {b_name}/{x}')
|
||||
if stat.S_ISDIR(sta.st_mode):
|
||||
self.assert_trees_equal(ca, cb)
|
||||
elif stat.S_ISLNK(sta.st_mode):
|
||||
self.assertEqual(os.readlink(ca), os.readlink(cb))
|
||||
elif stat.S_ISREG(sta.st_mode):
|
||||
self.assert_files_have_same_content(ca, cb)
|
||||
|
||||
def setUp(self):
|
||||
capture = Capture()
|
||||
dnd_set_test_write_func(capture)
|
||||
os_window_id, window_id = dnd_test_create_fake_window()
|
||||
capture.window_id = window_id
|
||||
capture.os_window_id = os_window_id
|
||||
self.capture = capture
|
||||
self.test_dir = os.path.realpath(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
self.kitten_wd = os.path.join(self.test_dir, 'kitten')
|
||||
os.mkdir(self.kitten_wd)
|
||||
self.src_data_dir = os.path.join(self.test_dir, 'src')
|
||||
os.mkdir(self.src_data_dir)
|
||||
self.messages_from_kitten = ''
|
||||
self.set_options({'tab_bar_style': 'hidden'})
|
||||
|
||||
def send_dnd_command_to_kitten(self, payload=b'', as_base64=False, flush=False, t='T', **metadata):
|
||||
header = f'\x1b]{DND_CODE};'
|
||||
metadata['t'] = t
|
||||
for k, v in metadata.items():
|
||||
header = header + f'{k}={v}:'
|
||||
self.pty.write_to_child(header.encode())
|
||||
if not payload:
|
||||
self.pty.write_to_child(b'\x1b\\', flush=flush)
|
||||
return
|
||||
if isinstance(payload, str):
|
||||
payload = payload.encode()
|
||||
payload = memoryview(standard_b64encode(payload) if as_base64 else payload)
|
||||
for i in range(0, len(payload), 4096):
|
||||
end = i + 4096
|
||||
is_last = end >= len(payload)
|
||||
chunk = payload[i : min(i + 4096, len(payload))]
|
||||
if i == 0:
|
||||
self.pty.write_to_child(f'm={0 if is_last else 1};'.encode())
|
||||
else:
|
||||
self.pty.write_to_child(f'\x1b]{DND_CODE};m={0 if is_last else 1};'.encode())
|
||||
self.pty.write_to_child(chunk)
|
||||
self.pty.write_to_child(b'\x1b\\', flush=is_last and flush)
|
||||
|
||||
def finish_setup(self, remote_client: bool = False, cli_args=(), stdin_fd=None):
|
||||
cmd = [kitten_exe(), 'dnd']
|
||||
cmd += list(cli_args)
|
||||
self.pty = self.enterContext(PTY(argv=cmd, cwd=self.kitten_wd, rows=25, columns=80, window_id=self.capture.window_id, stdin_fd=stdin_fd))
|
||||
self.capture.pty = self.pty
|
||||
self.pty.callbacks.printbuf = self
|
||||
self.screen = self.pty.screen
|
||||
self.reset_kitten(remote_client, clear_tdir=False)
|
||||
self.assertTrue(self.probe_state('drop_wanted'))
|
||||
self.assertEqual(remote_client, self.probe_state('drop_is_remote_client'))
|
||||
if self.probe_state('drag_can_offer'):
|
||||
self.assertEqual(remote_client, self.probe_state('drag_is_remote_client'))
|
||||
|
||||
def reset_kitten(self, remote_client: bool, clear_tdir=True):
|
||||
if clear_tdir:
|
||||
self.send_dnd_command_to_kitten('PING')
|
||||
self.wait_for_responses('PONG')
|
||||
shutil.rmtree(self.kitten_wd)
|
||||
os.mkdir(self.kitten_wd)
|
||||
shutil.rmtree(self.src_data_dir)
|
||||
os.mkdir(self.src_data_dir)
|
||||
self.send_dnd_command_to_kitten('SETUP_REMOTE' if remote_client else 'SETUP_LOCAL')
|
||||
self.wait_for_responses('SETUP_DONE')
|
||||
|
||||
def get_button_geometry(self, are_present: bool = True):
|
||||
self.send_dnd_command_to_kitten('GEOMETRY')
|
||||
self.pty.wait_till(lambda: bool(self.messages_from_kitten))
|
||||
self.assertTrue(
|
||||
self.messages_from_kitten.startswith('GEOMETRY') and self.messages_from_kitten.endswith('\n'),
|
||||
f'Unexpected messages from kitten: {self.messages_from_kitten!r}',
|
||||
)
|
||||
q, self.messages_from_kitten = self.messages_from_kitten.rstrip(), ''
|
||||
parts = tuple(map(int, q.split(':')[1:]))
|
||||
copy, move = parts[:4], parts[4:]
|
||||
if are_present:
|
||||
self.assertGreater(copy[2], 4)
|
||||
self.assertGreater(move[2], 4)
|
||||
else:
|
||||
self.assertEqual(copy, (0, 0, 0, 0))
|
||||
self.assertEqual(move, (0, 0, 0, 0))
|
||||
return copy, move
|
||||
|
||||
def append(self, text):
|
||||
self.messages_from_kitten += text
|
||||
|
||||
def wait_for_responses(self, *responses, timeout=10):
|
||||
q = '\n'.join(responses)
|
||||
|
||||
def wait_till():
|
||||
return q == self.messages_from_kitten.strip()
|
||||
|
||||
try:
|
||||
self.pty.wait_till(wait_till, timeout, lambda: f'Responses so far: Expected:\n{q!r}\nActual:\n{self.messages_from_kitten.strip()!r}\n')
|
||||
finally:
|
||||
self.messages_from_kitten = ''
|
||||
|
||||
def wait_for_state(self, q, expected, timeout=10):
|
||||
self.pty.wait_till(lambda: self.probe_state(q) == expected, timeout, lambda: f'{q}: {self.probe_state(q)!r}')
|
||||
|
||||
def probe_state(self, which: str):
|
||||
return dnd_test_probe_state(self.capture.window_id, which)
|
||||
|
||||
def roundtrip(self):
|
||||
self.send_dnd_command_to_kitten('PING')
|
||||
self.wait_for_responses('PONG')
|
||||
|
||||
def exit_kitten(self):
|
||||
self.pty.write_to_child('\x1b[27u') # ]
|
||||
self.pty.wait_till_child_exits(require_exit_code=0)
|
||||
|
||||
def tearDown(self):
|
||||
dnd_set_test_write_func(None)
|
||||
dnd_test_cleanup_fake_window(self.capture.os_window_id)
|
||||
self.capture = None
|
||||
self.screen = None
|
||||
self.pty = None
|
||||
|
||||
def test_dnd_kitten_drop(self):
|
||||
img_drop_path = 'images/image.png'
|
||||
self.finish_setup(cli_args=(f'--drop=image/png:{img_drop_path}', '--confirm-drop-overwrite'))
|
||||
with self.subTest(remote=False):
|
||||
self.dnd_kitten_drop(False, img_drop_path)
|
||||
self.reset_kitten(True)
|
||||
with self.subTest(remote=True):
|
||||
self.dnd_kitten_drop(True, img_drop_path)
|
||||
self.exit_kitten()
|
||||
|
||||
def test_dnd_kitten_overwrite_filesystem_aliases(self):
|
||||
def filesystem_aliases(src_rel: str, dest_rel: str) -> bool:
|
||||
with tempfile.TemporaryDirectory(dir=self.test_dir) as tdir:
|
||||
os.makedirs(os.path.dirname(os.path.join(tdir, dest_rel)), exist_ok=True)
|
||||
open(os.path.join(tdir, dest_rel), 'wb').close()
|
||||
return os.path.exists(os.path.join(tdir, src_rel))
|
||||
|
||||
aliases = tuple(
|
||||
x
|
||||
for x in (
|
||||
('case', 'report.txt', 'Report.txt'),
|
||||
('unicode', 'cafe\u0301.txt', 'caf\u00e9.txt'),
|
||||
('directory', 'folder/file.txt', 'Folder/file.txt'),
|
||||
)
|
||||
if filesystem_aliases(x[1], x[2])
|
||||
)
|
||||
if not aliases:
|
||||
self.skipTest('The filesystem does not alias names differing in case or Unicode normalization')
|
||||
self.finish_setup(cli_args=('--confirm-drop-overwrite',))
|
||||
for (name, src_rel, dest_rel), remote, action, accepted in itertools.product(
|
||||
aliases, (False, True), (GLFW_DRAG_OPERATION_COPY, GLFW_DRAG_OPERATION_MOVE), (False, True)
|
||||
):
|
||||
with self.subTest(alias=name, remote=remote, action=action, accepted=accepted):
|
||||
self.reset_kitten(remote)
|
||||
src = os.path.join(self.src_data_dir, src_rel)
|
||||
dest = os.path.join(self.kitten_wd, dest_rel)
|
||||
for path, content in ((src, b'incoming'), (dest, b'original')):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, 'wb') as f:
|
||||
f.write(content)
|
||||
self.assertTrue(os.path.samefile(os.path.join(self.kitten_wd, src_rel), dest))
|
||||
copy, move = self.get_button_geometry()
|
||||
button = copy if action == GLFW_DRAG_OPERATION_COPY else move
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False, ['text/uri-list'], button[0] + 1, button[1] + 1)
|
||||
self.wait_for_state('drop_action', action)
|
||||
dnd_test_fake_drop_event(self.capture.window_id, True, ['text/uri-list'], button[0] + 1, button[1] + 1)
|
||||
self.wait_for_state('drop_data_requests', ((1, 0, 0),))
|
||||
uri = as_file_url(self.src_data_dir, src_rel.split('/')[0])
|
||||
dnd_test_fake_drop_data(self.capture.window_id, 'text/uri-list', (uri + '\r\n').encode())
|
||||
self.pty.wait_till(lambda: 'overwrite existing' in self.pty.screen_contents() or self.probe_state('drop_action') == 0)
|
||||
with open(dest, 'rb') as f:
|
||||
self.assertEqual(b'original', f.read(), 'destination changed before overwrite confirmation')
|
||||
self.assertIn('overwrite existing', self.pty.screen_contents())
|
||||
self.pty.write_to_child('\x1b[13u' if accepted else '\x1b[27u')
|
||||
self.wait_for_state('last_drop_action', action if accepted else 0)
|
||||
self.wait_for_state('drop_action', 0)
|
||||
with open(dest, 'rb') as f:
|
||||
self.assertEqual(b'incoming' if accepted else b'original', f.read())
|
||||
if accepted and action == GLFW_DRAG_OPERATION_MOVE and not remote:
|
||||
self.assertFalse(os.path.exists(src))
|
||||
else:
|
||||
with open(src, 'rb') as f:
|
||||
self.assertEqual(b'incoming', f.read())
|
||||
self.exit_kitten()
|
||||
|
||||
def dnd_kitten_drop(self, remote_client, img_drop_path):
|
||||
copy, move = self.get_button_geometry()
|
||||
all_mimes = 'text/uri-list a/b c/d'
|
||||
for b, expected in ((copy, GLFW_DRAG_OPERATION_COPY), (move, GLFW_DRAG_OPERATION_MOVE)):
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False, all_mimes.split(), b[0] + 1, b[1] + 1)
|
||||
self.wait_for_state('drop_action', expected)
|
||||
self.assertEqual('text/uri-list', self.probe_state('drop_mimes').rstrip('\x00'))
|
||||
self.send_dnd_command_to_kitten('DROP_MIMES')
|
||||
self.wait_for_responses(all_mimes)
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False)
|
||||
self.send_dnd_command_to_kitten('DROP_MIMES')
|
||||
self.wait_for_responses('')
|
||||
large_mimes = ((all_mimes + ' ') * 300).rstrip()
|
||||
self.assertGreater(len(large_mimes), 4096)
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False, large_mimes.split(), copy[0] + 1, copy[1] + 1)
|
||||
self.wait_for_state('drop_action', GLFW_DRAG_OPERATION_COPY)
|
||||
self.send_dnd_command_to_kitten('DROP_MIMES')
|
||||
self.wait_for_responses(large_mimes)
|
||||
del large_mimes
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False)
|
||||
self.send_dnd_command_to_kitten('DROP_MIMES')
|
||||
self.wait_for_responses('')
|
||||
all_mimes += ' image/png'
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False, all_mimes.split(), copy[0] + 1, copy[1] + 1)
|
||||
self.wait_for_state('drop_action', GLFW_DRAG_OPERATION_COPY)
|
||||
self.assertEqual('text/uri-list\x00image/png', self.probe_state('drop_mimes').rstrip('\x00'))
|
||||
dnd_test_fake_drop_event(self.capture.window_id, True, all_mimes.split(), copy[0] + 1, copy[1] + 1)
|
||||
self.send_dnd_command_to_kitten('DROP_MIMES')
|
||||
self.wait_for_responses(all_mimes)
|
||||
self.assertEqual('text/uri-list\x00image/png', self.probe_state('drop_mimes').rstrip('\x00'))
|
||||
self.wait_for_state('drop_data_requests', ((1, 0, 0), (4, 0, 0)))
|
||||
self.assertEqual('text/uri-list', self.probe_state('drop_getting_data_for_mime'))
|
||||
create_fs(self.src_data_dir)
|
||||
uri_list, path_list = [], []
|
||||
for x in sorted(os.listdir(self.src_data_dir)):
|
||||
uri_list.append(as_file_url(self.src_data_dir, x))
|
||||
uri_list = ['moose:cow', '# file:///frog/march'] + uri_list
|
||||
uri_list.insert(3, 'ignore://me')
|
||||
for x in uri_list:
|
||||
if x.startswith('#'):
|
||||
continue
|
||||
if x.startswith('file://'):
|
||||
path_list.append(unquote(urlparse(x).path))
|
||||
else:
|
||||
path_list.append('')
|
||||
dnd_test_fake_drop_data(self.capture.window_id, 'text/uri-list', '\r\n'.join(uri_list).encode())
|
||||
self.assertEqual('image/png', self.probe_state('drop_getting_data_for_mime'))
|
||||
|
||||
def send_file_in_chunks(f, mime, sz=3072):
|
||||
while True:
|
||||
chunk = f.read(sz)
|
||||
if not chunk:
|
||||
break
|
||||
dnd_test_fake_drop_data(self.capture.window_id, mime, chunk, 0, True)
|
||||
dnd_test_fake_drop_data(self.capture.window_id, mime, b'')
|
||||
|
||||
self.send_dnd_command_to_kitten('DROP_IS_REMOTE')
|
||||
self.wait_for_responses(str(remote_client))
|
||||
|
||||
with open(os.path.join(self.src_data_dir, 'some-image.png'), 'rb') as f:
|
||||
send_file_in_chunks(f, 'image/png', 1117)
|
||||
|
||||
self.send_dnd_command_to_kitten('DROP_URI_LIST')
|
||||
self.wait_for_responses('|'.join(path_list))
|
||||
jn = os.path.join
|
||||
self.assert_files_have_same_content(jn(self.src_data_dir, 'some-image.png'), jn(self.kitten_wd, img_drop_path))
|
||||
shutil.rmtree(os.path.dirname(jn(self.kitten_wd, img_drop_path)))
|
||||
self.wait_for_state('last_drop_action', GLFW_DRAG_OPERATION_COPY)
|
||||
self.wait_for_state('drop_action', 0)
|
||||
self.assert_trees_equal(self.src_data_dir, self.kitten_wd)
|
||||
|
||||
# ---- edge case: blank lines in text/uri-list are treated as empty entries ----
|
||||
# RFC 2483 allows blank lines; parse_uri_list should skip them cleanly.
|
||||
with tempfile.NamedTemporaryFile(dir=self.src_data_dir, suffix='.txt', delete=False) as tf:
|
||||
tf.write(b'edge case blank line test')
|
||||
edge_file = tf.name
|
||||
blank_line_uri_list = ('\r\n' + as_file_url(self.src_data_dir, os.path.basename(edge_file)) + '\r\n\r\n').encode()
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False, ['text/uri-list'], copy[0] + 1, copy[1] + 1)
|
||||
self.wait_for_state('drop_action', GLFW_DRAG_OPERATION_COPY)
|
||||
dnd_test_fake_drop_event(self.capture.window_id, True, ['text/uri-list'], copy[0] + 1, copy[1] + 1)
|
||||
self.wait_for_state('drop_data_requests', ((1, 0, 0),))
|
||||
dnd_test_fake_drop_data(self.capture.window_id, 'text/uri-list', blank_line_uri_list)
|
||||
self.wait_for_state('drop_action', 0)
|
||||
# The file should have been copied despite surrounding blank lines in the URI list.
|
||||
self.assertTrue(
|
||||
os.path.exists(jn(self.kitten_wd, os.path.basename(edge_file))), 'File from URI list with surrounding blank lines should be copied to destination'
|
||||
)
|
||||
os.unlink(edge_file)
|
||||
|
||||
# ---- overwrite confirmation: Enter key allows the overwrite ----
|
||||
# kitten_wd already has 'some-image.png'; dropping the same filename again triggers confirmation.
|
||||
enter_content = b'overwrite-enter-test-content'
|
||||
overwrite_uri = (as_file_url(self.src_data_dir, 'some-image.png') + '\r\n').encode()
|
||||
|
||||
def do_overwrite_drop(src_content, key_press, action=GLFW_DRAG_OPERATION_COPY):
|
||||
with open(jn(self.src_data_dir, 'some-image.png'), 'wb') as f:
|
||||
f.write(src_content)
|
||||
orig_content = b'content-to-be-overwritten'
|
||||
path = jn(self.kitten_wd, 'some-image.png')
|
||||
os.unlink(path)
|
||||
with open(path, 'wb') as f:
|
||||
f.write(orig_content)
|
||||
expected_dest_content = src_content if action == GLFW_DRAG_OPERATION_COPY else orig_content
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False, ['text/uri-list'], copy[0] + 1, copy[1] + 1)
|
||||
self.wait_for_state('drop_action', GLFW_DRAG_OPERATION_COPY)
|
||||
dnd_test_fake_drop_event(self.capture.window_id, True, ['text/uri-list'], copy[0] + 1, copy[1] + 1)
|
||||
self.wait_for_state('drop_data_requests', ((1, 0, 0),))
|
||||
dnd_test_fake_drop_data(self.capture.window_id, 'text/uri-list', overwrite_uri)
|
||||
self.pty.wait_till(lambda: 'overwrite existing' in self.pty.screen_contents())
|
||||
self.pty.write_to_child(key_press)
|
||||
self.wait_for_state('last_drop_action', action)
|
||||
self.wait_for_state('drop_action', 0)
|
||||
with open(jn(self.kitten_wd, 'some-image.png'), 'rb') as f:
|
||||
self.assertEqual(expected_dest_content, f.read())
|
||||
|
||||
do_overwrite_drop(enter_content, '\x1b[13u')
|
||||
do_overwrite_drop(b'overwrite-esc-test-content', '\x1b[27u', 0) # ]]]
|
||||
|
||||
# ---- move operation: source items deleted for local client only ----
|
||||
move_file = jn(self.src_data_dir, 'move_test.txt')
|
||||
move_dir = jn(self.src_data_dir, 'move_test_dir')
|
||||
move_link = jn(self.src_data_dir, 'move_test_link')
|
||||
os.makedirs(move_dir)
|
||||
with open(jn(move_dir, 'inside.txt'), 'wb') as f:
|
||||
f.write(b'nested file in move dir')
|
||||
with open(move_file, 'wb') as f:
|
||||
f.write(b'move test content')
|
||||
os.symlink('nonexistent_target', move_link)
|
||||
move_uri = (
|
||||
as_file_url(self.src_data_dir, 'move_test.txt')
|
||||
+ '\r\n'
|
||||
+ as_file_url(self.src_data_dir, 'move_test_dir')
|
||||
+ '\r\n'
|
||||
+ as_file_url(self.src_data_dir, 'move_test_link')
|
||||
+ '\r\n'
|
||||
).encode()
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False, ['text/uri-list'], move[0] + 1, move[1] + 1)
|
||||
self.wait_for_state('drop_action', GLFW_DRAG_OPERATION_MOVE)
|
||||
dnd_test_fake_drop_event(self.capture.window_id, True, ['text/uri-list'], move[0] + 1, move[1] + 1)
|
||||
self.wait_for_state('drop_data_requests', ((1, 0, 0),))
|
||||
dnd_test_fake_drop_data(self.capture.window_id, 'text/uri-list', move_uri)
|
||||
self.wait_for_state('last_drop_action', GLFW_DRAG_OPERATION_MOVE)
|
||||
self.wait_for_state('drop_action', 0)
|
||||
self.roundtrip()
|
||||
if remote_client:
|
||||
# Remote move: source items must NOT be deleted (the source app handles deletion)
|
||||
self.assertTrue(os.path.exists(move_file), 'remote move: source file must not be deleted')
|
||||
self.assertTrue(os.path.isdir(move_dir), 'remote move: source directory must not be deleted')
|
||||
self.assertTrue(os.path.lexists(move_link), 'remote move: source symlink must not be deleted')
|
||||
else:
|
||||
# Local move: source items must be deleted after successful move
|
||||
self.assertFalse(os.path.exists(move_file), 'local move: source file must be deleted')
|
||||
self.assertFalse(os.path.exists(move_dir), 'local move: source directory must be deleted')
|
||||
self.assertFalse(os.path.lexists(move_link), 'local move: source symlink must be deleted')
|
||||
|
||||
# ---- data URI: inline data should be written to data-uri-N.ext in the destination ----
|
||||
data_uri_content_1 = b'data uri plain text content'
|
||||
data_uri_b64 = standard_b64encode(data_uri_content_1).decode()
|
||||
data_uri_content_2 = b'\x89PNG\r\n\x1a\n' + b'\x00' * 8 # fake PNG bytes
|
||||
data_uri_b64_2 = standard_b64encode(data_uri_content_2).decode()
|
||||
data_uri_list = (f'data:text/plain;base64,{data_uri_b64}\r\ndata:image/png;base64,{data_uri_b64_2}\r\n').encode()
|
||||
dnd_test_fake_drop_event(self.capture.window_id, False, ['text/uri-list'], copy[0] + 1, copy[1] + 1)
|
||||
self.wait_for_state('drop_action', GLFW_DRAG_OPERATION_COPY)
|
||||
dnd_test_fake_drop_event(self.capture.window_id, True, ['text/uri-list'], copy[0] + 1, copy[1] + 1)
|
||||
self.wait_for_state('drop_data_requests', ((1, 0, 0),))
|
||||
dnd_test_fake_drop_data(self.capture.window_id, 'text/uri-list', data_uri_list)
|
||||
self.wait_for_state('last_drop_action', GLFW_DRAG_OPERATION_COPY)
|
||||
self.wait_for_state('drop_action', 0)
|
||||
data_uri_file_1 = jn(self.kitten_wd, 'data-uri-1.txt')
|
||||
data_uri_file_2 = jn(self.kitten_wd, 'data-uri-2.png')
|
||||
self.assertTrue(os.path.exists(data_uri_file_1), f'data URI file 1 should be created at {data_uri_file_1}')
|
||||
self.assertTrue(os.path.exists(data_uri_file_2), f'data URI file 2 should be created at {data_uri_file_2}')
|
||||
with open(data_uri_file_1, 'rb') as f:
|
||||
self.assertEqual(data_uri_content_1, f.read())
|
||||
with open(data_uri_file_2, 'rb') as f:
|
||||
self.assertEqual(data_uri_content_2, f.read())
|
||||
os.unlink(data_uri_file_1)
|
||||
os.unlink(data_uri_file_2)
|
||||
|
||||
def assert_files_have_same_content(self, a, b):
|
||||
with open(a, 'rb') as fa, open(b, 'rb') as fb:
|
||||
self.assertEqual(fa.read(), fb.read(), f'{a} ({os.path.getsize(a)}) != {b} ({os.path.getsize(b)})')
|
||||
|
||||
def test_dnd_kitten_stdin(self):
|
||||
from .graphics import png_data
|
||||
|
||||
drag_thumbnail = os.path.join(self.test_dir, 'drag.png')
|
||||
with open(drag_thumbnail, 'wb') as f:
|
||||
f.write(png_data)
|
||||
file_path = os.path.join(self.kitten_wd, 'text.txt')
|
||||
file_data = b'file contents'
|
||||
with open(file_path, 'wb') as f:
|
||||
f.write(file_data)
|
||||
stdin_data = b'<b>hello</b>\x00\xff'
|
||||
for cli_args, expected in (
|
||||
((), {'text/plain': stdin_data}),
|
||||
(('--drag=text/plain:-',), {'text/plain': stdin_data}),
|
||||
(('--drag=text/plain:/dev/stdin',), {'text/plain': stdin_data}),
|
||||
(('--drag=text/html:-',), {'text/html': stdin_data}),
|
||||
(('--drag=text/html:/dev/stdin',), {'text/html': stdin_data}),
|
||||
(('--drag=text/html:-', '--drag=text/plain:/dev/stdin'), {'text/html': stdin_data, 'text/plain': stdin_data}),
|
||||
((f'--drag=text/plain:{file_path}', '--drag=text/html:-'), {'text/plain': file_data, 'text/html': stdin_data}),
|
||||
((f'--drag=text/html:{file_path}',), {'text/plain': stdin_data, 'text/html': file_data}),
|
||||
((f'--drag=text/plain:{file_path}', '--drag=text/plain:-'), {'text/plain': stdin_data}),
|
||||
(('--drag=text/plain:-', f'--drag=text/plain:{file_path}'), {'text/plain': file_data}),
|
||||
):
|
||||
with self.subTest(cli_args=cli_args):
|
||||
read_fd, write_fd = os.pipe()
|
||||
with os.fdopen(write_fd, 'wb') as f:
|
||||
f.write(stdin_data)
|
||||
self.finish_setup(cli_args=(f'--drag-thumbnail={drag_thumbnail}',) + cli_args, stdin_fd=read_fd)
|
||||
try:
|
||||
self.assertTrue(self.probe_state('can_offer'))
|
||||
copy, move = self.get_button_geometry()
|
||||
dnd_test_start_drag_offer(self.capture.window_id, copy[0] + 1, copy[1] + 1)
|
||||
self.send_dnd_command_to_kitten('DRAG_ACTIVE')
|
||||
self.wait_for_responses('DRAG_ACTIVE')
|
||||
self.send_dnd_command_to_kitten('DRAG_OK')
|
||||
self.wait_for_responses('DRAG_OK')
|
||||
self.assertEqual(set(self.probe_state('drag_mimes')), set(expected))
|
||||
for mime, payload in expected.items():
|
||||
self.assertEqual(self.read_drag_data(mime), payload)
|
||||
finally:
|
||||
self.exit_kitten()
|
||||
|
||||
def test_dnd_kitten_drag(self):
|
||||
from .graphics import png_data
|
||||
|
||||
drag_thumbnail = os.path.join(self.test_dir, 'drag.png')
|
||||
with open(drag_thumbnail, 'wb') as f:
|
||||
f.write(png_data)
|
||||
img_drag_path = 'image.png'
|
||||
|
||||
def create_files():
|
||||
with open(os.path.join(self.kitten_wd, img_drag_path), 'wb') as f:
|
||||
self.img_drag_data = os.urandom(10113)
|
||||
f.write(self.img_drag_data)
|
||||
create_fs(self.src_data_dir)
|
||||
|
||||
create_files()
|
||||
tl = tuple(os.path.join(self.src_data_dir, x) for x in os.listdir(self.src_data_dir))
|
||||
self.finish_setup(cli_args=(f'--drag-thumbnail={drag_thumbnail}', f'--drag=image/png:{img_drag_path}') + tl) # )))
|
||||
with self.subTest(remote_client=False):
|
||||
self.dnd_kitten_drag(False, img_drag_path)
|
||||
self.reset_kitten(True)
|
||||
create_files()
|
||||
with self.subTest(remote_client=True):
|
||||
self.dnd_kitten_drag(True, img_drag_path)
|
||||
self.exit_kitten()
|
||||
self.img_drag_data = None
|
||||
|
||||
def read_drag_data(self, mime, timeout=10):
|
||||
# self.pty.log_data_flow = True
|
||||
ans = b''
|
||||
end_time = time.monotonic() + timeout
|
||||
while time.monotonic() <= end_time:
|
||||
try:
|
||||
chunk = dnd_test_drag_get_data(self.capture.window_id, mime)
|
||||
if not chunk:
|
||||
return ans
|
||||
ans += chunk
|
||||
except OSError as err:
|
||||
if err.errno == errno.EAGAIN:
|
||||
self.pty.process_input_from_child(timeout=end_time - time.monotonic())
|
||||
continue
|
||||
chunk = ans = b''
|
||||
raise
|
||||
chunk = ans = b''
|
||||
raise TimeoutError(f'timed out waiting for data from drag_get_data for {mime}')
|
||||
|
||||
def dnd_kitten_drag(self, remote_client, img_drop_path):
|
||||
# self.pty.log_data_flow = True
|
||||
copy, move = self.get_button_geometry()
|
||||
self.wait_for_state('can_offer', True)
|
||||
self.wait_for_state('drag_operations', 0)
|
||||
|
||||
def wait_for_drag_active(active=True):
|
||||
self.send_dnd_command_to_kitten('DRAG_ACTIVE')
|
||||
self.wait_for_responses('DRAG_ACTIVE' if active else 'DRAG_INACTIVE')
|
||||
if active:
|
||||
self.send_dnd_command_to_kitten('DRAG_OK')
|
||||
self.wait_for_responses('DRAG_OK')
|
||||
|
||||
def start_drag(x, y, expected):
|
||||
dnd_test_start_drag_offer(self.capture.window_id, x, y)
|
||||
wait_for_drag_active()
|
||||
self.wait_for_state('drag_operations', expected)
|
||||
self.wait_for_state('drag_thumbnail_size', 4)
|
||||
|
||||
def end_drag(canceled=True):
|
||||
dnd_test_drag_finish(self.capture.window_id, canceled)
|
||||
wait_for_drag_active(False)
|
||||
self.wait_for_state('drag_operations', 0)
|
||||
|
||||
start_drag(move[0] + 1, move[1] + 1, 2)
|
||||
self.assertEqual(set(self.probe_state('drag_mimes')), {'image/png', 'text/uri-list'})
|
||||
end_drag()
|
||||
start_drag(copy[0] + 1, copy[1] + 1, 1)
|
||||
end_drag()
|
||||
start_drag(1, 1, 3)
|
||||
dnd_test_drag_notify(self.capture.window_id, 0, 'text/uri-list')
|
||||
dnd_test_drag_notify(self.capture.window_id, 1, '', GLFW_DRAG_OPERATION_MOVE)
|
||||
dnd_test_force_drag_dropped(self.capture.window_id)
|
||||
dnd_test_drag_notify(self.capture.window_id, 2)
|
||||
self.send_dnd_command_to_kitten('DRAG_STATUS')
|
||||
self.wait_for_responses('text/uri-list:2:true')
|
||||
self.assertEqual(self.img_drag_data, self.read_drag_data('image/png'))
|
||||
# if remote_client:
|
||||
# self.pty.log_data_flow = True
|
||||
uri_list = self.read_drag_data('text/uri-list').decode().splitlines()
|
||||
paths = set()
|
||||
for line in uri_list:
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#'):
|
||||
purl = urlparse(line)
|
||||
if purl.scheme == 'file':
|
||||
fpath = purl.path.rstrip('/') or '/'
|
||||
paths.add(fpath)
|
||||
if remote_client:
|
||||
self.assertNotEqual(self.src_data_dir, os.path.dirname(fpath))
|
||||
else:
|
||||
self.assertEqual(self.src_data_dir, os.path.dirname(fpath))
|
||||
src_items = set(os.listdir(self.src_data_dir))
|
||||
self.assertEqual(src_items, {os.path.basename(x) for x in paths})
|
||||
if remote_client:
|
||||
for actual in paths:
|
||||
expected = os.path.join(self.src_data_dir, os.path.basename(actual))
|
||||
if os.path.isdir(actual):
|
||||
self.assert_trees_equal(expected, actual)
|
||||
elif os.path.islink(actual):
|
||||
self.assertEqual(os.readlink(expected), os.readlink(actual))
|
||||
else:
|
||||
self.assert_files_have_same_content(expected, actual)
|
||||
src_items_before = set(os.listdir(self.src_data_dir))
|
||||
end_drag(False)
|
||||
if remote_client:
|
||||
# After a move drag finishes, all source files from text/uri-list should be deleted
|
||||
for name in src_items_before:
|
||||
item_path = os.path.join(self.src_data_dir, name)
|
||||
self.assertFalse(os.path.lexists(item_path), f'move drag: {name} should have been deleted from source')
|
||||
@@ -0,0 +1,342 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from kitty.fast_data_types import Region
|
||||
from kitty.layout.base import carve_docks, lgd, outer_region_of
|
||||
from kitty.layout.interface import Splits, Stack, Tall
|
||||
from kitty.tabs import DetachedGroup
|
||||
from kitty.tabs import Tab as RealTab
|
||||
from kitty.types import DockSpec, parse_dock_spec
|
||||
from kitty.window_list import WindowGroup, WindowList, reset_group_id_counter
|
||||
|
||||
from .base import BaseTest
|
||||
from .layout import Tab, Window
|
||||
|
||||
VIEWPORT = Region((0, 0, 999, 599, 1000, 600))
|
||||
CELL_WIDTH, CELL_HEIGHT = 10, 20
|
||||
# The test windows have a margin, border and padding of one pixel on every edge
|
||||
DECORATION = 3
|
||||
|
||||
|
||||
class CountingWindow(Window):
|
||||
def __init__(self, win_id: int) -> None:
|
||||
super().__init__(win_id)
|
||||
self.set_geometry_calls = 0
|
||||
|
||||
def set_geometry(self, geometry):
|
||||
self.set_geometry_calls += 1
|
||||
super().set_geometry(geometry)
|
||||
|
||||
|
||||
def make_layout(cls):
|
||||
ans = cls(1, 1)
|
||||
ans.set_active_window_in_os_window = lambda idx: None
|
||||
ans.swap_windows_in_os_window = lambda a, b: None
|
||||
return ans
|
||||
|
||||
|
||||
def make_windows(layout, num=2):
|
||||
t = Tab()
|
||||
t.current_layout = layout
|
||||
t.windows = ans = WindowList(t)
|
||||
reset_group_id_counter()
|
||||
for i in range(num):
|
||||
layout.add_window(ans, CountingWindow(i + 1))
|
||||
ans.set_active_group_idx(0)
|
||||
return ans
|
||||
|
||||
|
||||
def add_dock(layout, windows, win_id, edge='bottom', size='1', focusable=True, owner=None):
|
||||
w = CountingWindow(win_id)
|
||||
layout.add_window(windows, w, dock=parse_dock_spec(edge, size, focusable), dock_owner=owner)
|
||||
return w
|
||||
|
||||
|
||||
def rect(r):
|
||||
return r.left, r.top, r.left + r.width, r.top + r.height
|
||||
|
||||
|
||||
def overlaps(a, b):
|
||||
al, at, ar, ab = rect(a)
|
||||
bl, bt, br, bb = rect(b)
|
||||
return al < br and bl < ar and at < bb and bt < ab
|
||||
|
||||
|
||||
class TestDocks(BaseTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.set_options({'tab_bar_style': 'hidden'})
|
||||
self.viewport_patch = patch('kitty.layout.base.viewport_for_window', return_value=(VIEWPORT, VIEWPORT, 1000, 600, CELL_WIDTH, CELL_HEIGHT))
|
||||
self.viewport_patch.start()
|
||||
|
||||
def tearDown(self):
|
||||
self.viewport_patch.stop()
|
||||
super().tearDown()
|
||||
|
||||
def check_no_overlaps(self, windows):
|
||||
regions = [(g.id, outer_region_of(g.geometry)) for g in windows.iter_visible_groups()]
|
||||
for i, (gid, r) in enumerate(regions):
|
||||
left, top, right, bottom = rect(r)
|
||||
self.assertTrue(0 <= left and 0 <= top and right <= 1000 and bottom <= 600, f'group {gid} is outside the viewport: {r}')
|
||||
for oid, o in regions[i + 1 :]:
|
||||
self.assertFalse(overlaps(r, o), f'groups {gid} and {oid} overlap: {r} {o}')
|
||||
|
||||
def test_dock_spec_parsing(self):
|
||||
self.ae(parse_dock_spec('left', '3'), DockSpec('left', 3, False, True))
|
||||
self.ae(parse_dock_spec('top', ' 12.5% ', False), DockSpec('top', 12.5, True, False))
|
||||
self.ae(parse_dock_spec('top', '100%').size_as_string, '100%')
|
||||
for edge, size in (('middle', '1'), ('top', '0'), ('top', '-1'), ('top', '0%'), ('top', '101%'), ('top', 'x'), ('top', '1.5'), ('top', 'nan%')):
|
||||
with self.subTest(edge=edge, size=size), self.assertRaises(ValueError):
|
||||
parse_dock_spec(edge, size)
|
||||
spec = parse_dock_spec('right', '30%', False)
|
||||
self.ae(spec.as_launch_args('window'), ['--type=window-dock', '--dock-edge=right', '--dock-size=30%', '--dock-skip-focus'])
|
||||
self.ae(parse_dock_spec('top', '2').as_launch_args('tab'), ['--type=tab-dock', '--dock-edge=top', '--dock-size=2'])
|
||||
|
||||
def test_carving(self):
|
||||
def dock(edge, size):
|
||||
g = WindowGroup(parse_dock_spec(edge, size))
|
||||
g.add_window(Window(len(groups) + 1))
|
||||
groups.append(g)
|
||||
return g
|
||||
|
||||
groups: list[WindowGroup] = []
|
||||
top, left, bottom = dock('top', '2'), dock('left', '10%'), dock('bottom', '1')
|
||||
content, placements = carve_docks(VIEWPORT, groups, CELL_WIDTH, CELL_HEIGHT)
|
||||
self.ae([g for g, r in placements], groups)
|
||||
regions = {g.id: rect(r) for g, r in placements}
|
||||
# earlier docks span the full extent, later docks fit into what remains
|
||||
self.ae(regions[top.id], (0, 0, 1000, 2 * CELL_HEIGHT + 2 * DECORATION))
|
||||
self.ae(regions[left.id], (0, 46, 100, 600))
|
||||
self.ae(regions[bottom.id], (100, 600 - CELL_HEIGHT - 2 * DECORATION, 1000, 600))
|
||||
self.ae(rect(content), (100, 46, 1000, 574))
|
||||
|
||||
# When space runs out, later docks shrink first and the content can be squeezed to nothing
|
||||
groups = []
|
||||
dock('top', '90%'), dock('bottom', '20%')
|
||||
content, placements = carve_docks(VIEWPORT, groups, CELL_WIDTH, CELL_HEIGHT)
|
||||
self.ae([r.height for g, r in placements], [540, 60])
|
||||
self.ae(content.height, 0)
|
||||
groups = []
|
||||
dock('top', '90%'), dock('bottom', '50%')
|
||||
content, placements = carve_docks(VIEWPORT, groups, CELL_WIDTH, CELL_HEIGHT)
|
||||
self.ae([r.height for g, r in placements], [540, 60])
|
||||
content, placements = carve_docks(Region((0, 0, -1, -1, 0, 0)), groups, CELL_WIDTH, CELL_HEIGHT)
|
||||
self.ae([r.height for g, r in placements], [0, 0])
|
||||
|
||||
def test_tab_docks(self):
|
||||
q = make_layout(Tall)
|
||||
windows = make_windows(q, 2)
|
||||
status = add_dock(q, windows, 10, 'bottom', '1', focusable=False)
|
||||
side = add_dock(q, windows, 11, 'left', '20%')
|
||||
# docks are not part of the layout
|
||||
self.ae(windows.num_groups, 2)
|
||||
self.ae(len(windows), 4)
|
||||
# the non focusable dock did not take focus, the other one did
|
||||
self.assertIs(windows.active_window, side)
|
||||
self.assertIs(windows.active_main_window, windows.id_map[1])
|
||||
q(windows)
|
||||
self.ae(rect(outer_region_of(status.geometry)), (0, 600 - CELL_HEIGHT - 2 * DECORATION, 1000, 600))
|
||||
self.ae(rect(outer_region_of(side.geometry)), (0, 0, 200, 574))
|
||||
self.ae(status.geometry.ynum, 1)
|
||||
self.ae(rect(lgd.central), (200, 0, 1000, 574))
|
||||
self.assertTrue(all(w.is_visible_in_layout for w in windows))
|
||||
self.check_no_overlaps(windows)
|
||||
# cannot focus a dock that skips focus
|
||||
self.assertFalse(windows.set_active_group(windows.group_for_window(status).id))
|
||||
windows.set_active_window_group_for(status)
|
||||
self.assertIs(windows.active_window, side)
|
||||
# normal window operations do not apply to docks
|
||||
self.assertFalse(q.move_window(windows, 1))
|
||||
self.assertIsNone(windows.group_idx_for_window(side))
|
||||
# going back to the layout
|
||||
windows.activate_next_window_group(1)
|
||||
self.assertIs(windows.active_window, windows.id_map[2])
|
||||
windows.make_previous_group_active()
|
||||
self.assertIs(windows.active_window, side)
|
||||
# closing the dock returns focus to the layout
|
||||
windows.remove_window(side)
|
||||
self.assertIs(windows.active_window, windows.id_map[2])
|
||||
q(windows)
|
||||
self.ae(rect(lgd.central), (0, 0, 1000, 574))
|
||||
|
||||
def test_window_docks(self):
|
||||
q = make_layout(Tall)
|
||||
windows = make_windows(q, 2)
|
||||
owner = windows.groups[1]
|
||||
main = windows.id_map[2]
|
||||
bottom = add_dock(q, windows, 10, 'bottom', '2', owner=owner)
|
||||
right = add_dock(q, windows, 11, 'right', '25%', owner=owner)
|
||||
self.ae(owner.docks, [windows.group_for_window(bottom), windows.group_for_window(right)])
|
||||
self.assertIs(windows.active_window, right)
|
||||
# Focusing a dock makes its owner the active normal group
|
||||
self.assertIs(windows.active_main_group, owner)
|
||||
q(windows)
|
||||
allocated = outer_region_of(owner.allocated_geometry)
|
||||
content = outer_region_of(main.geometry)
|
||||
dock_regions = [outer_region_of(w.geometry) for w in (bottom, right)]
|
||||
# The owner and its docks exactly share the area the layout gave the owner
|
||||
self.ae(sum(r.width * r.height for r in [content] + dock_regions), allocated.width * allocated.height)
|
||||
for r in [content] + dock_regions:
|
||||
self.assertTrue(rect(r)[0] >= allocated.left and rect(r)[2] <= allocated.left + allocated.width)
|
||||
self.ae(rect(dock_regions[0])[1], allocated.top + allocated.height - 2 * CELL_HEIGHT - 2 * DECORATION)
|
||||
self.ae(dock_regions[1].width, allocated.width // 4)
|
||||
self.check_no_overlaps(windows)
|
||||
# The decorations chosen by the layout for the owner are preserved
|
||||
self.ae(main.geometry.spaces.left - main.geometry.compensatory.left, DECORATION)
|
||||
|
||||
# Relayouts resize the owner's windows only once
|
||||
for w in windows:
|
||||
w.set_geometry_calls = 0
|
||||
q(windows)
|
||||
self.ae({w.id: w.set_geometry_calls for w in windows}, {1: 1, 2: 1, 10: 1, 11: 1})
|
||||
|
||||
# Closing the owner orphans its docks, they are hidden and closed by the tab
|
||||
windows.remove_window(main)
|
||||
self.ae(windows.num_groups, 1)
|
||||
self.ae([list(d) for d in windows.orphaned_docks], [[bottom], [right]])
|
||||
self.assertIs(windows.active_window, windows.id_map[1])
|
||||
q(windows)
|
||||
self.assertFalse(bottom.is_visible_in_layout or right.is_visible_in_layout)
|
||||
windows.remove_window(bottom)
|
||||
windows.remove_window(right)
|
||||
self.ae(windows.orphaned_docks, [])
|
||||
self.ae(len(windows), 1)
|
||||
|
||||
def test_docks_follow_owner_visibility(self):
|
||||
q = make_layout(Stack)
|
||||
windows = make_windows(q, 2)
|
||||
dock = add_dock(q, windows, 10, 'top', '1', owner=windows.groups[0])
|
||||
overlay = CountingWindow(11)
|
||||
q.add_window(windows, overlay, overlay_for=dock.id)
|
||||
self.assertIs(windows.group_for_window(overlay), windows.group_for_window(dock))
|
||||
self.assertIs(windows.active_window, overlay)
|
||||
q(windows)
|
||||
self.ae((dock.is_visible_in_layout, overlay.is_visible_in_layout), (False, True))
|
||||
self.assertTrue(windows.id_map[1].is_visible_in_layout)
|
||||
windows.set_active_group_idx(1)
|
||||
q(windows)
|
||||
self.assertFalse(windows.id_map[1].is_visible_in_layout or overlay.is_visible_in_layout)
|
||||
self.assertTrue(windows.id_map[2].is_visible_in_layout)
|
||||
self.check_no_overlaps(windows)
|
||||
|
||||
def test_removing_earlier_group_keeps_dock_owner_active(self):
|
||||
q = make_layout(Tall)
|
||||
windows = make_windows(q, 3)
|
||||
dock = add_dock(q, windows, 10, owner=windows.groups[2])
|
||||
self.assertIs(windows.active_window, dock)
|
||||
windows.remove_window(windows.id_map[1])
|
||||
self.assertIs(windows.active_window, dock)
|
||||
self.assertIs(windows.active_main_window, windows.id_map[3])
|
||||
|
||||
def test_dock_neighbors(self):
|
||||
q = make_layout(Tall)
|
||||
windows = make_windows(q, 2)
|
||||
g1, g2 = windows.groups
|
||||
outer = add_dock(q, windows, 10, 'bottom', owner=g2)
|
||||
inner = add_dock(q, windows, 11, 'bottom', owner=g2)
|
||||
add_dock(q, windows, 12, 'right', owner=g2, focusable=False)
|
||||
tab_dock = add_dock(q, windows, 13, 'top')
|
||||
q(windows)
|
||||
gid = {w.id: windows.group_for_window(w).id for w in windows}
|
||||
|
||||
def neighbors(wid):
|
||||
return {k: v for k, v in q.neighbors_for_any_window(windows.id_map[wid], windows).items() if v}
|
||||
|
||||
# the innermost dock is next to its owner, docks that skip focus are skipped
|
||||
self.ae(neighbors(2), {'left': [g1.id], 'bottom': [gid[11]], 'top': [gid[13]]})
|
||||
self.ae(neighbors(11), {'left': [g1.id], 'top': [g2.id], 'bottom': [gid[10]]})
|
||||
self.ae(neighbors(10), {'left': [g1.id], 'top': [gid[11]]})
|
||||
self.ae(neighbors(1), {'right': [g2.id], 'top': [gid[13]]})
|
||||
windows.set_active_group_idx(1)
|
||||
self.ae(neighbors(13), {'bottom': [g2.id]})
|
||||
# neighbors for windows in the layout are unchanged when there are no docks
|
||||
windows.remove_window(tab_dock)
|
||||
windows.remove_window(outer)
|
||||
windows.remove_window(inner)
|
||||
self.ae(neighbors(1), {'right': [g2.id]})
|
||||
|
||||
def test_splits_ignore_docks(self):
|
||||
q = make_layout(Splits)
|
||||
windows = make_windows(q, 0)
|
||||
for wid in (1, 2):
|
||||
q.add_window(windows, CountingWindow(wid), location='vsplit')
|
||||
add_dock(q, windows, 10, 'left', '5', owner=windows.groups[0])
|
||||
add_dock(q, windows, 11, 'top', '2')
|
||||
# new windows are never split off a docked window
|
||||
q.add_window(windows, CountingWindow(3), location='hsplit')
|
||||
q(windows)
|
||||
self.ae(set(q.pairs_root.all_window_ids()), {g.id for g in windows.groups})
|
||||
self.assertIsNone(q.layout_action('rotate', (), windows) if windows.active_dock else None)
|
||||
self.check_no_overlaps(windows)
|
||||
windows.set_active_window_group_for(windows.id_map[10])
|
||||
q.insert_window_next_to(windows, windows.id_map[10], windows.id_map[2], True, True)
|
||||
self.ae(set(q.pairs_root.all_window_ids()), {g.id for g in windows.groups})
|
||||
|
||||
def test_layout_state_ignores_docks(self):
|
||||
q = make_layout(Tall)
|
||||
windows = make_windows(q, 2)
|
||||
add_dock(q, windows, 10, owner=windows.groups[0])
|
||||
add_dock(q, windows, 11, 'top')
|
||||
state = windows.serialize_layout_state()
|
||||
window_id_map = {w.id: w.id for w in windows}
|
||||
self.assertIsNotNone(windows.unserialize_layout_state(state, window_id_map))
|
||||
del window_id_map[10], window_id_map[11]
|
||||
self.assertIsNotNone(windows.unserialize_layout_state(state, window_id_map))
|
||||
|
||||
def test_detach_and_attach_carry_docks(self):
|
||||
q = make_layout(Tall)
|
||||
windows = make_windows(q, 2)
|
||||
owner = windows.groups[0]
|
||||
dock = add_dock(q, windows, 10, 'right', '3', owner=owner)
|
||||
dock_overlay = CountingWindow(11)
|
||||
q.add_window(windows, dock_overlay, overlay_for=dock.id)
|
||||
boss = SimpleNamespace(mark_window_for_close=Mock())
|
||||
|
||||
def make_tab(windows):
|
||||
tab = SimpleNamespace(id=2, os_window_id=1, current_layout=q, windows=windows, mark_tab_bar_dirty=Mock(), relayout=Mock())
|
||||
tab.post_window_removal_update = Mock()
|
||||
for name in ('remove_window', 'detach_window', '_add_window', '_take_ownership_of_window', 'attach_window', 'attach_windows', 'set_active_window'):
|
||||
setattr(tab, name, getattr(RealTab, name).__get__(tab))
|
||||
return tab
|
||||
|
||||
src = make_tab(windows)
|
||||
for w in windows:
|
||||
w.change_tab = Mock()
|
||||
with patch('kitty.tabs.detach_window'), patch('kitty.tabs.get_boss', return_value=boss):
|
||||
detached = src.detach_window(windows.id_map[1])
|
||||
self.assertIsInstance(detached, DetachedGroup)
|
||||
self.ae([w.id for w in detached.windows], [1])
|
||||
self.ae([(spec.edge, [w.id for w in ws]) for spec, ws in detached.docks], [('right', [10, 11])])
|
||||
self.ae([w.id for w in windows], [2])
|
||||
self.ae(windows.orphaned_docks, [])
|
||||
boss.mark_window_for_close.assert_not_called()
|
||||
|
||||
dest_windows = make_windows(q, 0)
|
||||
dest_windows.add_window(CountingWindow(5))
|
||||
dest = make_tab(dest_windows)
|
||||
with patch('kitty.tabs.attach_window'):
|
||||
dest.attach_windows(detached)
|
||||
new_owner = dest_windows.group_for_window(detached.windows[0])
|
||||
self.ae([[w.id for w in d] for d in new_owner.docks], [[10, 11]])
|
||||
self.ae(new_owner.docks[0].dock, parse_dock_spec('right', '3'))
|
||||
self.assertIs(dest_windows.active_window, detached.windows[0])
|
||||
|
||||
def test_closing_last_window_closes_docks(self):
|
||||
q = make_layout(Tall)
|
||||
windows = make_windows(q, 2)
|
||||
tab_dock = add_dock(q, windows, 10, 'top')
|
||||
owned = add_dock(q, windows, 11, owner=windows.groups[1])
|
||||
boss = SimpleNamespace(mark_window_for_close=Mock())
|
||||
tab = SimpleNamespace(id=2, os_window_id=1, windows=windows, post_window_removal_update=Mock())
|
||||
remove = RealTab.remove_window.__get__(tab)
|
||||
with patch('kitty.tabs.remove_window'), patch('kitty.tabs.get_boss', return_value=boss):
|
||||
remove(windows.id_map[2])
|
||||
self.ae([c.args[0] for c in boss.mark_window_for_close.call_args_list], [owned])
|
||||
boss.mark_window_for_close.reset_mock()
|
||||
remove(owned)
|
||||
boss.mark_window_for_close.assert_not_called()
|
||||
remove(windows.id_map[1])
|
||||
self.ae([c.args[0] for c in boss.mark_window_for_close.call_args_list], [tab_dock])
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import gc
|
||||
import os
|
||||
import tempfile
|
||||
from base64 import standard_b64encode
|
||||
|
||||
from kitty.launch import EditCmd, parse_edit_message
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
def encode_msg(*fields: tuple[str, str], simple: frozenset[str] = frozenset({'file_inode', 'file_data', 'abort_signaled', 'version'})) -> str:
|
||||
parts = []
|
||||
for k, v in fields:
|
||||
if k not in simple:
|
||||
v = standard_b64encode(v.encode('utf-8')).decode('ascii')
|
||||
parts.append(f'{k}={v}')
|
||||
return ','.join(parts)
|
||||
|
||||
|
||||
class TestEditInKitty(BaseTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.set_options()
|
||||
self.tdir = tempfile.mkdtemp()
|
||||
|
||||
def tearDown(self):
|
||||
self.rmtree_ignoring_errors(self.tdir)
|
||||
super().tearDown()
|
||||
|
||||
def test_edit_message_parsing(self):
|
||||
path = os.path.join(self.tdir, 'file.txt')
|
||||
with open(path, 'w') as f:
|
||||
f.write('local')
|
||||
st = os.stat(path)
|
||||
msg = encode_msg(
|
||||
('cwd', self.tdir),
|
||||
('a', '--type=tab'),
|
||||
('a', '+17'),
|
||||
('a', 'file.txt'),
|
||||
('file_inode', f'{st.st_dev}:{st.st_ino}:{st.st_mtime_ns}'),
|
||||
('file_data', standard_b64encode(b'local').decode('ascii')),
|
||||
)
|
||||
req = parse_edit_message(msg)
|
||||
self.ae(req.args, ['--type=tab', '+17', 'file.txt'])
|
||||
self.ae(req.cwd, self.tdir)
|
||||
self.ae(req.file_inode, (st.st_dev, st.st_ino))
|
||||
self.ae(req.file_data, b'local')
|
||||
self.ae(req.abort_signaled, '')
|
||||
|
||||
c = EditCmd(msg, False)
|
||||
self.ae(c.line_number, 17)
|
||||
self.ae(c.file_name, 'file.txt')
|
||||
self.ae(c.file_localpath, path)
|
||||
self.assertTrue(c.is_local_file)
|
||||
# no temporary directory is needed for a local file
|
||||
self.ae(c.tdir, '')
|
||||
|
||||
def test_edit_of_non_local_file_uses_own_tdir(self):
|
||||
msg = encode_msg(
|
||||
('cwd', self.tdir),
|
||||
('a', 'no-such-file.txt'),
|
||||
('file_inode', '1:2:3'),
|
||||
('file_data', standard_b64encode(b'remote data').decode('ascii')),
|
||||
)
|
||||
c = EditCmd(msg, True)
|
||||
self.assertFalse(c.is_local_file)
|
||||
self.assertTrue(c.tdir)
|
||||
self.assertNotEqual(os.path.realpath(c.tdir), os.path.realpath(self.tdir))
|
||||
self.ae(c.file_localpath, os.path.join(c.tdir, 'no-such-file.txt'))
|
||||
with open(c.file_localpath) as f:
|
||||
self.ae(f.read(), 'remote data')
|
||||
tdir = c.tdir
|
||||
del c
|
||||
gc.collect()
|
||||
self.assertFalse(os.path.exists(tdir), 'The temporary directory created for the edit was not deleted')
|
||||
|
||||
def test_edit_message_cannot_overwrite_internal_state(self):
|
||||
# A program writing to the terminal must not be able to point tdir at a
|
||||
# directory of its choosing, which would then be deleted recursively
|
||||
# when the EditCmd object is destroyed.
|
||||
victim = os.path.join(self.tdir, 'victim')
|
||||
os.mkdir(victim)
|
||||
with open(os.path.join(victim, 'data'), 'w') as f:
|
||||
f.write('precious')
|
||||
msg = encode_msg(('tdir', victim), ('abort_signaled', 'closed'), ('child_is_remote', 'yes'), ('is_local_file', 'yes'))
|
||||
c = EditCmd(msg, False)
|
||||
self.ae(c.tdir, '')
|
||||
self.ae(c.abort_signaled, 'interrupt')
|
||||
self.ae(c.child_is_remote, False)
|
||||
del c
|
||||
gc.collect()
|
||||
self.assertTrue(os.path.exists(os.path.join(victim, 'data')), 'The edit protocol message deleted a directory of its choosing')
|
||||
|
||||
def test_unknown_edit_message_keys_are_ignored(self):
|
||||
msg = encode_msg(('cwd', self.tdir), ('a', 'x.txt'), ('some_unknown_key', 'value'), ('file_inode', '1:2:3'))
|
||||
c = EditCmd(msg, False)
|
||||
self.assertFalse(hasattr(c, 'some_unknown_key'))
|
||||
# __slots__ prevents even a deliberate attempt at adding state
|
||||
with self.assertRaises(AttributeError):
|
||||
c.some_unknown_key = 'value'
|
||||
|
||||
def test_malformed_edit_messages(self):
|
||||
for inode in ('', 'a:b:c', '1:2', '1:2:x'):
|
||||
req = parse_edit_message(encode_msg(('file_inode', inode)))
|
||||
self.ae(req.file_inode, (-1, -1))
|
||||
self.ae(req.file_size, -1)
|
||||
self.assertRaises(ValueError, EditCmd, encode_msg(('version', '1'), ('a', 'x.txt')), False)
|
||||
@@ -0,0 +1,796 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
from collections import namedtuple
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from kittens.transfer.rsync import Differ, Hasher, Patcher, parse_ftc
|
||||
from kittens.transfer.utils import set_paths
|
||||
from kitty.constants import kitten_exe
|
||||
from kitty.file_transmission import Action, Compression, FileTransmissionCommand, FileType, TransmissionType, ZlibDecompressor
|
||||
from kitty.file_transmission import TestFileTransmission as FileTransmission
|
||||
|
||||
from .base import PTY, BaseTest
|
||||
|
||||
|
||||
def response(id='test', msg='', file_id='', name='', action='status', status='', size=-1):
|
||||
ans = {'action': 'status'}
|
||||
if id:
|
||||
ans['id'] = id
|
||||
if file_id:
|
||||
ans['file_id'] = file_id
|
||||
if name:
|
||||
ans['name'] = name
|
||||
if status:
|
||||
ans['status'] = status
|
||||
if size > -1:
|
||||
ans['size'] = size
|
||||
return ans
|
||||
|
||||
|
||||
def names_in(path):
|
||||
for dirpath, dirnames, filenames in os.walk(path):
|
||||
for d in dirnames + filenames:
|
||||
yield os.path.relpath(os.path.join(dirpath, d), path)
|
||||
|
||||
|
||||
def serialized_cmd(**fields) -> str:
|
||||
if 'id' not in fields:
|
||||
fields['id'] = 'test'
|
||||
for k, A in (('action', Action), ('ftype', FileType), ('ttype', TransmissionType), ('compression', Compression)):
|
||||
if k in fields:
|
||||
fields[k] = A[fields[k]]
|
||||
if isinstance(fields.get('data'), str):
|
||||
fields['data'] = fields['data'].encode('utf-8')
|
||||
ans = FileTransmissionCommand(**fields)
|
||||
return ans.serialize()
|
||||
|
||||
|
||||
def generate_data(block_size, num_blocks, *extra) -> bytes:
|
||||
extra = ''.join(extra)
|
||||
b = b'_' * (block_size * num_blocks) + extra.encode()
|
||||
ans = bytearray(b)
|
||||
for i in range(num_blocks):
|
||||
offset = i * block_size
|
||||
p = str(i).encode()
|
||||
ans[offset : offset + len(p)] = p
|
||||
return bytes(ans)
|
||||
|
||||
|
||||
def patch_data(data, *patches):
|
||||
total_patch_size = 0
|
||||
ans = bytearray(data)
|
||||
for patch in patches:
|
||||
o, sep, r = patch.partition(':')
|
||||
r = r.encode()
|
||||
total_patch_size += len(r)
|
||||
offset = int(o)
|
||||
ans[offset : offset + len(r)] = r
|
||||
return bytes(ans), len(patches), total_patch_size
|
||||
|
||||
|
||||
def run_roundtrip_test(self: 'TestFileTransmission', src_data, changed, num_of_patches, total_patch_size):
|
||||
buf = memoryview(bytearray(30))
|
||||
signature = bytearray(0)
|
||||
p = Patcher(len(changed))
|
||||
n = p.signature_header(buf)
|
||||
signature.extend(buf[:n])
|
||||
src = memoryview(changed)
|
||||
bs = p.block_size
|
||||
while src:
|
||||
n = p.sign_block(src[:bs], buf)
|
||||
signature.extend(buf[:n])
|
||||
src = src[bs:]
|
||||
d = Differ()
|
||||
src = memoryview(signature)
|
||||
while src:
|
||||
d.add_signature_data(src[:13])
|
||||
src = src[13:]
|
||||
d.finish_signature_data()
|
||||
del src, signature
|
||||
src = memoryview(src_data)
|
||||
delta = bytearray(0)
|
||||
|
||||
def read_into(b):
|
||||
nonlocal src
|
||||
n = min(len(b), len(src))
|
||||
if n > 0:
|
||||
b[:n] = src[:n]
|
||||
src = src[n:]
|
||||
return n
|
||||
|
||||
def write_delta(b):
|
||||
delta.extend(b)
|
||||
|
||||
while d.next_op(read_into, write_delta):
|
||||
pass
|
||||
delta = memoryview(delta)
|
||||
del src
|
||||
|
||||
def read_at(pos, output) -> int:
|
||||
b = changed[pos:]
|
||||
amt = min(len(output), len(b))
|
||||
output[:amt] = b[:amt]
|
||||
return amt
|
||||
|
||||
output = bytearray(0)
|
||||
|
||||
def write_changes(b):
|
||||
output.extend(b)
|
||||
|
||||
def debug_msg():
|
||||
return f'\n\nsrc:\n{src_data.decode()}\nchanged:\n{changed.decode()}\noutput:\n{output.decode()}'
|
||||
|
||||
try:
|
||||
while delta:
|
||||
p.apply_delta_data(delta[:11], read_at, write_changes)
|
||||
delta = delta[11:]
|
||||
p.finish_delta_data()
|
||||
except Exception as err:
|
||||
self.fail(f'{err}\n{debug_msg()}')
|
||||
self.assertEqual(src_data, bytes(output), debug_msg())
|
||||
limit = 2 * (p.block_size * num_of_patches)
|
||||
if limit > -1:
|
||||
self.assertLessEqual(p.total_data_in_delta, limit, f'Unexpectedly poor delta performance: {total_patch_size=} {p.total_data_in_delta=} {limit=}')
|
||||
|
||||
|
||||
def test_rsync_roundtrip(self: 'TestFileTransmission') -> None:
|
||||
block_size = 16
|
||||
src_data = generate_data(block_size, 16)
|
||||
changed, num_of_patches, total_patch_size = patch_data(src_data, '3:patch1', '16:patch2', '130:ptch3', '176:patch4', '222:XXYY')
|
||||
|
||||
run_roundtrip_test(self, src_data, src_data[block_size:], 1, block_size)
|
||||
run_roundtrip_test(self, src_data, changed, num_of_patches, total_patch_size)
|
||||
run_roundtrip_test(self, src_data, b'', -1, 0)
|
||||
run_roundtrip_test(self, src_data, src_data, 0, 0)
|
||||
run_roundtrip_test(self, src_data, changed[: len(changed) - 3], num_of_patches, total_patch_size)
|
||||
run_roundtrip_test(self, src_data, changed[:37] + changed[81:], num_of_patches, total_patch_size)
|
||||
|
||||
block_size = 13
|
||||
src_data = generate_data(block_size, 17, 'trailer')
|
||||
changed, num_of_patches, total_patch_size = patch_data(src_data, '0:patch1', '19:patch2')
|
||||
run_roundtrip_test(self, src_data, changed, num_of_patches, total_patch_size)
|
||||
run_roundtrip_test(self, src_data, changed[: len(changed) - 3], num_of_patches, total_patch_size)
|
||||
run_roundtrip_test(self, src_data, changed + b'xyz...', num_of_patches, total_patch_size)
|
||||
|
||||
|
||||
class PtyFileTransmission(FileTransmission):
|
||||
def __init__(self, pty, allow=True):
|
||||
self.pty = pty
|
||||
super().__init__(allow=allow)
|
||||
self.pty.callbacks.ftc = self
|
||||
|
||||
def write_ftc_to_child(self, payload: FileTransmissionCommand, appendleft: bool = False, use_pending: bool = True) -> bool:
|
||||
# print('to kitten:', payload)
|
||||
self.pty.write_to_child('\x1b]' + payload.serialize(prefix_with_osc_code=True) + '\x1b\\', flush=False)
|
||||
return True
|
||||
|
||||
|
||||
class TransferPTY(PTY):
|
||||
def __init__(self, cmd, cwd, allow=True, env=None):
|
||||
super().__init__(cmd, cwd=cwd, env=env, rows=200, columns=120)
|
||||
self.fc = PtyFileTransmission(self, allow=allow)
|
||||
|
||||
|
||||
class TestFileTransmission(BaseTest):
|
||||
def setUp(self):
|
||||
self.direction_receive = False
|
||||
self.kitty_home = self.kitty_cwd = self.kitten_home = self.kitten_cwd = ''
|
||||
super().setUp()
|
||||
self.tdir = os.path.realpath(tempfile.mkdtemp())
|
||||
self.responses = []
|
||||
self.orig_home = os.environ.get('HOME')
|
||||
|
||||
def tearDown(self):
|
||||
self.rmtree_ignoring_errors(self.tdir)
|
||||
self.responses = []
|
||||
if self.orig_home is None:
|
||||
os.environ.pop('HOME', None)
|
||||
else:
|
||||
os.environ['HOME'] = self.orig_home
|
||||
super().tearDown()
|
||||
|
||||
def clean_tdir(self):
|
||||
for x in os.listdir(self.tdir):
|
||||
x = os.path.join(self.tdir, x)
|
||||
if os.path.isdir(x):
|
||||
shutil.rmtree(x)
|
||||
else:
|
||||
os.remove(x)
|
||||
self.responses = []
|
||||
|
||||
def cr(self, a, b):
|
||||
def f(r):
|
||||
r.pop('size', None)
|
||||
return r
|
||||
|
||||
a = tuple(f(r) for r in a if r.get('status') != 'PROGRESS')
|
||||
b = tuple(f(r) for r in b if r.get('status') != 'PROGRESS')
|
||||
self.ae(a, b)
|
||||
|
||||
def assertResponses(self, ft, limit=1024, **kw):
|
||||
self.responses.append(response(**kw))
|
||||
self.cr(ft.test_responses[:limit], self.responses[:limit])
|
||||
|
||||
def assertPathEqual(self, a, b):
|
||||
a = os.path.abspath(os.path.realpath(a))
|
||||
b = os.path.abspath(os.path.realpath(b))
|
||||
self.ae(a, b)
|
||||
|
||||
def test_rsync_roundtrip(self):
|
||||
test_rsync_roundtrip(self)
|
||||
|
||||
def test_rsync_invalid_block_size(self):
|
||||
from kittens.transfer.rsync import RsyncError
|
||||
|
||||
for block_size in (0, 1024 * 1024 + 1):
|
||||
d = Differ()
|
||||
with self.assertRaises(RsyncError):
|
||||
d.add_signature_data(bytes(8) + block_size.to_bytes(4, 'little'))
|
||||
|
||||
def test_file_put_differential(self):
|
||||
from kitty.file_transmission import PatchFile
|
||||
|
||||
def start_receiving():
|
||||
ft = FileTransmission()
|
||||
ft.handle_serialized_command(serialized_cmd(action='send'))
|
||||
ft.test_responses = []
|
||||
return ft
|
||||
|
||||
def started_ttype(ft):
|
||||
q = [r for r in ft.test_responses if r.get('status') == 'STARTED']
|
||||
self.ae(len(q), 1)
|
||||
return q[0].get('ttype', 'simple')
|
||||
|
||||
def signature_sent(ft):
|
||||
return b''.join(r['data'] for r in ft.test_responses if r.get('action') == 'data' and r.get('data'))
|
||||
|
||||
base = os.path.join(self.tdir, 'diff')
|
||||
os.mkdir(base)
|
||||
|
||||
# a differential transfer to a plain regular file works as usual
|
||||
dest = os.path.join(base, 'f.bin')
|
||||
before = b'hello world ' * 5000
|
||||
after = (b'hello world ' * 4000) + (b'goodbye!' * 2000)
|
||||
with open(dest, 'wb') as f:
|
||||
f.write(before)
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='r', name=dest, ftype='regular', ttype='rsync'))
|
||||
self.ae(started_ttype(ft), 'rsync')
|
||||
d = Differ()
|
||||
d.add_signature_data(signature_sent(ft))
|
||||
d.finish_signature_data()
|
||||
src = memoryview(after)
|
||||
delta = bytearray()
|
||||
|
||||
def read_into(b):
|
||||
nonlocal src
|
||||
n = min(len(b), len(src))
|
||||
b[:n] = src[:n]
|
||||
src = src[n:]
|
||||
return n
|
||||
|
||||
while d.next_op(read_into, delta.extend):
|
||||
pass
|
||||
chunks = memoryview(bytes(delta))
|
||||
while len(chunks) > 4096:
|
||||
ft.handle_serialized_command(serialized_cmd(action='data', file_id='r', data=bytes(chunks[:4096])))
|
||||
chunks = chunks[4096:]
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='r', data=bytes(chunks)))
|
||||
with open(dest, 'rb') as f:
|
||||
self.ae(f.read(), after)
|
||||
self.ae(sorted(names_in(base)), ['f.bin'])
|
||||
|
||||
# a sender must not be able to use a differential transfer to read
|
||||
# through a symlink it plants at the destination in the same transfer
|
||||
secret_dir = os.path.join(base, 'secret')
|
||||
os.mkdir(secret_dir)
|
||||
secret = os.path.join(secret_dir, 'secret.txt')
|
||||
secret_data = b'super secret data' * 1000
|
||||
with open(secret, 'wb') as f:
|
||||
f.write(secret_data)
|
||||
sdest = os.path.join(base, 'innocent.bin')
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='s', name=sdest, ftype='symlink'))
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='s', data='path:' + secret))
|
||||
self.assertTrue(os.path.islink(sdest))
|
||||
ft.test_responses = []
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='r', name=sdest, ftype='regular', ttype='rsync'))
|
||||
self.ae(started_ttype(ft), 'simple')
|
||||
self.ae(signature_sent(ft), b'')
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='r', data='replacement'))
|
||||
self.assertFalse(os.path.islink(sdest))
|
||||
with open(sdest, 'rb') as f:
|
||||
self.ae(f.read(), b'replacement')
|
||||
with open(secret, 'rb') as f:
|
||||
self.ae(f.read(), secret_data)
|
||||
self.ae(sorted(names_in(secret_dir)), ['secret.txt'])
|
||||
|
||||
# likewise for a destination with more than one link to it
|
||||
hdest = os.path.join(base, 'hard.bin')
|
||||
other = os.path.join(base, 'other.bin')
|
||||
with open(hdest, 'wb') as f:
|
||||
f.write(b'original')
|
||||
os.link(hdest, other)
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='r', name=hdest, ftype='regular', ttype='rsync'))
|
||||
self.ae(started_ttype(ft), 'simple')
|
||||
self.ae(signature_sent(ft), b'')
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='r', data='replacement'))
|
||||
with open(other, 'rb') as f:
|
||||
self.ae(f.read(), b'original')
|
||||
|
||||
# and PatchFile itself must never follow a symlink, in case the
|
||||
# destination is swapped after it is created but before it is read
|
||||
pf = PatchFile(sdest, len(secret_data))
|
||||
os.remove(sdest)
|
||||
os.symlink(secret, sdest)
|
||||
with self.assertRaises(OSError):
|
||||
pf.next_signature_block(memoryview(bytearray(64)))
|
||||
# its temporary file goes next to the destination, not next to the
|
||||
# symlink target
|
||||
tf = pf.dest_file
|
||||
tf.close()
|
||||
self.assertPathEqual(os.path.dirname(tf.name), base)
|
||||
os.remove(tf.name)
|
||||
|
||||
def test_file_put_existing_directory(self):
|
||||
def start_receiving():
|
||||
ft = FileTransmission()
|
||||
ft.handle_serialized_command(serialized_cmd(action='send'))
|
||||
ft.test_responses = []
|
||||
return ft
|
||||
|
||||
def statuses(ft):
|
||||
return [r['status'] for r in ft.test_responses if r.get('action') == 'status']
|
||||
|
||||
base = os.path.join(self.tdir, 'existing')
|
||||
dest_dir = os.path.join(base, 'dir')
|
||||
os.makedirs(os.path.join(dest_dir, 'child'))
|
||||
dir_link = os.path.join(base, 'dir_link')
|
||||
os.symlink(dest_dir, dir_link)
|
||||
|
||||
# a regular file must not replace an existing directory or a symlink
|
||||
# to one, and data sent for it must be silently discarded
|
||||
for dest in (dest_dir, dir_link):
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='f', name=dest, ftype='regular'))
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='f', data='xyz'))
|
||||
self.ae(statuses(ft), [f'EISDIR:Cannot replace the existing directory {dest} with a file'])
|
||||
self.assertTrue(os.path.isdir(dest))
|
||||
self.assertTrue(os.path.islink(dir_link))
|
||||
self.ae(set(names_in(dest_dir)), {'child'})
|
||||
|
||||
# a symlink must not replace an existing directory
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='s', name=dest_dir, ftype='symlink'))
|
||||
self.ae(statuses(ft), [f'EISDIR:Cannot replace the existing directory {dest_dir} with a file'])
|
||||
self.assertTrue(os.path.isdir(dest_dir))
|
||||
|
||||
# but it may replace a symlink to a directory
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='s', name=dir_link, ftype='symlink'))
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='s', data='path:elsewhere'))
|
||||
self.ae(statuses(ft)[-1], 'OK')
|
||||
self.ae(os.readlink(dir_link), 'elsewhere')
|
||||
|
||||
# failure to create parent directories gives a clear error
|
||||
blocker = os.path.join(base, 'blocker')
|
||||
with open(blocker, 'w'):
|
||||
pass
|
||||
dest = os.path.join(blocker, 'sub', 'f')
|
||||
ft = start_receiving()
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='f', name=dest, ftype='regular'))
|
||||
ft.handle_serialized_command(serialized_cmd(action='end_data', file_id='f', data='xyz'))
|
||||
self.ae(statuses(ft), ['STARTED', f'ENOTDIR:Failed to create the directory {os.path.dirname(dest)}: Not a directory'])
|
||||
|
||||
def test_file_get(self):
|
||||
# send refusal
|
||||
for quiet in (0, 1, 2):
|
||||
ft = FileTransmission(allow=False)
|
||||
ft.handle_serialized_command(serialized_cmd(action='receive', id='x', quiet=quiet))
|
||||
self.cr(ft.test_responses, [] if quiet == 2 else [response(id='x', status='EPERM:User refused the transfer')])
|
||||
self.assertFalse(ft.active_sends)
|
||||
# reading metadata for specs
|
||||
cwd = os.path.join(self.tdir, 'cwd')
|
||||
home = os.path.join(self.tdir, 'home')
|
||||
os.mkdir(cwd), os.mkdir(home)
|
||||
with set_paths(cwd=cwd, home=home):
|
||||
ft = FileTransmission()
|
||||
self.responses = []
|
||||
ft.handle_serialized_command(serialized_cmd(action='receive', size=1))
|
||||
self.assertResponses(ft, status='OK')
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='missing', name='XXX'))
|
||||
self.responses.append(response(status='ENOENT:Failed to read spec', file_id='missing'))
|
||||
self.assertResponses(ft, status='OK', name=home)
|
||||
ft = FileTransmission()
|
||||
self.responses = []
|
||||
ft.handle_serialized_command(serialized_cmd(action='receive', size=2))
|
||||
self.assertResponses(ft, status='OK')
|
||||
with open(os.path.join(home, 'a'), 'w') as f:
|
||||
f.write('a')
|
||||
os.mkdir(f.name + 'd')
|
||||
with open(os.path.join(f.name + 'd', 'b'), 'w') as f2:
|
||||
f2.write('bbb')
|
||||
os.symlink(f.name, f.name + 'd/s')
|
||||
os.link(f.name, f.name + 'd/h')
|
||||
os.symlink('XXX', f.name + 'd/q')
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='a', name='a'))
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='b', name='ad'))
|
||||
files = {r['name']: r for r in ft.test_responses if r['action'] == 'file'}
|
||||
self.ae(len(files), 6)
|
||||
q = files[f.name]
|
||||
tgt = q['status'].encode('ascii')
|
||||
self.ae(q['size'], 1), self.assertNotIn('ftype', q)
|
||||
q = files[f.name + 'd']
|
||||
self.ae(q['ftype'], 'directory')
|
||||
q = files[f.name + 'd/b']
|
||||
self.ae(q['size'], 3)
|
||||
q = files[f.name + 'd/s']
|
||||
self.ae(q['ftype'], 'symlink')
|
||||
self.ae(q['data'], tgt)
|
||||
q = files[f.name + 'd/h']
|
||||
self.ae(q['ftype'], 'link')
|
||||
self.ae(q['data'], tgt)
|
||||
q = files[f.name + 'd/q']
|
||||
self.ae(q['ftype'], 'symlink')
|
||||
self.assertNotIn('data', q)
|
||||
base = os.path.join(self.tdir, 'base')
|
||||
os.mkdir(base)
|
||||
src = os.path.join(base, 'src.bin')
|
||||
data = os.urandom(16 * 1024)
|
||||
with open(src, 'wb') as f:
|
||||
f.write(data)
|
||||
sl = os.path.join(base, 'src.link')
|
||||
os.symlink(src, sl)
|
||||
for compress in ('none', 'zlib'):
|
||||
ft = FileTransmission()
|
||||
self.responses = []
|
||||
ft.handle_serialized_command(serialized_cmd(action='receive', size=1))
|
||||
self.assertResponses(ft, status='OK')
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='src', name=src))
|
||||
ft.active_sends['test'].metadata_sent = True
|
||||
ft.test_responses = []
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='src', name=src, compression=compress))
|
||||
received = b''.join(x['data'] for x in ft.test_responses)
|
||||
if compress == 'zlib':
|
||||
received = ZlibDecompressor()(received, True)
|
||||
self.ae(data, received)
|
||||
ft.test_responses = []
|
||||
ft.handle_serialized_command(serialized_cmd(action='file', file_id='sl', name=sl, compression=compress))
|
||||
received = b''.join(x['data'] for x in ft.test_responses)
|
||||
self.ae(received.decode('utf-8'), src)
|
||||
|
||||
def test_check_bypass(self):
|
||||
import json
|
||||
from base64 import b85encode
|
||||
from time import time_ns
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.fast_data_types import AES256GCMEncrypt, EllipticCurveKey
|
||||
from kitty.file_transmission import check_bypass, encode_bypass
|
||||
|
||||
from .crypto import is_rlimit_memlock_too_low
|
||||
|
||||
if is_rlimit_memlock_too_low():
|
||||
self.skipTest('RLIMIT_MEMLOCK is too low')
|
||||
kitty_key, remote_key = EllipticCurveKey(), EllipticCurveKey()
|
||||
|
||||
def kitty_1(request_id: str, password: str) -> str:
|
||||
e = AES256GCMEncrypt(remote_key.derive_secret(kitty_key.public))
|
||||
encrypted = e.add_data_to_be_encrypted(f'{time_ns()}:{request_id};{password}'.encode(), True)
|
||||
return 'kitty-1:' + json.dumps(
|
||||
{k: b85encode(v).decode() for k, v in {'pubkey': remote_key.public, 'iv': e.iv, 'tag': e.tag, 'encrypted': encrypted}.items()}
|
||||
)
|
||||
|
||||
with patch('kitty.file_transmission.get_boss', return_value=SimpleNamespace(encryption_key=kitty_key)):
|
||||
self.assertTrue(check_bypass('secret', 'rid', kitty_1('rid', 'secret')))
|
||||
self.assertFalse(check_bypass('secret', 'rid', kitty_1('rid', 'wrong')))
|
||||
self.assertFalse(check_bypass('secret', 'rid', kitty_1('other', 'secret')))
|
||||
self.assertTrue(check_bypass('secret', 'rid', encode_bypass('rid', 'secret')))
|
||||
# when no bypass password is configured, bypass must never succeed
|
||||
self.assertFalse(check_bypass('', 'rid', kitty_1('rid', '')))
|
||||
self.assertFalse(check_bypass('', 'rid', encode_bypass('rid', '')))
|
||||
|
||||
def test_parse_ftc(self):
|
||||
def t(raw, *expected):
|
||||
a = []
|
||||
|
||||
def c(k, v):
|
||||
a.append(str(k, 'utf-8'))
|
||||
a.append(str(v, 'utf-8'))
|
||||
|
||||
parse_ftc(raw, c)
|
||||
self.ae(tuple(a), expected)
|
||||
|
||||
t('a=b', 'a', 'b')
|
||||
t('a=b;', 'a', 'b')
|
||||
t('a1=b1;c=d;;', 'a1', 'b1', 'c', 'd')
|
||||
t('a1=b1;c=d;;e', 'a1', 'b1', 'c', 'd')
|
||||
t('a1=b1;c=d;;;1=1', 'a1', 'b1', 'c', 'd', '1', '1')
|
||||
|
||||
def test_rsync_hashers(self):
|
||||
h = Hasher('xxh3-64')
|
||||
h.update(b'abcd')
|
||||
self.assertEqual(h.hexdigest(), '6497a96f53a89890')
|
||||
self.assertEqual(h.digest64(), 7248448420886124688)
|
||||
h128 = Hasher('xxh3-128')
|
||||
h128.update(b'abcd')
|
||||
self.assertEqual(h128.hexdigest(), '8d6b60383dfa90c21be79eecd1b1353d')
|
||||
|
||||
@contextmanager
|
||||
def run_kitten(self, cmd, home_dir='', allow=True, cwd=''):
|
||||
cwd = cwd or self.kitten_cwd or self.tdir
|
||||
cmd = [kitten_exe(), 'transfer'] + (['--direction=receive'] if self.direction_receive else []) + cmd
|
||||
env = {'PWD': cwd}
|
||||
env['HOME'] = home_dir or self.kitten_home or self.tdir
|
||||
with set_paths(home=self.kitty_home, cwd=self.kitty_cwd):
|
||||
pty = TransferPTY(cmd, cwd=cwd, allow=allow, env=env)
|
||||
i = 10
|
||||
while i > 0 and not pty.screen_contents().strip():
|
||||
pty.process_input_from_child()
|
||||
i -= 1
|
||||
yield pty
|
||||
|
||||
def basic_transfer_tests(self):
|
||||
src = os.path.join(self.tdir, 'src')
|
||||
self.src_data = os.urandom(11113)
|
||||
with open(src, 'wb') as s:
|
||||
s.write(self.src_data)
|
||||
dest = os.path.join(self.tdir, 'dest')
|
||||
with self.run_kitten([src, dest], allow=False) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=1)
|
||||
self.assertFalse(os.path.exists(dest))
|
||||
|
||||
def single_file(*cmd):
|
||||
with self.run_kitten(list(cmd) + [src, dest]) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
with open(dest, 'rb') as f:
|
||||
self.assertEqual(self.src_data, f.read())
|
||||
|
||||
single_file()
|
||||
single_file()
|
||||
single_file('--transmit-deltas')
|
||||
with open(dest, 'wb') as d:
|
||||
d.write(os.urandom(1023))
|
||||
single_file('--transmit-deltas')
|
||||
os.remove(dest)
|
||||
single_file('--transmit-deltas')
|
||||
single_file('--compress=never')
|
||||
single_file('--compress=always')
|
||||
single_file('--transmit-deltas', '--compress=never')
|
||||
|
||||
def empty_file(*cmd, existing_dest_data=None):
|
||||
esrc = os.path.join(self.tdir, 'esrc')
|
||||
edest = os.path.join(self.tdir, 'edest')
|
||||
open(esrc, 'wb').close()
|
||||
if existing_dest_data is None:
|
||||
if os.path.exists(edest):
|
||||
os.remove(edest)
|
||||
else:
|
||||
with open(edest, 'wb') as d:
|
||||
d.write(existing_dest_data)
|
||||
with self.run_kitten(list(cmd) + [esrc, edest]) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
self.assertTrue(os.path.isfile(edest), f'{edest} was not created by: {cmd}')
|
||||
self.ae(os.path.getsize(edest), 0, f'{edest} is not empty after: {cmd}')
|
||||
|
||||
empty_file()
|
||||
# an existing destination must be truncated
|
||||
empty_file(existing_dest_data=b'stale')
|
||||
# an existing destination larger than the signature threshold causes an rsync transfer
|
||||
empty_file('--transmit-deltas', existing_dest_data=os.urandom(8192))
|
||||
empty_file('--transmit-deltas')
|
||||
|
||||
def multiple_files(*cmd):
|
||||
src = os.path.join(self.tdir, 'msrc')
|
||||
dest = os.path.join(self.tdir, 'mdest')
|
||||
if os.path.exists(src):
|
||||
shutil.rmtree(src)
|
||||
os.mkdir(src)
|
||||
os.makedirs(dest, exist_ok=True)
|
||||
|
||||
expected = {}
|
||||
Entry = namedtuple('Entry', 'relpath mtime mode nlink')
|
||||
|
||||
def entry(path, base=src):
|
||||
st = os.stat(path, follow_symlinks=False)
|
||||
mtime = st.st_mtime_ns
|
||||
if stat.S_ISDIR(st.st_mode):
|
||||
mtime = 0 # mtime is flaky for dirs on CI even empty ones
|
||||
return Entry(os.path.relpath(path, base), mtime, oct(st.st_mode), st.st_nlink)
|
||||
|
||||
def se(path):
|
||||
e = entry(path)
|
||||
expected[e.relpath] = e
|
||||
|
||||
b = Path(src)
|
||||
with open(b / 'simple', 'wb') as f:
|
||||
f.write(os.urandom(1317))
|
||||
os.fchmod(f.fileno(), 0o766)
|
||||
os.link(f.name, b / 'hardlink')
|
||||
os.utime(f.name, (1.3, 1.3))
|
||||
se(f.name)
|
||||
se(str(b / 'hardlink'))
|
||||
os.mkdir(b / 'empty')
|
||||
se(str(b / 'empty'))
|
||||
with open(b / 'emptyfile', 'wb') as f:
|
||||
os.fchmod(f.fileno(), 0o640)
|
||||
os.utime(f.name, (2345.6, 2345.6))
|
||||
se(f.name)
|
||||
s = b / 'sub'
|
||||
os.mkdir(s)
|
||||
with open(s / 'reg', 'wb') as f:
|
||||
f.write(os.urandom(113))
|
||||
os.utime(f.name, (1171.3, 1171.3))
|
||||
se(f.name)
|
||||
se(str(s))
|
||||
os.symlink('/', b / 'abssym')
|
||||
os.utime(b / 'abssym', (1234.5, 1234.5), follow_symlinks=False)
|
||||
se(b / 'abssym')
|
||||
os.symlink('sub/reg', b / 'sym')
|
||||
os.utime(b / 'sym', (6789.1, 6789.1), follow_symlinks=False)
|
||||
se(b / 'sym')
|
||||
|
||||
with self.run_kitten(list(cmd) + [src, dest]) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
|
||||
actual = {}
|
||||
|
||||
def de(path):
|
||||
e = entry(path, os.path.join(dest, os.path.basename(src)))
|
||||
if e.relpath != '.':
|
||||
actual[e.relpath] = e
|
||||
|
||||
for dirpath, dirnames, filenames in os.walk(dest):
|
||||
for x in dirnames:
|
||||
de(os.path.join(dirpath, x))
|
||||
for x in filenames:
|
||||
de(os.path.join(dirpath, x))
|
||||
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
for key, e in expected.items():
|
||||
ex = os.path.join(src, key)
|
||||
ax = os.path.join(dest, os.path.basename(src), key)
|
||||
if os.path.islink(ex):
|
||||
self.ae(os.readlink(ex), os.readlink(ax))
|
||||
elif os.path.isfile(ex):
|
||||
with open(ex, 'rb') as ef, open(ax, 'rb') as af:
|
||||
self.assertEqual(ef.read(), af.read())
|
||||
|
||||
multiple_files()
|
||||
multiple_files('--compress=always')
|
||||
self.clean_tdir()
|
||||
multiple_files('--transmit-deltas')
|
||||
multiple_files('--transmit-deltas')
|
||||
|
||||
def setup_dirs(self):
|
||||
self.clean_tdir()
|
||||
self.kitty_home = os.path.join(self.tdir, 'kitty-home')
|
||||
self.kitty_cwd = os.path.join(self.tdir, 'kitty-cwd')
|
||||
self.kitten_home = os.path.join(self.tdir, 'kitten-home')
|
||||
self.kitten_cwd = os.path.join(self.tdir, 'kitten-cwd')
|
||||
tuple(map(os.mkdir, (self.kitty_home, self.kitty_cwd, self.kitten_home, self.kitten_cwd)))
|
||||
|
||||
def create_src(self, base):
|
||||
src = os.path.join(base, 'src')
|
||||
with open(src, 'wb') as s:
|
||||
s.write(self.src_data)
|
||||
return src
|
||||
|
||||
def mirror_test(self, src, dest, prefix=''):
|
||||
self.create_src(src)
|
||||
os.symlink('/', os.path.join(src, 'sym'))
|
||||
os.mkdir(os.path.join(src, 'sub'))
|
||||
os.link(os.path.join(src, 'src'), os.path.join(src, 'sub', 'hardlink'))
|
||||
with self.run_kitten(['--mode=mirror', f'{prefix}src', f'{prefix}sym', f'{prefix}sub']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(dest, 'src'))
|
||||
os.remove(os.path.join(dest, 'sym'))
|
||||
shutil.rmtree(os.path.join(dest, 'sub'))
|
||||
|
||||
def test_transfer_receive_existing_links(self):
|
||||
self.direction_receive = True
|
||||
for link in (os.symlink, os.link):
|
||||
for args in ([], ['--compress=always'], ['--transmit-deltas']):
|
||||
for data in (b'', b'incoming contents' * 1024):
|
||||
with self.subTest(link=link.__name__, args=args, size=len(data)):
|
||||
self.clean_tdir()
|
||||
base = Path(self.tdir)
|
||||
src = base / 'source'
|
||||
src.write_bytes(data)
|
||||
src.chmod(0o644)
|
||||
target = base / 'unrelated'
|
||||
original = b'keep these contents' * 1024
|
||||
target.write_bytes(original)
|
||||
target.chmod(0o600)
|
||||
before = target.stat()
|
||||
dest = base / 'downloads' / 'received'
|
||||
dest.parent.mkdir()
|
||||
link(target, dest)
|
||||
with self.run_kitten([*args, str(src), str(dest)]) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
self.assertFalse(dest.is_symlink())
|
||||
self.assertFalse(os.path.samefile(target, dest))
|
||||
self.ae(dest.read_bytes(), data)
|
||||
self.ae(stat.S_IMODE(dest.stat().st_mode), 0o644)
|
||||
self.ae(target.read_bytes(), original)
|
||||
self.ae(target.stat().st_mtime_ns, before.st_mtime_ns)
|
||||
self.ae(stat.S_IMODE(target.stat().st_mode), 0o600)
|
||||
self.ae(os.listdir(dest.parent), ['received'])
|
||||
|
||||
def test_transfer_receive(self):
|
||||
self.direction_receive = True
|
||||
self.basic_transfer_tests()
|
||||
|
||||
self.setup_dirs()
|
||||
self.create_src(self.kitty_home)
|
||||
|
||||
# dir expansion with single transfer
|
||||
with self.run_kitten(['~/src', '~/src']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(self.kitten_home, 'src'))
|
||||
|
||||
with self.run_kitten(['src', 'src']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(self.kitten_cwd, 'src'))
|
||||
|
||||
# dir expansion with multiple transfers
|
||||
os.symlink('/', os.path.join(self.kitty_home, 'sym'))
|
||||
with self.run_kitten(['~/src', '~/sym', '~']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(self.kitten_home, 'src'))
|
||||
os.remove(os.path.join(self.kitten_home, 'sym'))
|
||||
|
||||
with self.run_kitten(['src', 'sym', '.']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(self.kitten_cwd, 'src'))
|
||||
os.remove(os.path.join(self.kitten_cwd, 'sym'))
|
||||
|
||||
# mirroring
|
||||
self.setup_dirs()
|
||||
self.mirror_test(self.kitty_home, self.kitten_home)
|
||||
|
||||
def test_transfer_send(self):
|
||||
self.basic_transfer_tests()
|
||||
src = os.path.join(self.tdir, 'src')
|
||||
with open(src, 'wb') as s:
|
||||
s.write(self.src_data)
|
||||
|
||||
self.setup_dirs()
|
||||
self.create_src(self.kitten_home)
|
||||
|
||||
# dir expansion with single transfer
|
||||
with self.run_kitten(['~/src', '~/src']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(self.kitty_home, 'src'))
|
||||
|
||||
self.create_src(self.kitten_cwd)
|
||||
with self.run_kitten(['src', 'src']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(self.kitty_home, 'src'))
|
||||
|
||||
# dir expansion with multiple transfers
|
||||
os.symlink('/', os.path.join(self.kitten_home, 'sym'))
|
||||
with self.run_kitten(['~/src', '~/sym', '~']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(self.kitty_home, 'src'))
|
||||
os.remove(os.path.join(self.kitty_home, 'sym'))
|
||||
|
||||
os.symlink('/', os.path.join(self.kitten_cwd, 'sym'))
|
||||
with self.run_kitten(['src', 'sym', '.']) as pty:
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
os.remove(os.path.join(self.kitty_home, 'src'))
|
||||
os.remove(os.path.join(self.kitty_home, 'sym'))
|
||||
|
||||
# mirroring
|
||||
self.setup_dirs()
|
||||
self.mirror_test(self.kitten_home, self.kitty_home, prefix='~/')
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
_plat = sys.platform.lower()
|
||||
is_macos = 'darwin' in _plat
|
||||
|
||||
|
||||
class TestGLFW(BaseTest):
|
||||
def test_os_window_size_calculation(self):
|
||||
from kitty.utils import get_new_os_window_size
|
||||
|
||||
def t(w, h, width=0, height=0, unit='cells', incremental=False):
|
||||
self.ae((w, h), get_new_os_window_size(metrics, width, height, unit, incremental, has_window_scaling))
|
||||
|
||||
with self.subTest(has_window_scaling=False):
|
||||
has_window_scaling = False
|
||||
metrics = {
|
||||
'width': 200,
|
||||
'height': 100,
|
||||
'framebuffer_width': 200,
|
||||
'framebuffer_height': 100,
|
||||
'xscale': 2.0,
|
||||
'yscale': 2.0,
|
||||
'xdpi': 192.0,
|
||||
'ydpi': 192.0,
|
||||
'cell_width': 8,
|
||||
'cell_height': 16,
|
||||
}
|
||||
t(80 * metrics['cell_width'], 100, 80)
|
||||
t(80 * metrics['cell_width'] + metrics['width'], 100, 80, incremental=True)
|
||||
t(1217, 100, 1217, unit='pixels')
|
||||
t(1217 + metrics['width'], 100, 1217, unit='pixels', incremental=True)
|
||||
|
||||
with self.subTest(has_window_scaling=True):
|
||||
has_window_scaling = True
|
||||
metrics['framebuffer_width'] = metrics['width'] * 2
|
||||
metrics['framebuffer_height'] = metrics['height'] * 2
|
||||
t(80 * metrics['cell_width'] / metrics['xscale'], 100, 80)
|
||||
t(80 * metrics['cell_width'] / metrics['xscale'] + metrics['width'], 100, 80, incremental=True)
|
||||
t(1217, 100, 1217, unit='pixels')
|
||||
t(1217 + metrics['width'], 100, 1217, unit='pixels', incremental=True)
|
||||
|
||||
@unittest.skipIf(is_macos, 'Skipping test on macOS because glfw-cocoa.so is not built with backend_utils')
|
||||
def test_utf_8_strndup(self):
|
||||
import ctypes
|
||||
|
||||
from kitty.constants import glfw_path
|
||||
|
||||
backend_utils = glfw_path('x11')
|
||||
lib = ctypes.CDLL(backend_utils)
|
||||
libc = ctypes.CDLL(None)
|
||||
|
||||
class allocated_c_char_p(ctypes.c_char_p):
|
||||
def __del__(self):
|
||||
libc.free(self)
|
||||
|
||||
utf_8_strndup = lib.utf_8_strndup
|
||||
utf_8_strndup.restype = allocated_c_char_p
|
||||
utf_8_strndup.argtypes = (ctypes.c_char_p, ctypes.c_size_t)
|
||||
|
||||
def test(string):
|
||||
string_bytes = bytes(string, 'utf-8')
|
||||
prev_part_bytes = b''
|
||||
prev_length_bytes = -1
|
||||
for length in range(len(string) + 1):
|
||||
part = string[:length]
|
||||
part_bytes = bytes(part, 'utf-8')
|
||||
length_bytes = len(part_bytes)
|
||||
for length_bytes_2 in range(prev_length_bytes + 1, length_bytes):
|
||||
self.ae(utf_8_strndup(string_bytes, length_bytes_2).value, prev_part_bytes)
|
||||
self.ae(utf_8_strndup(string_bytes, length_bytes).value, part_bytes)
|
||||
prev_part_bytes = part_bytes
|
||||
prev_length_bytes = length_bytes
|
||||
self.ae(utf_8_strndup(string_bytes, len(string_bytes) + 1).value, string_bytes) # Try to go one character after the end of the string
|
||||
|
||||
self.ae(utf_8_strndup(None, 2).value, None)
|
||||
self.ae(utf_8_strndup(b'', 2).value, b'')
|
||||
|
||||
test('ö')
|
||||
test('>a<')
|
||||
test('>ä<')
|
||||
test('>ế<')
|
||||
test('>𐍈<')
|
||||
test('∮ E⋅da = Q, n → ∞, 𐍈∑ f(i) = ∏ g(i)')
|
||||
self.ae(utf_8_strndup(b'\xf0\x9f\x98\xb8', 3).value, b'')
|
||||
self.ae(utf_8_strndup(b'\xc3\xb6\xf0\x9f\x98\xb8', 4).value, b'\xc3\xb6')
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
import sys
|
||||
import zlib
|
||||
from base64 import standard_b64encode
|
||||
from contextlib import suppress
|
||||
|
||||
write = getattr(sys.stdout, 'buffer', sys.stdout).write
|
||||
|
||||
|
||||
def clear_screen():
|
||||
write(b'\033[2J')
|
||||
|
||||
|
||||
def move_cursor(x, y):
|
||||
write(f'\033[{y};{x}H'.encode('ascii'))
|
||||
|
||||
|
||||
def write_gr_cmd(cmd, payload):
|
||||
cmd = ','.join(f'{k}={v}' for k, v in cmd.items())
|
||||
w = write
|
||||
w(b'\033_G'), w(cmd.encode('ascii')), w(b';'), w(payload), w(b'\033\\')
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def display(data, width, height, x, y, z, ncols=0, nrows=0):
|
||||
move_cursor(x, y)
|
||||
cmd = {'a': 'T', 's': width, 'v': height, 'c': ncols, 'r': nrows, 'S': len(data), 'z': z}
|
||||
data = zlib.compress(data)
|
||||
cmd['o'] = 'z'
|
||||
data = standard_b64encode(data)
|
||||
while data:
|
||||
chunk, data = data[:4096], data[4096:]
|
||||
m = 1 if data else 0
|
||||
cmd['m'] = m
|
||||
write_gr_cmd(cmd, chunk)
|
||||
cmd.clear()
|
||||
|
||||
|
||||
def display_png_file(path):
|
||||
cmd = {'a': 'T', 't': 'f', 'f': '100'}
|
||||
path = os.path.abspath(path)
|
||||
if not isinstance(path, bytes):
|
||||
path = path.encode(sys.getfilesystemencoding() or 'utf-8')
|
||||
data = standard_b64encode(path)
|
||||
write_gr_cmd(cmd, data)
|
||||
|
||||
|
||||
def main():
|
||||
from kitty.constants import logo_png_file
|
||||
|
||||
photo = sys.argv[-1]
|
||||
if not photo.lower().endswith('.png'):
|
||||
raise SystemExit('Must specify a PNG file to display')
|
||||
clear_screen()
|
||||
display(b'\xdd\xdd\xdd\xff', 1, 1, 0, 0, -10, 40, 20)
|
||||
with open(logo_png_file.replace('.png', '.rgba'), 'rb') as f:
|
||||
display(f.read(), 256, 256, 0, 5, -9)
|
||||
display(b'\0\0\0\xaa', 1, 1, 0, 7, -8, 40, 3)
|
||||
move_cursor(5, 8)
|
||||
print('kitty is \033[3m\033[32mawesome\033[m!')
|
||||
move_cursor(0, 21)
|
||||
print('Photo...')
|
||||
display_png_file(photo)
|
||||
with suppress(EOFError, KeyboardInterrupt):
|
||||
input()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from kittens.hints.main import handle_result
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestHints(BaseTest):
|
||||
def test_multiple_selection_actions(self):
|
||||
for matches in ([], [''], ['alpha', 'beta']):
|
||||
for joiner, expected in (('auto', 'alpha beta'), ('json', '[\n\t"alpha",\n\t"beta"\n]'), ('0', 'alpha'), ('-1', 'beta')):
|
||||
with self.subTest(matches=matches, joiner=joiner):
|
||||
boss: Any = Mock()
|
||||
window = Mock()
|
||||
boss.window_id_map = {1: window}
|
||||
data = {
|
||||
'customize_processing': '',
|
||||
'type': 'word',
|
||||
'programs': ['@', '*', '@test', '-'],
|
||||
'match': matches,
|
||||
'groupdicts': [{} for _ in matches],
|
||||
'multiple_joiner': joiner,
|
||||
}
|
||||
with patch('kittens.hints.main.set_clipboard_string') as clipboard, patch('kittens.hints.main.set_primary_selection') as primary:
|
||||
handle_result([], data, 1, boss)
|
||||
if any(matches):
|
||||
clipboard.assert_called_once_with(expected)
|
||||
primary.assert_called_once_with(expected)
|
||||
boss.set_clipboard_buffer.assert_called_once_with('test', expected)
|
||||
window.paste_text.assert_called_once_with(expected)
|
||||
else:
|
||||
clipboard.assert_not_called()
|
||||
primary.assert_not_called()
|
||||
boss.set_clipboard_buffer.assert_not_called()
|
||||
window.paste_text.assert_not_called()
|
||||
|
||||
def test_custom_handler_receives_empty_selection(self):
|
||||
boss: Any = Mock()
|
||||
custom_handler = Mock()
|
||||
data = {'customize_processing': 'custom.py', 'type': 'word', 'match': [], 'groupdicts': [], 'extra_cli_args': ['extra']}
|
||||
with patch('kittens.hints.main.load_custom_processor', return_value={'handle_result': custom_handler}):
|
||||
handle_result([], data, 1, boss)
|
||||
custom_handler.assert_called_once_with([], data, 1, boss, ['extra'])
|
||||
|
||||
def test_named_groups_are_passed_to_program(self):
|
||||
boss: Any = Mock()
|
||||
boss.window_id_map = {}
|
||||
handle_result(
|
||||
[],
|
||||
{
|
||||
'customize_processing': '',
|
||||
'type': 'regex',
|
||||
'programs': ['echo'],
|
||||
'match': ['ignored'],
|
||||
'groupdicts': [{'name': 'value', 'empty': None}],
|
||||
'multiple_joiner': '',
|
||||
'cwd': '/tmp',
|
||||
},
|
||||
1,
|
||||
boss,
|
||||
)
|
||||
boss.open_url.assert_called_once_with(['name=value', 'empty='], 'echo', cwd='/tmp')
|
||||
Binary file not shown.
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, kitty contributors
|
||||
|
||||
from functools import partial
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from kitty.boss import Boss
|
||||
from kitty.launch import load_watch_modules
|
||||
from kitty.tabs import SpecialWindow
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class IterableArgumentsTest(BaseTest):
|
||||
def test_window_creation_with_iterable_arguments(self):
|
||||
for method in ('_new_os_window', '_new_tab'):
|
||||
for container in (list, tuple, iter):
|
||||
for values in ((), ('/bin/echo', 'hello')):
|
||||
with self.subTest(method=method, container=container, values=values):
|
||||
tm = SimpleNamespace(new_tab=Mock())
|
||||
boss = SimpleNamespace(active_window=None, os_window_map={1: tm}, active_tab_manager=tm, add_os_window=Mock(return_value=1))
|
||||
boss.args_to_special_window = partial(Boss.args_to_special_window, boss)
|
||||
with (
|
||||
patch('kitty.boss.get_options'),
|
||||
patch('kitty.boss.create_sessions', return_value=iter((SimpleNamespace(),))) as sessions,
|
||||
):
|
||||
getattr(Boss, method)(boss, container(values))
|
||||
call = sessions.call_args if method == '_new_os_window' else tm.new_tab.call_args
|
||||
special = call.kwargs['special_window']
|
||||
if values:
|
||||
self.ae(special.cmd, list(values))
|
||||
else:
|
||||
self.assertIsNone(special)
|
||||
|
||||
def test_special_window_arguments_are_preserved(self):
|
||||
special = SpecialWindow(['/bin/echo', 'hello'])
|
||||
tm = SimpleNamespace(new_tab=Mock())
|
||||
boss = SimpleNamespace(os_window_map={1: tm}, active_tab_manager=tm, add_os_window=Mock(return_value=1))
|
||||
with (
|
||||
patch('kitty.boss.get_options'),
|
||||
patch('kitty.boss.create_sessions', return_value=iter((SimpleNamespace(),))) as sessions,
|
||||
):
|
||||
Boss._new_os_window(boss, special)
|
||||
Boss._new_tab(boss, special)
|
||||
self.assertIs(sessions.call_args.kwargs['special_window'], special)
|
||||
self.assertIs(tm.new_tab.call_args.kwargs['special_window'], special)
|
||||
|
||||
def test_config_error_iterable(self):
|
||||
for container in (list, tuple, iter):
|
||||
for values in ((), ('configuration error',)):
|
||||
with self.subTest(container=container, values=values):
|
||||
boss = SimpleNamespace(show_error=Mock())
|
||||
Boss.show_bad_config_lines(boss, (), container(values))
|
||||
message = boss.show_error.call_args.args[1]
|
||||
self.ae(message, 'In final effective configuration:\nconfiguration error' if values else '')
|
||||
|
||||
def test_watcher_iterable(self):
|
||||
for container in (list, tuple, iter):
|
||||
for values in ((), ('watcher.py',)):
|
||||
with self.subTest(container=container, values=values):
|
||||
on_load, on_close = Mock(), Mock()
|
||||
with (
|
||||
patch('kitty.launch.get_boss', return_value=None),
|
||||
patch('kitty.launch.resolve_custom_file', side_effect=lambda path: path),
|
||||
patch.dict('kitty.launch.watcher_modules', {}, clear=True),
|
||||
patch('runpy.run_path', return_value={'on_load': on_load, 'on_close': on_close}) as load,
|
||||
):
|
||||
watchers = load_watch_modules(container(values))
|
||||
if values:
|
||||
self.ae(watchers.on_close, [on_close])
|
||||
load.assert_called_once_with('watcher.py', run_name='__kitty_watcher__')
|
||||
on_load.assert_called_once_with(None, {})
|
||||
else:
|
||||
self.assertIsNone(watchers)
|
||||
load.assert_not_called()
|
||||
@@ -0,0 +1,946 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from functools import partial
|
||||
from types import SimpleNamespace
|
||||
|
||||
import kitty.fast_data_types as defines
|
||||
from kitty.key_encoding import EventType, KeyEvent, decode_key_event, encode_key_event
|
||||
from kitty.keys import Mappings
|
||||
from kitty.options.utils import KeyFallbackType
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestKeys(BaseTest):
|
||||
def test_encode_key_event(self):
|
||||
enc = defines.encode_key_for_tty
|
||||
ae = self.assertEqual
|
||||
shift, alt, ctrl, super, hyper, meta = (
|
||||
defines.GLFW_MOD_SHIFT,
|
||||
defines.GLFW_MOD_ALT,
|
||||
defines.GLFW_MOD_CONTROL,
|
||||
defines.GLFW_MOD_SUPER,
|
||||
defines.GLFW_MOD_HYPER,
|
||||
defines.GLFW_MOD_META,
|
||||
)
|
||||
num_lock, caps_lock = defines.GLFW_MOD_NUM_LOCK, defines.GLFW_MOD_CAPS_LOCK
|
||||
press, repeat, release = defines.GLFW_PRESS, defines.GLFW_REPEAT, defines.GLFW_RELEASE # noqa
|
||||
|
||||
def csi(mods=0, num=1, action=1, shifted_key=0, alternate_key=0, text=None, trailer='u'):
|
||||
ans = '\033['
|
||||
if isinstance(num, str):
|
||||
num = ord(num)
|
||||
if num != 1 or mods or shifted_key or alternate_key or text:
|
||||
ans += f'{num}'
|
||||
if shifted_key or alternate_key:
|
||||
if isinstance(shifted_key, str):
|
||||
shifted_key = ord(shifted_key)
|
||||
ans += ':' + (f'{shifted_key}' if shifted_key else '')
|
||||
if alternate_key:
|
||||
if isinstance(alternate_key, str):
|
||||
alternate_key = ord(alternate_key)
|
||||
ans += f':{alternate_key}'
|
||||
if mods or action > 1 or text:
|
||||
m = 0
|
||||
if mods & shift:
|
||||
m |= 1
|
||||
if mods & alt:
|
||||
m |= 2
|
||||
if mods & ctrl:
|
||||
m |= 4
|
||||
if mods & super:
|
||||
m |= 8
|
||||
if mods & hyper:
|
||||
m |= 16
|
||||
if mods & meta:
|
||||
m |= 32
|
||||
if action > 1 or m:
|
||||
ans += f';{m + 1}'
|
||||
if action > 1:
|
||||
ans += f':{action}'
|
||||
elif text:
|
||||
ans += ';'
|
||||
if text:
|
||||
ans += ';' + ':'.join(map(str, map(ord, text)))
|
||||
return ans + trailer
|
||||
|
||||
def mods_test(key, plain=None, shift=None, ctrl=None, alt=None, calt=None, cshift=None, ashift=None, csi_num=None, trailer='u'):
|
||||
c = partial(csi, num=csi_num or key, trailer=trailer)
|
||||
e = partial(enc, key=key)
|
||||
|
||||
def a(a, b):
|
||||
ae(a, b, f'{a.encode("ascii")} != {b.encode("ascii")}')
|
||||
|
||||
def w(a, b):
|
||||
return c(b) if a is None else a
|
||||
|
||||
a(e(), plain or c())
|
||||
a(e(mods=defines.GLFW_MOD_SHIFT), w(shift, defines.GLFW_MOD_SHIFT))
|
||||
a(e(mods=defines.GLFW_MOD_CONTROL), w(ctrl, defines.GLFW_MOD_CONTROL))
|
||||
a(e(mods=defines.GLFW_MOD_ALT | defines.GLFW_MOD_CONTROL), w(calt, defines.GLFW_MOD_ALT | defines.GLFW_MOD_CONTROL))
|
||||
a(e(mods=defines.GLFW_MOD_SHIFT | defines.GLFW_MOD_CONTROL), w(cshift, defines.GLFW_MOD_CONTROL | defines.GLFW_MOD_SHIFT))
|
||||
a(e(mods=defines.GLFW_MOD_SHIFT | defines.GLFW_MOD_ALT), w(ashift, defines.GLFW_MOD_ALT | defines.GLFW_MOD_SHIFT))
|
||||
|
||||
def mkp(name, *a, **kw):
|
||||
for x in (f'GLFW_FKEY_{name}', f'GLFW_FKEY_KP_{name}'):
|
||||
k = getattr(defines, x)
|
||||
mods_test(k, *a, **kw)
|
||||
|
||||
mkp('ENTER', '\x0d', alt='\033\x0d', ctrl='\x0d', shift='\x0d', ashift='\033\x0d', calt='\033\x0d', cshift='\x0d')
|
||||
mods_test(defines.GLFW_FKEY_ESCAPE, '\x1b', alt='\033\033', ctrl='\x1b', shift='\x1b', calt='\x1b\x1b', cshift='\x1b', ashift='\x1b\x1b')
|
||||
mods_test(defines.GLFW_FKEY_BACKSPACE, '\x7f', alt='\033\x7f', ctrl='\x08', shift='\x7f', ashift='\033\x7f', cshift='\x08', calt='\x1b\x08')
|
||||
mods_test(defines.GLFW_FKEY_TAB, '\t', alt='\033\t', shift='\x1b[Z', ctrl='\t', ashift='\x1b\x1b[Z', cshift='\x1b[Z', calt='\x1b\t')
|
||||
mkp('INSERT', csi_num=2, trailer='~')
|
||||
mkp('DELETE', csi_num=3, trailer='~')
|
||||
mkp('PAGE_UP', csi_num=5, trailer='~')
|
||||
mkp('PAGE_DOWN', csi_num=6, trailer='~')
|
||||
mkp('HOME', csi_num=1, trailer='H')
|
||||
mkp('END', csi_num=1, trailer='F')
|
||||
mods_test(defines.GLFW_FKEY_F1, '\x1bOP', csi_num=1, trailer='P')
|
||||
mods_test(defines.GLFW_FKEY_F2, '\x1bOQ', csi_num=1, trailer='Q')
|
||||
mods_test(defines.GLFW_FKEY_F3, '\x1bOR', csi_num=13, trailer='~')
|
||||
mods_test(defines.GLFW_FKEY_F4, '\x1bOS', csi_num=1, trailer='S')
|
||||
mods_test(defines.GLFW_FKEY_F5, csi_num=15, trailer='~')
|
||||
mods_test(defines.GLFW_FKEY_F6, csi_num=17, trailer='~')
|
||||
mods_test(defines.GLFW_FKEY_F7, csi_num=18, trailer='~')
|
||||
mods_test(defines.GLFW_FKEY_F8, csi_num=19, trailer='~')
|
||||
mods_test(defines.GLFW_FKEY_F9, csi_num=20, trailer='~')
|
||||
mods_test(defines.GLFW_FKEY_F10, csi_num=21, trailer='~')
|
||||
mods_test(defines.GLFW_FKEY_F11, csi_num=23, trailer='~')
|
||||
mods_test(defines.GLFW_FKEY_F12, csi_num=24, trailer='~')
|
||||
mkp('UP', csi_num=1, trailer='A')
|
||||
mkp('DOWN', csi_num=1, trailer='B')
|
||||
mkp('RIGHT', csi_num=1, trailer='C')
|
||||
mkp('LEFT', csi_num=1, trailer='D')
|
||||
|
||||
# legacy key tests {{{
|
||||
# start legacy letter tests (auto generated by gen-key-constants.py do not edit)
|
||||
ae(enc(ord('`'), shifted_key=ord('~')), '`')
|
||||
ae(enc(ord('`'), shifted_key=ord('~'), mods=shift), '~')
|
||||
ae(enc(ord('`'), shifted_key=ord('~'), mods=alt), '\x1b' + '`')
|
||||
ae(enc(ord('`'), shifted_key=ord('~'), mods=shift | alt), '\x1b' + '~')
|
||||
ae(enc(ord('`'), shifted_key=ord('~'), mods=ctrl), '`')
|
||||
ae(enc(ord('`'), shifted_key=ord('~'), mods=ctrl | alt), '\x1b' + '`')
|
||||
ae(enc(ord('1'), shifted_key=ord('!')), '1')
|
||||
ae(enc(ord('1'), shifted_key=ord('!'), mods=shift), '!')
|
||||
ae(enc(ord('1'), shifted_key=ord('!'), mods=alt), '\x1b' + '1')
|
||||
ae(enc(ord('1'), shifted_key=ord('!'), mods=shift | alt), '\x1b' + '!')
|
||||
ae(enc(ord('1'), shifted_key=ord('!'), mods=ctrl), '1')
|
||||
ae(enc(ord('1'), shifted_key=ord('!'), mods=ctrl | alt), '\x1b' + '1')
|
||||
ae(enc(ord('2'), shifted_key=ord('@')), '2')
|
||||
ae(enc(ord('2'), shifted_key=ord('@'), mods=shift), '@')
|
||||
ae(enc(ord('2'), shifted_key=ord('@'), mods=alt), '\x1b' + '2')
|
||||
ae(enc(ord('2'), shifted_key=ord('@'), mods=shift | alt), '\x1b' + '@')
|
||||
ae(enc(ord('2'), shifted_key=ord('@'), mods=ctrl), '\x00')
|
||||
ae(enc(ord('2'), shifted_key=ord('@'), mods=ctrl | alt), '\x1b' + '\x00')
|
||||
ae(enc(ord('3'), shifted_key=ord('#')), '3')
|
||||
ae(enc(ord('3'), shifted_key=ord('#'), mods=shift), '#')
|
||||
ae(enc(ord('3'), shifted_key=ord('#'), mods=alt), '\x1b' + '3')
|
||||
ae(enc(ord('3'), shifted_key=ord('#'), mods=shift | alt), '\x1b' + '#')
|
||||
ae(enc(ord('3'), shifted_key=ord('#'), mods=ctrl), '\x1b')
|
||||
ae(enc(ord('3'), shifted_key=ord('#'), mods=ctrl | alt), '\x1b' + '\x1b')
|
||||
ae(enc(ord('4'), shifted_key=ord('$')), '4')
|
||||
ae(enc(ord('4'), shifted_key=ord('$'), mods=shift), '$')
|
||||
ae(enc(ord('4'), shifted_key=ord('$'), mods=alt), '\x1b' + '4')
|
||||
ae(enc(ord('4'), shifted_key=ord('$'), mods=shift | alt), '\x1b' + '$')
|
||||
ae(enc(ord('4'), shifted_key=ord('$'), mods=ctrl), '\x1c')
|
||||
ae(enc(ord('4'), shifted_key=ord('$'), mods=ctrl | alt), '\x1b' + '\x1c')
|
||||
ae(enc(ord('5'), shifted_key=ord('%')), '5')
|
||||
ae(enc(ord('5'), shifted_key=ord('%'), mods=shift), '%')
|
||||
ae(enc(ord('5'), shifted_key=ord('%'), mods=alt), '\x1b' + '5')
|
||||
ae(enc(ord('5'), shifted_key=ord('%'), mods=shift | alt), '\x1b' + '%')
|
||||
ae(enc(ord('5'), shifted_key=ord('%'), mods=ctrl), '\x1d')
|
||||
ae(enc(ord('5'), shifted_key=ord('%'), mods=ctrl | alt), '\x1b' + '\x1d')
|
||||
ae(enc(ord('6'), shifted_key=ord('^')), '6')
|
||||
ae(enc(ord('6'), shifted_key=ord('^'), mods=shift), '^')
|
||||
ae(enc(ord('6'), shifted_key=ord('^'), mods=alt), '\x1b' + '6')
|
||||
ae(enc(ord('6'), shifted_key=ord('^'), mods=shift | alt), '\x1b' + '^')
|
||||
ae(enc(ord('6'), shifted_key=ord('^'), mods=ctrl), '\x1e')
|
||||
ae(enc(ord('6'), shifted_key=ord('^'), mods=ctrl | alt), '\x1b' + '\x1e')
|
||||
ae(enc(ord('7'), shifted_key=ord('&')), '7')
|
||||
ae(enc(ord('7'), shifted_key=ord('&'), mods=shift), '&')
|
||||
ae(enc(ord('7'), shifted_key=ord('&'), mods=alt), '\x1b' + '7')
|
||||
ae(enc(ord('7'), shifted_key=ord('&'), mods=shift | alt), '\x1b' + '&')
|
||||
ae(enc(ord('7'), shifted_key=ord('&'), mods=ctrl), '\x1f')
|
||||
ae(enc(ord('7'), shifted_key=ord('&'), mods=ctrl | alt), '\x1b' + '\x1f')
|
||||
ae(enc(ord('8'), shifted_key=ord('*')), '8')
|
||||
ae(enc(ord('8'), shifted_key=ord('*'), mods=shift), '*')
|
||||
ae(enc(ord('8'), shifted_key=ord('*'), mods=alt), '\x1b' + '8')
|
||||
ae(enc(ord('8'), shifted_key=ord('*'), mods=shift | alt), '\x1b' + '*')
|
||||
ae(enc(ord('8'), shifted_key=ord('*'), mods=ctrl), '\x7f')
|
||||
ae(enc(ord('8'), shifted_key=ord('*'), mods=ctrl | alt), '\x1b' + '\x7f')
|
||||
ae(enc(ord('9'), shifted_key=ord('(')), '9')
|
||||
ae(enc(ord('9'), shifted_key=ord('('), mods=shift), '(')
|
||||
ae(enc(ord('9'), shifted_key=ord('('), mods=alt), '\x1b' + '9')
|
||||
ae(enc(ord('9'), shifted_key=ord('('), mods=shift | alt), '\x1b' + '(')
|
||||
ae(enc(ord('9'), shifted_key=ord('('), mods=ctrl), '9')
|
||||
ae(enc(ord('9'), shifted_key=ord('('), mods=ctrl | alt), '\x1b' + '9')
|
||||
ae(enc(ord('0'), shifted_key=ord(')')), '0')
|
||||
ae(enc(ord('0'), shifted_key=ord(')'), mods=shift), ')')
|
||||
ae(enc(ord('0'), shifted_key=ord(')'), mods=alt), '\x1b' + '0')
|
||||
ae(enc(ord('0'), shifted_key=ord(')'), mods=shift | alt), '\x1b' + ')')
|
||||
ae(enc(ord('0'), shifted_key=ord(')'), mods=ctrl), '0')
|
||||
ae(enc(ord('0'), shifted_key=ord(')'), mods=ctrl | alt), '\x1b' + '0')
|
||||
ae(enc(ord('-'), shifted_key=ord('_')), '-')
|
||||
ae(enc(ord('-'), shifted_key=ord('_'), mods=shift), '_')
|
||||
ae(enc(ord('-'), shifted_key=ord('_'), mods=alt), '\x1b' + '-')
|
||||
ae(enc(ord('-'), shifted_key=ord('_'), mods=shift | alt), '\x1b' + '_')
|
||||
ae(enc(ord('-'), shifted_key=ord('_'), mods=ctrl), '-')
|
||||
ae(enc(ord('-'), shifted_key=ord('_'), mods=ctrl | alt), '\x1b' + '-')
|
||||
ae(enc(ord('='), shifted_key=ord('+')), '=')
|
||||
ae(enc(ord('='), shifted_key=ord('+'), mods=shift), '+')
|
||||
ae(enc(ord('='), shifted_key=ord('+'), mods=alt), '\x1b' + '=')
|
||||
ae(enc(ord('='), shifted_key=ord('+'), mods=shift | alt), '\x1b' + '+')
|
||||
ae(enc(ord('='), shifted_key=ord('+'), mods=ctrl), '=')
|
||||
ae(enc(ord('='), shifted_key=ord('+'), mods=ctrl | alt), '\x1b' + '=')
|
||||
ae(enc(ord('['), shifted_key=ord('{')), '[')
|
||||
ae(enc(ord('['), shifted_key=ord('{'), mods=shift), '{')
|
||||
ae(enc(ord('['), shifted_key=ord('{'), mods=alt), '\x1b' + '[')
|
||||
ae(enc(ord('['), shifted_key=ord('{'), mods=shift | alt), '\x1b' + '{')
|
||||
ae(enc(ord('['), shifted_key=ord('{'), mods=ctrl), '\x1b')
|
||||
ae(enc(ord('['), shifted_key=ord('{'), mods=ctrl | alt), '\x1b' + '\x1b')
|
||||
ae(enc(ord(']'), shifted_key=ord('}')), ']')
|
||||
ae(enc(ord(']'), shifted_key=ord('}'), mods=shift), '}')
|
||||
ae(enc(ord(']'), shifted_key=ord('}'), mods=alt), '\x1b' + ']')
|
||||
ae(enc(ord(']'), shifted_key=ord('}'), mods=shift | alt), '\x1b' + '}')
|
||||
ae(enc(ord(']'), shifted_key=ord('}'), mods=ctrl), '\x1d')
|
||||
ae(enc(ord(']'), shifted_key=ord('}'), mods=ctrl | alt), '\x1b' + '\x1d')
|
||||
ae(enc(ord('\\'), shifted_key=ord('|')), '\\')
|
||||
ae(enc(ord('\\'), shifted_key=ord('|'), mods=shift), '|')
|
||||
ae(enc(ord('\\'), shifted_key=ord('|'), mods=alt), '\x1b' + '\\')
|
||||
ae(enc(ord('\\'), shifted_key=ord('|'), mods=shift | alt), '\x1b' + '|')
|
||||
ae(enc(ord('\\'), shifted_key=ord('|'), mods=ctrl), '\x1c')
|
||||
ae(enc(ord('\\'), shifted_key=ord('|'), mods=ctrl | alt), '\x1b' + '\x1c')
|
||||
ae(enc(ord(';'), shifted_key=ord(':')), ';')
|
||||
ae(enc(ord(';'), shifted_key=ord(':'), mods=shift), ':')
|
||||
ae(enc(ord(';'), shifted_key=ord(':'), mods=alt), '\x1b' + ';')
|
||||
ae(enc(ord(';'), shifted_key=ord(':'), mods=shift | alt), '\x1b' + ':')
|
||||
ae(enc(ord(';'), shifted_key=ord(':'), mods=ctrl), ';')
|
||||
ae(enc(ord(';'), shifted_key=ord(':'), mods=ctrl | alt), '\x1b' + ';')
|
||||
ae(enc(ord("'"), shifted_key=ord('"')), "'")
|
||||
ae(enc(ord("'"), shifted_key=ord('"'), mods=shift), '"')
|
||||
ae(enc(ord("'"), shifted_key=ord('"'), mods=alt), '\x1b' + "'")
|
||||
ae(enc(ord("'"), shifted_key=ord('"'), mods=shift | alt), '\x1b' + '"')
|
||||
ae(enc(ord("'"), shifted_key=ord('"'), mods=ctrl), "'")
|
||||
ae(enc(ord("'"), shifted_key=ord('"'), mods=ctrl | alt), '\x1b' + "'")
|
||||
ae(enc(ord(','), shifted_key=ord('<')), ',')
|
||||
ae(enc(ord(','), shifted_key=ord('<'), mods=shift), '<')
|
||||
ae(enc(ord(','), shifted_key=ord('<'), mods=alt), '\x1b' + ',')
|
||||
ae(enc(ord(','), shifted_key=ord('<'), mods=shift | alt), '\x1b' + '<')
|
||||
ae(enc(ord(','), shifted_key=ord('<'), mods=ctrl), ',')
|
||||
ae(enc(ord(','), shifted_key=ord('<'), mods=ctrl | alt), '\x1b' + ',')
|
||||
ae(enc(ord('.'), shifted_key=ord('>')), '.')
|
||||
ae(enc(ord('.'), shifted_key=ord('>'), mods=shift), '>')
|
||||
ae(enc(ord('.'), shifted_key=ord('>'), mods=alt), '\x1b' + '.')
|
||||
ae(enc(ord('.'), shifted_key=ord('>'), mods=shift | alt), '\x1b' + '>')
|
||||
ae(enc(ord('.'), shifted_key=ord('>'), mods=ctrl), '.')
|
||||
ae(enc(ord('.'), shifted_key=ord('>'), mods=ctrl | alt), '\x1b' + '.')
|
||||
ae(enc(ord('/'), shifted_key=ord('?')), '/')
|
||||
ae(enc(ord('/'), shifted_key=ord('?'), mods=shift), '?')
|
||||
ae(enc(ord('/'), shifted_key=ord('?'), mods=alt), '\x1b' + '/')
|
||||
ae(enc(ord('/'), shifted_key=ord('?'), mods=shift | alt), '\x1b' + '?')
|
||||
ae(enc(ord('/'), shifted_key=ord('?'), mods=ctrl), '\x1f')
|
||||
ae(enc(ord('/'), shifted_key=ord('?'), mods=ctrl | alt), '\x1b' + '\x1f')
|
||||
ae(enc(ord('a'), shifted_key=ord('A')), 'a')
|
||||
ae(enc(ord('a'), shifted_key=ord('A'), mods=shift), 'A')
|
||||
ae(enc(ord('a'), shifted_key=ord('A'), mods=alt), '\x1b' + 'a')
|
||||
ae(enc(ord('a'), shifted_key=ord('A'), mods=shift | alt), '\x1b' + 'A')
|
||||
ae(enc(ord('a'), shifted_key=ord('A'), mods=ctrl), '\x01')
|
||||
ae(enc(ord('a'), shifted_key=ord('A'), mods=ctrl | alt), '\x1b' + '\x01')
|
||||
ae(enc(ord('b'), shifted_key=ord('B')), 'b')
|
||||
ae(enc(ord('b'), shifted_key=ord('B'), mods=shift), 'B')
|
||||
ae(enc(ord('b'), shifted_key=ord('B'), mods=alt), '\x1b' + 'b')
|
||||
ae(enc(ord('b'), shifted_key=ord('B'), mods=shift | alt), '\x1b' + 'B')
|
||||
ae(enc(ord('b'), shifted_key=ord('B'), mods=ctrl), '\x02')
|
||||
ae(enc(ord('b'), shifted_key=ord('B'), mods=ctrl | alt), '\x1b' + '\x02')
|
||||
ae(enc(ord('c'), shifted_key=ord('C')), 'c')
|
||||
ae(enc(ord('c'), shifted_key=ord('C'), mods=shift), 'C')
|
||||
ae(enc(ord('c'), shifted_key=ord('C'), mods=alt), '\x1b' + 'c')
|
||||
ae(enc(ord('c'), shifted_key=ord('C'), mods=shift | alt), '\x1b' + 'C')
|
||||
ae(enc(ord('c'), shifted_key=ord('C'), mods=ctrl), '\x03')
|
||||
ae(enc(ord('c'), shifted_key=ord('C'), mods=ctrl | alt), '\x1b' + '\x03')
|
||||
ae(enc(ord('d'), shifted_key=ord('D')), 'd')
|
||||
ae(enc(ord('d'), shifted_key=ord('D'), mods=shift), 'D')
|
||||
ae(enc(ord('d'), shifted_key=ord('D'), mods=alt), '\x1b' + 'd')
|
||||
ae(enc(ord('d'), shifted_key=ord('D'), mods=shift | alt), '\x1b' + 'D')
|
||||
ae(enc(ord('d'), shifted_key=ord('D'), mods=ctrl), '\x04')
|
||||
ae(enc(ord('d'), shifted_key=ord('D'), mods=ctrl | alt), '\x1b' + '\x04')
|
||||
ae(enc(ord('e'), shifted_key=ord('E')), 'e')
|
||||
ae(enc(ord('e'), shifted_key=ord('E'), mods=shift), 'E')
|
||||
ae(enc(ord('e'), shifted_key=ord('E'), mods=alt), '\x1b' + 'e')
|
||||
ae(enc(ord('e'), shifted_key=ord('E'), mods=shift | alt), '\x1b' + 'E')
|
||||
ae(enc(ord('e'), shifted_key=ord('E'), mods=ctrl), '\x05')
|
||||
ae(enc(ord('e'), shifted_key=ord('E'), mods=ctrl | alt), '\x1b' + '\x05')
|
||||
ae(enc(ord('f'), shifted_key=ord('F')), 'f')
|
||||
ae(enc(ord('f'), shifted_key=ord('F'), mods=shift), 'F')
|
||||
ae(enc(ord('f'), shifted_key=ord('F'), mods=alt), '\x1b' + 'f')
|
||||
ae(enc(ord('f'), shifted_key=ord('F'), mods=shift | alt), '\x1b' + 'F')
|
||||
ae(enc(ord('f'), shifted_key=ord('F'), mods=ctrl), '\x06')
|
||||
ae(enc(ord('f'), shifted_key=ord('F'), mods=ctrl | alt), '\x1b' + '\x06')
|
||||
ae(enc(ord('g'), shifted_key=ord('G')), 'g')
|
||||
ae(enc(ord('g'), shifted_key=ord('G'), mods=shift), 'G')
|
||||
ae(enc(ord('g'), shifted_key=ord('G'), mods=alt), '\x1b' + 'g')
|
||||
ae(enc(ord('g'), shifted_key=ord('G'), mods=shift | alt), '\x1b' + 'G')
|
||||
ae(enc(ord('g'), shifted_key=ord('G'), mods=ctrl), '\x07')
|
||||
ae(enc(ord('g'), shifted_key=ord('G'), mods=ctrl | alt), '\x1b' + '\x07')
|
||||
ae(enc(ord('h'), shifted_key=ord('H')), 'h')
|
||||
ae(enc(ord('h'), shifted_key=ord('H'), mods=shift), 'H')
|
||||
ae(enc(ord('h'), shifted_key=ord('H'), mods=alt), '\x1b' + 'h')
|
||||
ae(enc(ord('h'), shifted_key=ord('H'), mods=shift | alt), '\x1b' + 'H')
|
||||
ae(enc(ord('h'), shifted_key=ord('H'), mods=ctrl), '\x08')
|
||||
ae(enc(ord('h'), shifted_key=ord('H'), mods=ctrl | alt), '\x1b' + '\x08')
|
||||
ae(enc(ord('i'), shifted_key=ord('I')), 'i')
|
||||
ae(enc(ord('i'), shifted_key=ord('I'), mods=shift), 'I')
|
||||
ae(enc(ord('i'), shifted_key=ord('I'), mods=alt), '\x1b' + 'i')
|
||||
ae(enc(ord('i'), shifted_key=ord('I'), mods=shift | alt), '\x1b' + 'I')
|
||||
ae(enc(ord('i'), shifted_key=ord('I'), mods=ctrl), '\t')
|
||||
ae(enc(ord('i'), shifted_key=ord('I'), mods=ctrl | alt), '\x1b' + '\t')
|
||||
ae(enc(ord('j'), shifted_key=ord('J')), 'j')
|
||||
ae(enc(ord('j'), shifted_key=ord('J'), mods=shift), 'J')
|
||||
ae(enc(ord('j'), shifted_key=ord('J'), mods=alt), '\x1b' + 'j')
|
||||
ae(enc(ord('j'), shifted_key=ord('J'), mods=shift | alt), '\x1b' + 'J')
|
||||
ae(enc(ord('j'), shifted_key=ord('J'), mods=ctrl), '\n')
|
||||
ae(enc(ord('j'), shifted_key=ord('J'), mods=ctrl | alt), '\x1b' + '\n')
|
||||
ae(enc(ord('k'), shifted_key=ord('K')), 'k')
|
||||
ae(enc(ord('k'), shifted_key=ord('K'), mods=shift), 'K')
|
||||
ae(enc(ord('k'), shifted_key=ord('K'), mods=alt), '\x1b' + 'k')
|
||||
ae(enc(ord('k'), shifted_key=ord('K'), mods=shift | alt), '\x1b' + 'K')
|
||||
ae(enc(ord('k'), shifted_key=ord('K'), mods=ctrl), '\x0b')
|
||||
ae(enc(ord('k'), shifted_key=ord('K'), mods=ctrl | alt), '\x1b' + '\x0b')
|
||||
ae(enc(ord('l'), shifted_key=ord('L')), 'l')
|
||||
ae(enc(ord('l'), shifted_key=ord('L'), mods=shift), 'L')
|
||||
ae(enc(ord('l'), shifted_key=ord('L'), mods=alt), '\x1b' + 'l')
|
||||
ae(enc(ord('l'), shifted_key=ord('L'), mods=shift | alt), '\x1b' + 'L')
|
||||
ae(enc(ord('l'), shifted_key=ord('L'), mods=ctrl), '\x0c')
|
||||
ae(enc(ord('l'), shifted_key=ord('L'), mods=ctrl | alt), '\x1b' + '\x0c')
|
||||
ae(enc(ord('m'), shifted_key=ord('M')), 'm')
|
||||
ae(enc(ord('m'), shifted_key=ord('M'), mods=shift), 'M')
|
||||
ae(enc(ord('m'), shifted_key=ord('M'), mods=alt), '\x1b' + 'm')
|
||||
ae(enc(ord('m'), shifted_key=ord('M'), mods=shift | alt), '\x1b' + 'M')
|
||||
ae(enc(ord('m'), shifted_key=ord('M'), mods=ctrl), '\r')
|
||||
ae(enc(ord('m'), shifted_key=ord('M'), mods=ctrl | alt), '\x1b' + '\r')
|
||||
ae(enc(ord('n'), shifted_key=ord('N')), 'n')
|
||||
ae(enc(ord('n'), shifted_key=ord('N'), mods=shift), 'N')
|
||||
ae(enc(ord('n'), shifted_key=ord('N'), mods=alt), '\x1b' + 'n')
|
||||
ae(enc(ord('n'), shifted_key=ord('N'), mods=shift | alt), '\x1b' + 'N')
|
||||
ae(enc(ord('n'), shifted_key=ord('N'), mods=ctrl), '\x0e')
|
||||
ae(enc(ord('n'), shifted_key=ord('N'), mods=ctrl | alt), '\x1b' + '\x0e')
|
||||
ae(enc(ord('o'), shifted_key=ord('O')), 'o')
|
||||
ae(enc(ord('o'), shifted_key=ord('O'), mods=shift), 'O')
|
||||
ae(enc(ord('o'), shifted_key=ord('O'), mods=alt), '\x1b' + 'o')
|
||||
ae(enc(ord('o'), shifted_key=ord('O'), mods=shift | alt), '\x1b' + 'O')
|
||||
ae(enc(ord('o'), shifted_key=ord('O'), mods=ctrl), '\x0f')
|
||||
ae(enc(ord('o'), shifted_key=ord('O'), mods=ctrl | alt), '\x1b' + '\x0f')
|
||||
ae(enc(ord('p'), shifted_key=ord('P')), 'p')
|
||||
ae(enc(ord('p'), shifted_key=ord('P'), mods=shift), 'P')
|
||||
ae(enc(ord('p'), shifted_key=ord('P'), mods=alt), '\x1b' + 'p')
|
||||
ae(enc(ord('p'), shifted_key=ord('P'), mods=shift | alt), '\x1b' + 'P')
|
||||
ae(enc(ord('p'), shifted_key=ord('P'), mods=ctrl), '\x10')
|
||||
ae(enc(ord('p'), shifted_key=ord('P'), mods=ctrl | alt), '\x1b' + '\x10')
|
||||
ae(enc(ord('q'), shifted_key=ord('Q')), 'q')
|
||||
ae(enc(ord('q'), shifted_key=ord('Q'), mods=shift), 'Q')
|
||||
ae(enc(ord('q'), shifted_key=ord('Q'), mods=alt), '\x1b' + 'q')
|
||||
ae(enc(ord('q'), shifted_key=ord('Q'), mods=shift | alt), '\x1b' + 'Q')
|
||||
ae(enc(ord('q'), shifted_key=ord('Q'), mods=ctrl), '\x11')
|
||||
ae(enc(ord('q'), shifted_key=ord('Q'), mods=ctrl | alt), '\x1b' + '\x11')
|
||||
ae(enc(ord('r'), shifted_key=ord('R')), 'r')
|
||||
ae(enc(ord('r'), shifted_key=ord('R'), mods=shift), 'R')
|
||||
ae(enc(ord('r'), shifted_key=ord('R'), mods=alt), '\x1b' + 'r')
|
||||
ae(enc(ord('r'), shifted_key=ord('R'), mods=shift | alt), '\x1b' + 'R')
|
||||
ae(enc(ord('r'), shifted_key=ord('R'), mods=ctrl), '\x12')
|
||||
ae(enc(ord('r'), shifted_key=ord('R'), mods=ctrl | alt), '\x1b' + '\x12')
|
||||
ae(enc(ord('s'), shifted_key=ord('S')), 's')
|
||||
ae(enc(ord('s'), shifted_key=ord('S'), mods=shift), 'S')
|
||||
ae(enc(ord('s'), shifted_key=ord('S'), mods=alt), '\x1b' + 's')
|
||||
ae(enc(ord('s'), shifted_key=ord('S'), mods=shift | alt), '\x1b' + 'S')
|
||||
ae(enc(ord('s'), shifted_key=ord('S'), mods=ctrl), '\x13')
|
||||
ae(enc(ord('s'), shifted_key=ord('S'), mods=ctrl | alt), '\x1b' + '\x13')
|
||||
ae(enc(ord('t'), shifted_key=ord('T')), 't')
|
||||
ae(enc(ord('t'), shifted_key=ord('T'), mods=shift), 'T')
|
||||
ae(enc(ord('t'), shifted_key=ord('T'), mods=alt), '\x1b' + 't')
|
||||
ae(enc(ord('t'), shifted_key=ord('T'), mods=shift | alt), '\x1b' + 'T')
|
||||
ae(enc(ord('t'), shifted_key=ord('T'), mods=ctrl), '\x14')
|
||||
ae(enc(ord('t'), shifted_key=ord('T'), mods=ctrl | alt), '\x1b' + '\x14')
|
||||
ae(enc(ord('u'), shifted_key=ord('U')), 'u')
|
||||
ae(enc(ord('u'), shifted_key=ord('U'), mods=shift), 'U')
|
||||
ae(enc(ord('u'), shifted_key=ord('U'), mods=alt), '\x1b' + 'u')
|
||||
ae(enc(ord('u'), shifted_key=ord('U'), mods=shift | alt), '\x1b' + 'U')
|
||||
ae(enc(ord('u'), shifted_key=ord('U'), mods=ctrl), '\x15')
|
||||
ae(enc(ord('u'), shifted_key=ord('U'), mods=ctrl | alt), '\x1b' + '\x15')
|
||||
ae(enc(ord('v'), shifted_key=ord('V')), 'v')
|
||||
ae(enc(ord('v'), shifted_key=ord('V'), mods=shift), 'V')
|
||||
ae(enc(ord('v'), shifted_key=ord('V'), mods=alt), '\x1b' + 'v')
|
||||
ae(enc(ord('v'), shifted_key=ord('V'), mods=shift | alt), '\x1b' + 'V')
|
||||
ae(enc(ord('v'), shifted_key=ord('V'), mods=ctrl), '\x16')
|
||||
ae(enc(ord('v'), shifted_key=ord('V'), mods=ctrl | alt), '\x1b' + '\x16')
|
||||
ae(enc(ord('w'), shifted_key=ord('W')), 'w')
|
||||
ae(enc(ord('w'), shifted_key=ord('W'), mods=shift), 'W')
|
||||
ae(enc(ord('w'), shifted_key=ord('W'), mods=alt), '\x1b' + 'w')
|
||||
ae(enc(ord('w'), shifted_key=ord('W'), mods=shift | alt), '\x1b' + 'W')
|
||||
ae(enc(ord('w'), shifted_key=ord('W'), mods=ctrl), '\x17')
|
||||
ae(enc(ord('w'), shifted_key=ord('W'), mods=ctrl | alt), '\x1b' + '\x17')
|
||||
ae(enc(ord('x'), shifted_key=ord('X')), 'x')
|
||||
ae(enc(ord('x'), shifted_key=ord('X'), mods=shift), 'X')
|
||||
ae(enc(ord('x'), shifted_key=ord('X'), mods=alt), '\x1b' + 'x')
|
||||
ae(enc(ord('x'), shifted_key=ord('X'), mods=shift | alt), '\x1b' + 'X')
|
||||
ae(enc(ord('x'), shifted_key=ord('X'), mods=ctrl), '\x18')
|
||||
ae(enc(ord('x'), shifted_key=ord('X'), mods=ctrl | alt), '\x1b' + '\x18')
|
||||
ae(enc(ord('y'), shifted_key=ord('Y')), 'y')
|
||||
ae(enc(ord('y'), shifted_key=ord('Y'), mods=shift), 'Y')
|
||||
ae(enc(ord('y'), shifted_key=ord('Y'), mods=alt), '\x1b' + 'y')
|
||||
ae(enc(ord('y'), shifted_key=ord('Y'), mods=shift | alt), '\x1b' + 'Y')
|
||||
ae(enc(ord('y'), shifted_key=ord('Y'), mods=ctrl), '\x19')
|
||||
ae(enc(ord('y'), shifted_key=ord('Y'), mods=ctrl | alt), '\x1b' + '\x19')
|
||||
ae(enc(ord('z'), shifted_key=ord('Z')), 'z')
|
||||
ae(enc(ord('z'), shifted_key=ord('Z'), mods=shift), 'Z')
|
||||
ae(enc(ord('z'), shifted_key=ord('Z'), mods=alt), '\x1b' + 'z')
|
||||
ae(enc(ord('z'), shifted_key=ord('Z'), mods=shift | alt), '\x1b' + 'Z')
|
||||
ae(enc(ord('z'), shifted_key=ord('Z'), mods=ctrl), '\x1a')
|
||||
ae(enc(ord('z'), shifted_key=ord('Z'), mods=ctrl | alt), '\x1b' + '\x1a')
|
||||
# end legacy letter tests
|
||||
# }}}
|
||||
|
||||
ae(enc(key=ord(':'), shifted_key=ord('/'), mods=shift | alt), '\x1b/')
|
||||
for key in '~!@#$%^&*()_+{}|:"<>?':
|
||||
ae(enc(key=ord(key), mods=alt), '\x1b' + key)
|
||||
ae(enc(key=ord(' ')), ' ')
|
||||
ae(enc(key=ord(' '), mods=ctrl | num_lock | caps_lock), '\0')
|
||||
ae(enc(key=ord(' '), mods=ctrl), '\0')
|
||||
ae(enc(key=ord(' '), mods=alt), '\x1b ')
|
||||
ae(enc(key=ord(' '), mods=shift), ' ')
|
||||
ae(enc(key=ord(' '), mods=ctrl | alt), '\x1b\0')
|
||||
ae(enc(key=ord(' '), mods=ctrl | shift), '\0')
|
||||
ae(enc(key=ord(' '), mods=alt | shift), '\x1b ')
|
||||
ae(enc(key=ord('i'), mods=ctrl | shift), csi(ctrl | shift, ord('i')))
|
||||
ae(enc(key=defines.GLFW_FKEY_LEFT_SHIFT), '')
|
||||
ae(enc(key=defines.GLFW_FKEY_CAPS_LOCK), '')
|
||||
|
||||
q = partial(enc, key=ord('a'))
|
||||
ae(q(), 'a')
|
||||
ae(q(text='a'), 'a')
|
||||
ae(q(action=repeat), 'a')
|
||||
ae(q(action=release), '')
|
||||
|
||||
# test disambiguate
|
||||
dq = partial(enc, key_encoding_flags=0b1)
|
||||
ae(dq(ord('a')), 'a')
|
||||
ae(dq(defines.GLFW_FKEY_ESCAPE), csi(num=27))
|
||||
ae(dq(defines.GLFW_FKEY_ENTER), '\r')
|
||||
ae(dq(defines.GLFW_FKEY_ENTER, mods=shift), csi(shift, 13))
|
||||
ae(dq(defines.GLFW_FKEY_TAB), '\t')
|
||||
ae(dq(defines.GLFW_FKEY_BACKSPACE), '\x7f')
|
||||
ae(dq(defines.GLFW_FKEY_TAB, mods=shift), csi(shift, 9))
|
||||
for mods in (ctrl, alt, ctrl | shift, alt | shift):
|
||||
ae(dq(ord('a'), mods=mods), csi(mods, ord('a')))
|
||||
ae(dq(ord(' '), mods=ctrl), csi(ctrl, ord(' ')))
|
||||
for k in (defines.GLFW_FKEY_KP_PAGE_UP, defines.GLFW_FKEY_KP_0):
|
||||
ae(dq(k), csi(num=k))
|
||||
ae(dq(k, mods=ctrl), csi(ctrl, num=k))
|
||||
ae(dq(defines.GLFW_FKEY_UP), '\x1b[A')
|
||||
ae(dq(defines.GLFW_FKEY_UP, mods=ctrl), csi(ctrl, 1, trailer='A'))
|
||||
|
||||
# test event type reporting
|
||||
tq = partial(enc, key_encoding_flags=0b10)
|
||||
ae(tq(ord('a')), 'a')
|
||||
ae(tq(ord('a'), action=defines.GLFW_REPEAT), csi(num='a', action=2))
|
||||
ae(tq(ord('a'), action=defines.GLFW_RELEASE), csi(num='a', action=3))
|
||||
ae(tq(ord('a'), action=defines.GLFW_RELEASE, mods=shift), csi(shift, num='a', action=3))
|
||||
tq = partial(enc, key_encoding_flags=0b11)
|
||||
ae(tq(defines.GLFW_FKEY_BACKSPACE), '\x7f')
|
||||
ae(tq(defines.GLFW_FKEY_BACKSPACE, action=release), '')
|
||||
tq = partial(enc, key_encoding_flags=0b11, mods=num_lock | caps_lock)
|
||||
ae(tq(defines.GLFW_FKEY_ENTER), '\r')
|
||||
ae(tq(defines.GLFW_FKEY_ENTER, action=release), '')
|
||||
|
||||
# test alternate key reporting
|
||||
aq = partial(enc, key_encoding_flags=0b100)
|
||||
ae(aq(ord('a')), 'a')
|
||||
ae(aq(ord('a'), shifted_key=ord('A')), 'a')
|
||||
ae(aq(ord('a'), mods=shift, shifted_key=ord('A')), csi(shift, 'a', shifted_key='A'))
|
||||
ae(aq(ord('a'), alternate_key=ord('A')), csi(num='a', alternate_key='A'))
|
||||
ae(aq(ord('a'), mods=shift, shifted_key=ord('A'), alternate_key=ord('b')), csi(shift, 'a', shifted_key='A', alternate_key='b'))
|
||||
|
||||
# test report all keys
|
||||
kq = partial(enc, key_encoding_flags=0b1000)
|
||||
ae(kq(ord('a')), csi(num='a'))
|
||||
ae(kq(ord('a'), action=defines.GLFW_REPEAT), csi(num='a'))
|
||||
ae(kq(ord('a'), mods=ctrl), csi(ctrl, num='a'))
|
||||
ae(kq(defines.GLFW_FKEY_UP), '\x1b[A')
|
||||
ae(kq(defines.GLFW_FKEY_LEFT_SHIFT), csi(num=defines.GLFW_FKEY_LEFT_SHIFT))
|
||||
ae(kq(defines.GLFW_FKEY_ENTER), '\x1b[13u')
|
||||
ae(kq(defines.GLFW_FKEY_ENTER, mods=ctrl), '\x1b[13;5u')
|
||||
ae(kq(defines.GLFW_FKEY_TAB), '\x1b[9u')
|
||||
ae(kq(defines.GLFW_FKEY_BACKSPACE), '\x1b[127u')
|
||||
|
||||
# test embed text
|
||||
eq = partial(enc, key_encoding_flags=0b11000)
|
||||
ae(eq(ord('a'), text='a'), csi(num='a', text='a'))
|
||||
ae(eq(ord('a'), mods=shift, text='A'), csi(shift, num='a', text='A'))
|
||||
ae(eq(ord('a'), mods=shift, text='AB'), csi(shift, num='a', text='AB'))
|
||||
|
||||
# test roundtripping via KeyEvent
|
||||
for mods in range(64):
|
||||
for action in EventType:
|
||||
for key in ('ENTER', 'a', 'TAB', 'F3'):
|
||||
for shifted_key in ('', 'X'):
|
||||
for alternate_key in ('', 'Y'):
|
||||
for text in ('', 'moose'):
|
||||
ev = KeyEvent(
|
||||
type=action,
|
||||
mods=mods,
|
||||
key=key,
|
||||
text=text,
|
||||
shifted_key=shifted_key,
|
||||
alternate_key=alternate_key,
|
||||
shift=bool(mods & 1),
|
||||
alt=bool(mods & 2),
|
||||
ctrl=bool(mods & 4),
|
||||
super=bool(mods & 8),
|
||||
hyper=bool(mods & 16),
|
||||
meta=bool(mods & 32),
|
||||
)
|
||||
ec = encode_key_event(ev)
|
||||
q = decode_key_event(ec[2:-1], ec[-1])
|
||||
self.ae(ev, q)
|
||||
|
||||
def test_encode_mouse_event(self):
|
||||
NORMAL_PROTOCOL, UTF8_PROTOCOL, SGR_PROTOCOL, URXVT_PROTOCOL = range(4)
|
||||
L, M, R = 1, 2, 3
|
||||
protocol = SGR_PROTOCOL
|
||||
|
||||
def enc(button=L, action=defines.PRESS, mods=0, x=1, y=1):
|
||||
return defines.test_encode_mouse(x, y, protocol, button, action, mods)
|
||||
|
||||
self.ae(enc(), '<0;1;1M')
|
||||
self.ae(enc(action=defines.RELEASE), '<0;1;1m')
|
||||
self.ae(enc(action=defines.MOVE, button=0), '<35;1;1M')
|
||||
self.ae(enc(action=defines.DRAG), '<32;1;1M')
|
||||
|
||||
self.ae(enc(R), '<2;1;1M')
|
||||
self.ae(enc(R, action=defines.RELEASE), '<2;1;1m')
|
||||
self.ae(enc(R, action=defines.DRAG), '<34;1;1M')
|
||||
|
||||
self.ae(enc(M), '<1;1;1M')
|
||||
self.ae(enc(M, action=defines.RELEASE), '<1;1;1m')
|
||||
self.ae(enc(M, action=defines.DRAG), '<33;1;1M')
|
||||
|
||||
self.ae(enc(x=1234, y=5678), '<0;1234;5678M')
|
||||
self.ae(enc(mods=defines.GLFW_MOD_SHIFT), '<4;1;1M')
|
||||
self.ae(enc(mods=defines.GLFW_MOD_ALT), '<8;1;1M')
|
||||
self.ae(enc(mods=defines.GLFW_MOD_CONTROL), '<16;1;1M')
|
||||
|
||||
def test_mapping(self):
|
||||
from kitty.config import load_config
|
||||
from kitty.options.utils import parse_shortcut
|
||||
|
||||
af = self.assertFalse
|
||||
|
||||
class Window:
|
||||
def __init__(self, id=1):
|
||||
self.key_seqs = []
|
||||
self.id = id
|
||||
|
||||
def send_key_sequence(self, *s):
|
||||
self.key_seqs.extend(s)
|
||||
|
||||
class TM(Mappings):
|
||||
def __init__(self, *lines, active_window=Window()):
|
||||
self.active_window = active_window
|
||||
self.windows = [active_window]
|
||||
bad_lines = []
|
||||
self.options = load_config(overrides=lines, accumulate_bad_lines=bad_lines)
|
||||
af(bad_lines)
|
||||
self.ignore_os_keyboard_processing = False
|
||||
super().__init__()
|
||||
|
||||
def get_active_window(self):
|
||||
return self.active_window
|
||||
|
||||
def match_windows(self, expr: str):
|
||||
for w in self.windows:
|
||||
if str(w.id) == expr:
|
||||
yield w
|
||||
|
||||
def show_error(self, title: str, msg: str) -> None:
|
||||
pass
|
||||
|
||||
def ring_bell(self) -> None:
|
||||
pass
|
||||
|
||||
def debug_print(self, *args, end: str = '\n') -> None:
|
||||
pass
|
||||
|
||||
def combine(self, action_definition: str) -> bool:
|
||||
self.actions.append(action_definition)
|
||||
if action_definition.startswith('push_keyboard_mode '):
|
||||
self.push_keyboard_mode(action_definition.partition(' ')[2])
|
||||
elif action_definition == 'pop_keyboard_mode':
|
||||
self.pop_keyboard_mode()
|
||||
return bool(action_definition)
|
||||
|
||||
def set_ignore_os_keyboard_processing(self, on: bool) -> None:
|
||||
self.ignore_os_keyboard_processing = on
|
||||
|
||||
def set_cocoa_global_shortcuts(self, opts):
|
||||
return {}
|
||||
|
||||
def get_options(self):
|
||||
return self.options
|
||||
|
||||
def __call__(self, *keys: str):
|
||||
self.actions = []
|
||||
self.active_window.key_seqs = []
|
||||
consumed = []
|
||||
for key in keys:
|
||||
sk = parse_shortcut(key)
|
||||
ev = defines.KeyEvent(sk.key, 0, 0, sk.mods)
|
||||
consumed.append(self.dispatch_possible_special_key(ev))
|
||||
return consumed
|
||||
|
||||
tm = TM('map ctrl+a new_window_with_cwd')
|
||||
self.ae(tm('ctrl+a'), [True])
|
||||
self.ae(tm.actions, ['new_window_with_cwd'])
|
||||
|
||||
tm = TM('map ctrl+f>2 set_font_size 20')
|
||||
self.ae(tm('ctrl+f', '2'), [True, True])
|
||||
self.ae(tm.actions, ['set_font_size 20'])
|
||||
af(tm.active_window.key_seqs)
|
||||
# unmatched multi key mapping should send all keys to child
|
||||
self.ae(tm('ctrl+f', '1'), [True, False])
|
||||
af(tm.actions)
|
||||
self.ae(len(tm.active_window.key_seqs), 1) # ctrl+f should have been sent to the window
|
||||
# multi-key mapping that is unmapped should send all keys to child
|
||||
tm = TM('map kitty_mod+p>f')
|
||||
self.ae(tm('ctrl+shift+p', 'f'), [True, False])
|
||||
self.ae(len(tm.active_window.key_seqs), 1)
|
||||
|
||||
# unmap
|
||||
tm = TM('map kitty_mod+enter')
|
||||
self.ae(tm('ctrl+shift+enter'), [False])
|
||||
|
||||
# single key mapping overrides previous all multi-key mappings with same prefix
|
||||
tm = TM('map kitty_mod+p new_window')
|
||||
self.ae(tm('ctrl+shift+p', 'f'), [True, False])
|
||||
self.ae(tm.actions, ['new_window'])
|
||||
# multi-key mapping overrides previous single key mapping with same prefix
|
||||
tm = TM('map kitty_mod+s>p new_window')
|
||||
self.ae(tm('ctrl+shift+s', 'p'), [True, True])
|
||||
self.ae(tm.actions, ['new_window'])
|
||||
# mix of single and multi-key mappings with same prefix
|
||||
tm = TM('map alt+p>1 multi1', 'map alt+p single1', 'map alt+p>2 multi2')
|
||||
self.ae(tm('alt+p', '2'), [True, True])
|
||||
self.ae(tm.actions, ['multi2'])
|
||||
self.ae(tm('alt+p', '1'), [True, False])
|
||||
af(tm.actions)
|
||||
self.ae(len(tm.active_window.key_seqs), 1)
|
||||
|
||||
# a single multi-key mapping should not prematurely match
|
||||
tm = TM('map alt+1>2>3 new_window')
|
||||
self.ae(tm('alt+1', '2'), [True, True])
|
||||
af(tm.actions)
|
||||
tm = TM('map alt+1>2>3 new_window')
|
||||
self.ae(tm('alt+1', '2', '3'), [True, True, True])
|
||||
self.ae(tm.actions, ['new_window'])
|
||||
|
||||
# changing a multi key mapping
|
||||
tm = TM('map kitty_mod+p>f new_window')
|
||||
self.ae(tm('ctrl+shift+p', 'f'), [True, True])
|
||||
self.ae(tm.actions, ['new_window'])
|
||||
|
||||
# different behavior with focus selection
|
||||
tm = TM('map --when-focus-on 2 kitty_mod+t')
|
||||
tm.windows.append(Window(2))
|
||||
self.ae(tm('ctrl+shift+t'), [True])
|
||||
tm.active_window = tm.windows[1]
|
||||
self.ae(tm('ctrl+shift+t'), [False])
|
||||
|
||||
# modal mappings
|
||||
tm = TM('map --new-mode mw --on-unknown end kitty_mod+f7', 'map --mode mw left neighboring_window left', 'map --mode mw right neighboring_window right')
|
||||
self.ae(tm('ctrl+shift+f7'), [True])
|
||||
self.ae(tm.actions, ['push_keyboard_mode mw'])
|
||||
self.ae(tm('right'), [True])
|
||||
self.ae(tm.actions, ['neighboring_window right'])
|
||||
self.ae(tm('left'), [True])
|
||||
self.ae(tm.actions, ['neighboring_window left'])
|
||||
self.ae(tm('x'), [True])
|
||||
af(tm.keyboard_mode_stack)
|
||||
|
||||
# passthrough_and_end: unknown key exits the mode and is passed through
|
||||
tm = TM('map --new-mode mw --on-unknown passthrough_and_end kitty_mod+f7', 'map --mode mw left neighboring_window left')
|
||||
self.ae(tm('ctrl+shift+f7'), [True])
|
||||
self.ae(tm.actions, ['push_keyboard_mode mw'])
|
||||
self.ae(tm('x'), [False])
|
||||
af(tm.keyboard_mode_stack)
|
||||
|
||||
# modal mapping with --on-action=end must restore OS keyboard processing
|
||||
tm = TM('map --new-mode mw --on-action end m', 'map --mode mw a new_window')
|
||||
self.ae(tm('m', 'a'), [True, True])
|
||||
self.ae(tm.actions, ['push_keyboard_mode mw', 'new_window'])
|
||||
af(tm.ignore_os_keyboard_processing)
|
||||
|
||||
def test_copy_or_noop_passthrough(self):
|
||||
from kitty.boss import Boss
|
||||
from kitty.conf.utils import KeyAction
|
||||
|
||||
class Window:
|
||||
def __init__(self, passthrough: bool):
|
||||
self.passthrough = passthrough
|
||||
self.calls = 0
|
||||
|
||||
def copy_or_noop(self) -> bool:
|
||||
self.calls += 1
|
||||
return self.passthrough
|
||||
|
||||
class TestBoss(Boss):
|
||||
window: Window
|
||||
|
||||
@property
|
||||
def active_window(self):
|
||||
return self.window
|
||||
|
||||
@property
|
||||
def active_tab(self):
|
||||
return None
|
||||
|
||||
boss = TestBoss.__new__(TestBoss)
|
||||
boss.args = SimpleNamespace(debug_keyboard=False)
|
||||
boss.window_for_dispatch = None
|
||||
|
||||
boss.window = Window(True)
|
||||
self.assertFalse(boss.dispatch_action(KeyAction('copy_or_noop')))
|
||||
self.ae(boss.window.calls, 1)
|
||||
|
||||
boss.window = Window(False)
|
||||
self.assertTrue(boss.dispatch_action(KeyAction('copy_or_noop')))
|
||||
self.ae(boss.window.calls, 1)
|
||||
|
||||
def test_match_physical_keys_removed(self):
|
||||
# match_physical_keys global option has been removed in favor of per-mapping --allow-fallback
|
||||
# Verify that get_shortcut does NOT match via alternate_key without per-mapping allow_fallback='ascii'
|
||||
from kitty.keys import get_shortcut
|
||||
from kitty.options.utils import KeyDefinition
|
||||
|
||||
ctrl = defines.GLFW_MOD_CONTROL
|
||||
cyrillic_s = 0x441 # Cyrillic 'с'
|
||||
latin_c = ord('c')
|
||||
|
||||
kd = KeyDefinition(definition='copy_to_clipboard') # default allow_fallback='shifted'
|
||||
keymap = {defines.SingleKey(ctrl, False, latin_c): [kd]}
|
||||
|
||||
# alternate_key should NOT match since default allow_fallback='shifted' (no 'ascii')
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, latin_c, ctrl)
|
||||
self.assertIsNone(get_shortcut(keymap, ev))
|
||||
|
||||
# direct key match still works
|
||||
ev = defines.KeyEvent(latin_c, 0, latin_c, ctrl)
|
||||
result = get_shortcut(keymap, ev)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertIs(result[0], kd)
|
||||
|
||||
def test_get_shortcut_per_mapping_fallback(self):
|
||||
from kitty.keys import get_shortcut
|
||||
from kitty.options.utils import KeyDefinition, KeyMapOptions, _convert_allow_fallback
|
||||
|
||||
ctrl = defines.GLFW_MOD_CONTROL
|
||||
shift = defines.GLFW_MOD_SHIFT
|
||||
cyrillic_s = 0x441 # Cyrillic 'с' (on physical 'c' key in Russian layout)
|
||||
latin_c = ord('c')
|
||||
|
||||
def make_kd(definition='test_action', allow_fallback='shifted'):
|
||||
opts = KeyMapOptions(allow_fallback=_convert_allow_fallback(allow_fallback))
|
||||
return KeyDefinition(definition=definition, options=opts)
|
||||
|
||||
# non-ASCII key + alternate_key + allow_fallback includes ascii → match
|
||||
kd_ascii = make_kd('copy', allow_fallback='ascii,shifted')
|
||||
keymap = {defines.SingleKey(ctrl, False, latin_c): [kd_ascii]}
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, latin_c, ctrl)
|
||||
result = get_shortcut(keymap, ev)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertIs(result[0], kd_ascii)
|
||||
|
||||
# sorting by fallback order
|
||||
kd1 = make_kd('ascii', allow_fallback='ascii,shifted')
|
||||
kd2 = make_kd('shifted', allow_fallback='shifted,ascii')
|
||||
keymap = {defines.SingleKey(ctrl, False, latin_c): [kd1, kd2]}
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, latin_c, ctrl)
|
||||
result = get_shortcut(keymap, ev)
|
||||
self.assertEqual(result, [kd1, kd2])
|
||||
keymap = {defines.SingleKey(0, False, latin_c): [kd1, kd2]}
|
||||
ev = defines.KeyEvent(ord('C'), latin_c, 0, shift)
|
||||
result = get_shortcut(keymap, ev)
|
||||
self.assertEqual(result, [kd2, kd1])
|
||||
|
||||
# non-ASCII key + alternate_key + allow_fallback='shifted' (no ascii) → no ascii match
|
||||
kd_shifted_only = make_kd('copy', allow_fallback='shifted')
|
||||
keymap = {defines.SingleKey(ctrl, False, latin_c): [kd_shifted_only]}
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, latin_c, ctrl)
|
||||
self.assertIsNone(get_shortcut(keymap, ev))
|
||||
|
||||
# shifted_key + allow_fallback='shifted' → match
|
||||
# When Shift+key pressed: key='C'(67), shifted_key='c'(99), lookup SingleKey(0, False, 'c')
|
||||
kd_shifted = make_kd('zoom', allow_fallback='shifted')
|
||||
keymap = {defines.SingleKey(0, False, latin_c): [kd_shifted]}
|
||||
ev = defines.KeyEvent(ord('C'), latin_c, 0, shift)
|
||||
result = get_shortcut(keymap, ev)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertIs(result[0], kd_shifted)
|
||||
|
||||
# shifted_key + allow_fallback='ascii' (no shifted) → no shifted match
|
||||
kd_ascii_only = make_kd('zoom', allow_fallback='ascii')
|
||||
keymap = {defines.SingleKey(0, False, latin_c): [kd_ascii_only]}
|
||||
ev = defines.KeyEvent(ord('C'), latin_c, 0, shift)
|
||||
self.assertIsNone(get_shortcut(keymap, ev))
|
||||
|
||||
# allow_fallback='' (empty) → no fallback at all
|
||||
kd_none = make_kd('copy', allow_fallback='')
|
||||
keymap = {defines.SingleKey(ctrl, False, latin_c): [kd_none]}
|
||||
# ascii fallback blocked
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, latin_c, ctrl)
|
||||
self.assertIsNone(get_shortcut(keymap, ev))
|
||||
# shifted fallback blocked
|
||||
ev = defines.KeyEvent(ord('C'), latin_c, 0, ctrl | shift)
|
||||
self.assertIsNone(get_shortcut(keymap, ev))
|
||||
|
||||
# ASCII key (Dvorak) + alternate_key → no fallback (non-ASCII guard: key must be > 127)
|
||||
kd_dvorak = make_kd('test', allow_fallback='ascii,shifted')
|
||||
keymap = {defines.SingleKey(ctrl, False, latin_c): [kd_dvorak]}
|
||||
ev = defines.KeyEvent(ord('k'), 0, latin_c, ctrl) # key='k' is ASCII
|
||||
self.assertIsNone(get_shortcut(keymap, ev))
|
||||
|
||||
# functional key (PUA range 0xE000+) + alternate_key → no fallback (functional keys excluded)
|
||||
kd_functional = make_kd('escape_action', allow_fallback='ascii,shifted')
|
||||
keymap = {defines.SingleKey(ctrl, False, latin_c): [kd_functional]}
|
||||
ev = defines.KeyEvent(0xE000, 0, latin_c, ctrl) # ESCAPE key (functional, PUA range)
|
||||
self.assertIsNone(get_shortcut(keymap, ev))
|
||||
|
||||
# boundary: 0xDFFF (last codepoint before PUA) → should match via ascii fallback
|
||||
kd_boundary = make_kd('boundary_action', allow_fallback='ascii,shifted')
|
||||
keymap = {defines.SingleKey(ctrl, False, latin_c): [kd_boundary]}
|
||||
ev = defines.KeyEvent(0xDFFF, 0, latin_c, ctrl)
|
||||
self.assertIsNotNone(get_shortcut(keymap, ev))
|
||||
|
||||
# boundary: 128 (first non-ASCII codepoint) → should match via ascii fallback
|
||||
ev = defines.KeyEvent(128, 0, latin_c, ctrl)
|
||||
self.assertIsNotNone(get_shortcut(keymap, ev))
|
||||
|
||||
# direct key match takes priority over alternate_key fallback
|
||||
kd_direct = make_kd('direct_action', allow_fallback='ascii,shifted')
|
||||
kd_alt = make_kd('alt_action', allow_fallback='ascii,shifted')
|
||||
keymap = {
|
||||
defines.SingleKey(ctrl, False, cyrillic_s): [kd_direct],
|
||||
defines.SingleKey(ctrl, False, latin_c): [kd_alt],
|
||||
}
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, latin_c, ctrl)
|
||||
result = get_shortcut(keymap, ev)
|
||||
self.assertIs(result[0], kd_direct) # direct match, not ascii fallback
|
||||
|
||||
def test_shortcut_matches_alternate_key(self):
|
||||
from kitty.keys import shortcut_matches
|
||||
|
||||
ctrl = defines.GLFW_MOD_CONTROL
|
||||
cyrillic_s = 0x441 # Cyrillic 'с'
|
||||
latin_c = ord('c')
|
||||
|
||||
s = defines.SingleKey(ctrl, False, latin_c)
|
||||
|
||||
# non-ASCII key + alternate_key → match (unconditional with non-ASCII guard)
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, latin_c, ctrl)
|
||||
self.assertTrue(shortcut_matches(s, ev))
|
||||
|
||||
# ASCII key + alternate_key → no match (non-ASCII guard blocks it)
|
||||
ev = defines.KeyEvent(ord('k'), 0, latin_c, ctrl)
|
||||
self.assertFalse(shortcut_matches(s, ev))
|
||||
|
||||
# direct key match still works
|
||||
ev = defines.KeyEvent(latin_c, 0, 0, ctrl)
|
||||
self.assertTrue(shortcut_matches(s, ev))
|
||||
|
||||
# no alternate_key → no match
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, 0, ctrl)
|
||||
self.assertFalse(shortcut_matches(s, ev))
|
||||
|
||||
# mods mismatch → no match even with alternate_key
|
||||
ev = defines.KeyEvent(cyrillic_s, 0, latin_c, defines.GLFW_MOD_ALT)
|
||||
self.assertFalse(shortcut_matches(s, ev))
|
||||
|
||||
# functional key (PUA range 0xE000+) + alternate_key → no match
|
||||
ev = defines.KeyEvent(0xE000, 0, latin_c, ctrl) # ESCAPE key (functional)
|
||||
self.assertFalse(shortcut_matches(s, ev))
|
||||
|
||||
def test_key_event_matches_alternate_key(self):
|
||||
from kitty.key_encoding import EventType, KeyEvent
|
||||
|
||||
ctrl = 0x4 # CTRL modifier in kitty protocol encoding
|
||||
|
||||
# non-ASCII key + alternate_key → match via alternate_key fallback
|
||||
ev = KeyEvent(type=EventType.PRESS, mods=ctrl, key='\u0441', alternate_key='c', ctrl=True) # Cyrillic 'с'
|
||||
self.assertTrue(ev.matches('ctrl+c'))
|
||||
|
||||
# direct key match still works
|
||||
ev = KeyEvent(type=EventType.PRESS, mods=ctrl, key='c', ctrl=True)
|
||||
self.assertTrue(ev.matches('ctrl+c'))
|
||||
|
||||
# ASCII key + alternate_key → no match (non-ASCII guard: key must be non-ASCII)
|
||||
ev = KeyEvent(type=EventType.PRESS, mods=ctrl, key='k', alternate_key='c', ctrl=True)
|
||||
self.assertFalse(ev.matches('ctrl+c'))
|
||||
|
||||
# no alternate_key → no match for non-ASCII key
|
||||
ev = KeyEvent(type=EventType.PRESS, mods=ctrl, key='\u0441', ctrl=True) # Cyrillic 'с', no alternate_key
|
||||
self.assertFalse(ev.matches('ctrl+c'))
|
||||
|
||||
# mods mismatch → no match even with alternate_key
|
||||
ev = KeyEvent(type=EventType.PRESS, mods=0x2, key='\u0441', alternate_key='c', alt=True) # ALT, not CTRL
|
||||
self.assertFalse(ev.matches('ctrl+c'))
|
||||
|
||||
# shifted_key still works alongside alternate_key
|
||||
ev = KeyEvent(type=EventType.PRESS, mods=0x1, key='C', shifted_key='c', shift=True)
|
||||
self.assertTrue(ev.matches('c'))
|
||||
|
||||
# functional key name (multi-char key like "ENTER") → no alternate_key fallback (guard blocks it)
|
||||
ev = KeyEvent(type=EventType.PRESS, mods=ctrl, key='ENTER', alternate_key='c', ctrl=True)
|
||||
self.assertFalse(ev.matches('ctrl+c'))
|
||||
|
||||
# functional key (single-char PUA 0xE000+) → no alternate_key fallback
|
||||
ev = KeyEvent(type=EventType.PRESS, mods=ctrl, key='\ue000', alternate_key='c', ctrl=True)
|
||||
self.assertFalse(ev.matches('ctrl+c'))
|
||||
|
||||
def test_allow_fallback_parsing(self):
|
||||
from kitty.options.utils import parse_map
|
||||
|
||||
def first_kd(val):
|
||||
return next(iter(parse_map(val)))
|
||||
|
||||
# default: no --allow-fallback → allow_fallback='shifted'
|
||||
kd = first_kd('ctrl+c copy_to_clipboard')
|
||||
self.ae(kd.options.allow_fallback, (KeyFallbackType.shifted,))
|
||||
|
||||
# --allow-fallback=shifted,ascii
|
||||
kd = first_kd('--allow-fallback=shifted,ascii ctrl+c copy_to_clipboard')
|
||||
self.assertIn(KeyFallbackType.shifted, kd.options.allow_fallback)
|
||||
self.assertIn(KeyFallbackType.alternate, kd.options.allow_fallback)
|
||||
|
||||
# --allow-fallback=ascii (only ascii, no shifted)
|
||||
kd = first_kd('--allow-fallback=ascii ctrl+c copy_to_clipboard')
|
||||
self.ae(kd.options.allow_fallback, (KeyFallbackType.alternate,))
|
||||
self.assertNotIn(KeyFallbackType.shifted, kd.options.allow_fallback)
|
||||
|
||||
# --allow-fallback=shifted (explicit, same as default)
|
||||
kd = first_kd('--allow-fallback=shifted ctrl+c copy_to_clipboard')
|
||||
self.ae(kd.options.allow_fallback, (KeyFallbackType.shifted,))
|
||||
|
||||
# invalid value raises
|
||||
self.assertRaises(ValueError, first_kd, '--allow-fallback=bogus ctrl+c copy_to_clipboard')
|
||||
|
||||
# order normalization: ascii,shifted → sorted as ascii,shifted
|
||||
kd = first_kd('--allow-fallback=ascii,shifted ctrl+c copy_to_clipboard')
|
||||
self.ae(kd.options.allow_fallback, (KeyFallbackType.alternate, KeyFallbackType.shifted))
|
||||
|
||||
# --allow-fallback=none → empty string (no fallback)
|
||||
kd = first_kd('--allow-fallback=none ctrl+c copy_to_clipboard')
|
||||
self.ae(kd.options.allow_fallback, ())
|
||||
|
||||
# combined with other options
|
||||
kd = first_kd('--when-focus-on 1 --allow-fallback=ascii ctrl+c copy_to_clipboard')
|
||||
self.ae(kd.options.allow_fallback, (KeyFallbackType.alternate,))
|
||||
self.ae(kd.options.when_focus_on, '1')
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,944 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import select
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
from collections.abc import Callable, Generator, Iterator, Sequence
|
||||
from contextlib import contextmanager, suppress
|
||||
from functools import lru_cache
|
||||
from tempfile import TemporaryDirectory, mkdtemp
|
||||
from typing import (
|
||||
Any,
|
||||
NoReturn,
|
||||
Optional,
|
||||
)
|
||||
|
||||
from . import is_ci
|
||||
|
||||
PARALLEL_THRESHOLD = 20
|
||||
|
||||
|
||||
def contents(package: str) -> Iterator[str]:
|
||||
try:
|
||||
if sys.version_info[:2] < (3, 10):
|
||||
raise ImportError("importlib.resources.files() doesn't work with frozen builds on python 3.9")
|
||||
from importlib.resources import files
|
||||
except ImportError:
|
||||
from importlib.resources import contents
|
||||
|
||||
return iter(contents(package))
|
||||
return (path.name for path in files(package).iterdir())
|
||||
|
||||
|
||||
def itertests(suite: unittest.TestSuite) -> Generator[unittest.TestCase, None, None]:
|
||||
stack = [suite]
|
||||
while stack:
|
||||
suite = stack.pop()
|
||||
for test in suite:
|
||||
if isinstance(test, unittest.TestSuite):
|
||||
stack.append(test)
|
||||
continue
|
||||
if test.__class__.__name__ == 'ModuleImportFailure':
|
||||
raise Exception('Failed to import a test module: %s' % test)
|
||||
yield test
|
||||
|
||||
|
||||
def find_all_tests(package: str = '', excludes: Sequence[str] = ('main', 'gr')) -> unittest.TestSuite:
|
||||
suits = []
|
||||
if not package:
|
||||
package = __name__.rpartition('.')[0] if '.' in __name__ else 'kitty_tests'
|
||||
for x in sorted(contents(package)):
|
||||
name, ext = os.path.splitext(x)
|
||||
if ext in ('.py', '.pyc') and name not in excludes:
|
||||
m = importlib.import_module(package + '.' + x.partition('.')[0])
|
||||
suits.append(unittest.defaultTestLoader.loadTestsFromModule(m))
|
||||
return unittest.TestSuite(suits)
|
||||
|
||||
|
||||
def filter_tests(suite: unittest.TestSuite, test_ok: Callable[[unittest.TestCase], bool]) -> unittest.TestSuite:
|
||||
ans = unittest.TestSuite()
|
||||
added: set[unittest.TestCase] = set()
|
||||
for test in itertests(suite):
|
||||
if test_ok(test) and test not in added:
|
||||
ans.addTest(test)
|
||||
added.add(test)
|
||||
return ans
|
||||
|
||||
|
||||
def filter_tests_by_name(suite: unittest.TestSuite, *names: str) -> unittest.TestSuite:
|
||||
names_ = {x if x.startswith('test_') else 'test_' + x for x in names}
|
||||
|
||||
def q(test: unittest.TestCase) -> bool:
|
||||
return test._testMethodName in names_
|
||||
|
||||
return filter_tests(suite, q)
|
||||
|
||||
|
||||
def filter_tests_by_module(suite: unittest.TestSuite, *names: str) -> unittest.TestSuite:
|
||||
names_ = frozenset(names)
|
||||
|
||||
def q(test: unittest.TestCase) -> bool:
|
||||
m = test.__class__.__module__.rpartition('.')[-1]
|
||||
return m in names_
|
||||
|
||||
return filter_tests(suite, q)
|
||||
|
||||
|
||||
def type_check() -> NoReturn:
|
||||
from kitty.cli_stub import generate_stub # type:ignore
|
||||
|
||||
generate_stub()
|
||||
from kittens.tui.operations_stub import generate_stub # type: ignore
|
||||
|
||||
generate_stub()
|
||||
os.execlp('ty', 'ty', 'check')
|
||||
|
||||
|
||||
def run_cli(suite: unittest.TestSuite, verbosity: int = 4) -> bool:
|
||||
r = unittest.TextTestRunner
|
||||
r.resultclass = unittest.TextTestResult
|
||||
runner = r(verbosity=verbosity)
|
||||
runner.tb_locals = True # type: ignore
|
||||
from .base import forwardable_stdio
|
||||
|
||||
with forwardable_stdio():
|
||||
result = runner.run(suite)
|
||||
sys.stdout.flush()
|
||||
sys.stderr.flush()
|
||||
return result.wasSuccessful()
|
||||
|
||||
|
||||
def find_testable_go_packages() -> tuple[set[str], dict[str, list[str]]]:
|
||||
test_functions: dict[str, list[str]] = {}
|
||||
ans = set()
|
||||
base = os.getcwd()
|
||||
pat = re.compile(r'^func Test([A-Z]\w+)', re.MULTILINE)
|
||||
for dirpath, dirnames, filenames in os.walk(base):
|
||||
if 'b' in dirnames and os.path.basename(dirpath) == 'bypy':
|
||||
dirnames.remove('b')
|
||||
for f in filenames:
|
||||
if f.endswith('_test.go'):
|
||||
q = os.path.relpath(dirpath, base)
|
||||
ans.add(q)
|
||||
with open(os.path.join(dirpath, f)) as s:
|
||||
raw = s.read()
|
||||
for m in pat.finditer(raw):
|
||||
test_functions.setdefault(m.group(1), []).append(q)
|
||||
return ans, test_functions
|
||||
|
||||
|
||||
@lru_cache
|
||||
def go_exe() -> str:
|
||||
return shutil.which('go') or ''
|
||||
|
||||
|
||||
class GoProc:
|
||||
def __init__(self, cmd: list[str]):
|
||||
from kitty.constants import kitty_exe
|
||||
|
||||
env = os.environ.copy()
|
||||
env['KITTY_PATH_TO_KITTY_EXE'] = kitty_exe()
|
||||
self.start_time = time.monotonic()
|
||||
self.end_time: float = 0.0
|
||||
self.tdir = mkdtemp(prefix='kitty-go-tests-')
|
||||
env['HOME'] = self.tdir
|
||||
if not env.get('GOCACHE') or not env.get('GOMODCACHE'):
|
||||
try:
|
||||
r = subprocess.run([cmd[0], 'env', 'GOCACHE', 'GOMODCACHE'], capture_output=True, text=True, timeout=10)
|
||||
if r.returncode == 0:
|
||||
gop, gomodp = r.stdout.strip().splitlines()
|
||||
if gop and not env.get('GOCACHE') and os.path.isdir(gop):
|
||||
env['GOCACHE'] = gop
|
||||
if gomodp and not env.get('GOMODCACHE') and os.path.isdir(gomodp):
|
||||
env['GOMODCACHE'] = gomodp
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
env['XDG_CONFIG_HOME'] = self.tdir + '/conf'
|
||||
os.mkdir(env['XDG_CONFIG_HOME'])
|
||||
env['XDG_CACHE_HOME'] = self.tdir + '/cache'
|
||||
os.mkdir(env['XDG_CACHE_HOME'])
|
||||
# start_new_session so that go tests cannot touch the terminal the
|
||||
# test suite is being run from, see detach_from_controlling_terminal()
|
||||
self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, stdin=subprocess.DEVNULL, start_new_session=True)
|
||||
self.stdout_fd = self.proc.stdout.fileno()
|
||||
|
||||
@property
|
||||
def runtime(self) -> float:
|
||||
return self.end_time - self.start_time
|
||||
|
||||
@property
|
||||
def returncode(self) -> int:
|
||||
return self.proc.returncode
|
||||
|
||||
def finish(self) -> None:
|
||||
"""Reap the process after its stdout has been fully drained."""
|
||||
assert self.proc.stdout is not None
|
||||
self.proc.stdout.close()
|
||||
self.proc.wait()
|
||||
self.end_time = time.monotonic()
|
||||
shutil.rmtree(self.tdir, ignore_errors=True)
|
||||
|
||||
|
||||
def run_go(packages: set[str], names: Sequence[str]) -> GoProc:
|
||||
go = go_exe()
|
||||
go_pkg_args = [f'github.com/kovidgoyal/kitty/{x}' for x in packages]
|
||||
cmd = [go, 'test', '--tags', 'testing', '-v', '-json']
|
||||
if names:
|
||||
cmd.extend(('-run', '^Test(?:' + '|'.join(re.escape(name) for name in names) + ')$'))
|
||||
cmd += go_pkg_args
|
||||
return GoProc(cmd)
|
||||
|
||||
|
||||
def reduce_go_pkgs(module: str, names: Sequence[str]) -> set[str]:
|
||||
if not go_exe():
|
||||
raise SystemExit('go executable not found, current path: ' + repr(os.environ.get('PATH', '')))
|
||||
go_packages, go_functions = find_testable_go_packages()
|
||||
if module:
|
||||
go_packages &= {module}
|
||||
if names:
|
||||
pkgs = set()
|
||||
for name in names:
|
||||
pkgs |= set(go_functions.get(name, []))
|
||||
go_packages &= pkgs
|
||||
return go_packages
|
||||
|
||||
|
||||
@contextmanager
|
||||
def env_vars(**kw: str) -> Iterator[None]:
|
||||
originals = {k: os.environ.get(k) for k in kw}
|
||||
os.environ.update(kw)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for k, v in originals.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def path_for_python_tests() -> str:
|
||||
"""The PATH used by tests: the built launcher dir followed by all entries not under the real home dir."""
|
||||
from kitty.constants import kitty_exe
|
||||
|
||||
current_home = os.path.expanduser('~') + os.sep
|
||||
paths = os.environ.get('PATH', '/usr/local/sbin:/usr/local/bin:/usr/bin').split(os.pathsep)
|
||||
path = os.pathsep.join(x for x in paths if not x.startswith(current_home))
|
||||
launcher_dir = os.path.dirname(kitty_exe())
|
||||
return f'{launcher_dir}{os.pathsep}{path}'
|
||||
|
||||
|
||||
def report_test_env() -> None:
|
||||
"""Print details of the environment tests will run in. Called once in the master process as workers have their stdout captured."""
|
||||
print('Running under CI:', is_ci)
|
||||
print('Using PATH in test environment:', path_for_python_tests())
|
||||
from kitty.fast_data_types import has_avx2, has_avx512, has_sse4_2
|
||||
|
||||
print(f'Intrinsics: {has_avx512=} {has_avx2=} {has_sse4_2=}')
|
||||
|
||||
|
||||
@contextmanager
|
||||
def env_for_python_tests() -> Iterator[None]:
|
||||
gohome = os.path.expanduser('~/go')
|
||||
slangc = os.environ.get('SLANGC') or shutil.which('slangc') or 'slangc'
|
||||
path = path_for_python_tests()
|
||||
with (
|
||||
TemporaryDirectory() as tdir,
|
||||
env_vars(
|
||||
HOME=tdir,
|
||||
KT_ORIGINAL_HOME=os.path.expanduser('~'),
|
||||
USERPROFILE=tdir,
|
||||
PATH=path,
|
||||
TERM='xterm-kitty',
|
||||
SLANGC=slangc,
|
||||
XDG_CONFIG_HOME=os.path.join(tdir, '.config'),
|
||||
XDG_CONFIG_DIRS=os.path.join(tdir, '.config'),
|
||||
XDG_DATA_DIRS=os.path.join(tdir, '.local', 'xdg'),
|
||||
XDG_CACHE_HOME=os.path.join(tdir, '.cache'),
|
||||
XDG_RUNTIME_DIR=os.path.join(tdir, '.cache', 'run'),
|
||||
PYTHONWARNINGS='error',
|
||||
),
|
||||
):
|
||||
if os.path.isdir(gohome):
|
||||
os.symlink(gohome, os.path.join(tdir, os.path.basename(gohome)))
|
||||
yield
|
||||
|
||||
|
||||
def send_record(write_fd: int, record: dict[str, Any]) -> None:
|
||||
data = (json.dumps(record) + '\n').encode()
|
||||
while data:
|
||||
n = os.write(write_fd, data)
|
||||
data = data[n:]
|
||||
|
||||
|
||||
class PipeTestResult(unittest.TestResult):
|
||||
"""Writes test results as newline-delimited JSON records to a file descriptor."""
|
||||
|
||||
def __init__(self, write_fd: int) -> None:
|
||||
super().__init__()
|
||||
self._wfd = write_fd
|
||||
self._test_start: float = 0.0
|
||||
|
||||
def _send(self, record: dict[str, Any]) -> None:
|
||||
send_record(self._wfd, record)
|
||||
|
||||
def _elapsed(self) -> float:
|
||||
return time.monotonic() - self._test_start
|
||||
|
||||
def startTest(self, test: unittest.TestCase) -> None:
|
||||
super().startTest(test)
|
||||
self._test_start = time.monotonic()
|
||||
self._send({'t': 'start', 'id': str(test)})
|
||||
|
||||
def addSuccess(self, test: unittest.TestCase) -> None:
|
||||
self._send({'t': 'ok', 'id': str(test), 'e': self._elapsed()})
|
||||
|
||||
def addError(self, test: unittest.TestCase, err: Any) -> None:
|
||||
super().addError(test, err)
|
||||
self._send({'t': 'error', 'id': str(test), 'e': self._elapsed(), 'msg': self._exc_info_to_string(err, test)})
|
||||
|
||||
def addFailure(self, test: unittest.TestCase, err: Any) -> None:
|
||||
super().addFailure(test, err)
|
||||
self._send({'t': 'fail', 'id': str(test), 'e': self._elapsed(), 'msg': self._exc_info_to_string(err, test)})
|
||||
|
||||
def addSkip(self, test: unittest.TestCase, reason: str) -> None:
|
||||
super().addSkip(test, reason)
|
||||
self._send({'t': 'skip', 'id': str(test), 'e': self._elapsed(), 'msg': reason})
|
||||
|
||||
def addExpectedFailure(self, test: unittest.TestCase, err: Any) -> None:
|
||||
super().addExpectedFailure(test, err)
|
||||
self._send({'t': 'xfail', 'id': str(test), 'e': self._elapsed(), 'msg': self._exc_info_to_string(err, test)})
|
||||
|
||||
def addUnexpectedSuccess(self, test: unittest.TestCase) -> None:
|
||||
super().addUnexpectedSuccess(test)
|
||||
self._send({'t': 'xpass', 'id': str(test), 'e': self._elapsed()})
|
||||
|
||||
def addSubTest(self, test: unittest.TestCase, subtest: unittest.TestCase, err: Any) -> None:
|
||||
super().addSubTest(test, subtest, err)
|
||||
if err is not None:
|
||||
record_type = 'fail' if issubclass(err[0], test.failureException) else 'error'
|
||||
self._send({'t': record_type, 'id': str(subtest), 'e': self._elapsed(), 'msg': self._exc_info_to_string(err, test)})
|
||||
|
||||
|
||||
def run_test_worker(tests: list[unittest.TestCase], write_fd: int, verbosity: Optional[int] = None) -> None:
|
||||
"""Execute in a child process: run tests, then exit, never returning.
|
||||
|
||||
With verbosity None, results are sent over write_fd as JSON records,
|
||||
otherwise they are printed to stdout. In both cases a final 'done' record
|
||||
is sent once the tests and their environment cleanup are complete, so the
|
||||
parent can detect a worker that exits early, for example because some code
|
||||
under test called os._exit(0). Such an exit cannot be detected in-process.
|
||||
"""
|
||||
worker_pid = os.getpid()
|
||||
exit_code = 1
|
||||
try:
|
||||
with env_for_python_tests():
|
||||
if verbosity is not None:
|
||||
ok = run_cli(unittest.TestSuite(tests), verbosity)
|
||||
else:
|
||||
from .base import forwardable_stdio
|
||||
|
||||
with forwardable_stdio():
|
||||
unittest.TestSuite(tests).run(PipeTestResult(write_fd))
|
||||
ok = True
|
||||
exit_code = 0 if ok else 1
|
||||
except BaseException:
|
||||
if os.getpid() != worker_pid:
|
||||
# A process forked by a test escaped from it, it must not report
|
||||
# anything on behalf of the worker
|
||||
os._exit(1)
|
||||
import traceback
|
||||
|
||||
with suppress(OSError):
|
||||
send_record(write_fd, {'t': 'worker_error', 'msg': traceback.format_exc()})
|
||||
exit_code = 1
|
||||
if os.getpid() == worker_pid:
|
||||
with suppress(OSError):
|
||||
send_record(write_fd, {'t': 'done'})
|
||||
with suppress(OSError):
|
||||
os.close(write_fd)
|
||||
os._exit(exit_code)
|
||||
|
||||
|
||||
def detach_from_controlling_terminal() -> None:
|
||||
"""Put the calling process into its own session, with no controlling terminal.
|
||||
|
||||
Tests must never depend on the terminal the test suite happens to be run
|
||||
from, and must never be able to disturb it. Without this, any program a
|
||||
test runs can reach it via /dev/tty; a job control aware shell for instance
|
||||
will make its own process group the foreground one on it, and a second such
|
||||
shell started while that is the case stops the entire test run with SIGTTIN.
|
||||
"""
|
||||
try:
|
||||
os.setsid()
|
||||
except OSError: # already a session leader
|
||||
pass
|
||||
|
||||
|
||||
def fork_test_workers(tests: list[unittest.TestCase]) -> tuple[list[int], list[int]]:
|
||||
"""Chunk tests and fork worker processes. Returns (pids, read_fds)."""
|
||||
n = min(os.cpu_count() or 4, 8, len(tests))
|
||||
# Round-robin assignment so slow and fast tests are spread across all workers
|
||||
chunks: list[list[unittest.TestCase]] = [[] for _ in range(n)]
|
||||
for i, test in enumerate(tests):
|
||||
chunks[i % n].append(test)
|
||||
pids: list[int] = []
|
||||
read_fds: list[int] = []
|
||||
for chunk in chunks:
|
||||
r, w = os.pipe()
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
os.close(r)
|
||||
detach_from_controlling_terminal()
|
||||
devnull = os.open(os.devnull, os.O_RDWR)
|
||||
os.dup2(devnull, 0)
|
||||
os.dup2(devnull, 1)
|
||||
os.dup2(devnull, 2)
|
||||
os.close(devnull)
|
||||
run_test_worker(chunk, w)
|
||||
# run_test_worker calls os._exit() — never returns
|
||||
os.close(w)
|
||||
read_fds.append(r)
|
||||
pids.append(pid)
|
||||
return pids, read_fds
|
||||
|
||||
|
||||
def worker_main(write_fd: int, ids_fd: int, verbosity: Optional[int] = None) -> None:
|
||||
import warnings
|
||||
|
||||
warnings.simplefilter('error')
|
||||
# we need fonts installed in the user home directory as well, so initialize
|
||||
# fontconfig before nuking $HOME and friends
|
||||
from kitty.fonts.common import all_fonts_map
|
||||
|
||||
all_fonts_map(True)
|
||||
|
||||
with open(ids_fd) as f:
|
||||
test_ids = json.load(f)
|
||||
tests = [getattr(importlib.import_module(t['module']), t['cls'])(t['method']) for t in test_ids]
|
||||
run_test_worker(tests, write_fd, verbosity)
|
||||
|
||||
|
||||
def spawn_test_worker(tests: list[unittest.TestCase], verbosity: Optional[int] = None) -> tuple['subprocess.Popen[bytes]', int]:
|
||||
"""Spawn a worker subprocess via kitty +runpy. Returns (proc, read_fd).
|
||||
|
||||
Used on macOS where fork() + threading is unsafe. With verbosity None the
|
||||
worker is detached from the terminal, otherwise it shares it with us."""
|
||||
from kitty.constants import kitty_exe
|
||||
|
||||
r, w = os.pipe()
|
||||
ids_r, ids_w = os.pipe()
|
||||
test_ids = [{'module': t.__class__.__module__, 'cls': t.__class__.__name__, 'method': t._testMethodName} for t in tests]
|
||||
detached = verbosity is None
|
||||
try:
|
||||
proc: subprocess.Popen[bytes] = subprocess.Popen(
|
||||
[kitty_exe(), '+runpy', f'from kitty_tests.main import *; worker_main({w}, {ids_r}, {verbosity!r})'],
|
||||
pass_fds=(w, ids_r),
|
||||
stdin=subprocess.DEVNULL if detached else None,
|
||||
stdout=subprocess.DEVNULL if detached else None,
|
||||
stderr=subprocess.DEVNULL if detached else None,
|
||||
start_new_session=detached, # see detach_from_controlling_terminal()
|
||||
)
|
||||
except BaseException:
|
||||
os.close(r)
|
||||
os.close(ids_w)
|
||||
raise
|
||||
finally:
|
||||
os.close(w)
|
||||
os.close(ids_r)
|
||||
with open(ids_w, 'w') as f:
|
||||
json.dump(test_ids, f)
|
||||
return proc, r
|
||||
|
||||
|
||||
def spawn_test_workers(tests: list[unittest.TestCase]) -> tuple[list[subprocess.Popen[bytes]], list[int]]:
|
||||
"""Chunk tests and spawn worker subprocesses. Returns (procs, read_fds)."""
|
||||
n = min(os.cpu_count() or 4, 8, len(tests))
|
||||
chunks: list[list[unittest.TestCase]] = [[] for _ in range(n)]
|
||||
for i, test in enumerate(tests):
|
||||
chunks[i % n].append(test)
|
||||
|
||||
procs: list[subprocess.Popen[bytes]] = []
|
||||
read_fds: list[int] = []
|
||||
|
||||
for chunk in chunks:
|
||||
proc, r = spawn_test_worker(chunk)
|
||||
read_fds.append(r)
|
||||
procs.append(proc)
|
||||
|
||||
return procs, read_fds
|
||||
|
||||
|
||||
def run_serial_tests(tests: list[unittest.TestCase], verbosity: int) -> bool:
|
||||
"""Run tests in a single child process that shares our terminal, printing
|
||||
results as they happen. The child is used so that it exiting before all
|
||||
tests have run is detected."""
|
||||
if sys.platform == 'darwin':
|
||||
proc, r = spawn_test_worker(tests, verbosity)
|
||||
pids: list[int] = []
|
||||
procs = [proc]
|
||||
else:
|
||||
r, w = os.pipe()
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
os.close(r)
|
||||
run_test_worker(tests, w, verbosity)
|
||||
os.close(w)
|
||||
pids, procs = [pid], []
|
||||
try:
|
||||
data = b''
|
||||
while chunk := os.read(r, 65536):
|
||||
data += chunk
|
||||
os.close(r)
|
||||
if pids:
|
||||
status = os.waitstatus_to_exitcode(os.waitpid(pids[0], 0)[1])
|
||||
else:
|
||||
status = procs[0].wait()
|
||||
except BaseException:
|
||||
terminate_workers(pids, procs, None)
|
||||
raise
|
||||
done = False
|
||||
worker_errors: list[str] = []
|
||||
for line in data.splitlines():
|
||||
if line:
|
||||
rec = json.loads(line)
|
||||
if rec['t'] == 'done':
|
||||
done = True
|
||||
elif rec['t'] == 'worker_error':
|
||||
worker_errors.append(rec['msg'])
|
||||
if not done:
|
||||
worker_errors.append(f'\nPython test process exited with status {status} before completing its tests')
|
||||
for msg in worker_errors:
|
||||
print(msg, file=sys.stderr)
|
||||
sys.stderr.flush()
|
||||
return status == 0 and not worker_errors
|
||||
|
||||
|
||||
_RED = '\x1b[31m'
|
||||
_GREEN = '\x1b[32m'
|
||||
_YELLOW = '\x1b[33m'
|
||||
_CYAN = '\x1b[36m'
|
||||
_RESET = '\x1b[0m'
|
||||
_BOLD = '\x1b[1m'
|
||||
_DIM = '\x1b[2m'
|
||||
|
||||
|
||||
def collect_worker_results(
|
||||
pids: list[int],
|
||||
procs: list[subprocess.Popen[bytes]],
|
||||
read_fds: list[int],
|
||||
total_py_tests: int,
|
||||
go_proc: Optional[GoProc] = None,
|
||||
) -> tuple[bool, bool]:
|
||||
"""Read JSON from worker pipes and go proc stdout, show live progress, print failures."""
|
||||
use_tty = sys.stdout.isatty()
|
||||
py_buffers: dict[int, bytes] = {fd: b'' for fd in read_fds}
|
||||
# read_fds are in the same order as the pids or procs they belong to
|
||||
worker_pid_for_fd = dict(zip(read_fds, pids + [p.pid for p in procs]))
|
||||
py_completed: set[int] = set()
|
||||
py_last_started: dict[int, str] = {}
|
||||
active_py = list(read_fds)
|
||||
go_buffer = b''
|
||||
go_active = go_proc is not None
|
||||
start = time.monotonic()
|
||||
|
||||
py_run = 0
|
||||
py_failures: list[tuple[str, str]] = []
|
||||
py_errors: list[tuple[str, str]] = []
|
||||
py_skipped = 0
|
||||
py_unexpected_successes: list[str] = []
|
||||
py_worker_errors: list[str] = []
|
||||
|
||||
go_run = 0
|
||||
go_failures: list[tuple[str, str]] = []
|
||||
go_test_output: dict[str, list[str]] = {}
|
||||
go_pkg_output: dict[str, list[str]] = {}
|
||||
go_other_output: list[str] = []
|
||||
|
||||
# (elapsed_seconds, label) for every completed test in both suites
|
||||
all_timings: list[tuple[float, str]] = []
|
||||
|
||||
def c(code: str, text: str) -> str:
|
||||
return (code + text + _RESET) if use_tty else text
|
||||
|
||||
def render_progress() -> str:
|
||||
elapsed = time.monotonic() - start
|
||||
parts: list[str] = []
|
||||
if total_py_tests > 0 or active_py:
|
||||
py_mark = c(_GREEN, ' ✓') if not active_py else ''
|
||||
parts.append(c(_CYAN + _BOLD, 'Py') + f' {py_run}/{total_py_tests}' + py_mark)
|
||||
if go_proc is not None:
|
||||
# Go total is omitted: t.Run() sub-tests inflate the count beyond
|
||||
# what static analysis of Test* functions can predict.
|
||||
go_mark = c(_GREEN, ' ✓') if not go_active else ''
|
||||
parts.append(c(_YELLOW + _BOLD, 'Go') + f' {go_run}' + go_mark)
|
||||
fail_count = len(py_failures) + len(py_errors) + len(go_failures)
|
||||
if fail_count:
|
||||
parts.append(c(_RED, f'{fail_count} failed'))
|
||||
return ' ' + ' '.join(parts) + ' ' + c(_DIM, f'[{elapsed:.1f}s]')
|
||||
|
||||
def show_progress(force: bool = False) -> None:
|
||||
line = render_progress()
|
||||
if use_tty:
|
||||
print(f'\r{line}\x1b[K', end='', flush=True)
|
||||
elif force or (total_py_tests > 0 and py_run % max(1, total_py_tests // 10) == 0):
|
||||
print(line, flush=True)
|
||||
|
||||
while active_py or go_active:
|
||||
watch = list(active_py)
|
||||
if go_active and go_proc is not None:
|
||||
watch.append(go_proc.stdout_fd)
|
||||
readable, _, _ = select.select(watch, [], [])
|
||||
|
||||
for fd in readable:
|
||||
if go_proc is not None and fd == go_proc.stdout_fd:
|
||||
try:
|
||||
chunk = os.read(fd, 65536)
|
||||
except OSError:
|
||||
chunk = b''
|
||||
if not chunk:
|
||||
if go_buffer:
|
||||
go_other_output.append(go_buffer.decode('utf-8', errors='replace'))
|
||||
go_active = False
|
||||
go_proc.finish()
|
||||
show_progress(force=True)
|
||||
continue
|
||||
go_buffer += chunk
|
||||
while b'\n' in go_buffer:
|
||||
raw, go_buffer = go_buffer.split(b'\n', 1)
|
||||
if not raw:
|
||||
continue
|
||||
try:
|
||||
evt: dict[str, Any] = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
go_other_output.append(raw.decode('utf-8', errors='replace') + '\n')
|
||||
continue
|
||||
action = evt.get('Action', '')
|
||||
test_name = evt.get('Test', '')
|
||||
pkg = evt.get('Package', '')
|
||||
if test_name:
|
||||
full = f'{pkg}.{test_name}' if pkg else test_name
|
||||
if action == 'run':
|
||||
go_test_output[full] = []
|
||||
elif action == 'output':
|
||||
go_test_output.setdefault(full, []).append(evt.get('Output', ''))
|
||||
elif action in ('pass', 'fail', 'skip'):
|
||||
go_run += 1
|
||||
elapsed_test = float(evt.get('Elapsed') or 0.0)
|
||||
if action == 'fail':
|
||||
output = ''.join(go_test_output.pop(full, []))
|
||||
go_failures.append((full, output))
|
||||
else:
|
||||
go_test_output.pop(full, None)
|
||||
all_timings.append((elapsed_test, f'[Go] {full}'))
|
||||
show_progress()
|
||||
else:
|
||||
if action == 'output':
|
||||
go_pkg_output.setdefault(pkg, []).append(evt.get('Output', ''))
|
||||
elif action == 'fail':
|
||||
# Package-level failure (e.g. build error): show if no test-level failures from it
|
||||
pkg_had_test_failure = any(f.startswith(pkg + '.') for f, _ in go_failures)
|
||||
if not pkg_had_test_failure:
|
||||
output = ''.join(go_pkg_output.pop(pkg, []))
|
||||
if output:
|
||||
go_failures.append((pkg, output))
|
||||
show_progress()
|
||||
else:
|
||||
go_pkg_output.pop(pkg, None)
|
||||
else:
|
||||
go_pkg_output.pop(pkg, None)
|
||||
else:
|
||||
try:
|
||||
chunk = os.read(fd, 65536)
|
||||
except OSError:
|
||||
chunk = b''
|
||||
if not chunk:
|
||||
active_py.remove(fd)
|
||||
os.close(fd)
|
||||
show_progress(force=True)
|
||||
continue
|
||||
py_buffers[fd] += chunk
|
||||
while b'\n' in py_buffers[fd]:
|
||||
raw_py, py_buffers[fd] = py_buffers[fd].split(b'\n', 1)
|
||||
if not raw_py:
|
||||
continue
|
||||
rec: dict[str, Any] = json.loads(raw_py)
|
||||
t = rec['t']
|
||||
elapsed_test = float(rec.get('e') or 0.0)
|
||||
if t == 'start':
|
||||
py_last_started[fd] = rec['id']
|
||||
elif t == 'done':
|
||||
py_completed.add(fd)
|
||||
elif t == 'ok':
|
||||
py_run += 1
|
||||
all_timings.append((elapsed_test, f'[Py] {rec["id"]}'))
|
||||
show_progress()
|
||||
elif t == 'fail':
|
||||
py_run += 1
|
||||
py_failures.append((rec['id'], rec['msg']))
|
||||
all_timings.append((elapsed_test, f'[Py] {rec["id"]}'))
|
||||
show_progress()
|
||||
elif t == 'error':
|
||||
py_run += 1
|
||||
py_errors.append((rec['id'], rec['msg']))
|
||||
all_timings.append((elapsed_test, f'[Py] {rec["id"]}'))
|
||||
show_progress()
|
||||
elif t == 'skip':
|
||||
py_run += 1
|
||||
py_skipped += 1
|
||||
all_timings.append((elapsed_test, f'[Py] {rec["id"]}'))
|
||||
show_progress()
|
||||
elif t == 'xfail':
|
||||
py_run += 1
|
||||
all_timings.append((elapsed_test, f'[Py] {rec["id"]}'))
|
||||
show_progress()
|
||||
elif t == 'xpass':
|
||||
py_run += 1
|
||||
py_unexpected_successes.append(rec['id'])
|
||||
all_timings.append((elapsed_test, f'[Py] {rec["id"]}'))
|
||||
show_progress()
|
||||
elif t == 'worker_error':
|
||||
py_worker_errors.append(rec['msg'])
|
||||
|
||||
exit_codes: dict[int, int] = {pid: os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]) for pid in pids}
|
||||
exit_codes.update((proc.pid, proc.wait()) for proc in procs)
|
||||
for fd, pid in worker_pid_for_fd.items():
|
||||
if fd not in py_completed:
|
||||
msg = f'Python test worker {pid} exited with status {exit_codes[pid]} before completing its tests'
|
||||
if last := py_last_started.get(fd):
|
||||
msg += f', the last test it started was: {last}'
|
||||
py_worker_errors.append(msg)
|
||||
elif exit_codes[pid] != 0:
|
||||
py_worker_errors.append(f'Python test worker {pid} exited with status {exit_codes[pid]}')
|
||||
|
||||
elapsed = time.monotonic() - start
|
||||
|
||||
if use_tty:
|
||||
print() # move past the progress line
|
||||
|
||||
sep1 = '=' * 70
|
||||
sep2 = '-' * 70
|
||||
|
||||
for msg in py_worker_errors:
|
||||
print(sep1)
|
||||
print(c(_RED + _BOLD, 'WORKER ERROR'))
|
||||
print(sep2)
|
||||
print(msg)
|
||||
|
||||
for label_text, items in (('FAIL', py_failures), ('ERROR', py_errors)):
|
||||
for tid, msg in items:
|
||||
print(sep1)
|
||||
print(f'{c(_RED + _BOLD, label_text)}: {tid}')
|
||||
print(sep2)
|
||||
print(msg)
|
||||
|
||||
for go_tid, go_output in go_failures:
|
||||
print(sep1)
|
||||
print(f'{c(_RED + _BOLD, "FAIL")}: {go_tid}')
|
||||
print(sep2)
|
||||
if go_output:
|
||||
print(go_output, end='' if go_output.endswith('\n') else '\n')
|
||||
|
||||
if go_proc is not None and go_proc.returncode != 0 and go_other_output:
|
||||
print(sep1)
|
||||
print(c(_RED + _BOLD, 'GO ERROR'))
|
||||
print(sep2)
|
||||
output = ''.join(go_other_output)
|
||||
print(output, end='' if output.endswith('\n') else '\n')
|
||||
|
||||
if py_unexpected_successes:
|
||||
print(sep1)
|
||||
print('Unexpected successes:')
|
||||
for tid in py_unexpected_successes:
|
||||
print(f' {tid}')
|
||||
|
||||
print(sep2)
|
||||
total_ran = py_run + go_run
|
||||
count_word = 'test' if total_ran == 1 else 'tests'
|
||||
print(f'Ran {total_ran} {count_word} in {elapsed:.3f}s')
|
||||
|
||||
all_timings.sort(reverse=True)
|
||||
slowest = all_timings[:5]
|
||||
if slowest:
|
||||
print()
|
||||
print(c(_DIM, 'Slowest tests:'))
|
||||
for t_elapsed, t_name in slowest:
|
||||
print(f' {c(_DIM, f"{t_elapsed:.3f}s")} {t_name}')
|
||||
|
||||
print()
|
||||
|
||||
python_ok = not (py_failures or py_errors or py_unexpected_successes or py_worker_errors)
|
||||
go_ok = go_proc is None or (go_proc.returncode == 0 and not go_failures)
|
||||
|
||||
if not python_ok or not go_ok:
|
||||
fail_parts: list[str] = []
|
||||
if py_failures:
|
||||
fail_parts.append(f'failures={len(py_failures)}')
|
||||
if py_errors:
|
||||
fail_parts.append(f'errors={len(py_errors)}')
|
||||
if py_unexpected_successes:
|
||||
fail_parts.append(f'unexpected successes={len(py_unexpected_successes)}')
|
||||
if py_worker_errors:
|
||||
fail_parts.append(f'worker errors={len(py_worker_errors)}')
|
||||
if go_failures:
|
||||
fail_parts.append(f'go failures={len(go_failures)}')
|
||||
elif go_proc is not None and go_proc.returncode != 0:
|
||||
fail_parts.append('go failed')
|
||||
result = f'FAILED ({", ".join(fail_parts)})'
|
||||
print(c(_RED + _BOLD, result))
|
||||
return False, go_ok
|
||||
|
||||
ok_msg = 'OK'
|
||||
if py_skipped:
|
||||
ok_msg += f' (skipped={py_skipped})'
|
||||
print(c(_GREEN + _BOLD, ok_msg))
|
||||
return True, True
|
||||
|
||||
|
||||
def terminate_workers(pids: list[int], procs: list['subprocess.Popen[bytes]'], go_proc: Optional[GoProc]) -> None:
|
||||
"""Kill any still running workers.
|
||||
|
||||
Workers run in their own sessions, so they do not get the SIGINT/SIGQUIT
|
||||
the terminal sends to the foreground job when the user interrupts the test
|
||||
run. Without this they would be left behind as orphans.
|
||||
"""
|
||||
import signal
|
||||
|
||||
for pid in pids:
|
||||
# waitpid() fails with ChildProcessError if pid was already reaped, which
|
||||
# also guarantees we never signal an unrelated process that reused it
|
||||
with suppress(ChildProcessError, OSError):
|
||||
if os.waitpid(pid, os.WNOHANG)[0] == 0:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
os.waitpid(pid, 0)
|
||||
# Popen.kill() is a no-op once the process has been reaped
|
||||
for proc in procs:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
if go_proc is not None:
|
||||
go_proc.proc.kill()
|
||||
go_proc.proc.wait()
|
||||
|
||||
|
||||
def run_tests(report_env: bool = False) -> None:
|
||||
report_env = report_env or is_ci
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
'name',
|
||||
nargs='*',
|
||||
default=[],
|
||||
help='The name of the test to run, for e.g. linebuf corresponds to test_linebuf. Can be specified multiple times.'
|
||||
' For go tests Something corresponds to TestSometing.',
|
||||
)
|
||||
parser.add_argument('--verbosity', default=4, type=int, help='Test verbosity')
|
||||
parser.add_argument(
|
||||
'--module',
|
||||
default='',
|
||||
help='Name of a test module to restrict to. For example: ssh. For Go tests this is the name of a package, for example: tools/cli',
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.name and args.name[0] in ('type-check', 'type_check', 'mypy'):
|
||||
type_check()
|
||||
|
||||
# Collect and filter all python tests upfront before any forking
|
||||
all_tests = find_all_tests()
|
||||
if args.module:
|
||||
all_tests = filter_tests_by_module(all_tests, args.module)
|
||||
if args.name:
|
||||
all_tests = filter_tests_by_name(all_tests, *args.name)
|
||||
tests_list = list(itertests(all_tests))
|
||||
|
||||
go_pkgs = reduce_go_pkgs(args.module, args.name)
|
||||
has_go = bool(go_pkgs)
|
||||
os.environ['ASAN_OPTIONS'] = 'detect_leaks=0'
|
||||
|
||||
# Validate filters before doing any work
|
||||
if args.module and not tests_list and not has_go:
|
||||
raise SystemExit('No test module named %s found' % args.module)
|
||||
if args.name and not tests_list and not has_go:
|
||||
raise SystemExit('No test named %s found' % ' '.join(args.name))
|
||||
|
||||
if report_env:
|
||||
report_test_env()
|
||||
|
||||
# Start Python workers; each worker calls env_for_python_tests independently
|
||||
# for full HOME/XDG isolation, as does the serial path below.
|
||||
# On macOS fork()+threading is unsafe, so use subprocess workers there.
|
||||
use_parallel = len(tests_list) > PARALLEL_THRESHOLD
|
||||
worker_pids: list[int] = []
|
||||
worker_procs: list[subprocess.Popen[bytes]] = []
|
||||
read_fds: list[int] = []
|
||||
if use_parallel:
|
||||
if sys.platform == 'darwin':
|
||||
worker_procs, read_fds = spawn_test_workers(tests_list)
|
||||
else:
|
||||
# Pre-initialize fonts once before forking so all worker processes inherit
|
||||
# the warm C-level fontconfig state and their own all_fonts_map() calls are fast.
|
||||
from kitty.fonts.common import all_fonts_map
|
||||
|
||||
all_fonts_map(True)
|
||||
worker_pids, read_fds = fork_test_workers(tests_list)
|
||||
|
||||
# Launch Go immediately so it runs in parallel with Python env setup and tests.
|
||||
if has_go:
|
||||
if report_env:
|
||||
print('Go executable:', go_exe())
|
||||
print('Go packages being tested:', ' '.join(go_pkgs))
|
||||
go_proc: Optional[GoProc] = run_go(go_pkgs, args.name)
|
||||
else:
|
||||
go_proc = None
|
||||
sys.stdout.flush()
|
||||
try:
|
||||
# Module filter with no python tests but go tests present: run go only
|
||||
if args.module and not tests_list:
|
||||
_, go_ok = collect_worker_results([], [], [], 0, go_proc=go_proc)
|
||||
raise SystemExit(0 if go_ok else 1)
|
||||
|
||||
if use_parallel:
|
||||
python_ok, go_ok = collect_worker_results(worker_pids, worker_procs, read_fds, len(tests_list), go_proc=go_proc)
|
||||
elif tests_list:
|
||||
# we need fonts installed in the user home directory as well, so initialize
|
||||
# fontconfig before nuking $HOME and friends
|
||||
from kitty.fonts.common import all_fonts_map
|
||||
|
||||
all_fonts_map(True)
|
||||
# run_test_worker() runs the tests with env_for_python_tests() as
|
||||
# they must never run against the real $HOME, some of them delete
|
||||
# files/directories in it.
|
||||
python_ok = run_serial_tests(tests_list, args.verbosity)
|
||||
if go_proc is not None:
|
||||
_, go_ok = collect_worker_results([], [], [], 0, go_proc=go_proc)
|
||||
else:
|
||||
go_ok = True
|
||||
else:
|
||||
python_ok = True
|
||||
if go_proc is not None:
|
||||
_, go_ok = collect_worker_results([], [], [], 0, go_proc=go_proc)
|
||||
else:
|
||||
go_ok = True
|
||||
except BaseException:
|
||||
terminate_workers(worker_pids, worker_procs, go_proc)
|
||||
raise
|
||||
|
||||
exit_code = 0 if (python_ok and go_ok) else 1
|
||||
|
||||
if exit_code != 0:
|
||||
print('\x1b[31mError\x1b[39m: Some tests failed!')
|
||||
raise SystemExit(exit_code)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import warnings
|
||||
|
||||
warnings.simplefilter('error')
|
||||
run_tests()
|
||||
@@ -0,0 +1,836 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from functools import partial
|
||||
from time import sleep
|
||||
|
||||
from kitty.config import load_config
|
||||
from kitty.fast_data_types import (
|
||||
GLFW_MOD_ALT,
|
||||
GLFW_MOD_CAPS_LOCK,
|
||||
GLFW_MOD_CONTROL,
|
||||
GLFW_MOD_SHIFT,
|
||||
GLFW_MOD_SUPER,
|
||||
GLFW_MOUSE_BUTTON_LEFT,
|
||||
GLFW_MOUSE_BUTTON_RIGHT,
|
||||
MOUSE_SELECTION_WORD_AND_LINE_FROM_POINT,
|
||||
create_mock_window,
|
||||
mock_mouse_selection,
|
||||
send_mock_mouse_event_to_window,
|
||||
send_mock_scroll_event_to_window,
|
||||
set_options,
|
||||
update_mock_pointer,
|
||||
)
|
||||
|
||||
from .base import BaseTest, parse_bytes
|
||||
|
||||
|
||||
def send_mouse_event(
|
||||
window,
|
||||
button=-1,
|
||||
modifiers=0,
|
||||
is_release=False,
|
||||
x=0.0,
|
||||
y=0,
|
||||
clear_click_queue=False,
|
||||
pixel_x=None,
|
||||
pixel_y=None,
|
||||
):
|
||||
ix = int(x)
|
||||
in_left_half_of_cell = x - ix < 0.5
|
||||
return send_mock_mouse_event_to_window(window, button, modifiers, is_release, ix, y, clear_click_queue, in_left_half_of_cell, pixel_x, pixel_y)
|
||||
|
||||
|
||||
class TestMouse(BaseTest):
|
||||
def test_link_hover_modifiers(self):
|
||||
s = self.create_screen(cols=60)
|
||||
s.draw('https://example.invalid/')
|
||||
parse_bytes(s, b'\r\n\x1b]8;;https://example.invalid/\x1b\\hyperlink\x1b]8;;\x1b\\\r\nsrc/file.py:42')
|
||||
w = create_mock_window(s)
|
||||
hover = partial(send_mouse_event, w, x=2)
|
||||
normal_shape = send_mouse_event(w, x=50)
|
||||
link_shape = hover()
|
||||
self.assertNotEqual(normal_shape, link_shape)
|
||||
|
||||
def configure(*lines):
|
||||
set_options(load_config(overrides=('clear_all_mouse_actions yes', 'detect_url_regex [[:alnum:]_./-]+:[0-9]+', *lines)))
|
||||
|
||||
def check(mods, clickable, y=0):
|
||||
self.ae(hover(modifiers=mods, y=y), link_shape if clickable else normal_shape)
|
||||
expected = ('https://example.invalid/', 'hyperlink', 'src/file.py:42')[y] if clickable else ''
|
||||
self.ae(''.join(s.text_for_marked_url()), expected)
|
||||
# The renderer uses bit 1 of the selection buffer for URL underlines.
|
||||
self.ae(sum(bool(cell & 2) for cell in s.current_selections()), len(expected))
|
||||
|
||||
mods = GLFW_MOD_CONTROL | GLFW_MOD_SHIFT
|
||||
configure('mouse_map ctrl+shift+left release grabbed,ungrabbed mouse_handle_click link')
|
||||
for y in (0, 1, 2):
|
||||
for held, clickable in (
|
||||
(0, False),
|
||||
(GLFW_MOD_CONTROL, False),
|
||||
(mods, True),
|
||||
(mods | GLFW_MOD_ALT, False),
|
||||
(mods | GLFW_MOD_CAPS_LOCK, True),
|
||||
(0, False),
|
||||
):
|
||||
# Repeated events in the same cell must respond to modifier changes.
|
||||
check(held, clickable, y)
|
||||
|
||||
configure('mouse_map left click ungrabbed mouse_handle_click selection link prompt')
|
||||
check(0, True)
|
||||
check(mods, False)
|
||||
parse_bytes(s, b'\x1b[?1000h')
|
||||
normal_shape = send_mouse_event(w, x=50)
|
||||
check(0, False)
|
||||
configure('mouse_map alt+left release grabbed mouse_click_url')
|
||||
check(GLFW_MOD_ALT, True)
|
||||
check(0, False)
|
||||
parse_bytes(s, b'\x1b[?1000l')
|
||||
normal_shape = send_mouse_event(w, x=50)
|
||||
check(GLFW_MOD_ALT, False)
|
||||
|
||||
configure('action_alias follow_link mouse_handle_click link', 'mouse_map alt+left release ungrabbed follow_link')
|
||||
check(GLFW_MOD_ALT, True)
|
||||
check(0, False)
|
||||
configure('mouse_map left click ungrabbed combine : mouse_handle_click link : discard_event')
|
||||
check(0, True)
|
||||
configure('mouse_map left click ungrabbed mouse_click_url_or_select')
|
||||
check(0, True)
|
||||
configure('mouse_map left click ungrabbed mouse_click_url', 'mouse_map left click ungrabbed')
|
||||
check(0, False)
|
||||
|
||||
for event in ('press', 'release', 'click'):
|
||||
configure(f'mouse_map cmd+left {event} ungrabbed mouse_handle_click link')
|
||||
check(GLFW_MOD_SUPER, True)
|
||||
check(0, False)
|
||||
for event in ('doublepress', 'triplepress', 'doubleclick'):
|
||||
configure(f'mouse_map left {event} ungrabbed mouse_click_url')
|
||||
check(0, False)
|
||||
|
||||
def test_link_hover_key_events(self):
|
||||
s = self.create_screen(cols=60)
|
||||
s.draw('https://example.invalid/')
|
||||
w = create_mock_window(s)
|
||||
link_shape = send_mouse_event(w, x=2)
|
||||
mods = GLFW_MOD_CONTROL | GLFW_MOD_SHIFT
|
||||
set_options(
|
||||
load_config(
|
||||
overrides=(
|
||||
'clear_all_mouse_actions yes',
|
||||
'mouse_map ctrl+shift+left release grabbed,ungrabbed mouse_handle_click link',
|
||||
'mouse_map cmd+left release grabbed,ungrabbed mouse_handle_click link',
|
||||
)
|
||||
)
|
||||
)
|
||||
for tracking in (False, True):
|
||||
parse_bytes(s, b'\x1b[?1000h' if tracking else b'\x1b[?1000l')
|
||||
normal_shape = send_mouse_event(w, x=50)
|
||||
send_mouse_event(w, x=2)
|
||||
for held in (mods, GLFW_MOD_SUPER):
|
||||
for old, new, highlighted in ((0, held, True), (held, 0, False)):
|
||||
self.ae(update_mock_pointer(w, old, new), (link_shape if highlighted else normal_shape, True))
|
||||
self.ae(bool(''.join(s.text_for_marked_url())), highlighted)
|
||||
self.ae(update_mock_pointer(w, 0, held, False)[1], False)
|
||||
self.ae(''.join(s.text_for_marked_url()), '')
|
||||
for old, new in ((0, GLFW_MOD_SHIFT), (mods, GLFW_MOD_SUPER), (mods, mods | GLFW_MOD_CAPS_LOCK)):
|
||||
self.ae(update_mock_pointer(w, old, new)[1], False)
|
||||
for drag in (1, 2):
|
||||
self.ae(update_mock_pointer(w, 0, mods, True, drag)[1], False)
|
||||
|
||||
def test_link_hover_preserves_border_cursor(self):
|
||||
s = self.create_screen(cols=60)
|
||||
s.draw('https://example.invalid/')
|
||||
w = create_mock_window(s)
|
||||
send_mouse_event(w, x=2)
|
||||
mods = GLFW_MOD_CONTROL | GLFW_MOD_SHIFT
|
||||
for border in (1, 2):
|
||||
shape, updated = update_mock_pointer(w, 0, 0, True, 0, border)
|
||||
self.ae(updated, False)
|
||||
self.ae(update_mock_pointer(w, 0, mods, True, 0, border), (shape, False))
|
||||
|
||||
def test_link_hover_cleared_by_output(self):
|
||||
s = self.create_screen(cols=60)
|
||||
w = create_mock_window(s)
|
||||
mods = GLFW_MOD_CONTROL | GLFW_MOD_SHIFT
|
||||
set_options(load_config(overrides=('clear_all_mouse_actions yes', 'mouse_map ctrl+shift+left release ungrabbed mouse_handle_click link')))
|
||||
|
||||
def marked():
|
||||
return ''.join(s.text_for_marked_url())
|
||||
|
||||
def setup():
|
||||
s.reset()
|
||||
s.draw('https://example.invalid/')
|
||||
return send_mouse_event(w, x=2, modifiers=mods)
|
||||
|
||||
parse_bytes(s, b'\x1b[?1000h')
|
||||
grabbed_shape = send_mouse_event(w, x=50)
|
||||
s.reset()
|
||||
normal_shape = send_mouse_event(w, x=50)
|
||||
for output, expected in (
|
||||
(b' suffix', normal_shape),
|
||||
(b'\r\x1b[Kplain text', normal_shape),
|
||||
(b'\x1b[2J', normal_shape),
|
||||
(b'\x1b[?1000h\r\x1b[K', grabbed_shape),
|
||||
(b'\x1b[?1000h', None),
|
||||
(b'\x1b[3;1Hother line', None),
|
||||
):
|
||||
with self.subTest(output=output):
|
||||
link_shape = setup()
|
||||
self.assertNotIn(link_shape, (normal_shape, grabbed_shape))
|
||||
self.ae(marked(), 'https://example.invalid/')
|
||||
# Output alone, with the modifiers still held, must update the pointer
|
||||
shape = update_mock_pointer(w, mods, mods, True, 0, 0, None, False, partial(parse_bytes, s, output))[0]
|
||||
self.ae(shape, expected or link_shape)
|
||||
self.ae(bool(marked()), expected is None)
|
||||
if expected is not None:
|
||||
# Releasing the modifiers after the output changes nothing
|
||||
setup()
|
||||
self.ae(update_mock_pointer(w, mods, 0, True, 0, 0, None, False, partial(parse_bytes, s, output)), (expected, False))
|
||||
self.ae(marked(), '')
|
||||
|
||||
def test_link_hover_stays_consistent(self):
|
||||
s = self.create_screen(cols=30)
|
||||
s.draw('x' * 6 + 'https://example.invalid/')
|
||||
w = create_mock_window(s)
|
||||
normal_shape = send_mouse_event(w, x=2)
|
||||
link_shape = send_mouse_event(w, x=29)
|
||||
mods = GLFW_MOD_CONTROL | GLFW_MOD_SHIFT
|
||||
|
||||
def configure(*lines):
|
||||
set_options(load_config(overrides=('clear_all_mouse_actions yes', *lines)))
|
||||
|
||||
def marked():
|
||||
return ''.join(s.text_for_marked_url())
|
||||
|
||||
# The cell under the mouse is stale once it moves into the padding
|
||||
configure('mouse_map ctrl+shift+left release ungrabbed mouse_handle_click link')
|
||||
send_mouse_event(w, x=29)
|
||||
self.ae(update_mock_pointer(w, 0, mods, True, 0, 0, None, True), (normal_shape, False))
|
||||
self.ae(marked(), '')
|
||||
send_mouse_event(w, x=29)
|
||||
self.ae(update_mock_pointer(w, mods, 0, True, 0, 0, None, True), (normal_shape, True))
|
||||
self.ae(marked(), '')
|
||||
|
||||
# The mouse tracking mode can change without the mouse moving
|
||||
configure('mouse_map left click ungrabbed mouse_click_url')
|
||||
send_mouse_event(w, x=10)
|
||||
self.ae(update_mock_pointer(w, 0, GLFW_MOD_ALT, True, 0, 0, None, False, partial(parse_bytes, s, b'\x1b[?1000h'))[1], True)
|
||||
self.ae(marked(), '')
|
||||
parse_bytes(s, b'\x1b[?1000l')
|
||||
|
||||
# Pointer shape changes from the program keep the hand over a highlighted link
|
||||
send_mouse_event(w, x=10)
|
||||
self.ae(update_mock_pointer(w, 0, 0, True, 0, 0, 'wait')[0], link_shape)
|
||||
self.ae(marked(), 'https://example.invalid/')
|
||||
|
||||
def test_pointer_shape_during_mouse_drag(self):
|
||||
s = self.create_screen(cols=60)
|
||||
parse_bytes(s, b'\x1b[?1000h')
|
||||
w = create_mock_window(s)
|
||||
for drag in (1, 2):
|
||||
for name in ('grabbing', 'ew-resize'):
|
||||
s.change_pointer_shape('=', name)
|
||||
expected = send_mouse_event(w, x=2)
|
||||
s.change_pointer_shape('=', 'text')
|
||||
self.ae(update_mock_pointer(w, 0, 0, True, drag, 0, name)[0], expected)
|
||||
|
||||
def test_mouse_selection(self):
|
||||
s = self.create_screen(options=dict(rectangle_select_modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL))
|
||||
w = create_mock_window(s)
|
||||
ev = partial(send_mouse_event, w)
|
||||
|
||||
def mouse_selection(code: int) -> None:
|
||||
mock_mouse_selection(w, s.callbacks.current_mouse_button, code)
|
||||
|
||||
s.callbacks.mouse_selection = mouse_selection
|
||||
|
||||
def sel():
|
||||
return ''.join(s.text_for_selection())
|
||||
|
||||
def init():
|
||||
s.reset()
|
||||
s.draw('pqrst')
|
||||
s.draw('uvwxy')
|
||||
s.draw('ABCDE')
|
||||
s.draw('FGHIJ')
|
||||
s.draw('KLMNO')
|
||||
s.draw('12345')
|
||||
s.draw('67890')
|
||||
s.draw('abcde')
|
||||
s.draw('fghij')
|
||||
s.draw('klmno')
|
||||
|
||||
def press(x=0, y=0, modifiers=0, button=GLFW_MOUSE_BUTTON_LEFT):
|
||||
ev(button, x=x, y=y, modifiers=modifiers)
|
||||
|
||||
def release(x=0, y=0, button=GLFW_MOUSE_BUTTON_LEFT):
|
||||
ev(button, x=x, y=y, is_release=True, clear_click_queue=True)
|
||||
|
||||
def move(x=0, y=0, button=-1, q=None):
|
||||
ev(x=x, y=y, button=button)
|
||||
if q is not None:
|
||||
sl = sel()
|
||||
from kitty.window import as_text
|
||||
|
||||
self.ae(sl, q, f'{sl!r} != {q!r} after movement to x={x} y={y}. Screen contents: {as_text(s)!r}')
|
||||
|
||||
def multi_click(x=0, y=0, count=2, modifiers=0):
|
||||
clear_click_queue = True
|
||||
while count > 0:
|
||||
count -= 1
|
||||
ev(GLFW_MOUSE_BUTTON_LEFT, x=x, y=y, modifiers=modifiers, clear_click_queue=clear_click_queue)
|
||||
clear_click_queue = False
|
||||
|
||||
def scroll(x=0, y=0, up=True):
|
||||
move(x=x, y=y, button=-2 if up else -3)
|
||||
|
||||
# Single line click, move, release test
|
||||
init()
|
||||
press()
|
||||
move(x=3.6, q='1234')
|
||||
release(x=3.6)
|
||||
self.ae(sel(), '1234')
|
||||
press(x=4), release(x=0.6)
|
||||
self.ae(sel(), '234')
|
||||
|
||||
# multi line movement
|
||||
init()
|
||||
press(x=2, y=2)
|
||||
move(x=2, y=1, q='890ab')
|
||||
move(x=2.6, y=1, q='90ab')
|
||||
move(y=1, q='67890ab')
|
||||
move(x=4, y=1, q='0ab')
|
||||
move(x=4.6, y=1, q='ab')
|
||||
move(q='1234567890ab')
|
||||
move(x=2, y=3, q='cdefg')
|
||||
move(y=3, q='cde')
|
||||
move(x=0.6, y=3, q='cdef')
|
||||
move(x=2.6, y=3, q='cdefgh')
|
||||
move(x=4.6, y=3, q='cdefghij')
|
||||
|
||||
# Single cell select
|
||||
init()
|
||||
press(), release(1)
|
||||
self.ae(sel(), '1')
|
||||
press(3), release(2)
|
||||
self.ae(sel(), '3')
|
||||
|
||||
# Multi-line click release
|
||||
init()
|
||||
press(1, 1), release(3.6, 2)
|
||||
self.ae(sel(), '7890abcd')
|
||||
press(1.6, 1), release(3, 2)
|
||||
self.ae(sel(), '890abc')
|
||||
press(3.6, 4), release(2, 2)
|
||||
self.ae(sel(), 'cdefghijklmn')
|
||||
press(3, 4), release(2.6, 2)
|
||||
self.ae(sel(), 'defghijklm')
|
||||
|
||||
# Word select with drag
|
||||
s.reset()
|
||||
s.draw('ab cd')
|
||||
s.draw(' f gh')
|
||||
s.draw(' stuv')
|
||||
s.draw('X Y')
|
||||
multi_click(x=1.4)
|
||||
self.ae(sel(), 'ab')
|
||||
move(2.6)
|
||||
self.ae(sel(), 'ab ')
|
||||
move(3.6)
|
||||
self.ae(sel(), 'ab cd')
|
||||
move(2.6)
|
||||
self.ae(sel(), 'ab ')
|
||||
release(3.6, 1)
|
||||
self.ae(sel(), 'ab cd f gh')
|
||||
multi_click(x=1, y=2)
|
||||
self.ae(sel(), 'stuvX')
|
||||
release()
|
||||
multi_click(x=3.6)
|
||||
self.ae(sel(), 'cd')
|
||||
move(0.2)
|
||||
release()
|
||||
self.ae(sel(), 'ab cd')
|
||||
multi_click(x=4.4)
|
||||
self.ae(sel(), 'cd')
|
||||
move(x=4.4, y=1)
|
||||
self.ae(sel(), 'cd f gh')
|
||||
move(x=4.4, y=0)
|
||||
self.ae(sel(), 'cd')
|
||||
release()
|
||||
multi_click(x=4.4, y=1)
|
||||
self.ae(sel(), 'gh')
|
||||
move(x=4.4, y=0)
|
||||
self.ae(sel(), 'cd f gh')
|
||||
move(x=4.4, y=1)
|
||||
self.ae(sel(), 'gh')
|
||||
release()
|
||||
multi_click(x=4.4)
|
||||
self.ae(sel(), 'cd')
|
||||
move()
|
||||
self.ae(sel(), 'ab cd')
|
||||
move(x=1, y=1)
|
||||
self.ae(sel(), 'ab cd f')
|
||||
move()
|
||||
self.ae(sel(), 'ab cd')
|
||||
release()
|
||||
multi_click(x=1.4)
|
||||
self.ae(sel(), 'ab')
|
||||
move(x=4.4)
|
||||
self.ae(sel(), 'ab cd')
|
||||
move(x=4.4, y=1)
|
||||
self.ae(sel(), 'ab cd f gh')
|
||||
move(x=4.4)
|
||||
self.ae(sel(), 'ab cd')
|
||||
|
||||
# Line select with drag
|
||||
s.reset()
|
||||
s.draw('1 2 3')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw('4 5 6')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw('7 8 9X')
|
||||
multi_click(x=1, count=3)
|
||||
self.ae(sel(), str(s.line(0)))
|
||||
move(y=1)
|
||||
self.ae(sel(), '1 2 3\n4 5 6')
|
||||
move(y=2)
|
||||
self.ae(sel(), '1 2 3\n4 5 6\n7 8 9X')
|
||||
move(y=1)
|
||||
self.ae(sel(), '1 2 3\n4 5 6')
|
||||
move()
|
||||
self.ae(sel(), str(s.line(0)))
|
||||
release()
|
||||
multi_click(y=1, count=3)
|
||||
self.ae(sel(), '4 5 6')
|
||||
move(y=0)
|
||||
self.ae(sel(), '1 2 3\n4 5 6')
|
||||
move(y=1)
|
||||
self.ae(sel(), '4 5 6')
|
||||
move(y=2)
|
||||
self.ae(sel(), '4 5 6\n7 8 9X')
|
||||
release()
|
||||
s.reset()
|
||||
s.draw(' 123')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw(' 456')
|
||||
s.linefeed(), s.carriage_return()
|
||||
multi_click(x=1, count=3)
|
||||
self.ae(sel(), '123')
|
||||
move(x=2, y=1)
|
||||
self.ae(sel(), '123\n 456')
|
||||
release()
|
||||
press(x=2, y=1, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
release(x=2, y=1, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
self.ae(sel(), '123\n 456')
|
||||
press(button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
self.ae(sel(), ' 123\n 456')
|
||||
release(button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
|
||||
# line select for wrapped lines in scrollback
|
||||
s.reset()
|
||||
s.draw('ABCDE12345')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw(('X' * s.columns) * (s.lines - 1))
|
||||
multi_click(x=1, count=3)
|
||||
self.ae(sel(), 'ABCDE12345')
|
||||
s.reset()
|
||||
s.draw('ABCDE12345')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw('678')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw(('X' * s.columns) * (s.lines - 2))
|
||||
multi_click(x=1, y=1, count=3)
|
||||
self.ae(sel(), '678')
|
||||
press(x=2, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
release(x=2, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
self.ae(sel(), 'ABCDE12345\n678')
|
||||
|
||||
# line select for wrapped lines below viewport
|
||||
s.reset()
|
||||
s.scroll(100, False)
|
||||
# draw enough content to enable scrolling: fill lines-1 visual lines, then draw a long wrapped line
|
||||
s.draw(('X' * s.columns) * (s.lines - 1))
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw('ABCDE12345') # wraps to 2 visual lines, second one pushed below viewport
|
||||
# scroll up by 1 so top visual line of the wrapped text is visible but bottom wraps off-screen
|
||||
s.scroll(1, True)
|
||||
multi_click(x=1, y=s.lines - 1, count=3)
|
||||
self.ae(sel(), 'ABCDE12345')
|
||||
# extending selection to a line that wraps below viewport
|
||||
s.reset()
|
||||
s.scroll(100, False)
|
||||
s.draw(('X' * s.columns) * (s.lines - 2))
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw('678')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw('ABCDE12345')
|
||||
s.scroll(1, True)
|
||||
multi_click(x=1, y=3, count=3)
|
||||
self.ae(sel(), '678')
|
||||
press(x=2, y=s.lines - 1, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
release(x=2, y=s.lines - 1, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
self.ae(sel(), '678\nABCDE12345')
|
||||
s.scroll(100, False)
|
||||
|
||||
# word select for wrapped words in scrollback
|
||||
s.reset()
|
||||
s.draw('abcde12345')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw(('X' * s.columns) * (s.lines - 1))
|
||||
multi_click(x=1)
|
||||
self.ae(sel(), 'abcde12345')
|
||||
|
||||
# word select for wrapped words below viewport
|
||||
s.reset()
|
||||
s.scroll(100, False)
|
||||
s.draw(('X' * s.columns) * (s.lines - 1))
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw('abcde12345')
|
||||
s.scroll(1, True)
|
||||
multi_click(x=1, y=s.lines - 1)
|
||||
self.ae(sel(), 'abcde12345')
|
||||
s.scroll(100, False)
|
||||
|
||||
# Rectangle select
|
||||
init()
|
||||
press(x=1, y=1, modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL)
|
||||
move(x=3.6, y=3)
|
||||
self.ae(sel(), '789bcdghi')
|
||||
release(x=3, y=3)
|
||||
self.ae(sel(), '78bcgh')
|
||||
press(x=3.6, y=1, modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL)
|
||||
self.ae(sel(), '')
|
||||
move(x=1, y=3)
|
||||
self.ae(sel(), '789bcdghi')
|
||||
release(x=1.6)
|
||||
self.ae(sel(), '3489')
|
||||
|
||||
# scrolling
|
||||
init()
|
||||
press(x=1.6)
|
||||
scroll(x=1)
|
||||
self.ae(sel(), 'LMNO12')
|
||||
scroll(x=1)
|
||||
self.ae(sel(), 'GHIJKLMNO12')
|
||||
scroll(x=1, up=False)
|
||||
self.ae(sel(), 'LMNO12')
|
||||
scroll(x=2.6, up=False)
|
||||
self.ae(sel(), '3')
|
||||
release()
|
||||
# fractional scrolling
|
||||
init()
|
||||
s.fractional_scroll(-0.5)
|
||||
press()
|
||||
move(x=3.6, q='1234')
|
||||
release(x=3.6)
|
||||
self.ae(sel(), '1234')
|
||||
|
||||
# extending selections
|
||||
init()
|
||||
press()
|
||||
move(x=3.6, q='1234')
|
||||
release(x=3.6)
|
||||
self.ae(sel(), '1234')
|
||||
press(x=1, y=1, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
self.ae(sel(), '123456')
|
||||
move(x=2, y=1, q='1234567')
|
||||
release(x=3, y=1, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
self.ae(sel(), '12345678')
|
||||
init()
|
||||
press(y=2)
|
||||
move(x=3.6, y=2, q='abcd')
|
||||
press(x=3, y=0, button=GLFW_MOUSE_BUTTON_RIGHT)
|
||||
self.ae(sel(), '4567890abcd')
|
||||
|
||||
# blank line select
|
||||
s.reset()
|
||||
s.draw('abcde')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw('12345')
|
||||
press(x=0, y=0)
|
||||
move(x=2, y=2, q='abcde\n\n12')
|
||||
|
||||
# Line from begin select (alt+triple click): selects from column 0
|
||||
# (including any leading whitespace), unlike normal triple click which strips it
|
||||
s.reset()
|
||||
s.draw(' 123')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw(' 456')
|
||||
s.linefeed(), s.carriage_return()
|
||||
multi_click(x=1, count=3, modifiers=GLFW_MOD_ALT)
|
||||
self.ae(sel(), ' 123')
|
||||
multi_click(x=1, count=3)
|
||||
self.ae(sel(), '123')
|
||||
multi_click(x=1, count=3, modifiers=GLFW_MOD_ALT)
|
||||
move(y=1)
|
||||
self.ae(sel(), ' 123\n 456')
|
||||
release()
|
||||
|
||||
# Line from point select (ctrl+alt+triple click): selects from click
|
||||
# position to end of line; cannot start before the first non-blank char
|
||||
s.reset()
|
||||
s.draw(' 123')
|
||||
s.linefeed(), s.carriage_return()
|
||||
s.draw(' 456')
|
||||
s.linefeed(), s.carriage_return()
|
||||
multi_click(x=2, count=3, modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL)
|
||||
self.ae(sel(), '23')
|
||||
# click before first non-blank: selection starts at first non-blank
|
||||
multi_click(x=0, count=3, modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL)
|
||||
self.ae(sel(), '123')
|
||||
# click past last non-blank char: no selection created
|
||||
multi_click(x=4, count=3, modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL)
|
||||
self.ae(sel(), '')
|
||||
# drag to next line
|
||||
multi_click(x=2, count=3, modifiers=GLFW_MOD_ALT | GLFW_MOD_CONTROL)
|
||||
move(y=1)
|
||||
self.ae(sel(), '23\n 456')
|
||||
release()
|
||||
|
||||
# Word and line from point: selects the word at the click point and
|
||||
# extends the selection to the end of the line
|
||||
sel_word_and_line = MOUSE_SELECTION_WORD_AND_LINE_FROM_POINT
|
||||
s.reset()
|
||||
s.draw('ab cd')
|
||||
press(x=0)
|
||||
mock_mouse_selection(w, GLFW_MOUSE_BUTTON_LEFT, sel_word_and_line)
|
||||
self.ae(sel(), 'ab cd')
|
||||
press(x=3)
|
||||
mock_mouse_selection(w, GLFW_MOUSE_BUTTON_LEFT, sel_word_and_line)
|
||||
self.ae(sel(), 'cd')
|
||||
# click on space: no word, selects from space to end of line
|
||||
press(x=2)
|
||||
mock_mouse_selection(w, GLFW_MOUSE_BUTTON_LEFT, sel_word_and_line)
|
||||
self.ae(sel(), ' cd')
|
||||
# click past last non-blank char: no selection created
|
||||
press(x=4)
|
||||
mock_mouse_selection(w, GLFW_MOUSE_BUTTON_LEFT, sel_word_and_line)
|
||||
self.ae(sel(), '')
|
||||
|
||||
# Double-click on whitespace: no word found, no selection created
|
||||
s.reset()
|
||||
s.draw('ab cd')
|
||||
multi_click(x=2)
|
||||
self.ae(sel(), '')
|
||||
multi_click(x=2.4)
|
||||
self.ae(sel(), '')
|
||||
|
||||
def test_v120_scroll_direction_reversal(self):
|
||||
# A high resolution wheel delivers one physical detent as several
|
||||
# VALUE120 events, and the fractional remainder is carried between them.
|
||||
# Detents do not reliably total 120 units, so that carry is what lets an
|
||||
# undersized detent still scroll a line. But when the direction changes
|
||||
# the residual has the wrong sign, and the first detent of the new
|
||||
# direction gets spent cancelling it instead of scrolling.
|
||||
# The fragment sequences below were captured from a Logitech MX Master 3.
|
||||
from kitty.fast_data_types import test_scale_scroll
|
||||
|
||||
self.set_options() # scale_scroll reads wheel_scroll_multiplier
|
||||
cell = 40
|
||||
|
||||
def run(*v120):
|
||||
# scale_scroll is exercised in mouse tracking mode, which reduces
|
||||
# wheel_scroll_multiplier to its sign, so the result does not depend
|
||||
# on the configured multiplier.
|
||||
return test_scale_scroll([float(v) for v in v120], cell)
|
||||
|
||||
down = (-48, -32, -24, -24) # 128 units
|
||||
up = (48, 32, 24, 24)
|
||||
|
||||
# Five detents down, then one up. Every detent must scroll, including
|
||||
# the one that reverses direction. Before the residual was discarded on
|
||||
# a reversal, that last detent scrolled nothing.
|
||||
res = run(*(down * 5), *up)
|
||||
self.ae(-5, sum(res[:20]), f'detents before the reversal: {res}')
|
||||
self.ae(1, sum(res[20:]), f'detent that reversed direction: {res}')
|
||||
|
||||
# Repeated reversals keep working.
|
||||
res = run(*(down * 2), *(up * 2), *(down * 2))
|
||||
self.ae([-2, 2, -2], [sum(res[i : i + 8]) for i in range(0, 24, 8)])
|
||||
|
||||
# Scrolling in one direction is unaffected: the carry is retained, so a
|
||||
# run of undersized detents still scrolls about one line each.
|
||||
self.ae(-9, sum(run(*((-48, -24, -24, -16) * 10))))
|
||||
|
||||
# A fragment too small to be a detent does not scroll.
|
||||
self.ae(0, sum(run(8)))
|
||||
|
||||
def test_mapped_scroll_steps(self):
|
||||
from kitty.fast_data_types import test_mapped_scroll_steps as steps
|
||||
|
||||
LINES, V120, HIGHRES = 0, 1, 2 # GLFWOffsetType
|
||||
self.set_options()
|
||||
# Classic wheel: one step per click, whatever wheel_scroll_multiplier is
|
||||
self.ae(steps(LINES, [1.0, 1.0, -1.0]), [1, 1, -1])
|
||||
# High resolution wheel: one step per 120 units, however they are split
|
||||
self.ae(sum(steps(V120, [15.0] * 16)), 2)
|
||||
# Touchpad: one step per 100 logical pixels, independent of the font size
|
||||
self.ae(steps(HIGHRES, [30.0] * 10), [0, 0, 0, 1, 0, 0, 1, 0, 0, 1])
|
||||
# Reversing direction starts a fresh step instead of first cancelling the remainder
|
||||
self.ae(steps(HIGHRES, [150.0, -60.0, -40.0]), [1, 0, -1])
|
||||
# touch_scroll_multiplier scales touchpad steps and its sign flips them
|
||||
self.set_options({'touch_scroll_multiplier': -2.0})
|
||||
self.ae(steps(HIGHRES, [30.0, 30.0]), [0, -1])
|
||||
# Wheels only take the sign of wheel_scroll_multiplier and every click is a step
|
||||
self.set_options({'wheel_scroll_multiplier': -3.0})
|
||||
self.ae(steps(LINES, [1.0, 0.1]), [-1, -1])
|
||||
self.ae(steps(V120, [120.0, 240.0]), [-1, -2])
|
||||
|
||||
def test_mapped_scroll(self):
|
||||
from kitty.config import load_config
|
||||
|
||||
LINES, HIGHRES = 0, 2 # GLFWOffsetType
|
||||
MOMENTUM_BEGAN, MOMENTUM_ACTIVE, MOMENTUM_ENDED = 1, 3, 4 # GLFWMomentumType
|
||||
s = self.create_screen(lines=5, scrollback=50)
|
||||
errors = []
|
||||
opts = load_config(
|
||||
overrides=(
|
||||
'pixel_scroll no',
|
||||
'wheel_scroll_multiplier 1',
|
||||
'mouse_map ctrl+wheel_up press ungrabbed change_font_size all +1',
|
||||
'mouse_map ctrl+wheel_down press ungrabbed change_font_size all -1',
|
||||
'mouse_map alt+wheel_up press ungrabbed mouse_selection normal',
|
||||
'mouse_map ctrl+wheel_left press ungrabbed previous_tab',
|
||||
'mouse_map shift+wheel_left press ungrabbed previous_tab',
|
||||
'mouse_map shift+wheel_right press ungrabbed next_tab',
|
||||
),
|
||||
accumulate_bad_lines=errors,
|
||||
)
|
||||
self.ae(errors, [])
|
||||
set_options(opts)
|
||||
w = create_mock_window(s)
|
||||
for i in range(50):
|
||||
s.draw(f'{i}')
|
||||
s.carriage_return()
|
||||
s.linefeed()
|
||||
calls = []
|
||||
s.callbacks.change_font_size = lambda *a: calls.append(a[1])
|
||||
s.callbacks.mouse_selection = lambda code: mock_mouse_selection(w, s.callbacks.current_mouse_button, code)
|
||||
s.callbacks.previous_tab = lambda: calls.append('left')
|
||||
s.callbacks.next_tab = lambda: calls.append('right')
|
||||
|
||||
def scroll(y, mods=0, offset_type=LINES, momentum=0, x=0.0):
|
||||
send_mock_scroll_event_to_window(w, offset_type, x, float(y), mods, momentum)
|
||||
|
||||
def ac(expected_calls, scrolled_by):
|
||||
self.ae(calls, expected_calls)
|
||||
self.ae(s.scrolled_by, scrolled_by)
|
||||
del calls[:]
|
||||
|
||||
# Unmapped scrolling still scrolls the screen
|
||||
scroll(2)
|
||||
ac([], 2)
|
||||
# Mapped scrolling fires the action once per step instead
|
||||
scroll(1, GLFW_MOD_CONTROL)
|
||||
ac(['+'], 2)
|
||||
scroll(3, GLFW_MOD_CONTROL)
|
||||
ac(['+'] * 3, 2)
|
||||
scroll(-1, GLFW_MOD_CONTROL)
|
||||
ac(['-'], 2)
|
||||
# Touchpad events that do not complete a step are consumed
|
||||
scroll(60, GLFW_MOD_CONTROL, HIGHRES)
|
||||
ac([], 2)
|
||||
scroll(40, GLFW_MOD_CONTROL, HIGHRES)
|
||||
ac(['+'], 2)
|
||||
# A partial step does not survive unmapped scrolling in between
|
||||
scroll(60, GLFW_MOD_CONTROL, HIGHRES)
|
||||
scroll(1)
|
||||
ac([], 3)
|
||||
scroll(40, GLFW_MOD_CONTROL, HIGHRES)
|
||||
ac([], 3)
|
||||
# Momentum after a mapped gesture neither fires the action nor scrolls
|
||||
scroll(100, GLFW_MOD_CONTROL, HIGHRES)
|
||||
scroll(200, GLFW_MOD_CONTROL, HIGHRES, MOMENTUM_BEGAN)
|
||||
scroll(200, GLFW_MOD_CONTROL, HIGHRES, MOMENTUM_ACTIVE)
|
||||
ac(['+'], 3)
|
||||
# A horizontal unmapped gesture ends the mapped gesture, so its momentum scrolls
|
||||
scroll(0, x=10, offset_type=HIGHRES)
|
||||
scroll(-40, 0, HIGHRES, MOMENTUM_BEGAN)
|
||||
ac([], 1)
|
||||
# Modifiers or modes without a mapping scroll normally
|
||||
scroll(1, GLFW_MOD_ALT | GLFW_MOD_CONTROL)
|
||||
ac([], 2)
|
||||
parse_bytes(s, b'\x1b[?1000h') # grab the mouse
|
||||
scroll(1, GLFW_MOD_CONTROL)
|
||||
ac([], 2)
|
||||
parse_bytes(s, b'\x1b[?1000l')
|
||||
# The wheel cannot start a selection, it never releases
|
||||
scroll(1, GLFW_MOD_ALT)
|
||||
self.assertFalse(s.has_selection())
|
||||
ac([], 2)
|
||||
# Horizontal scrolling, positive offsets are leftwards
|
||||
scroll(0, GLFW_MOD_SHIFT, x=1)
|
||||
ac(['left'], 2)
|
||||
scroll(0, GLFW_MOD_SHIFT, x=-2)
|
||||
ac(['right'] * 2, 2)
|
||||
scroll(0, GLFW_MOD_SHIFT, HIGHRES, x=60)
|
||||
ac([], 2)
|
||||
scroll(0, GLFW_MOD_SHIFT, HIGHRES, x=40)
|
||||
ac(['left'], 2)
|
||||
# A diagonal event fires the mappings of both axes
|
||||
scroll(1, GLFW_MOD_CONTROL, x=1)
|
||||
ac(['+', 'left'], 2)
|
||||
# Horizontal jitter, without horizontal mappings, continues a mapped
|
||||
# vertical gesture, so its momentum is still swallowed
|
||||
scroll(100, GLFW_MOD_ALT, HIGHRES)
|
||||
scroll(0, GLFW_MOD_ALT, HIGHRES, x=10)
|
||||
scroll(-200, GLFW_MOD_ALT, HIGHRES, MOMENTUM_BEGAN)
|
||||
ac([], 2)
|
||||
# But horizontal scrolling in an unmapped direction, with horizontal
|
||||
# mappings, ends the gesture, so its momentum scrolls
|
||||
scroll(100, GLFW_MOD_CONTROL, HIGHRES)
|
||||
scroll(0, GLFW_MOD_CONTROL, HIGHRES, x=-10)
|
||||
scroll(-20, GLFW_MOD_CONTROL, HIGHRES, MOMENTUM_BEGAN)
|
||||
ac(['+'], 1)
|
||||
# Spent momentum ends the gesture, so a later unmapped event in the same
|
||||
# window with the same modifiers scrolls instead of being swallowed.
|
||||
# shift is mapped horizontally only, so vertical scrolling is unmapped.
|
||||
scroll(0, GLFW_MOD_SHIFT, HIGHRES, x=100)
|
||||
scroll(0, GLFW_MOD_SHIFT, HIGHRES, MOMENTUM_BEGAN, x=-200)
|
||||
scroll(0, GLFW_MOD_SHIFT, HIGHRES, MOMENTUM_ENDED, x=-100)
|
||||
ac(['left'], 1)
|
||||
scroll(1, GLFW_MOD_SHIFT)
|
||||
ac([], 2)
|
||||
|
||||
# A classic wheel has no end-of-gesture event, so a gesture is also
|
||||
# bounded by the time between its events and by the mouse mode, which
|
||||
# changes the set of mapped wheel buttons. Without that, an unmapped
|
||||
# direction would stay swallowed indefinitely. Reload the mappings so
|
||||
# that ctrl is mapped horizontally only, as in the mouse_map docs.
|
||||
opts = load_config(
|
||||
overrides=(
|
||||
'pixel_scroll no',
|
||||
'wheel_scroll_multiplier 1',
|
||||
'mouse_map ctrl+wheel_left press ungrabbed,grabbed previous_tab',
|
||||
'mouse_map ctrl+wheel_right press ungrabbed,grabbed next_tab',
|
||||
'mouse_map alt+wheel_up press ungrabbed change_font_size all +1',
|
||||
),
|
||||
accumulate_bad_lines=errors,
|
||||
)
|
||||
self.ae(errors, [])
|
||||
set_options(opts)
|
||||
# Vertical is unmapped for ctrl now, so it scrolls
|
||||
scroll(1, GLFW_MOD_CONTROL)
|
||||
ac([], 3)
|
||||
# A mapped horizontal event starts a gesture, during which off-axis
|
||||
# jitter is still swallowed
|
||||
scroll(0, GLFW_MOD_CONTROL, x=1)
|
||||
ac(['left'], 3)
|
||||
scroll(1, GLFW_MOD_CONTROL)
|
||||
ac([], 3)
|
||||
# But once the gesture times out, vertical scrolling works again
|
||||
sleep(0.3)
|
||||
scroll(1, GLFW_MOD_CONTROL)
|
||||
ac([], 4)
|
||||
# Changing the mouse mode ends the gesture too. alt+wheel_up is mapped
|
||||
# only when ungrabbed, so once grabbed the wheel goes to the program
|
||||
# instead of being swallowed as a continuation of the mapped gesture.
|
||||
scroll(1, GLFW_MOD_ALT)
|
||||
ac(['+'], 4)
|
||||
parse_bytes(s, b'\x1b[?1000h')
|
||||
s.callbacks.wtcbuf = b''
|
||||
scroll(1, GLFW_MOD_ALT)
|
||||
ac([], 4)
|
||||
self.assertTrue(s.callbacks.wtcbuf, 'the wheel event was not reported to the program')
|
||||
parse_bytes(s, b'\x1b[?1000l')
|
||||
@@ -0,0 +1,884 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from functools import partial
|
||||
|
||||
from kitty.fast_data_types import EXTEND_CELL, TEXT_SIZE_CODE, test_ch_and_idx, wcswidth
|
||||
|
||||
from .base import BaseTest, parse_bytes
|
||||
from .base import draw_multicell as multicell
|
||||
|
||||
|
||||
class TestMulticell(BaseTest):
|
||||
def test_multicell(self):
|
||||
test_multicell(self)
|
||||
|
||||
def test_overlay_line_does_not_crash_on_uninit_linebuf_view(self):
|
||||
# Regression: screen_draw_overlay_line accessed self->linebuf->line->cpu_cells
|
||||
# without ever calling linebuf_init_line, so on render paths that
|
||||
# initialize a stack-local Line (render_line_for_virtual_y) the shared
|
||||
# view's cpu_cells stayed NULL and the multicell-trim loop dereferenced
|
||||
# NULL + xstart * sizeof(CPUCell). Reproduces by placing a wide cell at
|
||||
# xstart>0 and triggering the overlay draw directly.
|
||||
for xstart in (1, 2, 3):
|
||||
s = self.create_screen(cols=10, lines=5)
|
||||
s.draw('好好') # two 2-cell wide chars covering columns 0..3
|
||||
s.test_draw_overlay_line('xy', xstart, 0) # would SIGSEGV without fix
|
||||
|
||||
def test_multicell_below_bottom_margin(self):
|
||||
# Regression: with the cursor below the bottom margin, the available
|
||||
# height computation underflowed and cells were written past the end
|
||||
# of the line buffer.
|
||||
s = self.create_screen(cols=10, lines=6)
|
||||
s.set_margins(1, 3) # 1-based indexing
|
||||
s.cursor.x, s.cursor.y = 0, s.lines - 1
|
||||
multicell(s, 'A', scale=2)
|
||||
self.ae((s.cursor.x, s.cursor.y), (2, s.lines - 2))
|
||||
for y in (s.lines - 2, s.lines - 1):
|
||||
for x in range(2):
|
||||
c = s.cpu_cells(y, x)
|
||||
self.assertIsNotNone(c['mcd'])
|
||||
self.ae((c['x'], c['y'], c['mcd']['scale']), (x, y - s.lines + 2, 2))
|
||||
|
||||
|
||||
def test_multicell(self: TestMulticell) -> None:
|
||||
from kitty.tab_bar import as_rgb
|
||||
from kitty.window import as_text
|
||||
|
||||
def as_ansi(add_history=False):
|
||||
return as_text(s, as_ansi=True, add_history=add_history)
|
||||
|
||||
def ac(x_, y_, **assertions): # assert cell
|
||||
cell = s.cpu_cells(y_, x_)
|
||||
msg = f'Assertion failed for cell at ({x_}, {y_})\n{cell}\n'
|
||||
failures = []
|
||||
|
||||
def ae(key):
|
||||
if key not in assertions:
|
||||
return
|
||||
if key in cell:
|
||||
val = cell[key]
|
||||
else:
|
||||
mcd = cell['mcd']
|
||||
if mcd is None:
|
||||
raise AssertionError(f'{msg}Unexpectedly not a multicell')
|
||||
val = mcd[key]
|
||||
if assertions[key] != val:
|
||||
failures.append(f'{key}: (expected) {assertions[key]!r} != {val!r}')
|
||||
|
||||
self.ae(test_ch_and_idx(0), (0, 0, 0))
|
||||
self.ae(test_ch_and_idx(1), (0, 1, 1))
|
||||
self.ae(test_ch_and_idx(0x80000000), (1, 0, 0x80000000))
|
||||
self.ae(test_ch_and_idx(0x80000001), (1, 1, 0x80000001))
|
||||
self.ae(test_ch_and_idx((1, 0)), (1, 0, 0x80000000))
|
||||
self.ae(test_ch_and_idx((1, 3)), (1, 3, 0x80000003))
|
||||
|
||||
ae('x')
|
||||
ae('y')
|
||||
ae('width')
|
||||
ae('scale')
|
||||
ae('subscale_n')
|
||||
ae('subscale_d')
|
||||
ae('vertical_align')
|
||||
ae('horizontal_align')
|
||||
ae('text')
|
||||
ae('natural_width')
|
||||
ae('next_char_was_wrapped')
|
||||
if failures:
|
||||
raise AssertionError(msg + '\n' + '\n'.join(failures))
|
||||
|
||||
if 'cursor' in assertions:
|
||||
self.ae(assertions['cursor'], (s.cursor.x, s.cursor.y), msg)
|
||||
|
||||
if 'is_multicell' in assertions:
|
||||
q = cell['mcd']
|
||||
if assertions['is_multicell']:
|
||||
if q is None:
|
||||
raise AssertionError(f'{msg}Unexpectedly not a multicell')
|
||||
else:
|
||||
if q is not None:
|
||||
raise AssertionError(f'{msg}Unexpectedly is a multicell')
|
||||
|
||||
def count_multicells(with_text=''):
|
||||
ans = 0
|
||||
for y in range(s.lines):
|
||||
for x in range(s.columns):
|
||||
c = s.cpu_cells(y, x)
|
||||
if c['mcd'] is not None and (not with_text or c['text'] == with_text):
|
||||
ans += 1
|
||||
return ans
|
||||
|
||||
def line_text(y):
|
||||
def ct(c):
|
||||
if c['text']:
|
||||
return c['text']
|
||||
if c['mcd']:
|
||||
return '_'
|
||||
return '\0'
|
||||
|
||||
return ''.join(ct(c) for c in s.cpu_cells(y))
|
||||
|
||||
def assert_line(text, y=None):
|
||||
if y is None:
|
||||
y = s.cursor.y
|
||||
self.ae(text, line_text(y))
|
||||
|
||||
def assert_cursor_at(x, y):
|
||||
self.ae((s.cursor.x, s.cursor.y), (x, y))
|
||||
|
||||
s = self.create_screen(cols=8, lines=4)
|
||||
s.draw('飛青進服三上')
|
||||
s.resize(s.lines, 5)
|
||||
self.ae('飛青', str(s.line(0)))
|
||||
|
||||
s = self.create_screen(cols=6, lines=6)
|
||||
|
||||
# Test basic multicell drawing
|
||||
s.reset()
|
||||
ac(0, 0, is_multicell=False)
|
||||
multicell(s, 'a')
|
||||
ac(0, 0, is_multicell=True, width=1, scale=1, subscale_n=0, x=0, y=0, text='a', natural_width=True, cursor=(1, 0))
|
||||
ac(0, 1, is_multicell=False), ac(1, 0, is_multicell=False), ac(1, 1, is_multicell=False)
|
||||
s.draw('莊')
|
||||
ac(0, 0, is_multicell=True, width=1, scale=1, subscale_n=0, x=0, y=0, text='a', natural_width=True)
|
||||
ac(1, 0, is_multicell=True, width=2, scale=1, subscale_n=0, x=0, y=0, text='莊', natural_width=True, cursor=(3, 0))
|
||||
ac(2, 0, is_multicell=True, width=2, scale=1, subscale_n=0, x=1, y=0, text='', natural_width=True)
|
||||
for x in range(s.columns):
|
||||
ac(x, 1, is_multicell=False)
|
||||
s.cursor.x = 0
|
||||
multicell(s, 'a', width=2, scale=2, subscale_n=3)
|
||||
ac(0, 0, is_multicell=True, width=2, scale=2, subscale_n=3, x=0, y=0, text='a', natural_width=False, cursor=(4, 0))
|
||||
for x in range(1, 4):
|
||||
ac(x, 0, is_multicell=True, width=2, scale=2, subscale_n=3, x=x, y=0, text='', natural_width=False)
|
||||
for x in range(0, 4):
|
||||
ac(x, 1, is_multicell=True, width=2, scale=2, subscale_n=3, x=x, y=1, text='', natural_width=False)
|
||||
|
||||
def comb(x, y):
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.x, s.cursor.y = x, y
|
||||
s.draw('\u0301')
|
||||
assert_cursor_at(x, y)
|
||||
ac(0, 0, text='a' if y else 'a\u0301', is_multicell=True)
|
||||
|
||||
for y in range(2):
|
||||
for x in range(1, 3):
|
||||
comb(x, y)
|
||||
comb(0, 1)
|
||||
|
||||
# Regression test for buffer overflow when a natural width (w=0) grapheme
|
||||
# cluster is longer than the ListOfChars stack buffer. See the accumulation
|
||||
# loop in screen_handle_multicell_command(). The cluster is accumulated in
|
||||
# full (overflowing the buffer before the fix) even though the text stored
|
||||
# per cell is later capped at MAX_NUM_CODEPOINTS_PER_CELL (24).
|
||||
capped = 'a' + '́' * 23
|
||||
s.reset()
|
||||
multicell(s, 'a' + '́' * 32)
|
||||
ac(0, 0, is_multicell=True, width=1, scale=1, x=0, y=0, text=capped, natural_width=True)
|
||||
# A second, even longer cluster exercises the heap-backed buffer after the first flush.
|
||||
s.reset()
|
||||
multicell(s, 'a' + '́' * 32 + 'b' + '́' * 48)
|
||||
ac(0, 0, is_multicell=True, x=0, y=0, text=capped, natural_width=True)
|
||||
ac(1, 0, is_multicell=True, x=0, y=0, text='b' + '́' * 23, natural_width=True)
|
||||
|
||||
s.reset()
|
||||
multicell(s, 'aüa', scale=2)
|
||||
self.ae(s.cursor.x, 6)
|
||||
s = self.create_screen(cols=7 * 7, lines=7)
|
||||
multicell(s, 'a', scale=7, width=7)
|
||||
for y in range(s.lines):
|
||||
for x in range(s.columns):
|
||||
ac(x, y, is_multicell=True, x=x, y=y)
|
||||
|
||||
# Test zero width roundtripping
|
||||
for preserved in '\xad\u200b\u2060':
|
||||
s.reset()
|
||||
multicell(s, f'|{preserved}|', scale=2)
|
||||
assert_cursor_at(4, 0)
|
||||
ac(0, 0, text=f'|{preserved}')
|
||||
|
||||
# Test wrapping
|
||||
s = self.create_screen(cols=6, lines=6)
|
||||
s.draw('x' * (s.columns - 1))
|
||||
multicell(s, 'a', scale=2)
|
||||
ac(s.columns - 1, 0, is_multicell=False, text='', next_char_was_wrapped=True)
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.draw('x' * s.columns)
|
||||
ac(s.cursor.x - 1, s.cursor.y, is_multicell=False, text='x', next_char_was_wrapped=False)
|
||||
ac(0, 0, is_multicell=True, text='a')
|
||||
ac(0, 1, is_multicell=True, text='', y=1)
|
||||
|
||||
# Test draw with cursor in a multicell
|
||||
s.reset()
|
||||
multicell(s, '12', scale=2)
|
||||
s.draw('\rx')
|
||||
ac(0, 0, is_multicell=False, text='x')
|
||||
ac(1, 0, is_multicell=False, text='')
|
||||
ac(0, 1, is_multicell=False, text='')
|
||||
ac(1, 1, is_multicell=False, text='')
|
||||
ac(2, 0, is_multicell=True, text='2')
|
||||
s.reset()
|
||||
s.draw('莊')
|
||||
s.cursor.x -= 1
|
||||
s.draw('a'), ac(0, 0, is_multicell=False), ac(1, 0, is_multicell=False)
|
||||
s.reset()
|
||||
s.draw('莊')
|
||||
s.cursor.x = 0
|
||||
s.draw('a'), ac(0, 0, is_multicell=False), ac(1, 0, is_multicell=False)
|
||||
s.reset()
|
||||
multicell(s, 'a', width=2, scale=2, subscale_n=3, subscale_d=4)
|
||||
s.cursor.x, s.cursor.y = 1, 1
|
||||
s.draw('b')
|
||||
self.ae(8, count_multicells())
|
||||
assert_cursor_at(5, 1)
|
||||
self.assertIn('b', str(s.linebuf))
|
||||
s.reset()
|
||||
s.cursor.x = 1
|
||||
s.draw('莊')
|
||||
s.cursor.x = 0
|
||||
s.draw('莊')
|
||||
ac(2, 0, is_multicell=False, text=' ')
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.x += 1
|
||||
multicell(s, 'b', scale=2)
|
||||
s.draw('莊')
|
||||
assert_cursor_at(2, 2)
|
||||
self.assertIn('莊', str(s.linebuf))
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.x += 1
|
||||
multicell(s, 'b', scale=2)
|
||||
assert_cursor_at(5, 0)
|
||||
s.draw('\u2716\ufe0f')
|
||||
assert_cursor_at(2, 2)
|
||||
s.reset()
|
||||
s.draw('莊')
|
||||
s.cursor.x = 0
|
||||
s.draw('b')
|
||||
self.ae(str(s.line(0)), 'b')
|
||||
s.reset()
|
||||
s.draw('莊')
|
||||
s.cursor.x = 1
|
||||
s.draw('b')
|
||||
self.ae(str(s.line(0)), ' b')
|
||||
|
||||
# Test multicell with cursor in a multicell
|
||||
def big_a(x, y=0, spaces=False, skip=False):
|
||||
s.reset()
|
||||
s.cursor.x, s.cursor.y = 1, 1
|
||||
multicell(s, 'a', scale=4)
|
||||
ac(1, 1, x=0, y=0, text='a', scale=4, width=1)
|
||||
s.cursor.x, s.cursor.y = x, y
|
||||
multicell(s, 'b', scale=2)
|
||||
if skip:
|
||||
self.ae(20, count_multicells())
|
||||
assert_cursor_at(2, 4)
|
||||
self.assertIn('a', str(s.linebuf))
|
||||
else:
|
||||
ac(x, y, text='b')
|
||||
self.ae(4, count_multicells())
|
||||
for x_ in range(1, 5):
|
||||
ac(x_, 4, text=' ' if spaces else '')
|
||||
|
||||
for y in (0, 1):
|
||||
big_a(0, y), big_a(1, y), big_a(2, y, spaces=True)
|
||||
big_a(2, 2, skip=True), big_a(5, 1, skip=True)
|
||||
|
||||
# Test multicell with combining and flag codepoints and default width
|
||||
def seq(text, *expected):
|
||||
s.reset()
|
||||
multicell(s, text)
|
||||
i = iter(expected)
|
||||
for x in range(s.cursor.x):
|
||||
cell = s.cpu_cells(0, x)
|
||||
if cell['x'] == 0:
|
||||
q = next(i)
|
||||
ac(x, 0, text=q, width=wcswidth(q))
|
||||
|
||||
seq('ab', 'a', 'b')
|
||||
flag = '\U0001f1ee\U0001f1f3'
|
||||
seq(flag + 'CD', flag, 'C', 'D')
|
||||
seq('àn̂X', 'à', 'n̂', 'X')
|
||||
seq('\U0001f1eea', '\U0001f1ee', 'a')
|
||||
del flag, seq
|
||||
|
||||
# Test insert chars with multicell (aka right shift)
|
||||
s.reset()
|
||||
s.draw('a')
|
||||
s.cursor.x = 0
|
||||
s.insert_characters(1)
|
||||
assert_line('\0a\0\0\0\0')
|
||||
s.reset()
|
||||
multicell(s, 'a', width=2)
|
||||
s.cursor.x = 0
|
||||
s.insert_characters(1)
|
||||
assert_line('\0a_\0\0\0')
|
||||
s.reset()
|
||||
multicell(s, 'a', width=2)
|
||||
s.cursor.x = 0
|
||||
s.insert_characters(2)
|
||||
assert_line('\0\0a_\0\0')
|
||||
s.reset()
|
||||
multicell(s, 'a', width=2)
|
||||
s.cursor.x = 1
|
||||
s.insert_characters(1)
|
||||
assert_line('\0\0\0\0\0\0')
|
||||
s.reset()
|
||||
s.cursor.x = 3
|
||||
multicell(s, 'a', width=2)
|
||||
s.cursor.x = 0
|
||||
s.insert_characters(1)
|
||||
assert_line('\0\0\0\0a_')
|
||||
s.reset()
|
||||
s.cursor.x = s.columns - 2
|
||||
multicell(s, 'a', width=2)
|
||||
s.cursor.x = 0
|
||||
s.insert_characters(1)
|
||||
assert_line('\0\0\0\0\0\0')
|
||||
# multiline
|
||||
s.reset()
|
||||
s.draw('a')
|
||||
multicell(s, 'b', scale=2)
|
||||
assert_line('ab_\0\0\0')
|
||||
assert_line('\0__\0\0\0', 1)
|
||||
s.cursor.x, s.cursor.y = 0, 0
|
||||
s.insert_characters(1)
|
||||
assert_line('\0a\0\0\0\0')
|
||||
assert_line('\0\0\0\0\0\0', 1)
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.x = 3
|
||||
s.insert_characters(1)
|
||||
assert_line('a_\0\0\0\0')
|
||||
assert_line('__\0\0\0\0', 1)
|
||||
|
||||
# Test delete chars with multicell (aka left shift)
|
||||
s.reset()
|
||||
s.draw(' 允许')
|
||||
s.cursor.x = 0
|
||||
s.delete_characters(1)
|
||||
for x in range(4):
|
||||
ac(x, 0, width=2)
|
||||
s.reset()
|
||||
multicell(s, 'a', width=2)
|
||||
s.cursor.x = 0
|
||||
s.delete_characters(1)
|
||||
assert_line('\0\0\0\0\0\0')
|
||||
s.reset()
|
||||
multicell(s, 'a', width=2)
|
||||
s.cursor.x = 1
|
||||
s.delete_characters(1)
|
||||
assert_line('\0\0\0\0\0\0')
|
||||
s.reset()
|
||||
s.draw('ab')
|
||||
multicell(s, 'a', width=2)
|
||||
s.cursor.x = 0
|
||||
s.delete_characters(2)
|
||||
assert_line('a_\0\0\0\0')
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', width=2), s.draw('c')
|
||||
s.cursor.x = 0
|
||||
s.delete_characters(1)
|
||||
assert_line('b_c\0\0\0')
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', width=2), s.draw('c')
|
||||
s.cursor.x = 0
|
||||
s.delete_characters(1)
|
||||
assert_line('b_c\0\0\0')
|
||||
s.reset(), s.draw('a'), multicell(s, 'b', width=2), s.draw('c')
|
||||
s.cursor.x = 0
|
||||
s.delete_characters(2)
|
||||
assert_line('\0c\0\0\0\0')
|
||||
s.reset(), s.draw('a'), multicell(s, 'b', width=2), s.draw('c')
|
||||
s.cursor.x = 1
|
||||
s.delete_characters(1)
|
||||
assert_line('a\0c\0\0\0')
|
||||
s.reset(), s.draw('a'), multicell(s, 'b', width=2), s.draw('c')
|
||||
s.cursor.x = 2
|
||||
s.delete_characters(1)
|
||||
assert_line('a\0c\0\0\0')
|
||||
# multiline
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
assert_line('ab_c\0\0')
|
||||
assert_line('\0__\0\0\0', 1)
|
||||
s.cursor.x, s.cursor.y = 0, 0
|
||||
s.delete_characters(1)
|
||||
assert_line('\0\0c\0\0\0')
|
||||
assert_line('\0\0\0\0\0\0', 1)
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.x = 3
|
||||
s.delete_characters(1)
|
||||
assert_line('a_\0\0\0\0')
|
||||
assert_line('__\0\0\0\0', 1)
|
||||
|
||||
# Erase characters (aka replace with null)
|
||||
s.reset()
|
||||
s.cursor.x = 1
|
||||
s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
s.cursor.x = 0
|
||||
s.erase_characters(1)
|
||||
assert_line('\0ab_c\0')
|
||||
s.erase_characters(2)
|
||||
assert_line('\0\0b_c\0')
|
||||
assert_line('\0\0__\0\0', 1)
|
||||
s.erase_characters(3)
|
||||
assert_line('\0\0\0\0c\0')
|
||||
assert_line('\0\0\0\0\0\0', 1)
|
||||
|
||||
# Erase in line
|
||||
for x in (1, 2):
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
s.cursor.x = x
|
||||
s.erase_in_line(0)
|
||||
assert_line('a\0\0\0\0\0')
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', width=2), s.draw('c')
|
||||
s.cursor.x = x
|
||||
s.erase_in_line(1)
|
||||
assert_line('\0\0\0c\0\0')
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
s.erase_in_line(2)
|
||||
for y in (0, 1):
|
||||
assert_line('\0\0\0\0\0\0', y)
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
s.cursor.y = 1
|
||||
s.erase_in_line(2)
|
||||
assert_line('a\0\0c\0\0', 0)
|
||||
assert_line('\0\0\0\0\0\0', 1)
|
||||
|
||||
# Clear scrollback
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
for i in range(s.lines):
|
||||
s.index()
|
||||
s.cursor.y = 0
|
||||
assert_line('\0__\0\0\0')
|
||||
s.clear_scrollback()
|
||||
assert_line('\0\0\0\0\0\0')
|
||||
|
||||
# Erase in line with cursor in the right half
|
||||
s.reset()
|
||||
s.cursor.x = 4
|
||||
multicell(s, 'b', width=2)
|
||||
s.cursor.x = 5
|
||||
s.erase_in_line(0)
|
||||
for x in range(s.columns):
|
||||
self.assertIsNone(s.cpu_cells(0, x)['mcd'])
|
||||
for cx in (3, 4, 5):
|
||||
s.reset()
|
||||
s.cursor.x = cx - 1
|
||||
multicell(s, 'b', scale=2)
|
||||
s.cursor.x = cx
|
||||
s.erase_in_line(0)
|
||||
for y in (0, 1):
|
||||
for x in range(s.columns):
|
||||
self.assertIsNone(s.cpu_cells(y, x)['mcd'], f'{cx} {y} {x}')
|
||||
|
||||
# Erase in display
|
||||
for x in (1, 2):
|
||||
s.reset(), s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
s.cursor.x = x
|
||||
s.erase_in_display(0)
|
||||
assert_line('a\0\0\0\0\0')
|
||||
s.reset(), s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
s.cursor.x, s.cursor.y = 2, 1
|
||||
s.erase_in_display(0)
|
||||
assert_line('a\0\0c\0\0', 0)
|
||||
assert_line('\0\0\0\0\0\0', 1)
|
||||
s.reset(), s.draw('a'), multicell(s, 'b', scale=2), s.draw('c')
|
||||
for i in range(s.lines):
|
||||
s.index()
|
||||
s.erase_in_display(22)
|
||||
assert_line('ab_c\0\0', -2)
|
||||
assert_line('\0__\0\0\0', -1)
|
||||
self.ae(s.historybuf.line(1).as_ansi(), f'a\x1b]{TEXT_SIZE_CODE};s=2;b\x07c')
|
||||
self.ae(s.historybuf.line(0).as_ansi(), ' ')
|
||||
|
||||
# Erase in display splitting a multiline char
|
||||
def no_mcd(*rows):
|
||||
for y in rows:
|
||||
for x in range(s.columns):
|
||||
self.assertIsNone(s.cpu_cells(y, x)['mcd'], f'{y} {x}')
|
||||
|
||||
for private in (False, True):
|
||||
s.reset()
|
||||
s.cursor.x, s.cursor.y = 2, 1
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.x, s.cursor.y = 4, 1
|
||||
s.erase_in_display(0, private)
|
||||
no_mcd(0, 1, 2)
|
||||
s.reset()
|
||||
s.cursor.x, s.cursor.y = 2, 1
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.x, s.cursor.y = 0, 2
|
||||
s.erase_in_display(1, private)
|
||||
no_mcd(0, 1, 2)
|
||||
|
||||
# char split between history and screen
|
||||
for how, y in ((1, 2), (2, 0)):
|
||||
for private in (False, True):
|
||||
s.reset()
|
||||
s.cursor.x, s.cursor.y = 2, s.lines - 2
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.y = s.lines - 1
|
||||
for i in range(s.lines - 1):
|
||||
s.index()
|
||||
self.ae(s.historybuf.count, s.lines - 1)
|
||||
self.assertIsNotNone(s.cpu_cells(0, 2)['mcd'])
|
||||
s.cursor.x, s.cursor.y = 0, y
|
||||
s.erase_in_display(how, private)
|
||||
no_mcd(0)
|
||||
self.assertNotIn(str(TEXT_SIZE_CODE), s.historybuf.line(0).as_ansi())
|
||||
|
||||
# Insert lines
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.x, s.cursor.y = 0, s.lines - 2
|
||||
multicell(s, 'b', scale=2)
|
||||
s.cursor.x, s.cursor.y = 0, 1
|
||||
s.insert_lines(1)
|
||||
for y in range(s.lines):
|
||||
assert_line('\0' * s.columns, y)
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.insert_lines(2)
|
||||
assert_line('\0' * s.columns, 0)
|
||||
assert_line('a_\0\0\0\0', 2)
|
||||
|
||||
# Delete lines
|
||||
s.reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.y = 1
|
||||
multicell(s, 'b', scale=2)
|
||||
s.delete_lines(1)
|
||||
for y in range(s.lines):
|
||||
assert_line('\0' * s.columns, y)
|
||||
|
||||
# ansi output
|
||||
def ta(expected):
|
||||
actual = as_ansi().rstrip()[3:]
|
||||
self.ae(expected, actual)
|
||||
s.reset()
|
||||
parse_bytes(s, actual.encode())
|
||||
actual2 = as_ansi().rstrip()[3:]
|
||||
self.ae(expected, actual2)
|
||||
s.reset()
|
||||
|
||||
s.reset()
|
||||
multicell(s, 'a', width=2, scale=3, subscale_n=1, subscale_d=2, vertical_align=3, horizontal_align=3)
|
||||
ta(f'\x1b]{TEXT_SIZE_CODE};w=2:s=3:n=1:d=2:v=3:h=3;a\x07')
|
||||
s.draw('a')
|
||||
multicell(s, 'b', width=2)
|
||||
s.draw('c')
|
||||
ta(f'a\x1b]{TEXT_SIZE_CODE};w=2;b\x07c')
|
||||
multicell(s, 'a')
|
||||
s.cursor.fg = as_rgb(0xFFFFFF)
|
||||
multicell(s, 'b')
|
||||
ta('a\x1b[38:2:255:255:255mb')
|
||||
multicell(s, 'a', scale=2)
|
||||
multicell(s, 'b', scale=2)
|
||||
ta(f'\x1b]{TEXT_SIZE_CODE};s=2;ab\x07')
|
||||
multicell(s, '😀a', scale=2)
|
||||
ta(f'\x1b]{TEXT_SIZE_CODE};s=2;😀a\x07')
|
||||
multicell(s, '😀', scale=2)
|
||||
multicell(s, 'b', width=1, scale=2)
|
||||
ta(f'\x1b]{TEXT_SIZE_CODE};s=2;😀\x07\x1b]{TEXT_SIZE_CODE};w=1:s=2;b\x07')
|
||||
multicell(s, 'a', scale=2)
|
||||
s.cursor.fg = as_rgb(0xFFFFFF)
|
||||
multicell(s, 'b', scale=2)
|
||||
ta(f'\x1b]{TEXT_SIZE_CODE};s=2;a\x07\x1b[38:2:255:255:255m\x1b]{TEXT_SIZE_CODE};s=2;b\x07\n\x1b[m\x1b[38:2:255:255:255m')
|
||||
multicell(s, 'a', scale=3)
|
||||
multicell(s, 'b', scale=2)
|
||||
ta(f'\x1b]{TEXT_SIZE_CODE};s=3;a\x07\x1b]{TEXT_SIZE_CODE};s=2;b\x07')
|
||||
|
||||
# rewrap with multicells
|
||||
s = self.create_screen(cols=6, lines=6, scrollback=20)
|
||||
o = s.lines, s.columns
|
||||
|
||||
def reset():
|
||||
s.resize(*o)
|
||||
s.reset()
|
||||
s.clear_scrollback()
|
||||
|
||||
def mc(x=None, y=None):
|
||||
if x is not None:
|
||||
s.cursor.x = x
|
||||
if y is not None:
|
||||
s.cursor.y = y
|
||||
|
||||
reset()
|
||||
multicell(s, 'a', scale=2)
|
||||
before = as_ansi()
|
||||
s.resize(s.lines + 1, s.columns)
|
||||
self.ae(before.rstrip(), as_ansi().rstrip())
|
||||
|
||||
reset()
|
||||
s.draw('a' * (s.columns - 2) + '😛' + 'bb')
|
||||
mc(4, 0)
|
||||
s.resize(s.lines, s.columns - 1)
|
||||
self.ae('\x1b[maaaa\x1b[m😛bb', as_ansi().rstrip())
|
||||
assert_cursor_at(0, 1)
|
||||
reset()
|
||||
s.draw('a' * (s.columns - 2) + '😛' + 'bb')
|
||||
mc(0, 1)
|
||||
s.resize(s.lines, s.columns - 2)
|
||||
assert_cursor_at(2, 1)
|
||||
self.ae('\x1b[maaaa\x1b[m😛bb', as_ansi().rstrip())
|
||||
reset()
|
||||
s.draw('a' * (s.columns - 2) + '😛' + 'bb')
|
||||
mc(5, 0)
|
||||
s.resize(s.lines, s.columns - 3)
|
||||
self.ae('\x1b[maaa\x1b[ma😛\x1b[mbb', as_ansi().rstrip()) # ]]]]]]]
|
||||
assert_cursor_at(2, 1)
|
||||
|
||||
def resize(lines, cols, cursorx=None, cursory=None):
|
||||
mc(cursorx, cursory)
|
||||
before = s.cursor.x, s.cursor.y
|
||||
cell = s.cpu_cells(s.cursor.y, s.cursor.x)
|
||||
cell.pop('next_char_was_wrapped')
|
||||
s.resize(lines, cols)
|
||||
ncell = s.cpu_cells(s.cursor.y, s.cursor.x)
|
||||
ncell.pop('next_char_was_wrapped')
|
||||
self.ae(cell, ncell, f'Cursor moved from: {before} to {(s.cursor.x, s.cursor.y)}')
|
||||
|
||||
reset()
|
||||
multicell(s, 'a', scale=3), s.draw('b' * (s.columns - 3))
|
||||
resize(s.lines, s.columns - 1, 5, 0)
|
||||
self.ae(f'\x1b[m\x1b]{TEXT_SIZE_CODE};s=3;a\x07bb\x1b[mb', as_ansi().rstrip()) # ]]
|
||||
ac(0, 0, is_multicell=True)
|
||||
ac(0, 1, is_multicell=True)
|
||||
ac(3, 1, is_multicell=False, text='b')
|
||||
reset()
|
||||
s.draw('X'), multicell(s, 'a', scale=3), s.draw('12345')
|
||||
resize(s.lines, s.columns - 1, 4, 0)
|
||||
self.ae(f'\x1b[mX\x1b]{TEXT_SIZE_CODE};s=3;a\x071\x1b[m23\x1b[m45', as_ansi().rstrip()) # ]]
|
||||
for y in (0, 1):
|
||||
ac(0, y, is_multicell=False), ac(1, y, is_multicell=True), ac(3, y, is_multicell=True)
|
||||
ac(0, 1, is_multicell=False, text='2'), ac(4, 1, is_multicell=False, text='3')
|
||||
|
||||
reset()
|
||||
s.draw('a' * (s.columns - 2)), s.draw('😛'), s.linefeed(), s.carriage_return(), s.draw('123')
|
||||
resize(s.lines, s.columns - 1, 5, 0)
|
||||
self.ae('\x1b[maaaa\x1b[m😛\n\x1b[m123', as_ansi().rstrip()) # ]]]]]]]
|
||||
|
||||
reset()
|
||||
s.draw('a' * (s.columns - 1)), s.draw('😛'), s.draw('bcd')
|
||||
resize(s.lines, s.columns + 1, 0, 1)
|
||||
self.ae('\x1b[maaaaa😛\x1b[mbcd', as_ansi().rstrip()) # ]]]]]]]
|
||||
|
||||
reset()
|
||||
s.draw('a' * s.columns), s.draw('😛'), s.draw('bcd')
|
||||
resize(s.lines, s.columns + 1, 0, 1)
|
||||
self.ae('\x1b[maaaaaa\x1b[m😛bcd', as_ansi().rstrip()) # ]]]]]]]
|
||||
ac(s.columns - 1, 0, next_char_was_wrapped=True)
|
||||
s.resize(s.lines, s.columns + 1)
|
||||
self.ae('\x1b[maaaaaa😛\x1b[mbcd', as_ansi().rstrip()) # ]]]]]]]
|
||||
|
||||
reset()
|
||||
s.draw('a' * (s.columns - 1)), multicell(s, 'X', scale=2), s.draw('bcd')
|
||||
resize(s.lines, s.columns + 1, 0, 2)
|
||||
self.ae(f'\x1b[maaaaa\x1b]{TEXT_SIZE_CODE};s=2;X\x07\x1b[mbcd', as_ansi().rstrip()) # ]]]]]]]
|
||||
for y in (0, 1):
|
||||
for x in (1, 2):
|
||||
ac(s.columns - x, y, is_multicell=True)
|
||||
for x in (0, 1):
|
||||
ac(x, y, is_multicell=False)
|
||||
reset()
|
||||
s.draw('a' * (s.columns - 1)), multicell(s, 'X', scale=2), s.draw('bcd1234!')
|
||||
s.resize(s.lines, s.columns + 2)
|
||||
self.ae(f'\x1b[maaaaa\x1b]{TEXT_SIZE_CODE};s=2;X\x07b\x1b[mcd1234\x1b[m!', as_ansi().rstrip()) # ]]]]]]]
|
||||
for y in (0, 1):
|
||||
for x in (1, 2):
|
||||
ac(s.columns - x - 1, y, is_multicell=True)
|
||||
for x in (0, 1):
|
||||
ac(x, y, is_multicell=False)
|
||||
|
||||
reset()
|
||||
multicell(s, 'X', scale=4), s.draw('abc')
|
||||
resize(3, 3, 5, 0)
|
||||
self.ae('\x1b[mabc', as_ansi().rstrip()) # ]]]]]]]
|
||||
reset()
|
||||
multicell(s, 'X', width=4), s.draw('abc')
|
||||
resize(3, 3, 4, 0)
|
||||
self.ae('\x1b[mabc', as_ansi().rstrip()) # ]]]]]]]
|
||||
reset()
|
||||
s.draw('1'), multicell(s, 'X', width=4), s.draw('abc')
|
||||
resize(3, 3, 5, 0)
|
||||
self.ae('\x1b[m1ab\x1b[mc', as_ansi().rstrip()) # ]]]]]]]
|
||||
|
||||
reset()
|
||||
suffix = '112233445555556666667'
|
||||
multicell(s, 'X', scale=4), s.draw(suffix)
|
||||
self.ae(str(s.historybuf), 'X11') # X is split between the buffers
|
||||
resize(6, s.columns + 1, 0, 5)
|
||||
self.ae(str(s.historybuf), 'X112')
|
||||
self.ae(str(s.linebuf.line(0)), '233')
|
||||
for y in range(3):
|
||||
for x in range(4):
|
||||
ac(x, y, is_multicell=True, x=x, y=y + 1)
|
||||
reset()
|
||||
multicell(s, 'X', scale=4), s.draw(suffix)
|
||||
resize(6, s.columns - 1, 0, 5)
|
||||
self.ae(f'X{suffix}', as_text(s, add_history=True))
|
||||
self.ae(str(s.historybuf), '1\nX1')
|
||||
self.ae(str(s.linebuf.line(0)), '2')
|
||||
for y in range(-2, 2):
|
||||
for x in range(4):
|
||||
ac(x, y, is_multicell=True, x=x, y=y + 2, text='X' if (x, y) == (0, -2) else '')
|
||||
|
||||
reset()
|
||||
multicell(s, 'AB', scale=2), s.draw('11223333334444445555556666667')
|
||||
self.ae(str(s.historybuf), 'AB11') # AB is split between the buffers
|
||||
resize(6, s.columns + 1, 0, 5)
|
||||
self.ae(str(s.historybuf), 'AB112')
|
||||
self.ae(str(s.linebuf.line(0)), '233')
|
||||
for x in range(2):
|
||||
ac(x, -1, is_multicell=True, x=x, y=0, text='' if x else 'A')
|
||||
ac(x, 0, is_multicell=True, x=x, y=1, text='')
|
||||
for x in range(2, 4):
|
||||
ac(x, -1, is_multicell=True, x=x - 2, y=0, text='' if x > 2 else 'B')
|
||||
ac(x, 0, is_multicell=True, x=x - 2, y=1, text='')
|
||||
|
||||
# resize without rewrap (alt screen)
|
||||
s = self.create_screen(lines=6, cols=6)
|
||||
s.toggle_alt_screen()
|
||||
|
||||
def reset_alt():
|
||||
s.reset()
|
||||
s.resize(6, 6)
|
||||
s.toggle_alt_screen()
|
||||
|
||||
multicell(s, 'XY', scale=3)
|
||||
s.resize(6, 5)
|
||||
for y in range(3):
|
||||
for x in range(3):
|
||||
ac(x, y, is_multicell=True, text='X' if x == 0 and y == 0 else '')
|
||||
for x in range(3, 5):
|
||||
ac(x, y, is_multicell=False, text='')
|
||||
reset_alt()
|
||||
multicell(s, 'XY', scale=3)
|
||||
s.resize(2, 6)
|
||||
for y in range(s.lines):
|
||||
for x in range(s.columns):
|
||||
ac(x, y, is_multicell=False, text='')
|
||||
|
||||
# selections
|
||||
s = self.create_screen(lines=5, cols=8)
|
||||
|
||||
def p(x=0, y=0, in_left_half_of_cell=True):
|
||||
return (x, y, in_left_half_of_cell)
|
||||
|
||||
def ss(start, end, rectangle_select=False, extend_mode=EXTEND_CELL):
|
||||
s.start_selection(start[0], start[1], rectangle_select, extend_mode, start[2])
|
||||
s.update_selection(end[0], end[1], end[2])
|
||||
|
||||
def asl(*ranges, bp=1):
|
||||
actual = s.current_selections()
|
||||
|
||||
def as_lists(x):
|
||||
a = []
|
||||
for y in range(s.lines):
|
||||
a.append(x[y * s.columns : (y + 1) * s.columns])
|
||||
return a
|
||||
|
||||
expected = bytearray(s.lines * s.columns)
|
||||
for y, x1, x2 in ranges:
|
||||
pos = y * s.columns
|
||||
for x in range(x1, x2 + 1):
|
||||
expected[pos + x] = bp
|
||||
for i, (e, a) in enumerate(zip(as_lists(bytes(expected)), as_lists(actual)[1:])):
|
||||
self.ae(e, a, f'Row: {i}')
|
||||
|
||||
def ast(*expected, strip_trailing_whitespace=False, as_ansi=False):
|
||||
actual = s.text_for_selection(as_ansi, strip_trailing_whitespace)
|
||||
self.ae(expected, actual)
|
||||
|
||||
def asa(*expected, strip_trailing_whitespace=False):
|
||||
ast(*expected, as_ansi=True, strip_trailing_whitespace=strip_trailing_whitespace)
|
||||
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', width=2), s.draw('c')
|
||||
ss(p(), p(x=1, in_left_half_of_cell=False))
|
||||
asl((0, 0, 2))
|
||||
ast('ab')
|
||||
asa(f'a\x1b]{TEXT_SIZE_CODE};w=2;b\x07', '\x1b[m')
|
||||
ss(p(x=2), p(x=3, in_left_half_of_cell=False))
|
||||
asl((0, 1, 3))
|
||||
ast('bc')
|
||||
asa(f'\x1b]{TEXT_SIZE_CODE};w=2;b\x07c', '\x1b[m')
|
||||
|
||||
s.reset()
|
||||
s.draw('a'), multicell(s, 'b', scale=2), s.draw('c'), multicell(s, 'd', scale=2)
|
||||
ss(p(), p(x=4, in_left_half_of_cell=False))
|
||||
asl((0, 0, 5), (1, 1, 2), (1, 4, 5))
|
||||
ast('abcd')
|
||||
asa(f'a\x1b]{TEXT_SIZE_CODE};s=2;b\x07c\x1b]{TEXT_SIZE_CODE};s=2;d\x07', '\x1b[m')
|
||||
ss(p(y=1, x=1), p(y=1, x=1, in_left_half_of_cell=False))
|
||||
asl((0, 1, 2), (1, 1, 2))
|
||||
ast('b')
|
||||
asa(f'\x1b]{TEXT_SIZE_CODE};s=2;b\x07', '\x1b[m')
|
||||
ss(p(y=1, x=0), p(y=1, x=1, in_left_half_of_cell=False)) # empty leading cell before multiline on y=1
|
||||
asl((0, 1, 2), (1, 0, 2))
|
||||
ast('b')
|
||||
asa(f'\x1b]{TEXT_SIZE_CODE};s=2;b\x07', '\x1b[m')
|
||||
|
||||
s.reset()
|
||||
multicell(s, 'X', scale=2), s.draw('123456abcd')
|
||||
for x in (0, 1, 2):
|
||||
ss(p(x=x), p(x=3, y=1, in_left_half_of_cell=False))
|
||||
asl((0, 0, 7), (1, 0, 3))
|
||||
ast('X123456', 'ab')
|
||||
asa(f'\x1b]{TEXT_SIZE_CODE};s=2;X\x07123456', 'ab', '\x1b[m')
|
||||
ss(p(y=1), p(y=1, x=3, in_left_half_of_cell=False))
|
||||
asl((0, 0, 1), (1, 0, 3))
|
||||
ast('X', 'ab')
|
||||
asa(f'\x1b]{TEXT_SIZE_CODE};s=2;X\x07', 'ab', '\x1b[m')
|
||||
|
||||
s = self.create_screen(lines=5, cols=24)
|
||||
|
||||
s.reset()
|
||||
multicell(s, 'ab cd ef', scale=2)
|
||||
ss(p(6, 1), p(9, 0, in_left_half_of_cell=False))
|
||||
ast('cd')
|
||||
asa(f'\x1b]{TEXT_SIZE_CODE};s=2;cd\x07', '\x1b[m')
|
||||
|
||||
s.reset()
|
||||
multicell(s, 'ab', scale=2), s.draw(' '), multicell(s, 'cd', scale=2), s.draw(' '), multicell(s, 'ef', scale=2)
|
||||
ss(p(6, 1), p(9, 0, in_left_half_of_cell=False))
|
||||
ast('cd')
|
||||
|
||||
# Hyperlinks
|
||||
s = self.create_screen(lines=5, cols=8)
|
||||
asu = partial(asl, bp=2)
|
||||
|
||||
def set_link(url=None, id=None):
|
||||
parse_bytes(s, '\x1b]8;id={};{}\x1b\\'.format(id or '', url or '').encode('utf-8'))
|
||||
|
||||
s.reset()
|
||||
set_link('url-a', 'a')
|
||||
multicell(s, 'ab', scale=2)
|
||||
for y in (0, 1):
|
||||
self.ae(s.line(y).hyperlink_ids(), (1, 1, 1, 1, 0, 0, 0, 0))
|
||||
for y in (0, 1):
|
||||
for x in (0, 3):
|
||||
self.ae('url-a', s.hyperlink_at(x, y))
|
||||
asu((0, 0, 3), (1, 0, 3))
|
||||
self.ae(s.current_url_text(), 'ab')
|
||||
|
||||
# URL detection
|
||||
s = self.create_screen(cols=60)
|
||||
|
||||
s.reset()
|
||||
url = 'http://moo.com'
|
||||
multicell(s, url, scale=2)
|
||||
s.detect_url(0, 0)
|
||||
self.ae(s.current_url_text(), url)
|
||||
asu((0, 0, len(url) * 2 - 1), (1, 0, len(url) * 2 - 1))
|
||||
# More tests for URL detection are in screen.py in detect_url()
|
||||
@@ -0,0 +1,488 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from base64 import standard_b64encode
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.notifications import Channel, DesktopIntegration, FreeDesktopIntegration, IconDataCache, NotificationManager, UIState, Urgency
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
def n(
|
||||
title='title',
|
||||
body='',
|
||||
urgency=Urgency.Normal,
|
||||
desktop_notification_id=1,
|
||||
icon_names=(),
|
||||
icon_path='',
|
||||
application_name='',
|
||||
notification_types=(),
|
||||
timeout=-1,
|
||||
sound='system',
|
||||
):
|
||||
return {
|
||||
'title': title,
|
||||
'body': body,
|
||||
'urgency': urgency,
|
||||
'id': desktop_notification_id,
|
||||
'icon_names': icon_names,
|
||||
'icon_path': icon_path,
|
||||
'application_name': application_name,
|
||||
'notification_types': notification_types,
|
||||
'timeout': timeout,
|
||||
'sound': sound,
|
||||
}
|
||||
|
||||
|
||||
class DesktopIntegration(DesktopIntegration):
|
||||
def initialize(self):
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.notifications = []
|
||||
self.close_events = []
|
||||
self.new_version_activated = False
|
||||
self.close_succeeds = True
|
||||
self.counter = 0
|
||||
|
||||
def query_live_notifications(self, channel_id, client_id):
|
||||
ids = [n['id'] for n in self.notifications]
|
||||
self.notification_manager.send_live_response(channel_id, client_id, tuple(ids))
|
||||
|
||||
def on_new_version_notification_activation(self, cmd, which) -> None:
|
||||
self.new_version_activated = which + 1
|
||||
|
||||
def close_notification(self, desktop_notification_id: int) -> bool:
|
||||
self.close_events.append(desktop_notification_id)
|
||||
if self.close_succeeds:
|
||||
self.notification_manager.notification_closed(desktop_notification_id)
|
||||
return self.close_succeeds
|
||||
|
||||
def notify(self, cmd, existing_desktop_notification_id) -> int:
|
||||
if existing_desktop_notification_id:
|
||||
did = existing_desktop_notification_id
|
||||
else:
|
||||
self.counter += 1
|
||||
did = self.counter
|
||||
title, body, urgency = cmd.title, cmd.body, (Urgency.Normal if cmd.urgency is None else cmd.urgency)
|
||||
ans = n(
|
||||
title,
|
||||
body,
|
||||
urgency,
|
||||
did,
|
||||
cmd.icon_names,
|
||||
os.path.basename(cmd.icon_path),
|
||||
cmd.application_name,
|
||||
cmd.notification_types,
|
||||
timeout=cmd.timeout,
|
||||
sound=cmd.sound_name,
|
||||
)
|
||||
self.notifications.append(ans)
|
||||
return self.counter
|
||||
|
||||
|
||||
class Channel(Channel):
|
||||
focused = visible = True
|
||||
|
||||
def __init__(self, *a):
|
||||
super().__init__(*a)
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.responses = []
|
||||
self.focus_events = []
|
||||
|
||||
def ui_state(self, channel_id):
|
||||
return UIState(self.focused, self.visible)
|
||||
|
||||
def focus(self, channel_id: int, activation_token: str) -> None:
|
||||
self.focus_events.append(activation_token)
|
||||
|
||||
def send(self, channel_id: int, osc_escape_code: str) -> bool:
|
||||
self.responses.append(osc_escape_code)
|
||||
|
||||
|
||||
class NotificationManager(NotificationManager):
|
||||
@property
|
||||
def filter_rules(self):
|
||||
yield from ('title:filterme',)
|
||||
|
||||
|
||||
def do_test(self: 'TestNotifications', tdir: str) -> None:
|
||||
di = DesktopIntegration(None)
|
||||
ch = Channel()
|
||||
nm = NotificationManager(di, ch, lambda *a, **kw: None, base_cache_dir=tdir)
|
||||
di.notification_manager = nm
|
||||
|
||||
def reset():
|
||||
di.reset()
|
||||
ch.reset()
|
||||
nm.reset()
|
||||
|
||||
def h(raw_data, osc_code=99, channel_id=1):
|
||||
nm.handle_notification_cmd(channel_id, osc_code, raw_data)
|
||||
|
||||
def activate(which=0, button=0):
|
||||
n = di.notifications[which]
|
||||
nm.notification_activated(n['id'], button)
|
||||
|
||||
def close(which=0):
|
||||
n = di.notifications[which]
|
||||
di.close_notification(n['id'])
|
||||
|
||||
def assert_events(focus=True, close=0, report='', close_response='', live=''):
|
||||
self.ae(ch.focus_events, [''] if focus else [])
|
||||
if report:
|
||||
self.assertIn(f'99;i={report};', ch.responses)
|
||||
else:
|
||||
for r in ch.responses:
|
||||
m = re.match(r'99;i=[a-z0-9]+;', r)
|
||||
self.assertIsNone(m, f'Unexpectedly found report response: {r}')
|
||||
if close_response:
|
||||
self.assertIn(f'99;i={close_response}:p=close;', ch.responses)
|
||||
else:
|
||||
for r in ch.responses:
|
||||
m = re.match(r'99;i=[a-z0-9]+:p=close;', r)
|
||||
self.assertIsNone(m, f'Unexpectedly found close response: {r}')
|
||||
if live:
|
||||
self.assertIn(f'99;i=live:p=alive;{live}', ch.responses)
|
||||
else:
|
||||
for r in ch.responses:
|
||||
m = re.match(r'99;i=[a-z0-9]+:p=alive;', r)
|
||||
self.assertIsNone(m, f'Unexpectedly found alive response: {r}')
|
||||
self.ae(di.close_events, [close] if close else [])
|
||||
|
||||
h('test it', osc_code=9)
|
||||
self.ae(di.notifications, [n(title='test it')])
|
||||
activate()
|
||||
assert_events()
|
||||
reset()
|
||||
|
||||
h('d=0:u=2:i=x;title')
|
||||
h('d=1:i=x:p=body;body')
|
||||
self.ae(di.notifications, [n(body='body', urgency=Urgency.Critical)])
|
||||
activate()
|
||||
assert_events()
|
||||
reset()
|
||||
|
||||
h('i=x:p=body:a=-focus;body')
|
||||
self.ae(di.notifications, [n(title='body')])
|
||||
activate()
|
||||
assert_events(focus=False)
|
||||
reset()
|
||||
|
||||
nm.send_new_version_notification('moose')
|
||||
self.ae(di.notifications, [n('kitty update available!', 'kitty version moose released')])
|
||||
activate()
|
||||
self.assertTrue(di.new_version_activated)
|
||||
reset()
|
||||
|
||||
h('i=x:e=1;' + standard_b64encode(b'title').decode('ascii'))
|
||||
self.ae(di.notifications, [n()])
|
||||
activate()
|
||||
assert_events()
|
||||
reset()
|
||||
|
||||
h('e=1;' + standard_b64encode(b'title').decode('ascii'))
|
||||
self.ae(di.notifications, [n()])
|
||||
activate()
|
||||
assert_events()
|
||||
reset()
|
||||
|
||||
h('d=0:i=x:a=-report;title')
|
||||
h('d=1:i=x:a=report;body')
|
||||
self.ae(di.notifications, [n(title='titlebody')])
|
||||
activate()
|
||||
assert_events(report='x')
|
||||
reset()
|
||||
|
||||
h('a=report;title')
|
||||
self.ae(di.notifications, [n()])
|
||||
activate()
|
||||
assert_events(report='0')
|
||||
reset()
|
||||
|
||||
h('d=0:i=y;title')
|
||||
h('d=1:i=y:p=xxx;title')
|
||||
self.ae(di.notifications, [n()])
|
||||
reset()
|
||||
|
||||
# test filtering
|
||||
h(';title')
|
||||
h(';filterme please')
|
||||
self.ae(di.notifications, [n()])
|
||||
reset()
|
||||
|
||||
# test closing interactions with reporting and activation
|
||||
h('i=c;title')
|
||||
self.ae(di.notifications, [n()])
|
||||
close()
|
||||
assert_events(focus=False, close=True)
|
||||
reset()
|
||||
h('i=c:c=1;title')
|
||||
self.ae(di.notifications, [n()])
|
||||
h('i=c:p=close')
|
||||
self.ae(di.notifications, [n()])
|
||||
assert_events(focus=False, close=True, close_response='c')
|
||||
reset()
|
||||
h('i=c:c=1;title')
|
||||
h('i=c:p=close')
|
||||
self.ae(di.notifications, [n()])
|
||||
assert_events(focus=False, close=True, close_response='c')
|
||||
reset()
|
||||
h('i=c;title')
|
||||
activate()
|
||||
close()
|
||||
h('i=c:p=close')
|
||||
self.ae(di.notifications, [n()])
|
||||
assert_events(focus=True, close=True)
|
||||
reset()
|
||||
h('i=c:a=report:c=1;title')
|
||||
activate()
|
||||
h('i=c:p=close')
|
||||
self.ae(di.notifications, [n()])
|
||||
assert_events(focus=True, report='c', close=True, close_response='c')
|
||||
reset()
|
||||
|
||||
h('i=a[;title')
|
||||
h('i=b;title')
|
||||
h('i=live:p=alive;')
|
||||
assert_events(focus=False, live='a,b')
|
||||
reset()
|
||||
|
||||
h(';title')
|
||||
self.ae(di.notifications, [n()])
|
||||
activate()
|
||||
assert_events()
|
||||
reset()
|
||||
|
||||
# test sounds
|
||||
def enc(x):
|
||||
return standard_b64encode(x.encode()).decode()
|
||||
|
||||
h(f's={enc("silent")};title')
|
||||
self.ae(di.notifications, [n(sound='silent')])
|
||||
h(f's={enc("custom")};title')
|
||||
self.ae(di.notifications[-1], n(desktop_notification_id=2, sound='custom'))
|
||||
reset()
|
||||
|
||||
# Test querying
|
||||
h('i=xyz:p=?')
|
||||
self.assertFalse(di.notifications)
|
||||
qr = 'a=focus,report:o=always,unfocused,invisible:u=0,1,2:p=title,body,?,close,icon,alive,buttons:c=1:w=1:s=system,silent,error,info,question,warn,warning'
|
||||
self.ae(ch.responses, [f'99;i=xyz:p=?;{qr}'])
|
||||
reset()
|
||||
h('p=?')
|
||||
self.assertFalse(di.notifications)
|
||||
self.ae(ch.responses, [f'99;i=0:p=?;{qr}'])
|
||||
|
||||
# Test MIME streaming
|
||||
for padding in (True, False):
|
||||
for extra in ('a', 'ab', 'abc', 'abcd'):
|
||||
text = 'some reasonably long text to test MIME streaming with: '
|
||||
encoded = standard_b64encode(text.encode()).decode()
|
||||
if not padding:
|
||||
encoded = encoded.rstrip('=')
|
||||
for t in encoded:
|
||||
h(f'i=s:e=1:d=0;{t}')
|
||||
h(f'i=s:e=1:d=0:p=body;{encoded[:13]}')
|
||||
h(f'i=s:e=1:d=0:p=body;{encoded[13:]}')
|
||||
h('i=s')
|
||||
self.ae(di.notifications, [n(text, text)])
|
||||
reset()
|
||||
|
||||
# Test application name and notification type
|
||||
def e(x):
|
||||
return standard_b64encode(x.encode()).decode()
|
||||
|
||||
h(f'i=t:d=0:f={e("app")}:t={e("1")};title')
|
||||
h(f'i=t:t={e("test")}')
|
||||
self.ae(
|
||||
di.notifications,
|
||||
[
|
||||
n(
|
||||
application_name='app',
|
||||
notification_types=(
|
||||
'1',
|
||||
'test',
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
reset()
|
||||
|
||||
# Test timeout
|
||||
h('w=3;title')
|
||||
self.ae(di.notifications, [n(timeout=3)])
|
||||
reset()
|
||||
|
||||
# Test Disk Cache
|
||||
dc = IconDataCache(base_cache_dir=tdir, max_cache_size=4)
|
||||
cache_dir = dc._ensure_state()
|
||||
for i in range(5):
|
||||
dc.add_icon(str(i), str(i).encode())
|
||||
self.ae(set(dc.keys()), set(map(str, range(1, 5))))
|
||||
del dc
|
||||
self.assertFalse(os.path.exists(cache_dir))
|
||||
|
||||
# Test icons
|
||||
def send_with_icon(data='', n='', g=''):
|
||||
m = ''
|
||||
if n:
|
||||
for x in n.split(','):
|
||||
m += f'n={standard_b64encode(x.encode()).decode()}:'
|
||||
if g:
|
||||
m += f'g=({g}:'
|
||||
h(f'i=9:d=0:{m};title')
|
||||
h(f'i=9:p=icon;{data}')
|
||||
|
||||
dc = nm.icon_data_cache
|
||||
send_with_icon(n='mycon,ic2')
|
||||
self.ae(di.notifications, [n(icon_names=('mycon', 'ic2'))])
|
||||
reset()
|
||||
send_with_icon(g='gid')
|
||||
self.ae(di.notifications, [n()])
|
||||
reset()
|
||||
send_with_icon(g='gid', data='1')
|
||||
self.ae(di.notifications, [n(icon_path=dc.hash(b'1'))])
|
||||
send_with_icon(g='gid', n='moose')
|
||||
self.ae(di.notifications[-1], n(icon_names=('moose',), icon_path=dc.hash(b'1')))
|
||||
send_with_icon(g='gid2', data='2')
|
||||
self.ae(di.notifications[-1], n(icon_path=dc.hash(b'2')))
|
||||
send_with_icon(data='3')
|
||||
self.ae(di.notifications[-1], n(icon_path=dc.hash(b'3')))
|
||||
reset()
|
||||
|
||||
|
||||
class TestNotifications(BaseTest):
|
||||
def test_desktop_notify(self):
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
do_test(self, tdir)
|
||||
|
||||
def test_freedesktop_close_before_created(self):
|
||||
import kitty.fast_data_types as fdt
|
||||
|
||||
sent: list[int] = []
|
||||
closed: list[int] = []
|
||||
replaces: list[object] = []
|
||||
|
||||
def send_notification(**kw: object) -> int:
|
||||
replaces.append(kw['replaces'])
|
||||
sent.append(len(sent) + 1)
|
||||
return sent[-1]
|
||||
|
||||
def close_notification(dbus_id: int) -> bool:
|
||||
closed.append(dbus_id)
|
||||
return True
|
||||
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tdir,
|
||||
patch.multiple(
|
||||
fdt,
|
||||
create=True,
|
||||
dbus_set_notification_callback=lambda *a: None,
|
||||
dbus_send_notification=send_notification,
|
||||
dbus_close_notification=close_notification,
|
||||
),
|
||||
):
|
||||
di = FreeDesktopIntegration(None)
|
||||
ch = Channel()
|
||||
nm = NotificationManager(di, ch, lambda *a, **kw: None, base_cache_dir=tdir)
|
||||
di.notification_manager = nm
|
||||
|
||||
# close requested before the notification daemon replies to Notify
|
||||
nm.handle_notification_cmd(1, 99, 'i=x:c=1;title')
|
||||
nm.handle_notification_cmd(1, 99, 'i=x:p=close;')
|
||||
self.ae(closed, [])
|
||||
self.assertIn('x', nm.in_progress_notification_commands_by_client_id)
|
||||
self.ae(ch.responses, [])
|
||||
di.dispatch_event_from_desktop('created', sent[-1], 101)
|
||||
self.ae(closed, [101])
|
||||
di.dispatch_event_from_desktop('closed', 101, 0)
|
||||
self.assertNotIn('x', nm.in_progress_notification_commands_by_client_id)
|
||||
self.ae(ch.responses, ['99;i=x:p=close;'])
|
||||
self.ae(di.pending_closes, set())
|
||||
|
||||
# replacement sent before the notification being replaced is created
|
||||
closed.clear(), ch.reset()
|
||||
nm.handle_notification_cmd(1, 99, 'i=r;first')
|
||||
first = sent[-1]
|
||||
nm.handle_notification_cmd(1, 99, 'i=r;second')
|
||||
second = sent[-1]
|
||||
self.ae(nm.in_progress_notification_commands_by_client_id['r'].title, 'second')
|
||||
di.dispatch_event_from_desktop('created', first, 201)
|
||||
self.ae(closed, [201])
|
||||
di.dispatch_event_from_desktop('closed', 201, 0)
|
||||
di.dispatch_event_from_desktop('created', second, 202)
|
||||
self.ae(closed, [201])
|
||||
self.ae(nm.in_progress_notification_commands_by_client_id['r'].title, 'second')
|
||||
self.ae(ch.responses, [])
|
||||
nm.handle_notification_cmd(1, 99, 'i=r;third')
|
||||
self.ae(closed, [201]) # replaced via the replaces argument to Notify, not closed
|
||||
self.ae(replaces[-3:], [0, 0, 202])
|
||||
|
||||
# normal close after creation
|
||||
closed.clear(), ch.reset()
|
||||
nm.handle_notification_cmd(1, 99, 'i=y;title')
|
||||
di.dispatch_event_from_desktop('created', sent[-1], 102)
|
||||
self.ae(closed, [])
|
||||
nm.handle_notification_cmd(1, 99, 'i=y:p=close;')
|
||||
self.ae(closed, [102])
|
||||
|
||||
def test_freedesktop_desktop_entry(self):
|
||||
import kitty.fast_data_types as fdt
|
||||
from kitty.xdg import desktop_file_id_for_appname, kitty_desktop_entry, xdg_data_dirs, xdg_data_home
|
||||
|
||||
desktop_entries: list[object] = []
|
||||
|
||||
def send_notification(**kw: object) -> int:
|
||||
desktop_entries.append(kw['desktop_entry'])
|
||||
return len(desktop_entries)
|
||||
|
||||
kitty_desktop_entry.set_override('net.kovidgoyal.kitty')
|
||||
try:
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tdir,
|
||||
patch.multiple(
|
||||
fdt,
|
||||
create=True,
|
||||
dbus_set_notification_callback=lambda *a: None,
|
||||
dbus_send_notification=send_notification,
|
||||
dbus_close_notification=lambda *a: True,
|
||||
),
|
||||
):
|
||||
di = FreeDesktopIntegration(None)
|
||||
nm = NotificationManager(di, Channel(), lambda *a, **kw: None, base_cache_dir=tdir)
|
||||
di.notification_manager = nm
|
||||
nm.handle_notification_cmd(1, 99, 'i=a;title')
|
||||
nm.handle_notification_cmd(1, 99, f'i=b:f={standard_b64encode(b"kitty").decode()};title')
|
||||
nm.handle_notification_cmd(1, 99, f'i=c:f={standard_b64encode(b"nvim").decode()};title')
|
||||
self.ae(desktop_entries, ['net.kovidgoyal.kitty', 'net.kovidgoyal.kitty', ''])
|
||||
finally:
|
||||
kitty_desktop_entry.clear_override()
|
||||
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
home, sysdir = os.path.join(tdir, 'home'), os.path.join(tdir, 'sys')
|
||||
for x in (os.path.join(home, 'applications', 'sub'), os.path.join(sysdir, 'applications')):
|
||||
os.makedirs(x)
|
||||
|
||||
def touch(*parts: str) -> None:
|
||||
open(os.path.join(*parts), 'w').close()
|
||||
|
||||
xdg_data_home.set_override(home)
|
||||
xdg_data_dirs.set_override((sysdir,))
|
||||
try:
|
||||
self.ae(desktop_file_id_for_appname('kitty'), '')
|
||||
touch(sysdir, 'applications', 'other.desktop')
|
||||
touch(home, 'applications', 'sub', 'net.kovidgoyal.kitty.desktop')
|
||||
self.ae(desktop_file_id_for_appname('kitty'), 'sub-net.kovidgoyal.kitty')
|
||||
touch(sysdir, 'applications', 'kitty.desktop')
|
||||
self.ae(desktop_file_id_for_appname('kitty'), 'kitty')
|
||||
finally:
|
||||
xdg_data_home.clear_override()
|
||||
xdg_data_dirs.clear_override()
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import subprocess
|
||||
|
||||
from kitty.constants import kitten_exe
|
||||
|
||||
from .base import PTY, BaseTest
|
||||
|
||||
|
||||
class TestNotify(BaseTest):
|
||||
def test_notify_close_escape_code(self):
|
||||
for title in ([], ['']):
|
||||
for wait in ([], ['--wait-till-closed']):
|
||||
with self.subTest(title=title, wait=wait):
|
||||
p = subprocess.run(
|
||||
[kitten_exe(), 'notify', '--only-print-escape-code', '--identifier=test', *wait, *title],
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
self.ae(p.returncode, 0, p.stderr)
|
||||
self.ae(p.stdout, b'\x1b]99;i=test:p=close;\x1b\\')
|
||||
|
||||
def test_notify_close_requires_identifier(self):
|
||||
for args, error in (([], b'non-empty TITLE'), ([''], b'non-empty TITLE'), (['--identifier=invalid:id'], b'Invalid identifier')):
|
||||
with self.subTest(args=args):
|
||||
p = subprocess.run([kitten_exe(), 'notify', '--only-print-escape-code', *args], capture_output=True, timeout=10)
|
||||
self.ae(p.returncode, 1)
|
||||
self.ae(p.stdout, b'')
|
||||
self.assertIn(error, p.stderr)
|
||||
|
||||
def test_notify_close_terminal(self):
|
||||
with PTY([kitten_exe(), 'notify', '--identifier=test']) as pty:
|
||||
pty.wait_till(lambda: bool(pty.callbacks.notifications))
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
self.ae(pty.callbacks.notifications, [(99, 'i=test:p=close;')])
|
||||
|
||||
def test_notify_close_wait(self):
|
||||
for title, response in (([], 'alive'), ([''], 'close')):
|
||||
with self.subTest(title=title), PTY([kitten_exe(), 'notify', '--identifier=test', '--wait-till-closed', *title]) as pty:
|
||||
messages = pty.callbacks.notifications
|
||||
pty.wait_till(lambda: bool(messages))
|
||||
self.ae(messages[0], (99, 'i=test:p=close;'))
|
||||
pty.wait_till(lambda: (99, 'i=test:p=alive;') in messages)
|
||||
self.ae(messages, [(99, 'i=test:p=close;'), (99, 'i=test:p=alive;')])
|
||||
messages.clear()
|
||||
pty.write_to_child('\x1b]99;i=test:p=alive;test\x1b\\')
|
||||
pty.wait_till(lambda: bool(messages))
|
||||
self.ae(messages, [(99, 'i=test:p=alive;')])
|
||||
pty.write_to_child(f'\x1b]99;i=test:p={response};\x1b\\')
|
||||
pty.wait_till_child_exits(require_exit_code=0)
|
||||
self.assertTrue(all(m == (99, 'i=test:p=alive;') for m in messages))
|
||||
@@ -0,0 +1,356 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
|
||||
from kitty.utils import get_editor
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
@contextmanager
|
||||
def patch_env(**kw):
|
||||
orig = os.environ.copy()
|
||||
for k, v in kw.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
yield
|
||||
os.environ.clear()
|
||||
os.environ.update(orig)
|
||||
|
||||
|
||||
class TestOpenActions(BaseTest):
|
||||
def test_parsing_of_open_actions(self):
|
||||
from kitty.open_actions import KeyAction, actions_for_url
|
||||
|
||||
self.set_options()
|
||||
spec = """
|
||||
protocol file
|
||||
mime text/*
|
||||
fragment_matches .
|
||||
AcTion launch $EDITOR $FILE_PATH $FRAGMENT
|
||||
action
|
||||
|
||||
protocol file
|
||||
mime text/*
|
||||
action ignored
|
||||
|
||||
ext py,txt
|
||||
action one
|
||||
action two
|
||||
"""
|
||||
|
||||
def actions(url):
|
||||
with patch_env(FILE_PATH='notgood'):
|
||||
return tuple(actions_for_url(url, spec))
|
||||
|
||||
def single(url, func, *args):
|
||||
acts = actions(url)
|
||||
self.ae(len(acts), 1)
|
||||
self.ae(acts[0].func, func)
|
||||
self.ae(acts[0].args, args)
|
||||
|
||||
single('file://hostname/tmp/moo.txt#23', 'launch', *get_editor(), '/tmp/moo.txt', '23')
|
||||
single('some thing.txt', 'ignored')
|
||||
self.ae(actions('x:///a.txt'), (KeyAction('one', ()), KeyAction('two', ())))
|
||||
|
||||
def test_config_dir_files_ignored(self):
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.colors import ThemeColors, ThemeFile
|
||||
from kitty.constants import config_dir_files_ignored, set_ignore_config_dir_files
|
||||
from kitty.guess_mime_type import clear_mime_cache, user_mime_map
|
||||
from kitty.open_actions import clear_caches, load_launch_actions, load_open_actions
|
||||
|
||||
self.set_options()
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
for name in (ThemeFile.dark.value, ThemeFile.light.value):
|
||||
with open(os.path.join(tdir, name), 'w') as f:
|
||||
f.write('background #123456\n')
|
||||
for name in ('open-actions.conf', 'launch-actions.conf'):
|
||||
with open(os.path.join(tdir, name), 'w') as f:
|
||||
f.write('protocol file\naction one\n')
|
||||
with open(os.path.join(tdir, 'mime.types'), 'w') as f:
|
||||
f.write('text/x-kitty-test kittytest\n')
|
||||
|
||||
def check(ignored: bool) -> None:
|
||||
clear_caches()
|
||||
clear_mime_cache()
|
||||
set_ignore_config_dir_files(ignored)
|
||||
try:
|
||||
self.ae(config_dir_files_ignored(), ignored)
|
||||
tc = ThemeColors()
|
||||
self.ae(tc.refresh(), not ignored)
|
||||
self.ae(tc.has_dark_theme, not ignored)
|
||||
self.ae(tc.has_light_theme, not ignored)
|
||||
self.ae(bool(load_open_actions()), not ignored)
|
||||
self.ae(bool(load_launch_actions()), not ignored)
|
||||
self.ae('.kittytest' in user_mime_map(), not ignored)
|
||||
finally:
|
||||
set_ignore_config_dir_files(False)
|
||||
clear_caches()
|
||||
clear_mime_cache()
|
||||
|
||||
with patch('kitty.colors.config_dir', tdir), patch('kitty.open_actions.config_dir', tdir), patch('kitty.constants.config_dir', tdir):
|
||||
check(False)
|
||||
check(True)
|
||||
|
||||
def test_auto_theme_file_deletion(self):
|
||||
import shutil
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.colors import ThemeColors, ThemeFile, theme_file_schemes
|
||||
|
||||
self.set_options()
|
||||
boss = SimpleNamespace(args=SimpleNamespace(debug_rendering=False))
|
||||
for theme in ThemeFile:
|
||||
scheme = theme_file_schemes[theme.value]
|
||||
for remove_directory in (False, True):
|
||||
with self.subTest(theme=theme.name, remove_directory=remove_directory), tempfile.TemporaryDirectory() as tdir:
|
||||
config_dir = os.path.join(tdir, 'kitty')
|
||||
os.mkdir(config_dir)
|
||||
for other in ThemeFile:
|
||||
with open(os.path.join(config_dir, other.value), 'w') as f:
|
||||
f.write('background #123456\nbackground_image /tmp/kitty-auto-theme.png\ntransparent_background_colors #234567@0.5\n')
|
||||
with (
|
||||
patch('kitty.colors.config_dir', config_dir),
|
||||
patch('kitty.colors.config_dir_files_ignored', return_value=False),
|
||||
patch('kitty.colors.get_boss', return_value=boss),
|
||||
patch('kitty.colors.patch_colors') as apply,
|
||||
):
|
||||
tc = ThemeColors()
|
||||
self.assertTrue(tc.refresh())
|
||||
self.assertTrue(tc.apply_theme(scheme))
|
||||
mtime = tc.themes[scheme].mtime
|
||||
apply.reset_mock()
|
||||
if remove_directory:
|
||||
shutil.rmtree(config_dir)
|
||||
else:
|
||||
os.unlink(os.path.join(config_dir, theme.value))
|
||||
changed = tc.refresh()
|
||||
self.assertFalse(tc.apply_theme(scheme), 'Deleted automatic theme was applied again')
|
||||
self.assertFalse(tc.has_applied_theme)
|
||||
self.ae(tc.applied_theme, '')
|
||||
for other in ThemeFile:
|
||||
self.ae(getattr(tc, f'has_{other.name}_theme'), not remove_directory and other is not theme)
|
||||
self.assertFalse(tc.refresh())
|
||||
self.assertFalse(tc.on_system_color_scheme_change(scheme))
|
||||
apply.assert_not_called()
|
||||
self.assertTrue(changed)
|
||||
os.makedirs(config_dir, exist_ok=True)
|
||||
path = os.path.join(config_dir, theme.value)
|
||||
with open(path, 'w') as f:
|
||||
f.write('background #abcdef\n')
|
||||
os.utime(path, ns=(mtime, mtime))
|
||||
self.assertTrue(tc.refresh())
|
||||
self.assertTrue(tc.apply_theme(scheme))
|
||||
apply.assert_called_once()
|
||||
self.ae(apply.call_args.args[0]['background'], 0xABCDEF)
|
||||
self.ae(apply.call_args.args[1], ())
|
||||
self.ae(apply.call_args.kwargs['background_image_options']['background_image'], ())
|
||||
self.assertFalse(tc.refresh())
|
||||
|
||||
def test_auto_theme_config_reload(self):
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.colors import ThemeColors, ThemeFile
|
||||
|
||||
self.set_options()
|
||||
boss = SimpleNamespace(args=SimpleNamespace(debug_rendering=False))
|
||||
with tempfile.TemporaryDirectory() as config_dir:
|
||||
path = os.path.join(config_dir, ThemeFile.dark.value)
|
||||
with (
|
||||
patch('kitty.colors.config_dir', config_dir),
|
||||
patch('kitty.colors.config_dir_files_ignored', return_value=False),
|
||||
patch('kitty.colors.get_boss', return_value=boss),
|
||||
patch('kitty.colors.glfw_get_system_color_theme', return_value='dark'),
|
||||
patch('kitty.colors.patch_colors') as apply,
|
||||
):
|
||||
tc = ThemeColors()
|
||||
# No theme file: reloading applies nothing
|
||||
tc.on_config_reload()
|
||||
apply.assert_not_called()
|
||||
self.ae(tc.applied_theme, '')
|
||||
# A theme file created after startup is applied on reload
|
||||
with open(path, 'w') as f:
|
||||
f.write('background #111111\n')
|
||||
tc.on_config_reload()
|
||||
apply.assert_called_once()
|
||||
self.ae(apply.call_args.args[0]['background'], 0x111111)
|
||||
self.ae(tc.applied_theme, 'dark')
|
||||
# Deleting it stops it from being applied
|
||||
apply.reset_mock()
|
||||
os.unlink(path)
|
||||
tc.on_config_reload()
|
||||
apply.assert_not_called()
|
||||
self.ae(tc.applied_theme, '')
|
||||
# Re-creating it applies it again
|
||||
with open(path, 'w') as f:
|
||||
f.write('background #222222\n')
|
||||
tc.on_config_reload()
|
||||
apply.assert_called_once()
|
||||
self.ae(apply.call_args.args[0]['background'], 0x222222)
|
||||
self.ae(tc.applied_theme, 'dark')
|
||||
# A theme only for a different color scheme is not applied
|
||||
apply.reset_mock()
|
||||
os.rename(path, os.path.join(config_dir, ThemeFile.light.value))
|
||||
tc.on_config_reload()
|
||||
apply.assert_not_called()
|
||||
self.ae(tc.applied_theme, '')
|
||||
self.assertTrue(tc.has_light_theme)
|
||||
self.assertFalse(tc.has_dark_theme)
|
||||
|
||||
def test_mime_cache(self):
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from kitty.fast_data_types import clear_mime_cache_data, mime_type_aliases, mime_type_for_filename
|
||||
from kitty.guess_mime_type import guess_type, mime_types_for_matching
|
||||
from kitty.open_actions import KeyAction, actions_for_url
|
||||
|
||||
if not shutil.which('update-mime-database'):
|
||||
self.skipTest('update-mime-database not available')
|
||||
|
||||
def build_cache(data_dir: str, xml: str) -> None:
|
||||
pkgs = os.path.join(data_dir, 'mime', 'packages')
|
||||
os.makedirs(pkgs)
|
||||
with open(os.path.join(pkgs, 'kitty-test.xml'), 'w') as f:
|
||||
f.write(MIME_CACHE_TEST_PACKAGE.replace('MIME_TYPES', xml))
|
||||
with patch_env(PKGSYSTEM_ENABLE_FSYNC='0'):
|
||||
subprocess.run(['update-mime-database', os.path.join(data_dir, 'mime')], check=True, capture_output=True)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
user, system = os.path.join(tdir, 'user'), os.path.join(tdir, 'system')
|
||||
build_cache(system, MIME_CACHE_TEST_TYPES)
|
||||
build_cache(
|
||||
user,
|
||||
(
|
||||
'<mime-type type="text/x-kt-user"><glob pattern="*.kuser"/><glob pattern="*.kext.override"/></mime-type>'
|
||||
'<mime-type type="text/x-kt-ext"><alias type="text/x-kt-user-alias"/></mime-type>'
|
||||
),
|
||||
)
|
||||
build_cache(os.path.join(tdir, 'ignored'), '<mime-type type="text/x-kt-ignored"><glob pattern="*.kuser"/></mime-type>')
|
||||
try:
|
||||
with patch_env(XDG_DATA_HOME=user, XDG_DATA_DIRS=f'relative/dir:{system}/:{tdir}/missing:{tdir}/ignored'):
|
||||
clear_mime_cache_data()
|
||||
for name, expected in MIME_CACHE_TEST_EXPECTATIONS.items():
|
||||
self.ae(mime_type_for_filename(name), expected, name)
|
||||
self.ae(guess_type('/a/b.kext'), 'text/x-kt-ext')
|
||||
self.ae(guess_type('/a/b.kjson'), 'text/json')
|
||||
self.assertRaises(TypeError, mime_type_for_filename, b'a.kext')
|
||||
|
||||
# aliases
|
||||
ext_names = ('text/x-kt-ext', 'text/x-kt-user-alias', 'application/x-kt-older', 'text/x-kt-old')
|
||||
self.ae(mime_type_aliases('text/x-kt-ext'), ext_names)
|
||||
self.ae(mime_type_aliases('text/x-kt-old'), ext_names)
|
||||
self.ae(mime_type_aliases('unknown/x-kt'), ('unknown/x-kt',))
|
||||
self.assertRaises(TypeError, mime_type_aliases, b'text/x-kt-ext')
|
||||
self.ae(mime_types_for_matching('b.kjson', 'text/json'), {'text/json', 'application/json', 'application/x-kt-json'})
|
||||
self.ae(guess_type('/a/Makefile'), 'text/x-kt-make')
|
||||
self.ae(mime_types_for_matching('/a/Makefile', 'text/x-kt-make'), {'text/x-kt-make', 'text/makefile'})
|
||||
self.set_options()
|
||||
spec = """
|
||||
mime text/x-kt-old
|
||||
action old
|
||||
|
||||
mime text/MakeFile
|
||||
action make
|
||||
|
||||
mime image/*, application/x-kt-j*
|
||||
action json
|
||||
"""
|
||||
for url, action in {'/tmp/b.kext': 'old', 'file:///tmp/Makefile': 'make', 'b.kjson': 'json', 'b.kuser': ''}.items():
|
||||
self.ae(tuple(actions_for_url(url, spec)), (KeyAction(action, ()),) if action else (), url)
|
||||
truncated = os.path.join(tdir, 'truncated')
|
||||
os.makedirs(os.path.join(truncated, 'mime'))
|
||||
with open(os.path.join(system, 'mime', 'mime.cache'), 'rb') as src, open(os.path.join(truncated, 'mime', 'mime.cache'), 'wb') as dest:
|
||||
dest.write(src.read()[:48])
|
||||
with patch_env(XDG_DATA_HOME=truncated, XDG_DATA_DIRS=f'{tdir}/missing'):
|
||||
clear_mime_cache_data()
|
||||
self.assertIsNone(mime_type_for_filename('a.kext'))
|
||||
|
||||
# strings in the cache that are not valid UTF-8 are ignored
|
||||
invalid = os.path.join(tdir, 'invalid')
|
||||
os.makedirs(os.path.join(invalid, 'mime'))
|
||||
with open(os.path.join(system, 'mime', 'mime.cache'), 'rb') as src, open(os.path.join(invalid, 'mime', 'mime.cache'), 'wb') as dest:
|
||||
data = src.read()
|
||||
self.assertIn(b'text/x-kt-ext\0', data)
|
||||
dest.write(data.replace(b'text/x-kt-ext\0', b'text/x-kt-\xffxt\0'))
|
||||
with patch_env(XDG_DATA_HOME=invalid, XDG_DATA_DIRS=f'{tdir}/missing'):
|
||||
clear_mime_cache_data()
|
||||
self.assertIsNone(mime_type_for_filename('a.kext'))
|
||||
self.ae(mime_type_for_filename('a.kjson'), 'application/json')
|
||||
self.ae(mime_type_aliases('text/x-kt-old'), ('application/x-kt-older', 'text/x-kt-old'))
|
||||
guess_type('/a/b.kext')
|
||||
|
||||
# lone surrogates cannot be encoded and so do not match
|
||||
with patch_env(XDG_DATA_HOME=user, XDG_DATA_DIRS=system):
|
||||
clear_mime_cache_data()
|
||||
self.assertIsNone(mime_type_for_filename('a\ud800.kext'))
|
||||
self.ae(mime_type_for_filename('a\udcff.kext'), 'text/x-kt-ext')
|
||||
self.ae(mime_type_aliases('text/\ud800'), ('text/\ud800',))
|
||||
guess_type('/a/b\ud800.kext')
|
||||
finally:
|
||||
clear_mime_cache_data()
|
||||
|
||||
|
||||
MIME_CACHE_TEST_PACKAGE = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
|
||||
MIME_TYPES
|
||||
</mime-info>
|
||||
"""
|
||||
|
||||
# Keep in sync with tools/utils/mime_cache_test.go
|
||||
MIME_CACHE_TEST_TYPES = """
|
||||
<mime-type type="text/x-kt-literal"><glob pattern="KittyLiteral"/></mime-type>
|
||||
<mime-type type="text/x-kt-cs"><glob pattern="*.KCS" case-sensitive="true"/></mime-type>
|
||||
<mime-type type="text/x-kt-ext"><glob pattern="*.kext"/><alias type="text/x-kt-old"/><alias type="application/x-kt-older"/></mime-type>
|
||||
<mime-type type="text/x-kt-long"><glob pattern="*.long.kext"/></mime-type>
|
||||
<mime-type type="text/x-kt-light"><glob pattern="*.kw" weight="40"/></mime-type>
|
||||
<mime-type type="text/x-kt-heavy"><glob pattern="*.kw" weight="80"/></mime-type>
|
||||
<mime-type type="text/x-kt-glob"><glob pattern="kglob[0-9].*"/></mime-type>
|
||||
<mime-type type="text/x-kt-negated-glob"><glob pattern="kneg[!0-9].*"/></mime-type>
|
||||
<mime-type type="text/x-kt-unicode"><glob pattern="*.kü"/></mime-type>
|
||||
<mime-type type="application/json"><glob pattern="*.kjson"/><alias type="application/x-kt-json"/></mime-type>
|
||||
<mime-type type="text/x-kt-make"><glob pattern="Makefile" case-sensitive="true"/></mime-type>
|
||||
<mime-type type="text/x-kt-system"><glob pattern="*.kuser"/></mime-type>
|
||||
"""
|
||||
|
||||
MIME_CACHE_TEST_EXPECTATIONS = {
|
||||
'KittyLiteral': 'text/x-kt-literal',
|
||||
'kittyliteral': 'text/x-kt-literal',
|
||||
'KITTYLITERAL': 'text/x-kt-literal',
|
||||
'xKittyLiteral': None,
|
||||
'a.KCS': 'text/x-kt-cs',
|
||||
'a.kcs': None,
|
||||
'a.kext': 'text/x-kt-ext',
|
||||
'A.KEXT': 'text/x-kt-ext',
|
||||
'/some/dir/a.kext': 'text/x-kt-ext',
|
||||
'dir.kext/noext': None,
|
||||
'x.long.kext': 'text/x-kt-long',
|
||||
'x.LONG.KEXT': 'text/x-kt-long',
|
||||
'xlong.kext': 'text/x-kt-ext',
|
||||
'a.kw': 'text/x-kt-heavy',
|
||||
'kglob1.txt': 'text/x-kt-glob',
|
||||
'KGLOB1.TXT': 'text/x-kt-glob',
|
||||
'kglobx.txt': None,
|
||||
'knegx.txt': 'text/x-kt-negated-glob',
|
||||
'kneg1.txt': None,
|
||||
'a.kü': 'text/x-kt-unicode',
|
||||
'a.KÜ': 'text/x-kt-unicode',
|
||||
'a.kuser': 'text/x-kt-user',
|
||||
'a.kext.override': 'text/x-kt-user',
|
||||
'': None,
|
||||
'a\0.kext': None,
|
||||
'notmatched': None,
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from kitty.constants import kitty_exe
|
||||
from kitty.fast_data_types import Color, test_cursor_blink_easing_function
|
||||
from kitty.options.utils import DELETE_ENV_VAR, EasingFunction, build_action_aliases, to_color
|
||||
from kitty.utils import log_error, shlex_split
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestConfParsing(BaseTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.error_messages = []
|
||||
log_error.redirect = self.error_messages.append
|
||||
self.tdir = tempfile.mkdtemp()
|
||||
|
||||
def tearDown(self):
|
||||
del log_error.redirect
|
||||
shutil.rmtree(self.tdir)
|
||||
super().tearDown()
|
||||
|
||||
def test_conf_parsing(self):
|
||||
conf_parsing(self)
|
||||
|
||||
def test_launcher(self):
|
||||
launcher(self)
|
||||
|
||||
def test_cli_parsing(self):
|
||||
cli_parsing(self)
|
||||
|
||||
def test_font_size_clamping(self):
|
||||
font_size_clamping(self)
|
||||
|
||||
def test_session_launch_option_expansion(self) -> None:
|
||||
from kitty.launch import LaunchSpec
|
||||
from kitty.options.types import defaults
|
||||
from kitty.session import parse_session
|
||||
|
||||
for command in (
|
||||
'--title bash --cwd $SESSION_DIR bash $COMMAND_ARG',
|
||||
'--title=bash --cwd=$SESSION_DIR bash $COMMAND_ARG',
|
||||
'--title bash --cwd $SESSION_DIR -- bash $COMMAND_ARG',
|
||||
'--title other --cwd $SESSION_DIR bash $COMMAND_ARG',
|
||||
):
|
||||
with self.subTest(command=command):
|
||||
(session,) = parse_session(f'launch {command}', defaults, environ={'SESSION_DIR': '/tmp/session', 'COMMAND_ARG': 'expanded'})
|
||||
spec = session.tabs[0].windows[0].launch_spec
|
||||
assert isinstance(spec, LaunchSpec)
|
||||
self.ae(spec.opts.cwd, '/tmp/session')
|
||||
self.ae(spec.args, ['bash', '$COMMAND_ARG'])
|
||||
|
||||
def test_session_discovery(self):
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.config import load_config
|
||||
from kitty.constants import config_dir
|
||||
from kitty.fast_data_types import set_options
|
||||
from kitty.session import get_all_known_sessions, seen_session_paths
|
||||
|
||||
def discover(*lines):
|
||||
bad_lines = []
|
||||
opts = load_config(overrides=('clear_all_shortcuts yes', *lines), accumulate_bad_lines=bad_lines)
|
||||
self.assertFalse(bad_lines)
|
||||
set_options(opts)
|
||||
return get_all_known_sessions()
|
||||
|
||||
with patch.dict(seen_session_paths, {}, clear=True):
|
||||
for args, name in (
|
||||
('work.kitty-session', 'work'),
|
||||
('--sort-by alphabetical work.kitty-session', 'work'),
|
||||
('--sort-by=alphabetical work.kitty-session', 'work'),
|
||||
('--active-only=no --sort-by recent work.kitty-session', 'work'),
|
||||
('work.kitty-session --sort-by alphabetical', 'work'),
|
||||
('-- "-work project.kitty-session"', '-work project'),
|
||||
('-- -0', '-0'),
|
||||
('', ''),
|
||||
('--sort-by alphabetical', ''),
|
||||
('--sort-by=alphabetical', ''),
|
||||
('--active-only', ''),
|
||||
('-1', ''),
|
||||
('-- -1', ''),
|
||||
('--sort-by alphabetical -- -2', ''),
|
||||
('--sort-by', ''),
|
||||
('--sort-by invalid work.kitty-session', ''),
|
||||
('--unknown work.kitty-session', ''),
|
||||
('--active-only=invalid work.kitty-session', ''),
|
||||
):
|
||||
with self.subTest(args=args):
|
||||
filename = f'{name}.kitty-session' if name != '-0' else name
|
||||
expected = {name: os.path.join(config_dir, filename)} if name else {}
|
||||
self.ae(discover(f'map f7 goto_session {args}'), expected)
|
||||
|
||||
seen_path = os.path.join(self.tdir, 'work.kitty-session')
|
||||
seen_session_paths['work'] = seen_path
|
||||
self.ae(
|
||||
discover(
|
||||
'action_alias project goto_session --sort-by alphabetical',
|
||||
'map f7 project work.kitty-session',
|
||||
'map f8 combine : goto_session --sort-by : project other.kitty-session',
|
||||
),
|
||||
{'work': seen_path, 'other': os.path.join(config_dir, 'other.kitty-session')},
|
||||
)
|
||||
|
||||
def test_launch_transparent_color_overrides(self) -> None:
|
||||
from kitty.launch import apply_colors
|
||||
from kitty.window import Window
|
||||
|
||||
cases = (
|
||||
(('transparent_background_colors=#ffffff@0.5', 'foreground=red'), ((Color(255, 255, 255), 0.5),)),
|
||||
(('foreground=red', 'transparent_background_colors=#ffffff@0.5'), ((Color(255, 255, 255), 0.5),)),
|
||||
(('transparent_background_colors=#ffffff@0.5', 'foreground=red', 'transparent_background_colors='), ()),
|
||||
(('transparent_background_colors=#ffffff@0.5', 'transparent_background_colors=#000000@0.25', 'foreground=red'), ((Color(0, 0, 0), 0.25),)),
|
||||
)
|
||||
for colors, expected in cases:
|
||||
with self.subTest(colors=colors):
|
||||
window = Window.__new__(Window)
|
||||
window.screen = self.create_screen()
|
||||
apply_colors(window, colors)
|
||||
actual = window.screen.color_profile.as_dict()
|
||||
self.ae(actual.get('transparent_background_colors', ()), expected)
|
||||
self.ae(actual['foreground'], 0xFF0000)
|
||||
|
||||
# colors that do not mention transparent_background_colors must leave existing ones unchanged
|
||||
window = Window.__new__(Window)
|
||||
window.screen = self.create_screen()
|
||||
apply_colors(window, ('transparent_background_colors=#ffffff@0.5',))
|
||||
apply_colors(window, ('foreground=red',))
|
||||
self.ae(window.screen.color_profile.as_dict().get('transparent_background_colors', ()), ((Color(255, 255, 255), 0.5),))
|
||||
apply_colors(window, ('transparent_background_colors=',))
|
||||
self.ae(window.screen.color_profile.as_dict().get('transparent_background_colors', ()), ())
|
||||
|
||||
|
||||
def cli_parsing(self):
|
||||
from kitty.cli import CLIOptions, Options, parse_cmdline, parse_option_spec
|
||||
|
||||
seq, disabled = parse_option_spec("""\
|
||||
--simple-string -s
|
||||
a simple string
|
||||
|
||||
|
||||
--list -l
|
||||
type=list
|
||||
a list
|
||||
|
||||
|
||||
--choice -c
|
||||
choices=a,b,c
|
||||
some choices
|
||||
|
||||
|
||||
--bool-set -1
|
||||
type=bool-set
|
||||
set a bool
|
||||
|
||||
|
||||
--bool-reset -0
|
||||
type=bool-reset
|
||||
unset a bool
|
||||
|
||||
|
||||
--int -i
|
||||
type=int
|
||||
a integer
|
||||
|
||||
|
||||
--float -f
|
||||
type=float
|
||||
a float
|
||||
|
||||
|
||||
--version -v
|
||||
type=bool-set
|
||||
version
|
||||
""")
|
||||
oc = Options(seq, usage='xxx', message='yyy', appname='test')
|
||||
oc.do_print = False
|
||||
|
||||
def t(args, leftover=(), fails=False, version_called=False, help_called=False, **expected):
|
||||
oc.help_called = oc.version_called = False
|
||||
args = list(shlex_split(args))
|
||||
ans = CLIOptions()
|
||||
if fails:
|
||||
if isinstance(fails, str):
|
||||
with self.assertRaisesRegex(SystemExit, fails):
|
||||
parse_cmdline(oc, disabled, ans, args=args)
|
||||
else:
|
||||
with self.assertRaises(SystemExit):
|
||||
parse_cmdline(oc, disabled, ans, args=args)
|
||||
else:
|
||||
actual_leftover = parse_cmdline(oc, disabled, ans, args=args)
|
||||
self.assertEqual(tuple(leftover), tuple(actual_leftover), f'{args}\n{ans}')
|
||||
for dest, defval in oc.values_map.items():
|
||||
val = expected.get(dest, defval)
|
||||
self.assertEqual(val, getattr(ans, dest, BaseTest), f'Failed to parse {dest} correctly for: {args}\n{ans}')
|
||||
self.assertEqual(version_called, oc.version_called, f'Failed to call version for: {args}\n{ans}')
|
||||
self.assertEqual(help_called, oc.help_called, f'Failed to call help for: {args}\n{ans}')
|
||||
|
||||
t('-1', bool_set=True)
|
||||
t('-01', bool_reset=False, bool_set=True)
|
||||
t('-01=y', bool_reset=False, bool_set=True)
|
||||
t('-01=n', bool_reset=False, bool_set=False)
|
||||
t('--simple-string xx moo -1', leftover=['moo', '-1'], simple_string='xx')
|
||||
t('--si -0 -- -1', leftover=['-1'], simple_string='-0')
|
||||
t('--simple-string=-0 -- -1', leftover=['-1'], simple_string='-0')
|
||||
t('--simple-string=--help -- -1', leftover=['-1'], simple_string='--help')
|
||||
t('--simple-string --help -- -1', leftover=['-1'], simple_string='--help')
|
||||
t('-1l=a --list=b -c b --list c', bool_set=True, choice='b', list=list('abc'))
|
||||
t('-1s= -l "" --list= x', leftover=['x'], bool_set=True, simple_string='', list=['', ''])
|
||||
t('--choice moo', fails=r'moo')
|
||||
t('--bool', fails='mbiguous')
|
||||
t('-1c moo', fails=r'moo')
|
||||
t('-10c=moo', fails=r'moo')
|
||||
t('-1 -h', fails=True, help_called=True)
|
||||
t('-1 --help', fails=True, help_called=True)
|
||||
t('-1 -0v', fails=True, version_called=True)
|
||||
t('-1 -v0', fails=True, version_called=True)
|
||||
t('-1 --version', fails=True, version_called=True)
|
||||
t('-f=3.142 --int 17', float=3.142, int=17)
|
||||
|
||||
|
||||
def font_size_clamping(self: 'BaseTest') -> None:
|
||||
from kitty.options.utils import MAXIMUM_FONT_SIZE, MINIMUM_FONT_SIZE, clamp_font_size
|
||||
|
||||
# the floor applies whatever the configured size
|
||||
self.ae(clamp_font_size(0, 11), MINIMUM_FONT_SIZE)
|
||||
self.ae(clamp_font_size(-100, 11), MINIMUM_FONT_SIZE)
|
||||
|
||||
# sizes inside the range come back untouched
|
||||
self.ae(clamp_font_size(11, 11), 11)
|
||||
self.ae(clamp_font_size(64, 11), 64)
|
||||
|
||||
# the ceiling is the larger of the multiple and the absolute maximum, so a
|
||||
# small configured size no longer implies a small maximum zoom
|
||||
self.ae(clamp_font_size(1e6, 4), MAXIMUM_FONT_SIZE)
|
||||
self.ae(clamp_font_size(1e6, 11), MAXIMUM_FONT_SIZE)
|
||||
self.ae(clamp_font_size(200, 4), 200)
|
||||
|
||||
# a large configured size keeps its proportional ceiling
|
||||
self.ae(clamp_font_size(1e6, 40), 400)
|
||||
self.ae(clamp_font_size(1e6, 100), 1000)
|
||||
|
||||
# and the ceiling is never below the absolute maximum
|
||||
for configured in (1, 4, 11, 25.6, 40, 100):
|
||||
self.assertGreaterEqual(clamp_font_size(1e6, configured), MAXIMUM_FONT_SIZE)
|
||||
|
||||
|
||||
def launcher(self):
|
||||
import tempfile
|
||||
|
||||
from kitty.constants import is_macos
|
||||
|
||||
kexe = kitty_exe()
|
||||
cfgdir = None
|
||||
|
||||
def get_report(cmdline: str, launch_services=False, config_dir: str = ''):
|
||||
nonlocal cfgdir
|
||||
args = list(shlex_split(cmdline))
|
||||
env = dict(os.environ)
|
||||
if launch_services:
|
||||
env['KITTY_LAUNCHED_BY_LAUNCH_SERVICES'] = '1'
|
||||
if config_dir:
|
||||
env['KITTY_CONFIG_DIRECTORY'] = config_dir
|
||||
cp = subprocess.run([kexe, '+testing-launcher-code'] + args, env=env, stdout=subprocess.PIPE)
|
||||
self.assertEqual(cp.returncode, 0)
|
||||
ans = {}
|
||||
for line in cp.stdout.decode().split('\n'):
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
key, val = line.split(':')
|
||||
except ValueError:
|
||||
raise AssertionError(f'Unexpected output from launcher: {line!r}\n{cp.stdout.decode()}')
|
||||
if '\x1e' in val:
|
||||
val = [x for x in val.split('\x1e') if x]
|
||||
else:
|
||||
val = val.strip()
|
||||
ans[key] = val
|
||||
if key == 'config_dir':
|
||||
cfgdir = val
|
||||
return ans, cp.stdout.decode().replace('\x1e', ' ')
|
||||
|
||||
def test(cmdline, assertions):
|
||||
r, output = get_report(cmdline, launch_services=assertions.get('launched_by_launch_services', '0') != '0')
|
||||
for key, expected in assertions.items():
|
||||
self.assertEqual(expected, r.get(key), f'Failed for {key} with command line: {cmdline}\nOutput:\n{output}')
|
||||
return output
|
||||
|
||||
def t(cmdline, **assertions):
|
||||
assertions['is_quick_access_terminal'] = '0'
|
||||
if cfgdir:
|
||||
assertions['config_dir'] = cfgdir
|
||||
assertions.setdefault('launched_by_launch_services', '0')
|
||||
test(cmdline, assertions)
|
||||
|
||||
def si(cmdline, **assertions):
|
||||
assertions['single_instance'] = '1'
|
||||
test(cmdline, assertions)
|
||||
|
||||
def dt(cmdline, **assertions):
|
||||
assertions['detach'] = 'true'
|
||||
test(cmdline, assertions)
|
||||
|
||||
def k(cmdline):
|
||||
assertions = {}
|
||||
assertions['argv'] = ['kitten'] + cmdline.split()
|
||||
for prefix in ('+kitten', '+ kitten'):
|
||||
output = test(prefix + ' ' + cmdline, assertions)
|
||||
self.assertIn('kitten_exe:', output)
|
||||
|
||||
def pn(cmdline, **assertions):
|
||||
ig = assertions.get('instance_group')
|
||||
assertions['instance_group'] = f'panel-{ig}' if ig else 'panel'
|
||||
assertions['single_instance'] = '1'
|
||||
assertions['session'] = ''
|
||||
test(cmdline, assertions)
|
||||
|
||||
t('', original_argv=[kexe], argv=[])
|
||||
t(
|
||||
'--title=xxx --start-as maximized -c=a -c b cat',
|
||||
title='xxx',
|
||||
start_as='maximized',
|
||||
config=['a', 'b'],
|
||||
original_argv=[kexe, '--title=xxx', '--start-as', 'maximized', '-c=a', '-c', 'b', 'cat'],
|
||||
argv=['cat'],
|
||||
)
|
||||
k('icat abc xyz')
|
||||
t('+kitten unwrapped xyz', argv=['+kitten', 'unwrapped', 'xyz'])
|
||||
t('+ kitten unwrapped xyz', original_argv=[kexe, '+', 'kitten', 'unwrapped', 'xyz'])
|
||||
si('--single-instance --instance-group=g -T 3', argv=[kexe, '--single-instance', '--instance-group=g', '-T', '3'])
|
||||
t('+open --help', argv=['+open', '--help'])
|
||||
t('+open -1 --help', argv=['+open', '-1', '--help'])
|
||||
si('+open -1 moose', argv=[kexe, '+open', '-1', 'moose'], open_urls=['moose'])
|
||||
si('+open -1 --instance-group=g x y', instance_group='g', open_urls=['x', 'y'])
|
||||
dt('--detach --session=moose --detached-log=xyz', detached_log='xyz', session='moose')
|
||||
pn('+kitten panel -1 --edge=left', edge='left')
|
||||
|
||||
if is_macos:
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
with open(tdir + '/macos-launch-services-cmdline', 'w') as f:
|
||||
f.write('kitty --title from-file\n')
|
||||
# File args are used when launched by launch services
|
||||
r, output = get_report('', launch_services=True, config_dir=tdir)
|
||||
self.assertEqual(r.get('title'), 'from-file', f'Expected title=from-file in:\n{output}')
|
||||
# User args passed via open --args are appended after file args (and override them)
|
||||
r, output = get_report('--title from-args', launch_services=True, config_dir=tdir)
|
||||
self.assertEqual(r.get('title'), 'from-args', f'Expected title=from-args to override from-file in:\n{output}')
|
||||
|
||||
|
||||
def conf_parsing(self):
|
||||
from kitty.config import defaults, load_config
|
||||
from kitty.constants import is_macos
|
||||
from kitty.fast_data_types import LEFT_EDGE, RIGHT_EDGE
|
||||
from kitty.fonts import FontModification, ModificationType, ModificationUnit, ModificationValue
|
||||
from kitty.options.utils import to_modifiers
|
||||
|
||||
bad_lines = []
|
||||
|
||||
def p(*lines, bad_line_num=0, num_err=None):
|
||||
del bad_lines[:]
|
||||
del self.error_messages[:]
|
||||
ans = load_config(overrides=lines, accumulate_bad_lines=bad_lines)
|
||||
if bad_line_num:
|
||||
self.ae(len(bad_lines), bad_line_num)
|
||||
else:
|
||||
self.assertFalse(bad_lines)
|
||||
if num_err is not None:
|
||||
self.ae(len(self.error_messages), num_err, '\n'.join(self.error_messages))
|
||||
return ans
|
||||
|
||||
def keys_for_func(opts, name):
|
||||
for key, defns in opts.keyboard_modes[''].keymap.items():
|
||||
for action in opts.alias_map.resolve_aliases(defns[0].definition):
|
||||
if action.func == name:
|
||||
yield key
|
||||
|
||||
opts = p('font_size 11.37', 'clear_all_shortcuts y', 'color23 red')
|
||||
self.ae(opts.font_size, 11.37)
|
||||
radius_opts = p('window_border_radius 7px')
|
||||
self.ae(radius_opts.window_border_radius, (7.0, 'px'))
|
||||
self.ae(defaults.hyperlink_target_position, 'top')
|
||||
for pos in ('top', 'bottom', 'below', 'tooltip'):
|
||||
self.ae(p(f'hyperlink_target_position {pos}').hyperlink_target_position, pos)
|
||||
self.ae(p('hyperlink_target_position xxx', bad_line_num=1).hyperlink_target_position, 'top')
|
||||
radius_opts = p('window_border_radius -2')
|
||||
self.ae(radius_opts.window_border_radius, (0.0, 'pt'))
|
||||
self.ae(opts.mouse_hide_wait[0], 0 if is_macos else 3)
|
||||
self.ae(opts.mouse_hide_wait[1], 0)
|
||||
self.ae(opts.mouse_hide_wait[2], 40)
|
||||
self.ae(opts.mouse_hide_wait[3], True)
|
||||
self.ae(opts.color23, Color(255, 0, 0))
|
||||
self.assertFalse(opts.keyboard_modes[''].keymap)
|
||||
opts = p("url_excluded_characters '''")
|
||||
self.ae(opts.url_excluded_characters, "'''")
|
||||
opts = p("url_excluded_characters abc'")
|
||||
self.ae(opts.url_excluded_characters, "abc'")
|
||||
opts = p('tab_bar_edge left')
|
||||
self.ae(opts.tab_bar_edge, LEFT_EDGE)
|
||||
opts = p('tab_bar_edge right')
|
||||
self.ae(opts.tab_bar_edge, RIGHT_EDGE)
|
||||
opts = p('tab_bar_align start')
|
||||
self.ae(opts.tab_bar_align, 'start')
|
||||
opts = p('tab_bar_align end')
|
||||
self.ae(opts.tab_bar_align, 'end')
|
||||
opts = p('tab_bar_align left')
|
||||
self.ae(opts.tab_bar_align, 'left')
|
||||
opts = p('tab_bar_align right')
|
||||
self.ae(opts.tab_bar_align, 'right')
|
||||
opts = p('clear_all_shortcuts y', 'map f1 next_window')
|
||||
self.ae(len(opts.keyboard_modes[''].keymap), 1)
|
||||
opts = p('clear_all_mouse_actions y', 'mouse_map left click ungrabbed mouse_click_url_or_select')
|
||||
self.ae(len(opts.mousemap), 1)
|
||||
opts = p(
|
||||
'clear_all_mouse_actions y',
|
||||
'mouse_map ctrl+wheel_up press ungrabbed,grabbed change_font_size all +1',
|
||||
'mouse_map shift+wheel_right press ungrabbed next_tab',
|
||||
)
|
||||
self.ae(
|
||||
{k.human_repr() for k in opts.mousemap},
|
||||
{'ctrl+wheel_up press ungrabbed', 'ctrl+wheel_up press grabbed', 'shift+wheel_right press ungrabbed'},
|
||||
)
|
||||
opts = p('strip_trailing_spaces always')
|
||||
self.ae(opts.strip_trailing_spaces, 'always')
|
||||
self.assertFalse(bad_lines)
|
||||
opts = p('pointer_shape_when_grabbed XXX', bad_line_num=1)
|
||||
self.ae(opts.pointer_shape_when_grabbed, defaults.pointer_shape_when_grabbed)
|
||||
opts = p('modify_font underline_position -2', 'modify_font underline_thickness 150%', 'modify_font size Test -1px')
|
||||
self.ae(
|
||||
opts.modify_font,
|
||||
{
|
||||
'underline_position': FontModification(ModificationType.underline_position, ModificationValue(-2.0, ModificationUnit.pt)),
|
||||
'underline_thickness': FontModification(ModificationType.underline_thickness, ModificationValue(150, ModificationUnit.percent)),
|
||||
'size:Test': FontModification(ModificationType.size, ModificationValue(-1.0, ModificationUnit.pixel), 'Test'),
|
||||
},
|
||||
)
|
||||
|
||||
# test the aliasing options
|
||||
opts = p('env A=1', 'env B=x$A', 'env C=', 'env D', 'clear_all_shortcuts y', 'kitten_alias a b --moo', 'map f1 kitten a arg')
|
||||
self.ae(opts.env, {'A': '1', 'B': 'x1', 'C': '', 'D': DELETE_ENV_VAR})
|
||||
|
||||
def ac(which=0):
|
||||
ka = tuple(opts.keyboard_modes[''].keymap.values())[0][0]
|
||||
acs = opts.alias_map.resolve_aliases(ka.definition)
|
||||
return acs[which]
|
||||
|
||||
ka = ac()
|
||||
self.ae(ka.func, 'kitten')
|
||||
self.ae(ka.args, ('b', '--moo', 'arg'))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'kitten_alias hints hints --hi', 'map f1 kitten hints XXX')
|
||||
ka = ac()
|
||||
self.ae(ka.func, 'kitten')
|
||||
self.ae(ka.args, ('hints', '--hi', 'XXX'))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'action_alias la launch --moo', 'map f1 la XXX')
|
||||
ka = ac()
|
||||
self.ae(ka.func, 'launch')
|
||||
self.ae(ka.args, ('--moo', 'XXX'))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'action_alias one launch --moo', 'action_alias two one recursive', 'map f1 two XXX')
|
||||
ka = ac()
|
||||
self.ae(ka.func, 'launch')
|
||||
self.ae(ka.args, ('--moo', 'recursive', 'XXX'))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'action_alias launch two 1', 'action_alias two launch 2', 'map f1 launch 3')
|
||||
ka = ac()
|
||||
self.ae(ka.func, 'launch')
|
||||
self.ae(ka.args, ('2', '1', '3'))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'action_alias launch launch --moo', 'map f1 launch XXX')
|
||||
ka = ac()
|
||||
self.ae(ka.func, 'launch')
|
||||
self.ae(ka.args, ('--moo', 'XXX'))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'action_alias cfs change_font_size current', 'map f1 cfs +2')
|
||||
ka = ac()
|
||||
self.ae(ka.func, 'change_font_size')
|
||||
self.ae(ka.args, (False, '+', 2.0))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'action_alias la launch --moo', 'map f1 combine : new_window : la ')
|
||||
self.ae((ac().func, ac(1).func), ('new_window', 'launch'))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'action_alias cc combine : new_window : launch --moo', 'map f1 cc XXX')
|
||||
self.ae((ac().func, ac(1).func), ('new_window', 'launch'))
|
||||
self.ae(ac(1).args, ('--moo', 'XXX'))
|
||||
|
||||
opts = p('clear_all_shortcuts y', 'action_alias ss kitten "space 1"', 'map f1 ss "space 2"')
|
||||
self.ae(ac().args, ('space 1', 'space 2'))
|
||||
|
||||
am = build_action_aliases({'la': 'launch --moo'})
|
||||
self.ae(am.resolve_aliases('la XXX')[0].args, ('--moo', 'XXX'))
|
||||
am.update(build_action_aliases({'la': 'launch --baa'}))
|
||||
self.ae(am.resolve_aliases('la XXX')[0].args, ('--baa', 'XXX'))
|
||||
|
||||
opts = p('kitty_mod alt')
|
||||
self.ae(opts.kitty_mod, to_modifiers('alt'))
|
||||
self.ae(next(keys_for_func(opts, 'next_layout')).mods, opts.kitty_mod)
|
||||
|
||||
opts = p('inactive_text_alpha 0.25')
|
||||
self.ae(opts.inactive_text_alpha, 0.25)
|
||||
opts = p('inactive_text_alpha -0.25')
|
||||
self.ae(opts.inactive_text_alpha, -0.25)
|
||||
opts = p('inactive_text_alpha 2')
|
||||
self.ae(opts.inactive_text_alpha, 1.0)
|
||||
opts = p('inactive_text_alpha -2')
|
||||
self.ae(opts.inactive_text_alpha, -1.0)
|
||||
|
||||
# deprecation handling
|
||||
opts = p('clear_all_shortcuts y', 'send_text all f1 hello')
|
||||
self.ae(len(opts.keyboard_modes[''].keymap), 1)
|
||||
opts = p('macos_hide_titlebar y' if is_macos else 'x11_hide_window_decorations y')
|
||||
self.assertTrue(opts.hide_window_decorations)
|
||||
self.ae(len(self.error_messages), 1)
|
||||
|
||||
# line breaks
|
||||
opts = p(' font', ' \t \t \\_size', ' \\ 12', '\\.35', 'col', '\\o', '\t \t\\r', '\\25', ' \\ blue')
|
||||
self.ae(opts.font_size, 12.35)
|
||||
self.ae(opts.color25, Color(0, 0, 255))
|
||||
|
||||
# cursor_blink_interval
|
||||
def cb(src, interval=-1, first=EasingFunction(), second=EasingFunction()):
|
||||
opts = p('cursor_blink_interval ' + src)
|
||||
self.ae((float(interval), first, second), (float(opts.cursor_blink_interval[0]), opts.cursor_blink_interval[1], opts.cursor_blink_interval[2]))
|
||||
|
||||
cb('3', 3)
|
||||
cb('-2.3', -2.3)
|
||||
cb('linear', first=EasingFunction('cubic-bezier', cubic_bezier_points=(0, 0.0, 1.0, 1.0)))
|
||||
cb('linear 19', 19, EasingFunction('cubic-bezier', cubic_bezier_points=(0, 0.0, 1.0, 1.0)))
|
||||
cb(
|
||||
'ease-in-out cubic-bezier(0.1, 0.2, 0.3, 0.4) 11',
|
||||
11,
|
||||
EasingFunction('cubic-bezier', cubic_bezier_points=(0.42, 0, 0.58, 1)),
|
||||
EasingFunction('cubic-bezier', cubic_bezier_points=(0.1, 0.2, 0.3, 0.4)),
|
||||
)
|
||||
cb('step-start', first=EasingFunction('steps', num_steps=1, jump_type='start'))
|
||||
cb('steps(7, jump-none)', first=EasingFunction('steps', num_steps=7, jump_type='none'))
|
||||
cb('linear(0, 0.25, 1)', first=EasingFunction('linear', linear_x=(0.0, 0.5, 1.0), linear_y=(0, 0.25, 1.0)))
|
||||
cb('linear(0, 0.25 75%, 1)', first=EasingFunction('linear', linear_x=(0.0, 0.75, 1.0), linear_y=(0, 0.25, 1.0)))
|
||||
cb('linear(0, 0.25 25% 75%, 1)', first=EasingFunction('linear', linear_x=(0.0, 0.25, 0.75, 1.0), linear_y=(0, 0.25, 0.25, 1.0)))
|
||||
|
||||
# test that easing functions give expected values
|
||||
def ef(spec, tests, only_single=True, duration=0.5, accuracy=0):
|
||||
cfv = p('cursor_blink_interval ' + spec).cursor_blink_interval
|
||||
self.set_options({'cursor_blink_interval': cfv})
|
||||
for t, expected in tests.items():
|
||||
actual = test_cursor_blink_easing_function(t, only_single, duration)
|
||||
if abs(actual - expected) > accuracy:
|
||||
self.ae(expected, actual, f'Failed for {spec=} with {t=}: {expected} != {actual}')
|
||||
|
||||
ef('linear', {0: 1, 0.25: 0.5, 0.5: 0, 0.75: 0.5, 1: 1}, only_single=False)
|
||||
|
||||
ef('linear(0, 0.25 25% 75%, 1)', {0: 0, 0.25: 0.25, 0.3: 0.25, 0.75: 0.25, 1: 1})
|
||||
linear_vals = {0: 0, 1: 1, 0.1234: 0.1234, 0.6453: 0.6453}
|
||||
for spec in ('linear', 'linear(0, 1)', 'cubic-bezier(0, 0, 1, 1)', 'cubic-bezier(0.2, 0.2, 0.7, 0.7)'):
|
||||
ef(spec, linear_vals)
|
||||
# test an almost linear function to test cubic bezier implementation
|
||||
ef('cubic-bezier(0.2, 0.2, 0.7, 0.71)', linear_vals, accuracy=0.01)
|
||||
ef('cubic-bezier(0.23, 0.2, 0.7, 0.71)', linear_vals, accuracy=0.01)
|
||||
|
||||
ef('steps(5)', {0: 0, 0.1: 0, 0.3: 0.2, 0.9: 0.8})
|
||||
ef('steps(5, start)', {0: 0.2, 0.1: 0.2, 0.3: 0.4, 0.9: 1})
|
||||
ef('steps(4, jump-both)', {0: 0.2, 0.1: 0.2, 0.3: 0.4, 0.9: 1})
|
||||
ef('steps(6, jump-none)', {0: 0, 0.1: 0.0, 0.3: 0.2, 0.9: 1})
|
||||
|
||||
# test various include modes
|
||||
base = os.path.join(self.tdir, 'glob')
|
||||
os.mkdir(base)
|
||||
with open(os.path.join(base, 'fg'), 'w') as f:
|
||||
print('foreground red', file=f)
|
||||
opts = p(f'include {f.name}', num_err=0)
|
||||
self.ae(opts.foreground, to_color('red'))
|
||||
with open(os.path.join(self.tdir, 'bg'), 'w') as f:
|
||||
print('background white', file=f)
|
||||
print('globinclude glob/*', file=f)
|
||||
print('envinclude ENVINCLUDE', file=f)
|
||||
print('geninclude g.py', file=f)
|
||||
print('geninclude g', file=f)
|
||||
with open(os.path.join(self.tdir, 'g.py'), 'w') as g:
|
||||
print('print("background_opacity .77")', file=g)
|
||||
print('print("background_blur 77")', file=g)
|
||||
with open(os.path.join(self.tdir, 'g'), 'w') as g:
|
||||
print('#!/bin/sh', file=g)
|
||||
print('echo background_image_linear y', file=g)
|
||||
print('echo background_image_layout clamped', file=g)
|
||||
os.chmod(g.fileno(), 0o700)
|
||||
os.environ['ENVINCLUDE'] = 'cursor yellow'
|
||||
opts = p(f'include {f.name}', num_err=0)
|
||||
os.environ.pop('ENVINCLUDE')
|
||||
self.ae(opts.foreground, to_color('red'))
|
||||
self.ae(opts.background, to_color('white'))
|
||||
self.ae(opts.cursor, to_color('yellow'))
|
||||
self.ae(opts.background_opacity, 0.77)
|
||||
self.ae(opts.background_blur, 77)
|
||||
self.ae(opts.background_image_linear, True)
|
||||
self.ae(opts.background_image_layout, 'clamped')
|
||||
with open(os.path.join(self.tdir, 'a'), 'w') as a:
|
||||
print('background red', file=a)
|
||||
print('include b', file=a)
|
||||
with open(os.path.join(self.tdir, 'b'), 'w') as a:
|
||||
print('foreground red', file=a)
|
||||
print('include a', file=a)
|
||||
opts = p(f'include {a.name}', num_err=0, bad_line_num=1)
|
||||
self.ae(opts.foreground, to_color('red'))
|
||||
self.ae(opts.background, to_color('red'))
|
||||
|
||||
# remap_modifier. NOTE: parsing only. Whether the permutation is applied
|
||||
# simultaneously rather than sequentially is a property of
|
||||
# apply_modifier_remap() in C and is NOT observable from this dict - a
|
||||
# sequential implementation would produce an identical one. That property is
|
||||
# covered end to end by tests/test-remap-e2e.sh, which asserts that the
|
||||
# encoded bytes actually exchange.
|
||||
self.ae(p().remap_modifiers, {})
|
||||
ctrl, hyper, sup = to_modifiers('ctrl'), to_modifiers('hyper'), to_modifiers('super')
|
||||
self.ae(p('remap_modifiers ctrl:hyper').remap_modifiers, {ctrl: hyper})
|
||||
# both directions of a swap are recorded
|
||||
self.ae(p('remap_modifiers ctrl:hyper hyper:ctrl').remap_modifiers, {ctrl: hyper, hyper: ctrl})
|
||||
# the last declaration for a given source wins, wherever it appears
|
||||
self.ae(p('remap_modifiers ctrl:hyper', 'kitty_mod ctrl', 'remap_modifiers ctrl:super').remap_modifiers, {ctrl: sup})
|
||||
# the destination may name more than one modifier
|
||||
self.ae(p('remap_modifiers ctrl:ctrl+shift').remap_modifiers, {ctrl: to_modifiers('ctrl+shift')})
|
||||
# every rejection must be REPORTED, never silently ignored: wrong arity, unknown
|
||||
# or non-remappable modifier names, a source naming more than one modifier, and
|
||||
# a mapping that does nothing
|
||||
for bad in (
|
||||
'remap_modifiers ctrl',
|
||||
'remap_modifiers ctrl:hyper super',
|
||||
'remap_modifiers ctrl:nosuchmod',
|
||||
'remap_modifiers nosuchmod:ctrl',
|
||||
'remap_modifiers ctrl+shift:hyper',
|
||||
'remap_modifiers ctrl:none',
|
||||
'remap_modifiers none:ctrl',
|
||||
'remap_modifiers ctrl:kitty_mod',
|
||||
'remap_modifiers kitty_mod:ctrl',
|
||||
'remap_modifiers caps_lock:ctrl',
|
||||
'remap_modifiers ctrl:num_lock',
|
||||
'remap_modifiers ctrl:ctrl',
|
||||
):
|
||||
self.ae(p(bad, num_err=1).remap_modifiers, {}, f'not rejected: {bad}')
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2025, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import shlex
|
||||
import subprocess
|
||||
|
||||
|
||||
def r(msg: str, cmdline: str) -> None:
|
||||
try:
|
||||
q = input('Test ' + msg + '? (y/n): ').lower()
|
||||
if q in ('y', 'yes'):
|
||||
try:
|
||||
subprocess.run(['kitten'] + shlex.split(cmdline))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except KeyboardInterrupt:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
r(
|
||||
'top panel check transpareny, no input focus, margins and struts',
|
||||
'panel -o background_opacity=0.2 --edge=top --lines=2 --margin-left=50 --margin-right=100',
|
||||
)
|
||||
|
||||
r('bottom panel, check struts', 'panel -o background_opacity=0.2 --edge=bottom --lines=2 --margin-left=100 --margin-right=50')
|
||||
|
||||
r('left panel, check struts', 'panel -o background_opacity=0.2 --edge=left --columns=2 --margin-top=50 --margin-bottom=100')
|
||||
|
||||
r('right panel, check struts', 'panel -o background_opacity=0.2 --edge=right --columns=2 --margin-top=50 --margin-bottom=100')
|
||||
|
||||
r(
|
||||
'background, check transparency and margins and no input focus',
|
||||
'panel -o background_opacity=0.2 --edge=background --margin-top=50 --margin-bottom=50 --margin-left=100 --margin-right=100',
|
||||
)
|
||||
|
||||
r('quake, check transparency and focus on show/re-show', 'quick-access-terminal')
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from base64 import standard_b64encode
|
||||
|
||||
from kitty.program_status import (
|
||||
MAX_BODY_BYTES,
|
||||
MAX_RECORDS,
|
||||
QUERY_REPLY,
|
||||
Clear,
|
||||
InvalidReport,
|
||||
Kind,
|
||||
ProgramStatus,
|
||||
Record,
|
||||
State,
|
||||
combined_status_symbol,
|
||||
parse_report,
|
||||
status_symbol,
|
||||
)
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
def b64(text: str, pad: bool = True) -> str:
|
||||
ans = standard_b64encode(text.encode()).decode()
|
||||
return ans if pad else ans.rstrip('=')
|
||||
|
||||
|
||||
class TestProgramStatus(BaseTest):
|
||||
def test_program_status_parsing(self):
|
||||
def p(body: str) -> Record | Clear:
|
||||
return parse_report(body)
|
||||
|
||||
def bad(body: str) -> None:
|
||||
with self.assertRaises(InvalidReport, msg=body):
|
||||
parse_report(body)
|
||||
|
||||
self.ae(QUERY_REPLY, '7501;?:states=idle,working,done,blocked,error:kinds=permission,question,auth')
|
||||
msg = 'Apply 3 to add, 1 to change, 0 to destroy?'
|
||||
self.ae(p(f'state=blocked:kind=permission:app=terraform:msg={b64(msg)}'), Record(state=State.blocked, kind=Kind.permission, app='terraform', msg=msg))
|
||||
# padding is optional
|
||||
self.ae(p(f'state=done:msg={b64("ab", pad=False)}:title={b64("x", pad=False)}'), Record(state=State.done, msg='ab', title='x'))
|
||||
# whitespace, malformed pairs, unknown keys and repeated keys
|
||||
self.ae(p(' state = idle :oops:=x:future=yes:Bad=1:app=a*b:state=working'), Record(state=State.working))
|
||||
# kind and progress only apply to some states, invalid values are absent
|
||||
self.ae(p('state=done:kind=auth:progress=10'), Record(state=State.done))
|
||||
self.ae(p('state=blocked:kind=other:progress=101'), Record(state=State.blocked))
|
||||
self.ae(p('state=working:progress=100'), Record(state=State.working, progress=100))
|
||||
self.ae(p('state=working:progress=-1'), Record(state=State.working))
|
||||
self.ae(p('state=working:app=a/b'), Record(state=State.working))
|
||||
self.ae(p('state=working:id=a/b-c.d_e+f'), Record(id='a/b-c.d_e+f', state=State.working))
|
||||
self.ae(p('state=clear'), Clear())
|
||||
self.ae(p('state=clear:id=x/y'), Clear('x/y'))
|
||||
# an unknown or missing state discards the report
|
||||
bad('state=paused')
|
||||
bad('app=x')
|
||||
bad('')
|
||||
# invalid ids discard the report rather than fall back to the root record
|
||||
for rid in ('', 'a//b', '/a', 'a/', 'a b', 'a*b', 'a,b', 'x' * 33, '/'.join('a' * 9), '/'.join(['x' * 32] * 8) + 'x'):
|
||||
bad(f'state=clear:id={rid}')
|
||||
# the longest id allowed by the segment limits is accepted, the 128 byte limit in the spec is an error
|
||||
rid = '/'.join(['x' * 32] * 8)
|
||||
self.ae(len(rid), 263)
|
||||
self.ae(p(f'state=idle:id={rid}'), Record(id=rid))
|
||||
bad('state=idle:id=a:id=a*b')
|
||||
# limits, checked even for values that are later replaced
|
||||
bad(f'state=idle:{"k" * 17}=1')
|
||||
bad(f'state=idle:{"K" * 17}=1')
|
||||
self.ae(p(f'state=idle:{"K" * 16}=1'), Record())
|
||||
# only ASCII whitespace is removed
|
||||
self.ae(p('\tstate=done\r\n'), Record(state=State.done))
|
||||
bad('\x1cstate=done')
|
||||
# the limit is on bytes, not on decoded text
|
||||
filler = 'state=idle:' + 'x=y:' * ((MAX_BODY_BYTES - 100) // 4)
|
||||
self.ae(parse_report(filler.encode() + b'\xff' * 30), Record())
|
||||
bad(filler.encode() + b'\xff' * 100)
|
||||
bad(f'state=idle:app={"a" * 33}:app=b')
|
||||
bad(f'state=idle:title={b64("x" * 193)}')
|
||||
bad(f'state=idle:msg={b64("x" * 2049)}')
|
||||
bad(f'state=idle:msg={"QUFB" * 684}:msg=QQ')
|
||||
bad('state=idle:' + 'x=y:' * 1100)
|
||||
p(f'state=idle:title={b64("x" * 192)}:msg={b64("y" * 2048)}')
|
||||
# invalid base64, utf-8 or control characters
|
||||
bad('state=idle:msg=Q')
|
||||
bad('state=idle:msg=QQ=Q')
|
||||
bad(f'state=idle:msg={standard_b64encode(b"\xff").decode()}')
|
||||
for cc in '\x00\t\n\x1b\x7f\x85\x9b':
|
||||
bad(f'state=idle:msg={b64("a" + cc)}')
|
||||
bad(f'state=idle:title={b64("a\nb")}')
|
||||
|
||||
def test_program_status_records(self):
|
||||
ps = ProgramStatus()
|
||||
# the escape code handler used by windows
|
||||
self.ae(ps.handle_escape_code(memoryview(b'?')), (QUERY_REPLY, False))
|
||||
self.ae(ps.handle_escape_code(b'state=working'), ('', True))
|
||||
self.ae(ps.handle_escape_code(b'state=working'), ('', False))
|
||||
with self.assertRaises(InvalidReport):
|
||||
ps.handle_escape_code(b'state=paused')
|
||||
ps.apply(parse_report('state=done:id=d'))
|
||||
self.ae(ps.handle_escape_code(b'process-exited'), ('', True))
|
||||
self.ae([r.id for r in ps], ['d'])
|
||||
self.ae(ps.handle_escape_code(b'process-exited'), ('', False))
|
||||
ps.clear()
|
||||
|
||||
def apply(body: str) -> bool:
|
||||
return ps.apply(parse_report(body))
|
||||
|
||||
def ids() -> list[str]:
|
||||
return [r.id for r in ps]
|
||||
|
||||
self.assertTrue(apply('state=working:app=deploy'))
|
||||
self.assertFalse(apply('state=working:app=deploy'))
|
||||
self.assertTrue(apply('state=working:id=us-east:progress=40'))
|
||||
self.assertTrue(apply('state=blocked:kind=permission:id=eu-west'))
|
||||
self.assertTrue(apply('state=working:id=eu-west/db:app=psql'))
|
||||
self.ae(ids(), ['', 'us-east', 'eu-west', 'eu-west/db'])
|
||||
# app is inherited from the nearest ancestor
|
||||
self.ae({d['id']: d['app'] for d in ps.as_list()}, {'': 'deploy', 'us-east': 'deploy', 'eu-west': 'deploy', 'eu-west/db': 'psql'})
|
||||
self.ae(ps.most_urgent(), ps.records['eu-west'])
|
||||
# a report replaces its record completely
|
||||
apply('state=working')
|
||||
self.ae(ps.records[''], Record(state=State.working))
|
||||
self.ae(ps.as_list()[0]['app'], '')
|
||||
# clear removes the record and every record beneath it
|
||||
apply('state=clear:id=eu')
|
||||
self.ae(len(ps.records), 4)
|
||||
apply('state=clear:id=eu-west')
|
||||
self.ae(ids(), ['us-east', ''])
|
||||
apply('state=clear')
|
||||
self.assertFalse(ps)
|
||||
# lifetime
|
||||
apply('state=working')
|
||||
apply('state=blocked:id=a')
|
||||
apply('state=idle:id=b')
|
||||
apply('state=done:id=c')
|
||||
apply('state=error:id=d')
|
||||
self.ae(ps.most_urgent(), ps.records['a'])
|
||||
self.assertTrue(ps.on_process_exit_or_prompt())
|
||||
self.ae(ids(), ['c', 'd'])
|
||||
self.ae(ps.most_urgent(), ps.records['d'])
|
||||
self.assertFalse(ps.on_process_exit_or_prompt())
|
||||
self.assertTrue(ps.on_seen_by_user())
|
||||
self.assertFalse(ps)
|
||||
# the least recently updated record is removed past the cap
|
||||
for i in range(MAX_RECORDS):
|
||||
apply(f'state=idle:id=r{i}')
|
||||
apply('state=working:id=r0')
|
||||
apply('state=idle:id=new')
|
||||
self.ae(len(ps.records), MAX_RECORDS)
|
||||
self.assertNotIn('r1', ps.records)
|
||||
self.assertIn('r0', ps.records)
|
||||
# an identical report still counts as recent for eviction
|
||||
self.assertFalse(apply('state=idle:id=r2'))
|
||||
apply('state=idle:id=newer')
|
||||
self.assertIn('r2', ps.records)
|
||||
self.assertNotIn('r3', ps.records)
|
||||
|
||||
def test_program_status_symbol(self):
|
||||
self.ae(status_symbol(None), '')
|
||||
self.ae(status_symbol(Record(state=State.idle)), '')
|
||||
self.ae(status_symbol(Record(state=State.working, progress=40)), '\uf110 40% ')
|
||||
self.ae(status_symbol(Record(state=State.working, progress=40), 2), '\uf110 2 40% ')
|
||||
self.ae(status_symbol(Record(state=State.blocked), 3), '\uf071 3 ')
|
||||
syms = {status_symbol(Record(state=s)) for s in State if s is not State.idle}
|
||||
self.ae(len(syms), 4)
|
||||
|
||||
def window(*bodies: str) -> ProgramStatus:
|
||||
ps = ProgramStatus()
|
||||
for b in bodies:
|
||||
ps.apply(parse_report(b))
|
||||
return ps
|
||||
|
||||
self.ae(combined_status_symbol([]), '')
|
||||
self.ae(combined_status_symbol([ProgramStatus(), window('state=idle')]), '')
|
||||
# the most urgent state wins and the windows in it are counted
|
||||
a, b, c = window('state=blocked'), window('state=working'), window('state=idle')
|
||||
self.ae(combined_status_symbol([a, b, c]), '\uf071 ')
|
||||
b.apply(parse_report('state=blocked:kind=auth'))
|
||||
self.ae(combined_status_symbol([a, b, c]), '\uf071 2 ')
|
||||
# several records in one window count as one window
|
||||
self.ae(combined_status_symbol([window('state=blocked', 'state=blocked:id=x'), c]), '\uf071 ')
|
||||
# ties are broken by the most recently updated record, across windows
|
||||
a, b = window('state=working:progress=10'), window('state=working:progress=20')
|
||||
self.ae(combined_status_symbol([a, b]), '\uf110 2 20% ')
|
||||
a.apply(parse_report('state=working:progress=30'))
|
||||
self.ae(combined_status_symbol([a, b]), '\uf110 2 30% ')
|
||||
self.ae(combined_status_symbol([b, a]), '\uf110 2 30% ')
|
||||
# an identical report does not change which record is shown
|
||||
b.apply(parse_report('state=working:progress=20'))
|
||||
self.ae(combined_status_symbol([a, b]), '\uf110 2 30% ')
|
||||
# the same rule applies to several records within one window
|
||||
w = window('state=working:id=x:progress=10', 'state=working:id=y:progress=20')
|
||||
self.ae(combined_status_symbol([w]), '\uf110 20% ')
|
||||
self.ae(w.handle_escape_code(b'state=working:id=x:progress=10'), ('', False))
|
||||
self.ae(combined_status_symbol([w]), '\uf110 20% ')
|
||||
# an identical report does not reorder the records either
|
||||
self.ae([d['id'] for d in w.as_list()], ['x', 'y'])
|
||||
w.apply(parse_report('state=working:id=x:progress=30'))
|
||||
self.ae(combined_status_symbol([w]), '\uf110 30% ')
|
||||
self.ae([d['id'] for d in w.as_list()], ['y', 'x'])
|
||||
@@ -0,0 +1,577 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from types import MethodType
|
||||
from typing import Any, cast
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from kitty.constants import kitty_exe
|
||||
from kitty.rc.base import PayloadGetter, all_command_names, command_for_name
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class Window:
|
||||
def __init__(self, id: int, os_window_id: int):
|
||||
self.id = id
|
||||
self.os_window_id = os_window_id
|
||||
|
||||
|
||||
class Boss:
|
||||
def __init__(self, windows: list[Window]):
|
||||
self.active_window = windows[0]
|
||||
self.all_windows = windows
|
||||
|
||||
def match_windows(self, expr: str, self_window: Window | None = None):
|
||||
if expr == 'all':
|
||||
yield from self.all_windows
|
||||
return
|
||||
for window in self.all_windows:
|
||||
if str(window.id) == expr:
|
||||
yield window
|
||||
|
||||
def match_tabs(self, expr: str):
|
||||
if expr == 'all':
|
||||
yield list(self.all_windows)
|
||||
|
||||
|
||||
class TestRemoteControl(BaseTest):
|
||||
def test_set_font_size_mapping(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
from kitty.rc.base import RemoteControlErrorWithoutTraceback
|
||||
|
||||
for all_windows in (False, True):
|
||||
for value, operation, size in (
|
||||
('12.5', None, 12.5),
|
||||
('0', None, 0.0),
|
||||
('+2', '+', 2.0),
|
||||
('-2', '-', 2.0),
|
||||
('*1.5', '*', 1.5),
|
||||
('/2', '/', 2.0),
|
||||
):
|
||||
with self.subTest(all_windows=all_windows, value=value):
|
||||
boss = Mock(spec=KittyBoss)
|
||||
args = ('set-font-size',) + (('--all',) if all_windows else ()) + ('--', value)
|
||||
KittyBoss.call_remote_control(boss, None, args)
|
||||
boss.change_font_size.assert_called_once_with(all_windows, operation, size)
|
||||
for value in ('*-2', '+-2', '/0', '*0', '+0', '-0', '*nan', '/inf', 'inf', '-nan', '*', '', 'abc'):
|
||||
with self.subTest(value=value):
|
||||
boss = Mock(spec=KittyBoss)
|
||||
with self.assertRaises(Exception):
|
||||
KittyBoss.call_remote_control(boss, None, ('set-font-size', '--', value))
|
||||
boss.change_font_size.assert_not_called()
|
||||
# payloads sent directly by kitten @ bypass message_to_kitty
|
||||
command = command_for_name('set-font-size')
|
||||
for payload in ({'size': -2, 'increment_op': '+'}, {'size': 0, 'increment_op': '/'}, {'size': -1}):
|
||||
with self.subTest(payload=payload):
|
||||
boss = Mock(spec=KittyBoss)
|
||||
with self.assertRaises(RemoteControlErrorWithoutTraceback):
|
||||
command.response_from_kitty(boss, None, PayloadGetter(command, payload))
|
||||
boss.change_font_size.assert_not_called()
|
||||
|
||||
def test_action_parse_errors(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
from kitty.rc.base import RemoteControlErrorWithoutTraceback
|
||||
from kitty.remote_control import handle_cmd
|
||||
|
||||
self.set_options()
|
||||
for action in ('goto_tab not-a-number', 'set_font_size invalid', 'unknown_action argument', 'goto_tab 1'):
|
||||
with self.subTest(action=action):
|
||||
boss = Mock(spec=KittyBoss, active_window=None, window_for_dispatch=None, dispatch_action=Mock(return_value=True))
|
||||
boss.combine = MethodType(KittyBoss.combine, boss)
|
||||
request = {'cmd': 'action', 'version': [0, 26, 0], 'payload': {'action': action}}
|
||||
if action == 'goto_tab 1':
|
||||
self.ae(handle_cmd(boss, None, request, 0, None), {'ok': True})
|
||||
boss.dispatch_action.assert_called_once()
|
||||
else:
|
||||
with self.assertRaises(RemoteControlErrorWithoutTraceback) as cm:
|
||||
handle_cmd(boss, None, request, 0, None)
|
||||
msg = str(cm.exception)
|
||||
self.assertTrue(msg.startswith(f'Failed to parse action: {action}: '), msg)
|
||||
if action == 'unknown_action argument':
|
||||
self.ae(msg, f'Failed to parse action: {action}: Unknown action: unknown_action')
|
||||
boss.dispatch_action.assert_not_called()
|
||||
boss.show_error.assert_not_called()
|
||||
|
||||
def test_cancel_async_auth_bypass(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
from kitty.remote_control import handle_cmd, is_cmd_allowed
|
||||
|
||||
self.set_options({'remote_control_password': {'secret': frozenset(('ls',))}})
|
||||
base = {'cmd': 'send_text', 'version': [0, 26, 0], 'payload': {'data': 'text:x'}, 'cancel_async': True}
|
||||
for extra in ({'async_id': 'x'}, {'async_id': 'x', 'password': 'wrong'}, {'async_id': 'x', 'password': 'secret'}, {'async': ''}):
|
||||
with self.subTest(extra=extra):
|
||||
self.assertIsNot(is_cmd_allowed({**base, **extra}, None, False, {}), True)
|
||||
# a genuine cancellation is allowed without a password and must only cancel
|
||||
pcmd = {**base, 'async': 'x'}
|
||||
self.assertIs(is_cmd_allowed(pcmd, None, False, {}), True)
|
||||
command = command_for_name('send_text')
|
||||
with patch.object(command, 'response_from_kitty') as rfk, patch.object(command, 'cancel_async_request') as car:
|
||||
self.assertIsNone(handle_cmd(Mock(spec=KittyBoss), None, pcmd, 0, None))
|
||||
rfk.assert_not_called()
|
||||
car.assert_called_once()
|
||||
# a cancellation must not register its stream, otherwise later requests
|
||||
# on that stream would be allowed without authentication
|
||||
from kitty.remote_control import active_streams, close_active_stream
|
||||
|
||||
sid = 'cancel-async-stream'
|
||||
self.addCleanup(close_active_stream, sid)
|
||||
pcmd = {'cmd': 'run', 'version': [0, 26, 0], 'stream_id': sid, 'async': 'y', 'cancel_async': True}
|
||||
self.assertIs(is_cmd_allowed(pcmd, None, False, {}), True)
|
||||
command = command_for_name('run')
|
||||
with patch.object(command, 'response_from_kitty') as rfk, patch.object(command, 'cancel_async_request') as car:
|
||||
self.assertIsNone(handle_cmd(Mock(spec=KittyBoss), None, pcmd, 0, None))
|
||||
rfk.assert_not_called()
|
||||
car.assert_called_once()
|
||||
self.assertNotIn(sid, active_streams)
|
||||
pcmd = {'cmd': 'run', 'version': [0, 26, 0], 'stream_id': sid, 'payload': {'cmdline': ['true'], 'data': ''}}
|
||||
self.assertIsNot(is_cmd_allowed(pcmd, None, False, {}), True)
|
||||
|
||||
def test_stream_continuation_auth(self):
|
||||
from base64 import standard_b64encode
|
||||
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
from kitty.remote_control import abort_active_stream, abort_active_streams_from, active_streams, handle_cmd, is_cmd_allowed, register_active_stream
|
||||
|
||||
self.set_options({'remote_control_password': {'secret': frozenset(('ls',))}})
|
||||
command = command_for_name('run')
|
||||
|
||||
def cleanup() -> None:
|
||||
for sid in tuple(active_streams):
|
||||
abort_active_stream(sid)
|
||||
|
||||
self.addCleanup(cleanup)
|
||||
|
||||
def chunk(sid: str, data: bytes = b'x', payload: dict[str, Any] | None = None, **kw: Any) -> dict[str, Any]:
|
||||
p: dict[str, Any] = {'cmdline': ['true'], 'data': standard_b64encode(data).decode('ascii'), **(payload or {})}
|
||||
return {'cmd': 'run', 'version': [0, 26, 0], 'stream_id': sid, 'async': 'a-' + sid, 'payload': p, **kw}
|
||||
|
||||
def open_stream(sid: str, peer_id: int = 0, window: Window | None = None) -> None:
|
||||
# handle_cmd() is only called for authorized requests
|
||||
r = handle_cmd(Mock(spec=KittyBoss), window, chunk(sid, stream=True), peer_id, None)
|
||||
self.ae(r, {'ok': True, 'stream': True})
|
||||
self.assertIn(sid, active_streams)
|
||||
|
||||
def allowed(pcmd: dict[str, Any], peer_id: int = 0, window: Window | None = None) -> bool:
|
||||
return is_cmd_allowed(pcmd, cast(Any, window), peer_id > 0, {}, peer_id) is True
|
||||
|
||||
# continuations from the same origin with only the data changed are allowed
|
||||
open_stream('s1', peer_id=7)
|
||||
self.assertTrue(allowed(chunk('s1', b'y'), 7))
|
||||
self.assertTrue(allowed(chunk('s1', b''), 7))
|
||||
# continuations must not change anything other than the data
|
||||
self.assertFalse(allowed(chunk('s1', payload={'cmdline': ['evil']}), 7))
|
||||
self.assertFalse(allowed(chunk('s1', payload={'env': ['A=b']}), 7))
|
||||
self.assertFalse(allowed({**chunk('s1'), 'async': 'other'}, 7))
|
||||
self.assertFalse(allowed({**chunk('s1'), 'cmd': 'set-window-logo'}, 7))
|
||||
# continuations must come from the origin that opened the stream
|
||||
self.assertFalse(allowed(chunk('s1'), 8))
|
||||
self.assertFalse(allowed(chunk('s1'), 0, Window(7, 1)))
|
||||
self.assertFalse(allowed(chunk('unknown'), 7))
|
||||
|
||||
# cancellations only abort streams opened from the same origin
|
||||
cancel = {'cmd': 'run', 'version': [0, 26, 0], 'stream_id': 's1', 'async': 'a-s1', 'cancel_async': True}
|
||||
self.assertIsNone(handle_cmd(Mock(spec=KittyBoss), None, dict(cancel), 8, None))
|
||||
self.assertIn('s1', active_streams)
|
||||
self.ae(command.stream_in_flight.stream_id, 's1')
|
||||
self.assertIsNone(handle_cmd(Mock(spec=KittyBoss), None, dict(cancel), 7, None))
|
||||
self.assertNotIn('s1', active_streams)
|
||||
self.ae(command.stream_in_flight.stream_id, '')
|
||||
self.assertIsNone(command.stream_in_flight.tempfile)
|
||||
self.assertFalse(allowed(chunk('s1'), 7))
|
||||
|
||||
# streams are aborted when the peer or window that opened them goes away
|
||||
w = Window(5, 1)
|
||||
open_stream('s2', peer_id=7)
|
||||
open_stream('s3', window=w)
|
||||
self.assertTrue(allowed(chunk('s3'), 0, w))
|
||||
abort_active_streams_from(peer_id=7)
|
||||
self.assertNotIn('s2', active_streams)
|
||||
self.assertIn('s3', active_streams)
|
||||
self.ae(command.stream_in_flight.stream_id, 's3')
|
||||
abort_active_streams_from(window_id=w.id)
|
||||
self.assertNotIn('s3', active_streams)
|
||||
self.ae(command.stream_in_flight.stream_id, '')
|
||||
|
||||
# a command has only one stream in flight, opening another aborts the first
|
||||
open_stream('s4', peer_id=7)
|
||||
open_stream('s5', peer_id=8)
|
||||
self.assertNotIn('s4', active_streams)
|
||||
self.assertFalse(allowed(chunk('s4'), 7))
|
||||
self.assertTrue(allowed(chunk('s5'), 8))
|
||||
|
||||
# the number of registered streams is bounded
|
||||
for i in range(40):
|
||||
register_active_stream(f'many-{i}', chunk(f'many-{i}'), None, 9)
|
||||
self.ae(len(active_streams), 32)
|
||||
self.assertNotIn('many-0', active_streams)
|
||||
self.assertIn('many-39', active_streams)
|
||||
|
||||
def test_kitten_password_restrictions(self):
|
||||
from kitty.remote_control import kitten_password_restrictions, remote_control_allowed
|
||||
|
||||
def allowed_cmds(rcp: str | bool) -> list[str]:
|
||||
passwords = {'pw': kitten_password_restrictions(rcp)}
|
||||
ans = []
|
||||
for cmd in ('ls', 'set-colors', 'set-font-size', 'launch', 'send-text'):
|
||||
try:
|
||||
if remote_control_allowed({'cmd': cmd, 'password': 'pw'}, passwords, None, {}):
|
||||
ans.append(cmd)
|
||||
except PermissionError:
|
||||
pass
|
||||
return ans
|
||||
|
||||
self.ae(allowed_cmds('ls set-colors'), ['ls', 'set-colors'])
|
||||
# a glob must match whole command names not be split into characters
|
||||
self.ae(allowed_cmds('set-*'), ['set-colors', 'set-font-size'])
|
||||
self.ae(allowed_cmds(''), ['ls', 'set-colors', 'set-font-size', 'launch', 'send-text'])
|
||||
self.ae(allowed_cmds(True), ['ls', 'set-colors', 'set-font-size', 'launch', 'send-text'])
|
||||
|
||||
def test_encrypted_command_replay(self):
|
||||
from kitty.constants import RC_ENCRYPTION_PROTOCOL_VERSION
|
||||
from kitty.fast_data_types import EllipticCurveKey
|
||||
from kitty.remote_control import CommandEncrypter, parse_cmd, seen_encrypted_commands
|
||||
|
||||
seen_encrypted_commands.clear()
|
||||
self.addCleanup(seen_encrypted_commands.clear)
|
||||
key = EllipticCurveKey()
|
||||
encrypter = CommandEncrypter(key.public, RC_ENCRYPTION_PROTOCOL_VERSION, 'pw')
|
||||
|
||||
def serialize(cmd: dict[str, Any]) -> memoryview:
|
||||
return memoryview(json.dumps(encrypter(cmd)).encode())
|
||||
|
||||
def cmd() -> dict[str, Any]:
|
||||
return {'cmd': 'ls', 'version': [0, 26, 0]}
|
||||
|
||||
with patch('kitty.remote_control.log_error') as log_error:
|
||||
c1, c2 = serialize(cmd()), serialize(cmd())
|
||||
self.ae(parse_cmd(c1, key)['password'], 'pw')
|
||||
self.ae(parse_cmd(c2, key)['password'], 'pw')
|
||||
log_error.assert_not_called()
|
||||
# replaying an accepted command is rejected
|
||||
self.ae(parse_cmd(c1, key), {})
|
||||
self.assertIn('already been received', log_error.call_args.args[0])
|
||||
# passwords that are not strings are rejected
|
||||
log_error.reset_mock()
|
||||
for bad in (1, None, ['pw'], {'a': 1}):
|
||||
encrypter.password = cast(str, bad)
|
||||
self.ae(parse_cmd(serialize(cmd()), key), {})
|
||||
self.assertIn('not a string', log_error.call_args.args[0])
|
||||
# expired commands are forgotten
|
||||
self.assertTrue(seen_encrypted_commands.seen)
|
||||
self.ae(seen_encrypted_commands.check_and_add(b'x', 0, 10), '')
|
||||
self.ae(seen_encrypted_commands.check_and_add(b'y', 0, 1 << 62), '')
|
||||
self.ae(seen_encrypted_commands.seen, {b'y'})
|
||||
# the number of remembered commands is bounded and unexpired commands
|
||||
# are never forgotten to make room
|
||||
seen_encrypted_commands.clear()
|
||||
with patch('kitty.remote_control.MAX_SEEN_ENCRYPTED_CMDS', 4):
|
||||
for i in range(4):
|
||||
self.ae(seen_encrypted_commands.check_and_add(bytes([i]), 100, 0), '')
|
||||
self.assertIn('too many', seen_encrypted_commands.check_and_add(b'z', 100, 0))
|
||||
self.assertIn('already', seen_encrypted_commands.check_and_add(bytes([0]), 100, 0))
|
||||
|
||||
def test_password_lookup_non_ascii(self):
|
||||
from kitty.remote_control import constant_time_lookup, is_cmd_allowed
|
||||
|
||||
passwords = {'pässword': 1, 'secret': 2, '\ud800': 3}
|
||||
self.ae(constant_time_lookup(passwords, 'pässword'), 1)
|
||||
self.ae(constant_time_lookup(passwords, 'secret'), 2)
|
||||
self.ae(constant_time_lookup(passwords, '\ud800'), 3)
|
||||
self.assertIsNone(constant_time_lookup(passwords, 'pässwort'))
|
||||
self.assertIsNone(constant_time_lookup(passwords, '€'))
|
||||
self.set_options({'remote_control_password': {'pässword': frozenset(('ls',))}})
|
||||
self.assertIs(is_cmd_allowed({'cmd': 'ls', 'password': 'pässword'}, None, True, {}), True)
|
||||
self.assertIs(is_cmd_allowed({'cmd': 'launch', 'password': 'pässword'}, None, True, {}), False)
|
||||
self.assertIsNone(is_cmd_allowed({'cmd': 'ls', 'password': 'ü'}, None, True, {}))
|
||||
|
||||
def test_select_window_cancel_only_own_request(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
from kitty.boss import VisualSelect
|
||||
|
||||
command = command_for_name('select-window')
|
||||
boss = Mock(spec=KittyBoss)
|
||||
boss.current_visual_select = None
|
||||
|
||||
def start_select(*a: Any, **kw: Any) -> None:
|
||||
boss.current_visual_select = VisualSelect(1, 1, None, None, 'x', a[1], False)
|
||||
|
||||
boss.visual_window_select_action.side_effect = start_select
|
||||
boss.match_tabs.return_value = iter(())
|
||||
tab = Mock()
|
||||
boss.active_tab = tab
|
||||
payload = {'async_id': 'mine', 'peer_id': 3, 'match': None, 'self': False}
|
||||
with patch.object(command, 'create_async_responder'):
|
||||
command.response_from_kitty(boss, None, PayloadGetter(command, payload))
|
||||
vs = boss.current_visual_select
|
||||
self.assertIsNotNone(vs)
|
||||
# cancelling some other async request does not cancel the visual select
|
||||
for async_id in ('other', ''):
|
||||
command.cancel_async_request(boss, None, PayloadGetter(command, {'async_id': async_id}))
|
||||
boss.cancel_current_visual_select.assert_not_called()
|
||||
# a visual select started by someone else is not cancelled either
|
||||
boss.current_visual_select = Mock()
|
||||
command.cancel_async_request(boss, None, PayloadGetter(command, {'async_id': 'mine'}))
|
||||
boss.cancel_current_visual_select.assert_not_called()
|
||||
# the request that started the visual select can cancel it
|
||||
with patch.object(command, 'create_async_responder'):
|
||||
command.response_from_kitty(boss, None, PayloadGetter(command, payload))
|
||||
command.cancel_async_request(boss, None, PayloadGetter(command, {'async_id': 'mine'}))
|
||||
boss.cancel_current_visual_select.assert_called_once()
|
||||
|
||||
def test_custom_auth_function_gets_self_window(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
|
||||
target = Mock(id=5)
|
||||
boss = Mock(spec=KittyBoss)
|
||||
boss.allow_remote_control = 'password'
|
||||
boss.peer_data_map = {}
|
||||
boss.window_id_map = {5: target}
|
||||
boss.encryption_key = None
|
||||
pcmd = {'cmd': 'ls', 'version': [0, 26, 0], 'kitty_window_id': 5, 'password': 'pw'}
|
||||
with patch('kitty.remote_control.parse_cmd', return_value=pcmd), patch('kitty.remote_control.is_cmd_allowed', return_value=False) as ica:
|
||||
KittyBoss._handle_remote_command(boss, memoryview(b''), None, 3)
|
||||
self.assertIs(ica.call_args.args[3]['self_window'], target)
|
||||
|
||||
def test_combine_parse_error_reporting(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
|
||||
self.set_options()
|
||||
boss = Mock(spec=KittyBoss)
|
||||
self.assertTrue(KittyBoss.combine(boss, 'goto_tab not-a-number'))
|
||||
boss.show_error.assert_called_once()
|
||||
boss.dispatch_action.assert_not_called()
|
||||
|
||||
def test_select_window_exclude_active(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
|
||||
command = command_for_name('select-window')
|
||||
for exclude_active in (False, True):
|
||||
with self.subTest(exclude_active=exclude_active):
|
||||
tab = Mock(all_window_ids_except_active_window=set())
|
||||
boss = Mock(active_tab=tab)
|
||||
args = ('select-window',) + (('--exclude-active',) if exclude_active else ())
|
||||
with patch.object(command, 'create_async_responder'):
|
||||
KittyBoss.call_remote_control(boss, None, args)
|
||||
self.ae(boss.visual_window_select_action.call_args.kwargs['only_window_ids'], set() if exclude_active else None)
|
||||
|
||||
def test_visual_window_select_empty_allowed_set(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
|
||||
self.set_options()
|
||||
for only_active_window_visible in (False, True):
|
||||
for only_window_ids, expected in ((set(), 0), (None, 1)):
|
||||
with self.subTest(only_active_window_visible=only_active_window_visible, only_window_ids=only_window_ids):
|
||||
window = Mock(id=1)
|
||||
tab = Mock(tab_manager_ref=Mock(return_value=None), os_window_id=1)
|
||||
tab.current_layout.only_active_window_visible = only_active_window_visible
|
||||
tab.windows.iter_windows_with_number.return_value = [(0, window)]
|
||||
boss = Mock()
|
||||
boss.select_window_in_tab_using_overlay = lambda *a: KittyBoss.select_window_in_tab_using_overlay(boss, *a)
|
||||
with patch('kitty.boss.current_os_window', return_value=1):
|
||||
KittyBoss.visual_window_select_action(boss, tab, Mock(), 'Choose', only_window_ids=only_window_ids)
|
||||
boss.visual_window_select_action_trigger.assert_called_once_with(expected)
|
||||
boss.choose_entry.assert_not_called()
|
||||
|
||||
def test_run_mapping_ignores_stdin(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
|
||||
command = command_for_name('run')
|
||||
for is_tty in (False, True):
|
||||
with self.subTest(is_tty=is_tty):
|
||||
stdin = Mock()
|
||||
stdin.isatty.return_value = is_tty
|
||||
boss = Mock()
|
||||
with patch('sys.stdin', stdin), patch.object(command, 'create_async_responder'):
|
||||
KittyBoss.call_remote_control(boss, None, ('run', 'cat'))
|
||||
boss.run_background_process.call_args.kwargs['notify_on_death'](0, None)
|
||||
stdin.buffer.read.assert_not_called()
|
||||
boss.run_background_process.assert_called_once()
|
||||
call = boss.run_background_process.call_args
|
||||
self.ae(call.args[0], ['cat'])
|
||||
self.ae(call.kwargs['stdin'], b'')
|
||||
|
||||
def test_set_enabled_layouts_configured(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
|
||||
for configured in (False, True):
|
||||
with self.subTest(configured=configured):
|
||||
options = self.set_options({'enabled_layouts': ['tall']})
|
||||
boss = Mock(active_tab=Mock())
|
||||
args = ('set-enabled-layouts',) + (('--configured',) if configured else ()) + ('stack',)
|
||||
|
||||
KittyBoss.call_remote_control(boss, None, args)
|
||||
|
||||
boss.active_tab.set_enabled_layouts.assert_called_once_with(['stack'])
|
||||
self.ae(options.enabled_layouts, ['stack'] if configured else ['tall'])
|
||||
|
||||
def test_ls_self_and_output_format(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
|
||||
self_window = Mock()
|
||||
boss = Mock(list_os_windows=Mock(return_value=[]), serialize_state_as_session=Mock(return_value=['a', 'b']))
|
||||
self.ae(KittyBoss.call_remote_control(boss, None, ('ls', '--output-format', 'session')), 'a\nb')
|
||||
boss.list_os_windows.assert_not_called()
|
||||
|
||||
KittyBoss.call_remote_control(boss, self_window, ('ls', '--self'))
|
||||
window_filter = boss.list_os_windows.call_args.args[2]
|
||||
self.assertIsNotNone(window_filter)
|
||||
self.assertTrue(window_filter(self_window))
|
||||
self.assertFalse(window_filter(Mock()))
|
||||
|
||||
def test_set_os_window_title_command_is_registered(self):
|
||||
self.assertIn('set_os_window_title', all_command_names())
|
||||
self.ae(command_for_name('set-os-window-title').name, 'set-os-window-title')
|
||||
|
||||
def test_set_os_window_title_dedupes_os_windows(self):
|
||||
windows = [Window(1, 11), Window(2, 11), Window(3, 22)]
|
||||
boss = Boss(windows)
|
||||
cmd = command_for_name('set-os-window-title')
|
||||
|
||||
with patch('kitty.rc.set_os_window_title.set_os_window_title_impl') as setter:
|
||||
cmd.response_from_kitty(boss, windows[0], PayloadGetter(cmd, {'match': 'all', 'self': True, 'title': 'repo'}))
|
||||
|
||||
self.ae({call.args for call in setter.call_args_list}, {(11, 'repo'), (22, 'repo')})
|
||||
|
||||
def test_set_os_window_title_without_title_resets_override(self):
|
||||
windows = [Window(1, 11)]
|
||||
boss = Boss(windows)
|
||||
cmd = command_for_name('set-os-window-title')
|
||||
|
||||
with patch('kitty.rc.set_os_window_title.set_os_window_title_impl') as setter:
|
||||
cmd.response_from_kitty(boss, windows[0], PayloadGetter(cmd, {'self': True}))
|
||||
|
||||
setter.assert_called_once_with(11, '')
|
||||
|
||||
def test_send_key_excludes_active_window(self):
|
||||
windows = [Window(1, 11), Window(2, 11)]
|
||||
boss = Boss(windows)
|
||||
cmd = command_for_name('send-key')
|
||||
keys = ['ctrl+a', 'ctrl+b']
|
||||
# selector -> (expected recipients without --exclude-active, with --exclude-active)
|
||||
cases = {
|
||||
'all': ({'all': True}, windows, windows[1:]),
|
||||
'match': ({'match': 'all'}, windows, windows[1:]),
|
||||
'match_tab': ({'match_tab': 'all'}, windows, windows[1:]),
|
||||
'default': ({}, windows[:1], []),
|
||||
}
|
||||
|
||||
for name, (selector, expected, expected_excluding_active) in cases.items():
|
||||
for exclude_active in (False, True):
|
||||
with (
|
||||
self.subTest(selector=name, exclude_active=exclude_active),
|
||||
patch.object(windows[0], 'send_key', create=True) as active,
|
||||
patch.object(windows[1], 'send_key', create=True) as other,
|
||||
):
|
||||
cmd.response_from_kitty(boss, None, PayloadGetter(cmd, {**selector, 'exclude_active': exclude_active, 'keys': keys}))
|
||||
|
||||
recipients = expected_excluding_active if exclude_active else expected
|
||||
for w, mock in ((windows[0], active), (windows[1], other)):
|
||||
if w in recipients:
|
||||
mock.assert_called_once_with(*keys)
|
||||
else:
|
||||
mock.assert_not_called()
|
||||
|
||||
def test_set_colors_transparent_background_colors(self):
|
||||
from kitty.fast_data_types import Color
|
||||
from kitty.rc.base import RemoteControlErrorWithoutTraceback, parse_subcommand_cli
|
||||
from kitty.remote_control import parse_rc_args
|
||||
|
||||
cmd = command_for_name('set-colors')
|
||||
|
||||
def payload(*args: str):
|
||||
opts, items = parse_subcommand_cli(cmd, ['set-colors'] + list(args))
|
||||
return cmd.message_to_kitty(parse_rc_args([])[0], opts, items)
|
||||
|
||||
# omitted means leave unchanged, explicitly empty means clear
|
||||
self.assertNotIn('transparent_background_colors', payload('foreground=red')['colors'])
|
||||
self.ae(payload('transparent_background_colors=')['colors']['transparent_background_colors'], '')
|
||||
self.ae(payload('transparent_background_colors=red@0.5')['colors']['transparent_background_colors'], '#ff0000@0.5')
|
||||
|
||||
windows = [Window(1, 11)]
|
||||
boss = Boss(windows)
|
||||
boss.color_settings_at_startup = {'foreground': Color(1, 2, 3)}
|
||||
boss.transparent_background_colors_at_startup = ((Color(0, 0, 0), 0.25),)
|
||||
|
||||
def response(p):
|
||||
with patch('kitty.colors.patch_colors') as patcher:
|
||||
cmd.response_from_kitty(boss, windows[0], PayloadGetter(cmd, p))
|
||||
patcher.assert_called_once()
|
||||
return patcher.call_args.args
|
||||
|
||||
self.ae(response({'colors': {'foreground': 0xFF0000}}), ({'foreground': 0xFF0000}, None, False))
|
||||
colors = {'foreground': 0xFF0000, 'transparent_background_colors': 'red@0.5'}
|
||||
self.ae(response({'colors': colors, 'configured': True}), ({'foreground': 0xFF0000}, ((Color(255, 0, 0), 0.5),), True))
|
||||
self.ae(colors['transparent_background_colors'], 'red@0.5') # payload must not be mutated
|
||||
self.ae(response({'colors': {'transparent_background_colors': ''}}), ({}, (), False))
|
||||
# reset implies configured even when the client does not set it
|
||||
self.ae(
|
||||
response({'colors': {'transparent_background_colors': 'red@0.5'}, 'reset': True}),
|
||||
({'foreground': int(Color(1, 2, 3))}, ((Color(0, 0, 0), 0.25),), True),
|
||||
)
|
||||
for bad in (0, 'not-a-color@0.5'):
|
||||
with self.subTest(bad=bad), self.assertRaises(RemoteControlErrorWithoutTraceback):
|
||||
response({'colors': {'transparent_background_colors': bad}})
|
||||
|
||||
|
||||
TALK_THREAD_SURVIVES_ACCEPT_ERROR = """
|
||||
import os, socket, sys, time
|
||||
from kitty.fast_data_types import ChildMonitor
|
||||
ls = socket.socket(socket.AF_UNIX)
|
||||
ls.bind(sys.argv[1])
|
||||
ls.listen(8)
|
||||
cm = ChildMonitor(lambda *a: None, None, -1, ls.fileno())
|
||||
a, b = socket.socketpair()
|
||||
cm.inject_peer(os.dup(a.fileno()))
|
||||
cm.fail_next_accepts(2)
|
||||
c = socket.socket(socket.AF_UNIX)
|
||||
c.connect(sys.argv[1])
|
||||
deadline = time.monotonic() + 10
|
||||
while cm.fail_next_accepts(-1) and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
assert cm.fail_next_accepts(-1) == 0, 'injected accept errors not consumed'
|
||||
cm.inject_peer(os.dup(b.fileno()))
|
||||
print('ok', flush=True)
|
||||
os._exit(0)
|
||||
"""
|
||||
|
||||
|
||||
TALK_THREAD_STALLED_PEER = """
|
||||
import os, socket
|
||||
from kitty.fast_data_types import ChildMonitor, send_data_to_peer
|
||||
cm = ChildMonitor(lambda *a: None, None)
|
||||
a, a_remote = socket.socketpair()
|
||||
b, b_remote = socket.socketpair()
|
||||
big = os.urandom(8 * 1024 * 1024)
|
||||
pa = cm.inject_peer(os.dup(a.fileno()))
|
||||
send_data_to_peer(pa, big)
|
||||
pb = cm.inject_peer(os.dup(b.fileno()))
|
||||
send_data_to_peer(pb, b'hello')
|
||||
b_remote.settimeout(10)
|
||||
assert b_remote.recv(16) == b'hello'
|
||||
a_remote.settimeout(10)
|
||||
got = bytearray()
|
||||
while len(got) < len(big):
|
||||
got += a_remote.recv(1024 * 1024)
|
||||
assert got == big, 'stalled peer response corrupted'
|
||||
print('ok', flush=True)
|
||||
os._exit(0)
|
||||
"""
|
||||
|
||||
|
||||
class TestTalkThread(BaseTest):
|
||||
def test_talk_thread_not_blocked_by_stalled_peer(self):
|
||||
p = subprocess.run([kitty_exe(), '+runpy', TALK_THREAD_STALLED_PEER], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(p.returncode, 0, p.stderr)
|
||||
self.assertIn('ok', p.stdout, p.stderr)
|
||||
|
||||
def test_talk_thread_survives_accept_errors(self):
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
p = subprocess.run([kitty_exe(), '+runpy', TALK_THREAD_SURVIVES_ACCEPT_ERROR, os.path.join(tdir, 's')], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(p.returncode, 0, p.stderr)
|
||||
self.assertIn('ok', p.stdout, p.stderr)
|
||||
self.assertEqual(p.stderr.count('accept() on talk socket failed'), 1, p.stderr)
|
||||
@@ -0,0 +1,345 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
import json
|
||||
from math import ceil
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from kitty.layout.base import lgd
|
||||
from kitty.rc.base import PayloadGetter
|
||||
from kitty.rc.resize_window import resize_window
|
||||
from kitty.rc.resize_window_edge import ResizeWindowEdge
|
||||
|
||||
from . import layout as geometry_tests
|
||||
|
||||
|
||||
class TestResizeEntry(geometry_tests.BaseTest):
|
||||
def test_reenter_resize_replaces_existing_overlay(self):
|
||||
from kitty.boss import Boss
|
||||
|
||||
launched = []
|
||||
|
||||
def create_kitten_handler(kitten, args):
|
||||
launched.append(args)
|
||||
raise AssertionError('Launched')
|
||||
|
||||
for name in ('resize_window', 'resize-window'):
|
||||
cmd = ResizeWindowEdge()
|
||||
base = Mock(is_resize_overlay=False)
|
||||
resize = Mock(is_resize_overlay=True)
|
||||
# Another overlay can temporarily cover the resize UI.
|
||||
other = Mock(is_resize_overlay=False)
|
||||
group = SimpleNamespace(windows=[base, resize, other])
|
||||
tab = SimpleNamespace(windows=SimpleNamespace(group_for_window=lambda w: group), set_active_window=Mock())
|
||||
base.tabref = other.tabref = lambda: tab
|
||||
session = cmd.start_session(resize, None)
|
||||
boss = SimpleNamespace(active_window=other, active_tab=tab, mark_window_for_close=Mock())
|
||||
with patch('kitty.rc.resize_window_edge.resize_window_edge', cmd), patch('kittens.runner.create_kitten_handler', create_kitten_handler):
|
||||
with self.assertRaisesRegex(AssertionError, 'Launched'):
|
||||
Boss.run_kitten_with_metadata(boss, name, args=['--strategy=edge'])
|
||||
# The new options are used, the old UI is closed and its snapshot is handed over
|
||||
self.ae(launched.pop(), ['--strategy=edge'])
|
||||
boss.mark_window_for_close.assert_called_once_with(resize)
|
||||
self.assertNotIn(resize, cmd.sessions)
|
||||
new_overlay = Mock()
|
||||
self.assertIs(cmd.start_session(new_overlay, None, session), session)
|
||||
self.assertIs(cmd.sessions[new_overlay], session)
|
||||
tab.set_active_window.assert_not_called()
|
||||
|
||||
def test_resize_reentry_is_scoped_to_kitten_and_pane(self):
|
||||
from kitty.boss import Boss
|
||||
|
||||
shell = SimpleNamespace(is_resize_overlay=False)
|
||||
resize = SimpleNamespace(is_resize_overlay=True)
|
||||
group = SimpleNamespace(windows=[shell])
|
||||
tab = SimpleNamespace(windows=SimpleNamespace(group_for_window=lambda w: group), set_active_window=Mock())
|
||||
window = SimpleNamespace(tabref=lambda: tab)
|
||||
boss = SimpleNamespace(active_window=window, active_tab=tab, mark_window_for_close=Mock())
|
||||
with patch('kittens.runner.create_kitten_handler', side_effect=AssertionError('Normal launch')):
|
||||
with self.assertRaisesRegex(AssertionError, 'Normal launch'):
|
||||
Boss.run_kitten_with_metadata(boss, 'resize_window')
|
||||
group.windows.append(resize)
|
||||
with self.assertRaisesRegex(AssertionError, 'Normal launch'):
|
||||
Boss.run_kitten_with_metadata(boss, 'hints')
|
||||
tab.set_active_window.assert_not_called()
|
||||
boss.mark_window_for_close.assert_not_called()
|
||||
|
||||
|
||||
class TestEdgeResize(geometry_tests.BaseSplitGeometryTest):
|
||||
make_layout = geometry_tests.TestSplitDragGeometry.make_layout
|
||||
positions = geometry_tests.TestSplitDragGeometry.positions
|
||||
fixed_dividers = geometry_tests.TestSplitDragGeometry.fixed_dividers
|
||||
|
||||
def resize(self, tab, window_id, edge, increment, fraction=0):
|
||||
changed = tab.current_layout.modify_size_of_window_edge(tab.windows, window_id, edge, increment, fraction)
|
||||
if changed:
|
||||
tab.relayout()
|
||||
return changed
|
||||
|
||||
def test_nested_edge_selection(self):
|
||||
shape = {'one': 1, 'two': {'one': 2, 'two': {'one': 3, 'two': 4}}}
|
||||
layout, windows, tab = self.make_layout(shape)
|
||||
expected = {1: {'right'}, 2: {'left', 'right'}, 3: {'left', 'right'}, 4: {'left'}}
|
||||
before = self.positions(layout)
|
||||
for window_id, edges in expected.items():
|
||||
found = {edge for edge in ('left', 'right', 'top', 'bottom') if layout.pair_for_window_edge(windows, window_id, edge)}
|
||||
self.ae(found, edges)
|
||||
self.assertIs(layout.pair_for_window_edge(windows, 2, 'left'), layout.pairs_root)
|
||||
self.assertIs(layout.pair_for_window_edge(windows, 2, 'right'), layout.pairs_root.two)
|
||||
self.assertIs(layout.pair_for_window_edge(windows, 3, 'left'), layout.pairs_root.two)
|
||||
self.assertIsNone(layout.pair_for_window_edge(windows, 999, 'left'))
|
||||
self.ae(self.positions(layout), before)
|
||||
shape = {'one': {'horizontal': False, 'one': 1, 'two': 2}, 'two': {'horizontal': False, 'one': 3, 'two': 4}}
|
||||
layout, windows, tab = self.make_layout(shape)
|
||||
for window_id, expected in ((1, {'right', 'bottom'}), (2, {'right', 'top'}), (3, {'left', 'bottom'}), (4, {'left', 'top'})):
|
||||
self.ae({edge for edge in ('left', 'right', 'top', 'bottom') if layout.pair_for_window_edge(windows, window_id, edge)}, expected)
|
||||
|
||||
def test_only_selected_same_axis_divider_moves(self):
|
||||
shapes = (
|
||||
{'one': 1, 'two': {'one': 2, 'two': {'one': 3, 'two': 4}}},
|
||||
{'one': {'one': 1, 'two': 2}, 'two': {'one': 3, 'two': 4}},
|
||||
{'one': 1, 'two': {'one': {'horizontal': False, 'one': 2, 'two': 3}, 'two': 4}},
|
||||
{'horizontal': False, 'one': 1, 'two': {'horizontal': False, 'one': 2, 'two': {'horizontal': False, 'one': 3, 'two': 4}}},
|
||||
)
|
||||
for shape in shapes:
|
||||
for minimal in (True, False):
|
||||
layout, windows, tab = self.make_layout(shape, minimal)
|
||||
for window_id in (1, 2, 3, 4):
|
||||
for edge in ('left', 'right', 'top', 'bottom'):
|
||||
pair = layout.pair_for_window_edge(windows, window_id, edge)
|
||||
if pair is None:
|
||||
continue
|
||||
fixed = self.fixed_dividers(pair)
|
||||
cell = lgd.cell_width if pair.horizontal else lgd.cell_height
|
||||
for increment in (2, -2):
|
||||
before = self.positions(layout)
|
||||
self.assertTrue(self.resize(tab, window_id, edge, increment))
|
||||
after = self.positions(layout)
|
||||
self.ae(after[id(pair)] - before[id(pair)], increment * cell)
|
||||
for pid, position in before.items():
|
||||
if pid != id(pair) and fixed(pid):
|
||||
self.ae(after[pid], position)
|
||||
self.check_extents_fit(layout)
|
||||
|
||||
def test_fractional_steps_limits_and_custom_fraction(self):
|
||||
for horizontal in (True, False):
|
||||
for window_id in (1, 2):
|
||||
for sign in (-1, 1):
|
||||
for remaining in (0, 1, 2, 3, 4, 5, 6, 10):
|
||||
for fraction in (1 / 3, 1 / 4, 1 / 2, 1):
|
||||
layout, windows, tab = self.make_layout({'horizontal': horizontal, 'one': 1, 'two': 2}, num=2)
|
||||
pair = layout.pairs_root
|
||||
edge = ('right' if window_id == 1 else 'left') if horizontal else ('bottom' if window_id == 1 else 'top')
|
||||
step = 2 * (lgd.cell_width if horizontal else lgd.cell_height)
|
||||
pair.move_divider(sign * (pair.width if horizontal else pair.height))
|
||||
tab.relayout()
|
||||
pair.move_divider(-sign * step * remaining)
|
||||
tab.relayout()
|
||||
before = self.positions(layout)[id(pair)]
|
||||
self.ae(self.resize(tab, window_id, edge, sign * 2, fraction), bool(remaining))
|
||||
self.ae(self.positions(layout)[id(pair)] - before, sign * step * ceil(remaining * fraction - 1e-9))
|
||||
while self.resize(tab, window_id, edge, sign * 2, fraction):
|
||||
self.check_extents_fit(layout)
|
||||
before = self.positions(layout)
|
||||
self.assertFalse(self.resize(tab, window_id, edge, sign * 2, fraction))
|
||||
self.ae(self.positions(layout), before)
|
||||
self.assertTrue(self.resize(tab, window_id, edge, -sign * 2, fraction))
|
||||
self.check_extents_fit(layout)
|
||||
|
||||
def test_partial_step_and_invalid_requests(self):
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': 2}, num=2)
|
||||
pair = layout.pairs_root
|
||||
pair.move_divider(pair.width)
|
||||
tab.relayout()
|
||||
partial = lgd.cell_width - 1
|
||||
pair.move_divider(-partial)
|
||||
tab.relayout()
|
||||
before = self.positions(layout)
|
||||
self.assertTrue(self.resize(tab, 1, 'right', 2, 0.25))
|
||||
self.ae(self.positions(layout)[id(pair)] - before[id(pair)], partial)
|
||||
for edge, window_id, increment, fraction in (
|
||||
('left', 1, 2, 0),
|
||||
('right', 999, 2, 0),
|
||||
('right', 1, 0, 0),
|
||||
('right', 1, 2, -1),
|
||||
('right', 1, 2, float('nan')),
|
||||
):
|
||||
before = self.positions(layout)
|
||||
self.assertFalse(self.resize(tab, window_id, edge, increment, fraction))
|
||||
self.ae(self.positions(layout), before)
|
||||
|
||||
def command(self, cmd, tab, window_id, operation, **payload):
|
||||
window = tab.windows.id_map[window_id]
|
||||
window.tabref = lambda: tab
|
||||
boss = SimpleNamespace(active_window=window)
|
||||
return json.loads(cmd.response_from_kitty(boss, window, PayloadGetter(cmd, {'self': True, 'operation': operation, **payload})))
|
||||
|
||||
def test_session_reset_restores_entry_geometry(self):
|
||||
layout, windows, tab = self.make_layout({'bias': 0.3, 'one': 1, 'two': {'bias': 0.4, 'one': 2, 'two': 3}}, num=3)
|
||||
cmd = ResizeWindowEdge()
|
||||
before = self.positions(layout)
|
||||
self.command(cmd, tab, 2, 'start')
|
||||
for edge, increment in (('left', 3), ('right', -2)):
|
||||
selected = self.command(cmd, tab, 2, 'select', edge=edge)
|
||||
self.ae(selected['selected'], edge)
|
||||
self.command(cmd, tab, 2, 'move', edge=edge, increment=increment, divider=selected['divider'])
|
||||
self.assertNotEqual(self.positions(layout), before)
|
||||
restored = self.command(cmd, tab, 2, 'reset')
|
||||
self.ae(self.positions(layout), before)
|
||||
self.ae(restored['selected'], '')
|
||||
self.assertIn('Restored', restored['status'])
|
||||
self.ae(layout.pairs_root.bias, 0.3)
|
||||
self.ae(layout.pairs_root.two.bias, 0.4)
|
||||
self.command(cmd, tab, 2, 'reset')
|
||||
self.ae(self.positions(layout), before)
|
||||
|
||||
def test_entry_selection_and_snapshot_survive_strategy_activation(self):
|
||||
for horizontal in (True, False):
|
||||
layout, windows, tab = self.make_layout({'horizontal': horizontal, 'bias': 0.3, 'one': 1, 'two': 2}, num=2)
|
||||
cmd = ResizeWindowEdge()
|
||||
before = self.positions(layout)
|
||||
# Boss takes the snapshot before either strategy has resized anything.
|
||||
cmd.start_session(windows.id_map[1], layout)
|
||||
layout.pairs_root.bias = 0.6
|
||||
tab.relayout()
|
||||
started = self.command(cmd, tab, 1, 'start')
|
||||
self.ae(started['selected'], 'right' if horizontal else 'bottom')
|
||||
self.assertTrue(started['divider'])
|
||||
self.command(cmd, tab, 1, 'start')
|
||||
self.command(cmd, tab, 1, 'reset')
|
||||
self.ae(self.positions(layout), before)
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': {'one': 2, 'two': 3}}, num=3)
|
||||
started = self.command(ResizeWindowEdge(), tab, 2, 'start')
|
||||
self.ae(started['edges'], ['left', 'right'])
|
||||
self.ae(started['selected'], '')
|
||||
|
||||
def test_no_internal_edge_and_unsupported_layout(self):
|
||||
layout, windows, tab = self.make_layout({'one': 1}, num=1)
|
||||
cmd = ResizeWindowEdge()
|
||||
before = self.positions(layout)
|
||||
started = self.command(cmd, tab, 1, 'start')
|
||||
self.ae(started['edges'], [])
|
||||
self.ae(started['selected'], '')
|
||||
self.command(cmd, tab, 1, 'move', edge='right', increment=2)
|
||||
self.ae(self.positions(layout), before)
|
||||
tab.current_layout = geometry_tests.create_layout(geometry_tests.Tall)
|
||||
unavailable = self.command(cmd, tab, 1, 'start')
|
||||
self.ae(unavailable['edges'], [])
|
||||
self.assertIn('requires the Splits layout', unavailable['status'])
|
||||
|
||||
def test_session_selection_stale_identity_and_structure_change(self):
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': 2}, num=2)
|
||||
cmd = ResizeWindowEdge()
|
||||
before = self.positions(layout)
|
||||
self.command(cmd, tab, 1, 'start')
|
||||
outside = self.command(cmd, tab, 1, 'select', edge='left')
|
||||
self.ae(outside['selected'], '')
|
||||
selected = self.command(cmd, tab, 1, 'select', edge='right')
|
||||
self.ae(selected['selected'], 'right')
|
||||
self.ae(self.positions(layout), before)
|
||||
stale = self.command(cmd, tab, 1, 'move', edge='right', divider='invalid', increment=2)
|
||||
self.ae(stale['selected'], '')
|
||||
self.ae(self.positions(layout), before)
|
||||
layout.pairs_root.horizontal = False
|
||||
tab.relayout()
|
||||
changed = self.positions(layout)
|
||||
refused = self.command(cmd, tab, 1, 'reset')
|
||||
self.assertIn('structure changed', refused['status'])
|
||||
self.ae(self.positions(layout), changed)
|
||||
|
||||
def test_window_reset_restores_same_entry_snapshot(self):
|
||||
layout, windows, tab = self.make_layout({'bias': 0.31, 'one': 1, 'two': {'bias': 0.43, 'one': 2, 'two': 3}}, num=3)
|
||||
window = windows.id_map[2]
|
||||
window.tabref = lambda: tab
|
||||
cmd = ResizeWindowEdge()
|
||||
cmd.start_session(window, layout)
|
||||
before = self.positions(layout)
|
||||
boss = SimpleNamespace(active_window=window, resize_layout_window=Mock())
|
||||
payload = PayloadGetter(resize_window, {'self': True, 'axis': 'reset', 'restore_entry_layout': True})
|
||||
with patch('kitty.rc.resize_window_edge.resize_window_edge', cmd):
|
||||
self.assertTrue(self.resize(tab, 2, 'left', 3))
|
||||
self.assertTrue(self.resize(tab, 2, 'right', -2))
|
||||
self.assertIsNone(resize_window.response_from_kitty(boss, window, payload))
|
||||
self.ae(self.positions(layout), before)
|
||||
boss.resize_layout_window.assert_not_called()
|
||||
layout.pairs_root.horizontal = False
|
||||
tab.relayout()
|
||||
changed = self.positions(layout)
|
||||
result = resize_window.response_from_kitty(boss, window, payload)
|
||||
self.assertIn('structure changed', result)
|
||||
self.ae(self.positions(layout), changed)
|
||||
|
||||
def test_reset_after_leaving_entry_layout_uses_default_reset(self):
|
||||
layout, windows, tab = self.make_layout({'bias': 0.3, 'one': 1, 'two': 2}, num=2)
|
||||
window = windows.id_map[1]
|
||||
window.tabref = lambda: tab
|
||||
cmd = ResizeWindowEdge()
|
||||
cmd.start_session(window, layout)
|
||||
boss = SimpleNamespace(active_window=window, resize_layout_window=Mock(return_value=None))
|
||||
payload = PayloadGetter(resize_window, {'self': True, 'axis': 'reset', 'increment': 2, 'restore_entry_layout': True})
|
||||
with patch('kitty.rc.resize_window_edge.resize_window_edge', cmd):
|
||||
tab.current_layout = geometry_tests.create_layout(geometry_tests.Tall)
|
||||
self.assertIsNone(resize_window.response_from_kitty(boss, window, payload))
|
||||
self.assertTrue(boss.resize_layout_window.call_args.kwargs['reset'])
|
||||
# Returning to the entry layout restores its snapshot again
|
||||
tab.current_layout = layout
|
||||
layout.pairs_root.bias = 0.6
|
||||
boss.resize_layout_window.reset_mock()
|
||||
self.assertIsNone(resize_window.response_from_kitty(boss, window, payload))
|
||||
boss.resize_layout_window.assert_not_called()
|
||||
self.ae(layout.pairs_root.bias, 0.3)
|
||||
|
||||
def test_no_snapshot_when_entered_in_other_layout(self):
|
||||
layout, windows, tab = self.make_layout({'bias': 0.3, 'one': 1, 'two': 2}, num=2)
|
||||
window = windows.id_map[1]
|
||||
window.tabref = lambda: tab
|
||||
tab.reset_window_sizes = Mock()
|
||||
cmd = ResizeWindowEdge()
|
||||
cmd.start_session(window, geometry_tests.create_layout(geometry_tests.Tall))
|
||||
layout.pairs_root.bias = 0.6
|
||||
started = self.command(cmd, tab, 1, 'start')
|
||||
self.assertTrue(started['divider'])
|
||||
moved = self.command(cmd, tab, 1, 'move', edge='right', increment=2, divider=started['divider'])
|
||||
self.ae(moved['status'], '')
|
||||
self.assertFalse(moved['failed'])
|
||||
# Sizes changed after entry must not be treated as the original sizes
|
||||
reset = self.command(cmd, tab, 1, 'reset')
|
||||
tab.reset_window_sizes.assert_called_once_with()
|
||||
self.assertNotIn('Restored', reset['status'])
|
||||
self.assertFalse(reset['failed'])
|
||||
|
||||
def test_failure_flag(self):
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': 2}, num=2)
|
||||
cmd = ResizeWindowEdge()
|
||||
self.command(cmd, tab, 1, 'start')
|
||||
self.assertTrue(self.command(cmd, tab, 1, 'select', edge='left')['failed'])
|
||||
selected = self.command(cmd, tab, 1, 'select', edge='right')
|
||||
self.assertFalse(selected['failed'])
|
||||
while not (moved := self.command(cmd, tab, 1, 'move', edge='right', increment=2, divider=selected['divider']))['failed']:
|
||||
pass
|
||||
self.assertIn('size limit', moved['status'])
|
||||
restored = self.command(cmd, tab, 1, 'reset')
|
||||
self.assertIn('Restored', restored['status'])
|
||||
self.assertFalse(restored['failed'])
|
||||
|
||||
def test_window_reset_without_session_keeps_default_behavior(self):
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': 2}, num=2)
|
||||
window = windows.id_map[1]
|
||||
window.tabref = lambda: tab
|
||||
boss = SimpleNamespace(active_window=window, resize_layout_window=Mock(return_value=None))
|
||||
cmd = ResizeWindowEdge()
|
||||
with patch('kitty.rc.resize_window_edge.resize_window_edge', cmd):
|
||||
for restore in (False, True):
|
||||
payload = PayloadGetter(resize_window, {'self': True, 'axis': 'reset', 'increment': 2, 'restore_entry_layout': restore})
|
||||
self.assertIsNone(resize_window.response_from_kitty(boss, window, payload))
|
||||
self.assertTrue(boss.resize_layout_window.call_args.kwargs['reset'])
|
||||
cmd.start_session(window, layout)
|
||||
before = boss.resize_layout_window.call_count
|
||||
# An ordinary remote-control reset always retains default-size reset.
|
||||
payload = PayloadGetter(resize_window, {'self': True, 'axis': 'reset', 'increment': 2})
|
||||
resize_window.response_from_kitty(boss, window, payload)
|
||||
self.ae(boss.resize_layout_window.call_count, before + 1)
|
||||
for fraction in (-1, 1.1, float('nan'), float('inf')):
|
||||
with self.assertRaises(ValueError):
|
||||
self.command(cmd, tab, 1, 'move', edge='bottom', fraction=fraction)
|
||||
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from copy import deepcopy
|
||||
from math import ceil
|
||||
from types import SimpleNamespace
|
||||
|
||||
from kitty.fast_data_types import Region
|
||||
from kitty.layout.base import lgd
|
||||
from kitty.layout.interface import Fat, Grid, Horizontal, Stack, Tall, Vertical
|
||||
from kitty.rc.base import PayloadGetter
|
||||
from kitty.rc.resize_window import resize_window
|
||||
from kitty.tabs import Tab
|
||||
|
||||
from . import layout as geometry_tests
|
||||
|
||||
|
||||
class TestFractionalResize(geometry_tests.BaseSplitGeometryTest):
|
||||
make_layout = geometry_tests.TestSplitDragGeometry.make_layout
|
||||
|
||||
def resize(self, tab, window_id, increment, horizontal, fraction=1 / 3):
|
||||
return Tab.resize_window_by(tab, window_id, increment, horizontal, fraction) is None
|
||||
|
||||
def test_fractional_splits_steps(self):
|
||||
for horizontal in (True, False):
|
||||
for window_id in (1, 2):
|
||||
for increment in (-2, 2):
|
||||
for remaining in (0, 1, 2, 3, 4, 5, 6, 10):
|
||||
with self.subTest(axis=horizontal, window=window_id, increment=increment, remaining=remaining):
|
||||
layout, windows, tab = self.make_layout({'horizontal': horizontal, 'one': 1, 'two': 2}, num=2)
|
||||
pair = layout.pairs_root
|
||||
size = pair.width if horizontal else pair.height
|
||||
cell = lgd.cell_width if horizontal else lgd.cell_height
|
||||
low = (cell + pair.border_width + 0.5) / size
|
||||
high = (size - cell - pair.border_width + 0.5) / size
|
||||
delta = layout.bias_increment_for_cell(windows, horizontal) * increment * (1 if window_id == 1 else -1)
|
||||
pair.bias = (high if delta > 0 else low) - remaining * delta
|
||||
tab.relayout()
|
||||
before = pair.bias
|
||||
self.ae(self.resize(tab, window_id, increment, horizontal), bool(remaining))
|
||||
self.assertAlmostEqual(pair.bias, before + delta * ((remaining + 2) // 3))
|
||||
self.check_extents_fit(layout)
|
||||
while self.resize(tab, window_id, increment, horizontal):
|
||||
self.check_extents_fit(layout)
|
||||
at_limit = pair.bias
|
||||
for _ in range(3):
|
||||
self.assertFalse(self.resize(tab, window_id, increment, horizontal))
|
||||
self.ae(pair.bias, at_limit)
|
||||
self.assertTrue(self.resize(tab, window_id, -increment, horizontal))
|
||||
self.check_extents_fit(layout)
|
||||
|
||||
def test_fractional_splits_partial_step_and_options(self):
|
||||
for fraction in (1 / 4, 1 / 3, 1 / 2, 1):
|
||||
for increment in (-2, 2):
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': 2}, num=2)
|
||||
pair = layout.pairs_root
|
||||
delta = layout.bias_increment_for_cell(windows, True) * increment
|
||||
limit = (
|
||||
(pair.width - lgd.cell_width - pair.border_width + 0.5) / pair.width
|
||||
if delta > 0
|
||||
else (lgd.cell_width + pair.border_width + 0.5) / pair.width
|
||||
)
|
||||
pair.bias = limit - 9.75 * delta
|
||||
tab.relayout()
|
||||
before = pair.bias
|
||||
self.assertTrue(self.resize(tab, 1, increment, True, fraction))
|
||||
expected = before + ceil(10 * fraction) * delta
|
||||
self.assertAlmostEqual(pair.bias, min(expected, limit) if delta > 0 else max(expected, limit))
|
||||
pair.bias = limit - 0.25 * delta
|
||||
tab.relayout()
|
||||
self.assertTrue(self.resize(tab, 1, increment, True, fraction))
|
||||
self.assertAlmostEqual(pair.bias, limit)
|
||||
self.assertFalse(self.resize(tab, 1, increment, True, fraction))
|
||||
self.check_extents_fit(layout)
|
||||
|
||||
def test_fractional_splits_nested_and_saturated(self):
|
||||
shape = {'one': 1, 'two': {'horizontal': False, 'one': 2, 'two': {'one': 3, 'two': 4}}}
|
||||
for minimal in (True, False):
|
||||
for increment in (-2, 2):
|
||||
layout, _windows, tab = self.make_layout(shape, minimal)
|
||||
pair = layout.pairs_root
|
||||
others = {id(p): p.bias for p in pair.self_and_descendants() if p is not pair}
|
||||
pair.bias = 0 if increment > 0 else 1
|
||||
tab.relayout()
|
||||
self.assertTrue(self.resize(tab, 2, -increment, True))
|
||||
self.assertGreater(pair.bias, 0.1)
|
||||
self.assertLess(pair.bias, 0.9)
|
||||
self.ae({id(p): p.bias for p in pair.self_and_descendants() if p is not pair}, others)
|
||||
self.check_extents_fit(layout)
|
||||
|
||||
def other_layout(self, cls, num, opts=''):
|
||||
layout = geometry_tests.create_layout(cls)
|
||||
if opts:
|
||||
layout.layout_opts = layout.parse_layout_opts(opts)
|
||||
layout.remove_all_biases()
|
||||
windows = geometry_tests.create_windows(layout, num)
|
||||
self.stub_dimensions(layout, Region((0, 0, 1499, 1099, 1500, 1100)))
|
||||
layout(windows)
|
||||
return layout, windows
|
||||
|
||||
def test_fractional_all_layouts(self):
|
||||
# Compare with actual ordinary resizing and rendered geometries. This
|
||||
# catches incorrect counts and accidental mutation during the probe.
|
||||
for cls in (Tall, Fat, Grid, Vertical, Horizontal):
|
||||
for num in (2, 5):
|
||||
for horizontal in (True, False):
|
||||
for increment in (-2, 2):
|
||||
for window_id in (1, num):
|
||||
with self.subTest(layout=cls.name, windows=num, axis=horizontal, increment=increment, window=window_id):
|
||||
reference, ref_windows = self.other_layout(cls, num)
|
||||
step = reference.bias_increment_for_cell(ref_windows, horizontal) * increment
|
||||
states = []
|
||||
for _ in range(500):
|
||||
before = tuple(w.geometry for w in ref_windows)
|
||||
if not reference.modify_size_of_window(ref_windows, window_id, step, horizontal):
|
||||
break
|
||||
reference(ref_windows)
|
||||
if tuple(w.geometry for w in ref_windows) == before:
|
||||
break
|
||||
states.append(deepcopy(reference.layout_state()))
|
||||
else:
|
||||
self.fail('Ordinary resizing did not stop')
|
||||
layout, windows = self.other_layout(cls, num)
|
||||
before = deepcopy(layout.layout_state())
|
||||
changed = layout.modify_size_of_window_by_fraction(windows, window_id, step, horizontal, 1 / 3)
|
||||
self.ae(changed, bool(states))
|
||||
self.ae(layout.layout_state(), states[(len(states) + 2) // 3 - 1] if states else before)
|
||||
|
||||
def test_fractional_tall_full_size_and_mirrored(self):
|
||||
for cls in (Tall, Fat):
|
||||
for opts in ('full_size=2', 'full_size=3;mirrored=yes'):
|
||||
for window_id in (1, 5):
|
||||
layout, windows = self.other_layout(cls, 5, opts)
|
||||
step = layout.bias_increment_for_cell(windows, cls.main_is_horizontal) * 2
|
||||
self.assertTrue(layout.modify_size_of_window_by_fraction(windows, window_id, step, cls.main_is_horizontal, 1 / 3))
|
||||
layout(windows)
|
||||
self.assertTrue(all(w.geometry.xnum > 0 and w.geometry.ynum > 0 for w in windows))
|
||||
|
||||
def test_fractional_unavailable_and_invalid(self):
|
||||
for cls in (Stack, Tall, Fat, Grid, Vertical, Horizontal):
|
||||
layout, windows = self.other_layout(cls, 1)
|
||||
before = deepcopy(layout.layout_state())
|
||||
self.assertFalse(layout.modify_size_of_window_by_fraction(windows, 1, 0.1, True, 1 / 3))
|
||||
self.ae(layout.layout_state(), before)
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': 2}, num=2)
|
||||
for window_id, increment, horizontal in ((999, 2, True), (1, 0, True), (1, 2, False)):
|
||||
self.assertFalse(self.resize(tab, window_id, increment, horizontal))
|
||||
for fraction in (0, -1, 1.1, float('nan'), float('inf')):
|
||||
self.assertFalse(layout.modify_size_of_window_by_fraction(windows, 1, 0.1, True, fraction))
|
||||
|
||||
def test_fractional_remote_validation_and_compatibility(self):
|
||||
calls = []
|
||||
boss = SimpleNamespace(resize_layout_window=lambda *a, **kw: calls.append(kw))
|
||||
window = SimpleNamespace(id=1)
|
||||
original = resize_window.windows_for_match_payload
|
||||
resize_window.windows_for_match_payload = lambda *a: [window]
|
||||
self.addCleanup(lambda: setattr(resize_window, 'windows_for_match_payload', original))
|
||||
for fraction in (None, 0, 1 / 3, 1):
|
||||
payload = {'increment': 2, 'axis': 'horizontal'}
|
||||
if fraction is not None:
|
||||
payload['fraction'] = fraction
|
||||
resize_window.response_from_kitty(boss, window, PayloadGetter(resize_window, payload))
|
||||
self.ae(calls[-1]['fraction'], fraction or 0)
|
||||
for fraction in (-1, 1.1, float('nan'), float('inf')):
|
||||
with self.assertRaises(ValueError):
|
||||
resize_window.response_from_kitty(boss, window, PayloadGetter(resize_window, {'fraction': fraction}))
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestSQP(BaseTest):
|
||||
def test_search_query_parser(self):
|
||||
from kitty.search_query_parser import ParseException, search
|
||||
|
||||
locations = 'id'
|
||||
universal_set = {1, 2, 3, 4, 5}
|
||||
|
||||
def get_matches(location, query, candidates):
|
||||
return {x for x in candidates if query == str(x)}
|
||||
|
||||
def t(q, expected=set()):
|
||||
actual = search(q, locations, universal_set, get_matches)
|
||||
self.ae(actual, expected)
|
||||
|
||||
t('id:1', {1})
|
||||
t('id:"1"', {1})
|
||||
t('id:1 and id:1', {1})
|
||||
t('id:1 or id:2', {1, 2})
|
||||
t('id:1 and id:2')
|
||||
t('not id:1', universal_set - {1})
|
||||
t('(id:1 or id:2) and id:1', {1})
|
||||
self.assertRaises(ParseException, t, '1')
|
||||
self.assertRaises(ParseException, t, '"id:1"')
|
||||
|
||||
def test_search_query_lexing(self):
|
||||
import re
|
||||
|
||||
from kitty.search_query_parser import ParseException, Parser, Token, TokenType, build_tree, lex_scanner
|
||||
|
||||
# Capturing groups in a re.Scanner lexicon break the mapping from
|
||||
# matched group to lexicon entry and are rejected outright by
|
||||
# Python 3.15, see https://github.com/python/cpython/issues/140797
|
||||
for pattern, _action in lex_scanner().__self__.lexicon:
|
||||
self.ae(re.compile(pattern).groups, 0, f'The lexicon pattern {pattern!r} uses a capturing group')
|
||||
|
||||
# A backslash escaped quote must not terminate a quoted word. The
|
||||
# parser escapes these before lexing, so test the lexer directly too.
|
||||
self.ae(lex_scanner()(r'"a\"b" c'), ([Token(TokenType.QUOTED_WORD, r'a\"b'), Token(TokenType.WORD, 'c')], ''))
|
||||
|
||||
p = Parser(allow_no_location=True)
|
||||
|
||||
def t(q, *expected):
|
||||
self.ae(tuple(p.tokenize(q)), expected)
|
||||
|
||||
opcode, word, quoted = TokenType.OPCODE, TokenType.WORD, TokenType.QUOTED_WORD
|
||||
t('id:1', (word, 'id:1'))
|
||||
t('id:"1"', (word, 'id:'), (quoted, '1'))
|
||||
t('""', (quoted, ''))
|
||||
t('"a b"', (quoted, 'a b'))
|
||||
t('"a\nb"', (quoted, 'a\nb'))
|
||||
t('"a(b)"', (quoted, 'a(b)'))
|
||||
t(r'"a\"b"', (quoted, 'a"b'))
|
||||
t(r'"a\\b"', (quoted, 'a\\b'))
|
||||
t(r'\"a\"', (word, '"a"'))
|
||||
t('(a or "b c")', (opcode, '('), (word, 'a'), (word, 'or'), (quoted, 'b c'), (opcode, ')'))
|
||||
self.assertRaises(ParseException, p.tokenize, '"unterminated')
|
||||
|
||||
tree = build_tree(r'id:"a\"b" and id:"c d"', 'id')
|
||||
self.ae([(n.location, n.query) for n in tree.iter_token_nodes()], [('id', 'a"b'), ('id', 'c d')])
|
||||
@@ -0,0 +1,293 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3
|
||||
|
||||
from functools import partial
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.config import load_config
|
||||
from kitty.fast_data_types import (
|
||||
GLFW_DRAG_OPERATION_COPY,
|
||||
GLFW_MOD_SHIFT,
|
||||
GLFW_MOUSE_BUTTON_LEFT,
|
||||
GLFW_MOUSE_BUTTON_RIGHT,
|
||||
MOUSE_SELECTION_DRAG_OR_NORMAL_SELECT,
|
||||
create_mock_window,
|
||||
mock_mouse_selection,
|
||||
set_options,
|
||||
)
|
||||
from kitty.window import Window
|
||||
|
||||
from .base import BaseTest, draw_multicell
|
||||
from .mouse import send_mouse_event
|
||||
|
||||
LEFT = GLFW_MOUSE_BUTTON_LEFT
|
||||
|
||||
|
||||
class TestSelectionDrag(BaseTest):
|
||||
def drag_screen(self, *config, cols=40, lines=6):
|
||||
s = self.create_screen(cols=cols, lines=lines, scrollback=20)
|
||||
errors = []
|
||||
opts = load_config(
|
||||
overrides=(
|
||||
'pixel_scroll no',
|
||||
'click_interval 0.5',
|
||||
'drag_threshold 5',
|
||||
'mouse_map left press ungrabbed mouse_selection drag_or_normal_select',
|
||||
*config,
|
||||
),
|
||||
accumulate_bad_lines=errors,
|
||||
)
|
||||
self.ae(errors, [])
|
||||
set_options(opts)
|
||||
w = create_mock_window(s)
|
||||
s.callbacks.mouse_selection = lambda code: mock_mouse_selection(w, s.callbacks.current_mouse_button, code)
|
||||
drags = []
|
||||
s.callbacks.drag_selection = lambda: drags.append(''.join(s.text_for_selection()))
|
||||
return s, partial(send_mouse_event, w), drags
|
||||
|
||||
@staticmethod
|
||||
def select(s, start=(0, 0), end=(5, 0), rectangle=False):
|
||||
s.start_selection(*start, rectangle, 0, True)
|
||||
s.update_selection(*end, True)
|
||||
|
||||
def test_selection_drag_gesture(self):
|
||||
s, ev, drags = self.drag_screen()
|
||||
s.draw('alpha beta gamma')
|
||||
self.select(s)
|
||||
ev(LEFT, x=1, pixel_x=12, clear_click_queue=True)
|
||||
self.ae(''.join(s.text_for_selection()), 'alpha')
|
||||
ev(x=1, pixel_x=16)
|
||||
ev(x=1, pixel_x=17) # Exactly the threshold is not a drag.
|
||||
self.ae(drags, [])
|
||||
self.ae(''.join(s.text_for_selection()), 'alpha')
|
||||
ev(x=1, pixel_x=18) # A drag can start without leaving the cell.
|
||||
ev(x=2)
|
||||
self.ae(drags, ['alpha'])
|
||||
self.ae(''.join(s.text_for_selection()), 'alpha')
|
||||
|
||||
# Native drag-and-drop consumes mouse-up, even if the drop is canceled.
|
||||
# The next gesture must work without delivering the previous release.
|
||||
ev(LEFT, x=6, clear_click_queue=True)
|
||||
ev(x=10)
|
||||
ev(LEFT, x=10, is_release=True)
|
||||
self.ae(''.join(s.text_for_selection()), 'beta')
|
||||
self.ae(drags, ['alpha'])
|
||||
ev(x=20)
|
||||
self.ae(drags, ['alpha'])
|
||||
|
||||
def test_selection_drag_clicks(self):
|
||||
s, ev, drags = self.drag_screen()
|
||||
s.draw('alpha beta gamma')
|
||||
self.select(s)
|
||||
ev(LEFT, x=1, clear_click_queue=True)
|
||||
ev(x=1, pixel_x=13)
|
||||
ev(LEFT, x=1, is_release=True)
|
||||
self.assertFalse(s.has_selection())
|
||||
ev(x=20)
|
||||
self.ae(drags, [])
|
||||
|
||||
for count, expected in ((2, 'alpha'), (3, 'alpha beta gamma')):
|
||||
with self.subTest(clicks=count):
|
||||
self.select(s)
|
||||
for i in range(count):
|
||||
ev(LEFT, x=1, clear_click_queue=i == 0)
|
||||
if i != count - 1:
|
||||
ev(LEFT, x=1, is_release=True)
|
||||
self.ae(''.join(s.text_for_selection()), expected)
|
||||
ev(x=12)
|
||||
ev(LEFT, x=12, is_release=True)
|
||||
self.assertTrue(s.has_selection())
|
||||
self.ae(drags, [])
|
||||
|
||||
def test_selection_drag_configuration(self):
|
||||
for config, button in (
|
||||
(('drag_threshold 0',), LEFT),
|
||||
(('mouse_map left press ungrabbed mouse_selection normal',), LEFT),
|
||||
(('mouse_map right press ungrabbed mouse_selection drag_or_normal_select',), GLFW_MOUSE_BUTTON_RIGHT),
|
||||
):
|
||||
with self.subTest(config=config):
|
||||
s, ev, drags = self.drag_screen(*config)
|
||||
s.draw('alpha beta gamma')
|
||||
self.select(s)
|
||||
ev(button, x=1, clear_click_queue=True)
|
||||
ev(x=4)
|
||||
ev(button, x=4, is_release=True)
|
||||
self.ae(drags, [])
|
||||
self.ae(''.join(s.text_for_selection()), 'lph')
|
||||
|
||||
s, ev, drags = self.drag_screen('mouse_map shift+left press grabbed mouse_selection drag_or_normal_select')
|
||||
s.draw('alpha beta gamma')
|
||||
self.select(s)
|
||||
s.set_mode(1002, True) # The terminal program owns unmodified mouse events.
|
||||
ev(LEFT, x=1, clear_click_queue=True)
|
||||
ev(x=4)
|
||||
ev(LEFT, x=4, is_release=True)
|
||||
self.ae(drags, [])
|
||||
self.ae(''.join(s.text_for_selection()), 'alpha')
|
||||
ev(LEFT, x=1, modifiers=GLFW_MOD_SHIFT, clear_click_queue=True)
|
||||
ev(x=4, modifiers=GLFW_MOD_SHIFT)
|
||||
self.ae(drags, ['alpha'])
|
||||
|
||||
def test_selection_drag_links(self):
|
||||
s, ev, drags = self.drag_screen('mouse_map left click ungrabbed')
|
||||
s.draw('https://example.com')
|
||||
urls = []
|
||||
s.callbacks.drag_url = lambda url, hyperlink_id: urls.append(url)
|
||||
self.select(s, (8, 0), (15, 0))
|
||||
ev(x=10)
|
||||
ev(LEFT, x=10, clear_click_queue=True)
|
||||
ev(x=11)
|
||||
self.ae(drags, ['example'])
|
||||
self.ae(urls, [])
|
||||
s.clear_selection()
|
||||
ev(x=10)
|
||||
self.assertNotIn(2, s.current_selections())
|
||||
ev(LEFT, x=10, clear_click_queue=True)
|
||||
ev(x=11)
|
||||
self.ae(urls, ['https://example.com'])
|
||||
self.ae(drags, ['example'])
|
||||
|
||||
def test_selection_drag_click_count(self):
|
||||
s, ev, drags = self.drag_screen()
|
||||
s.draw('https://example.com')
|
||||
urls = []
|
||||
s.callbacks.drag_url = lambda url, hyperlink_id: urls.append(url)
|
||||
codes = []
|
||||
dispatch = s.callbacks.mouse_selection
|
||||
|
||||
def record(code):
|
||||
codes.append(code)
|
||||
dispatch(code)
|
||||
|
||||
s.callbacks.mouse_selection = record
|
||||
# A native drag consumes mouse-up, so the press must not linger in the
|
||||
# click queue, otherwise the next press counts as a double press and
|
||||
# selects a word instead of starting a new gesture. This applies to
|
||||
# link drags just as much as to text drags.
|
||||
for i in range(1, 3):
|
||||
with self.subTest(gesture=i):
|
||||
ev(x=10)
|
||||
ev(LEFT, x=10, pixel_x=100)
|
||||
ev(x=10, pixel_x=106) # exceed the threshold without leaving the cell
|
||||
self.ae(codes, [MOUSE_SELECTION_DRAG_OR_NORMAL_SELECT] * i)
|
||||
self.ae(urls, ['https://example.com'] * i)
|
||||
self.ae(drags, [])
|
||||
|
||||
def test_selection_drag_hit_testing(self):
|
||||
for kind in ('forward', 'backward', 'rectangle', 'unicode', 'multicell', 'scrollback', 'alternate'):
|
||||
with self.subTest(kind=kind):
|
||||
s, ev, drags = self.drag_screen(cols=12, lines=4)
|
||||
if kind == 'alternate':
|
||||
s.toggle_alt_screen()
|
||||
if kind == 'multicell':
|
||||
s.draw('a')
|
||||
draw_multicell(s, 'X', scale=2)
|
||||
s.draw('bc')
|
||||
elif kind == 'unicode':
|
||||
s.draw('a中文😀e\u0301b')
|
||||
else:
|
||||
for i in range(8 if kind == 'scrollback' else 3):
|
||||
s.draw(f'{i} abcdefghij\r\n')
|
||||
if kind == 'scrollback':
|
||||
s.scroll(2, True)
|
||||
start, end = (2, 0), (5, 2)
|
||||
if kind == 'backward':
|
||||
start, end = end, start
|
||||
for y in range(s.lines):
|
||||
for x in range(s.columns):
|
||||
self.select(s, start, end, kind == 'rectangle')
|
||||
selected = bool(s.current_selections()[y * s.columns + x] & 1)
|
||||
text = ''.join(s.text_for_selection())
|
||||
before = len(drags)
|
||||
ev(LEFT, x=x, y=y, clear_click_queue=True)
|
||||
ev(x=x, y=y, pixel_x=x * 10 + 6)
|
||||
self.ae(len(drags) - before, int(selected), f'{kind}: cell {(x, y)}')
|
||||
if selected:
|
||||
self.ae(drags[-1], text)
|
||||
ev(LEFT, x=x, y=y, is_release=True)
|
||||
|
||||
def test_selection_drag_payload(self):
|
||||
s, _, _ = self.drag_screen()
|
||||
text = '中文 😀 e\u0301\t value\n' * 100
|
||||
w = SimpleNamespace(
|
||||
text_for_selection=lambda: text,
|
||||
screen=s,
|
||||
geometry=SimpleNamespace(left=0, right=400),
|
||||
os_window_id=1,
|
||||
)
|
||||
w.drag_thumbnails = partial(Window.drag_thumbnails, w)
|
||||
with (
|
||||
patch('kitty.window.draw_single_line_of_text', return_value=(b'\0' * 4, 1)) as draw,
|
||||
patch('kitty.window.start_drag_with_data') as start,
|
||||
patch('kitty.window.set_clipboard_string') as clipboard,
|
||||
):
|
||||
for macos in (True, False):
|
||||
with self.subTest(macos=macos), patch('kitty.window.is_macos', macos):
|
||||
Window.drag_selection(w)
|
||||
data = start.call_args.args[1]
|
||||
self.ae(data['text/plain'], text.encode('utf-8'))
|
||||
if macos:
|
||||
self.ae(len(data), 1) # Cocoa creates a separate drag item for each MIME type.
|
||||
else:
|
||||
self.ae(data['text/plain;charset=utf-8'], text.encode('utf-8'))
|
||||
self.ae(start.call_args.args[2:], (((b'\0' * 4, 1, 1),), GLFW_DRAG_OPERATION_COPY))
|
||||
preview = draw.call_args.args[1]
|
||||
self.assertLess(len(preview), 260)
|
||||
self.assertNotIn('\n', preview)
|
||||
self.assertNotIn('\t', preview)
|
||||
start.side_effect = OSError('drag canceled')
|
||||
with patch('kitty.window.log_error') as log:
|
||||
Window.drag_selection(w)
|
||||
log.assert_called_once()
|
||||
text = ''
|
||||
start.reset_mock()
|
||||
Window.drag_selection(w)
|
||||
start.assert_not_called()
|
||||
clipboard.assert_not_called()
|
||||
|
||||
def test_selection_drag_paste_policy(self):
|
||||
s, _, _ = self.drag_screen()
|
||||
for text, bracketed, confirm in (
|
||||
('single line', False, False),
|
||||
('first\nsecond', False, True),
|
||||
('first\nsecond', True, False),
|
||||
('text\x1b[31m', True, True),
|
||||
):
|
||||
with self.subTest(text=text, bracketed=bracketed):
|
||||
(s.set_mode if bracketed else s.reset_mode)(2004, True)
|
||||
pasted = []
|
||||
w = SimpleNamespace(destroyed=False, at_prompt=False, screen=s, paste_text=pasted.append)
|
||||
w.handle_dangerous_paste_confirmation = partial(Window.handle_dangerous_paste_confirmation, w)
|
||||
with patch('kitty.window.get_boss') as boss:
|
||||
Window.paste_with_actions(w, text, from_drop=True)
|
||||
self.ae(boss.return_value.choose.called, confirm)
|
||||
self.ae(pasted, [] if confirm else [text.encode('utf-8')])
|
||||
|
||||
def test_selection_drag_clipped_multicell(self):
|
||||
s, ev, drags = self.drag_screen(cols=12, lines=4)
|
||||
draw_multicell(s, 'X', scale=3)
|
||||
s.cursor_position(4, 1)
|
||||
s.linefeed()
|
||||
s.scroll(1, True)
|
||||
self.select(s, (0, 0), (3, 0))
|
||||
s.scroll(1, False)
|
||||
# The selected row has left the viewport. The remaining rows of the
|
||||
# large character are not highlighted and must not start a text drag.
|
||||
self.assertFalse(any(c & 1 for c in s.current_selections()))
|
||||
ev(LEFT, x=1, clear_click_queue=True)
|
||||
ev(x=1, pixel_x=16)
|
||||
self.ae(drags, [])
|
||||
ev(LEFT, x=1, is_release=True)
|
||||
|
||||
def test_selection_drag_resumes_rendering(self):
|
||||
s, ev, drags = self.drag_screen()
|
||||
s.draw('alpha beta gamma')
|
||||
self.select(s)
|
||||
self.assertTrue(s.pause_rendering(True, 5000))
|
||||
ev(LEFT, x=1, clear_click_queue=True)
|
||||
# Mouse selection ends synchronized output, including when preserving
|
||||
# an existing selection while waiting for the drag threshold.
|
||||
self.assertFalse(s.pause_rendering(False))
|
||||
ev(x=2)
|
||||
self.ae(drags, ['alpha'])
|
||||
@@ -0,0 +1,410 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from kitty.fast_data_types import Screen
|
||||
from kitty.os_window_size import WindowSize, WindowSizes, initial_window_size_func
|
||||
from kitty.session import get_os_window_sizing_data, parse_session
|
||||
|
||||
from .base import BaseTest, parse_bytes
|
||||
|
||||
|
||||
class TestSessions(BaseTest):
|
||||
def test_session_size_overrides_remembered_size(self) -> None:
|
||||
opts = self.set_options({'remember_window_size': True})
|
||||
with_size, without_size = parse_session('os_window_size 1180 760\nlaunch\nnew_os_window\nlaunch', opts)
|
||||
remembered = {'window-size': (900, 600)}
|
||||
sd = get_os_window_sizing_data(opts, with_size)
|
||||
self.ae((sd.remember_window_size, sd.initial_window_sizes), (False, WindowSizes(WindowSize(1180, 'px'), WindowSize(760, 'px'))))
|
||||
for session in (without_size, None):
|
||||
sd = get_os_window_sizing_data(opts, session)
|
||||
self.assertTrue(sd.remember_window_size)
|
||||
self.ae(initial_window_size_func(sd, remembered)(10, 20, 72, 72, 1, 1), (900, 600))
|
||||
|
||||
def test_session_os_window_geometry(self) -> None:
|
||||
from kitty.fast_data_types import WINDOW_FULLSCREEN, WINDOW_MAXIMIZED, WINDOW_NORMAL
|
||||
from kitty.tabs import os_window_geometry_as_session
|
||||
|
||||
opts = self.set_options()
|
||||
first, second = parse_session('os_window_position -1200x80\nlaunch\nnew_os_window\nlaunch', opts)
|
||||
self.ae((first.os_window_position, second.os_window_position), ((-1200, 80), None))
|
||||
with self.assertRaises(ValueError):
|
||||
tuple(parse_session('os_window_position 100\nlaunch', opts))
|
||||
|
||||
g = {'x': -1200, 'y': 80, 'width': 1180, 'height': 760, 'state': WINDOW_MAXIMIZED}
|
||||
lines = os_window_geometry_as_session(g)
|
||||
self.ae(lines, ['os_window_size 1180 760', 'os_window_position -1200x80', 'os_window_state maximized'])
|
||||
self.ae(os_window_geometry_as_session(g, include_position=False), [lines[0], lines[2]])
|
||||
(s,) = parse_session('\n'.join(lines + ['launch']), opts)
|
||||
size = WindowSizes(WindowSize(1180, 'px'), WindowSize(760, 'px'))
|
||||
self.ae((s.os_window_size, s.os_window_position, s.os_window_state), (size, (-1200, 80), 'maximized'))
|
||||
for state, name in ((WINDOW_FULLSCREEN, 'fullscreen'), (WINDOW_NORMAL, 'normal')):
|
||||
self.ae(os_window_geometry_as_session({**g, 'state': state})[-1], f'os_window_state {name}')
|
||||
|
||||
def test_scrollback_for_restore(self) -> None:
|
||||
from kitty.logout_session import sanitize_restored_output, scrollback_for_restore
|
||||
from kitty.window import as_text
|
||||
|
||||
def restore(data: bytes, cols: int = 10, lines: int = 4, scrollback: int = 20) -> Screen:
|
||||
s = self.create_screen(cols=cols, lines=lines, scrollback=scrollback)
|
||||
s.restore_scrollback(sanitize_restored_output(data.decode()).encode())
|
||||
return s
|
||||
|
||||
def text(s: Screen) -> list[str]:
|
||||
return as_text(s, add_history=True).rstrip('\n').splitlines()
|
||||
|
||||
src = self.create_screen(cols=10, lines=4, scrollback=20)
|
||||
parse_bytes(
|
||||
src, b''.join(b'line %d\r\n' % i for i in range(8)) + b'\x1b[31mred\x1b[m 0123456789abcdef\r\n\x1b]8;;https://x.org\x1b\\link\x1b]8;;\x1b\\'
|
||||
)
|
||||
expected, expected_ansi = text(src), as_text(src, as_ansi=True, add_history=True).rstrip('\n')
|
||||
# Output on the alternate screen, such as from a full screen program, is not restored
|
||||
parse_bytes(src, b'\x1b[?1049hfull screen program')
|
||||
data = scrollback_for_restore(src)
|
||||
self.assertNotIn(b'full screen program', data)
|
||||
self.assertFalse(data.endswith(b'\r\n'))
|
||||
same_width = restore(data)
|
||||
self.ae(text(same_width), expected)
|
||||
self.ae(as_text(same_width, as_ansi=True, add_history=True).rstrip('\n'), expected_ansi)
|
||||
# Wrapped lines are re-wrapped to the width of the new screen
|
||||
wider = restore(data, cols=30)
|
||||
self.ae(text(wider)[-2:], ['red 0123456789abcdef', 'link'])
|
||||
self.assertTrue(any(url.endswith('https://x.org') for url, hyperlink_id in wider.hyperlinks_as_set()))
|
||||
|
||||
# The scrollback pager history is not saved, so at most scrollback + lines lines are restored
|
||||
src = self.create_screen(cols=10, lines=4, scrollback=5)
|
||||
parse_bytes(src, b'\r\n'.join(b'%d' % i for i in range(30)))
|
||||
self.ae(text(restore(scrollback_for_restore(src), scrollback=50)), [str(i) for i in range(21, 30)])
|
||||
|
||||
# The shell prompt the cursor is at is not restored, since the restored shell shows a new one
|
||||
def restored_lines(data: bytes, lines: int = 6) -> list[str]:
|
||||
src = self.create_screen(cols=20, lines=lines, scrollback=50)
|
||||
parse_bytes(src, data)
|
||||
return text(restore(scrollback_for_restore(src), cols=20, lines=lines, scrollback=50))
|
||||
|
||||
prompt, output = b'\x1b]133;A\x07', b'\x1b]133;C\x07'
|
||||
self.ae(restored_lines(prompt + b'$ ls\r\n' + output + b'a\r\nb\r\n' + prompt + b'$ partial'), ['$ ls', 'a', 'b'])
|
||||
two_line_prompt = prompt + b'~/project on main\r\n$ '
|
||||
self.ae(restored_lines(two_line_prompt + b'ls\r\n' + output + b'a\r\n' + two_line_prompt), ['~/project on main', '$ ls', 'a'])
|
||||
many = b''.join(b'%d\r\n' % i for i in range(10))
|
||||
self.ae(restored_lines(prompt + b'$ seq\r\n' + output + many + prompt + b'$ ', lines=4), ['$ seq'] + [str(i) for i in range(10)])
|
||||
# A running command is restored with all its output
|
||||
self.ae(restored_lines(prompt + b'$ tail -f log\r\n' + output + b'a\r\nb'), ['$ tail -f log', 'a', 'b'])
|
||||
|
||||
# Shell integration marks are not restored, so restored output is not treated as the output of a command
|
||||
src = self.create_screen(cols=20, lines=6, scrollback=50)
|
||||
parse_bytes(src, prompt + b'$ ls\r\n' + output + b'a\r\n' + prompt + b'$ ')
|
||||
data = scrollback_for_restore(src)
|
||||
self.assertIn(b'\x1b]133;C', data)
|
||||
self.assertNotIn('\x1b]133;', sanitize_restored_output(data.decode()))
|
||||
|
||||
# Output larger than the parser buffer
|
||||
big = self.create_screen(cols=80, lines=4, scrollback=20)
|
||||
big.restore_scrollback(b''.join(b'%05d %s\r\n' % (i, b'x' * 70) for i in range(16000)))
|
||||
self.ae(text(big)[-1], '15999 ' + 'x' * 70)
|
||||
|
||||
# Restoring scrollback while the child is writing to the screen raises instead of crashing
|
||||
s = self.create_screen()
|
||||
s.test_create_write_buffer()
|
||||
with self.assertRaises(RuntimeError):
|
||||
s.restore_scrollback(b'x')
|
||||
|
||||
def test_sanitize_restored_output(self) -> None:
|
||||
from kitty.logout_session import sanitize_restored_output as s
|
||||
|
||||
sgr, link, link_end, sized = '\x1b[1;38:2:1:2:3m', '\x1b]8;id=1;https://x.org\x1b\\', '\x1b]8;;\x07', '\x1b]66;s=2;big\x1b\\'
|
||||
text = f'{sgr}bold\x1b[m {link}link{link_end} {sized}\ttab\r\n'
|
||||
self.ae(s(text), text)
|
||||
for unsafe, expected in (
|
||||
('\x1b]52;c;aGVsbG8=\x07', 'ab'),
|
||||
('\x1b]133;A\x1b\\', 'ab'),
|
||||
('\x1b]99;;notification\x1b\\', 'ab'),
|
||||
('\x1bP@kitty-cmd{"cmd":"ls"}\x1b\\', 'ab'),
|
||||
('\x1b_Gf=100;AAAA\x1b\\', 'ab'),
|
||||
('\x1b[2J', 'ab'),
|
||||
('\x1b[?1049h', 'ab'),
|
||||
('\x1bc', 'ab'),
|
||||
('\x07\x08\x0c', 'ab'),
|
||||
('\x1b', 'a'), # ESC followed by a character is an escape code
|
||||
('\x9b2J', 'a2Jb'), # C1 control codes are removed, leaving harmless text
|
||||
('\x1b]0;title', 'a'), # an unterminated OSC consumes the rest of the text
|
||||
):
|
||||
with self.subTest(unsafe=unsafe):
|
||||
self.ae(s(f'a{unsafe}b'), expected)
|
||||
|
||||
def test_logout_snapshots(self) -> None:
|
||||
from .crypto import is_rlimit_memlock_too_low
|
||||
|
||||
if is_rlimit_memlock_too_low():
|
||||
self.skipTest('RLIMIT_MEMLOCK is too low')
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
import time
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.constants import unserialize_launch_flag
|
||||
from kitty.fast_data_types import Secret
|
||||
from kitty.logout_session import (
|
||||
LOGOUT_CONFIRMATION_TIMEOUT,
|
||||
ProcessState,
|
||||
claim_snapshots,
|
||||
delete_snapshot,
|
||||
finish_restore,
|
||||
is_logout_in_progress,
|
||||
load_snapshot,
|
||||
lock_snapshot_for_saver,
|
||||
new_key_id,
|
||||
read_key_id,
|
||||
release_saver_lock,
|
||||
remove_all_snapshots,
|
||||
remove_orphaned_keys,
|
||||
remove_stale_snapshots,
|
||||
restore_snapshots,
|
||||
save_snapshot,
|
||||
)
|
||||
from kitty.utils import log_error
|
||||
|
||||
class FakeKeyStore:
|
||||
def __init__(self) -> None:
|
||||
self.keys: dict[str, Secret] = {}
|
||||
self.fail = False
|
||||
|
||||
def store(self, key_id: str, key: Secret) -> None:
|
||||
if self.fail:
|
||||
raise OSError('User interaction is not allowed')
|
||||
self.keys[key_id] = key
|
||||
|
||||
def read(self, key_id: str) -> Secret | None:
|
||||
if self.fail:
|
||||
raise OSError('User interaction is not allowed')
|
||||
return self.keys.get(key_id)
|
||||
|
||||
def delete(self, key_id: str) -> None:
|
||||
self.keys.pop(key_id, None)
|
||||
|
||||
def list_ids(self) -> list[str]:
|
||||
if self.fail:
|
||||
raise OSError('User interaction is not allowed')
|
||||
return list(self.keys)
|
||||
|
||||
errors: list[str] = []
|
||||
log_error.redirect = errors.append
|
||||
self.addCleanup(delattr, log_error, 'redirect')
|
||||
opts = self.set_options()
|
||||
tdir = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tdir, True)
|
||||
base = os.path.join(tdir, 'saved-at-logout')
|
||||
state = ProcessState(('--config', 'other.conf'), tdir, {'SECRET_VAR': 'value'}, 0)
|
||||
session = shlex.join(['launch', unserialize_launch_flag + json.dumps({'id': 7})])
|
||||
ks = FakeKeyStore()
|
||||
|
||||
def save(pid: int, argv: tuple[str, ...] = state.argv) -> str:
|
||||
return save_snapshot(base, pid, session, {7: b'\x1b]52;c;eA==\x07seven', 8: b'eight'}, state._replace(argv=argv), ks)
|
||||
|
||||
def mode(path: str) -> int:
|
||||
return stat.S_IMODE(os.stat(path).st_mode)
|
||||
|
||||
def raw(path: str, name: str) -> bytes:
|
||||
with open(os.path.join(path, name), 'rb') as f:
|
||||
return f.read()
|
||||
|
||||
# The saved state is readable only by the user and is encrypted with a key in the key store
|
||||
path = save(11)
|
||||
self.ae((mode(base), mode(path), mode(os.path.join(path, 'scrollback', '7')), mode(os.path.join(path, 'process.json'))), (0o700, 0o700, 0o600, 0o600))
|
||||
self.ae(list(ks.keys), [read_key_id(path)])
|
||||
for name, plaintext in (('process.json', b'SECRET_VAR'), ('session.kitty-session', b'launch'), ('scrollback/7', b'seven')):
|
||||
self.assertNotIn(plaintext, raw(path, name))
|
||||
# Snapshots from before this instance was started are from an earlier logout and were never restored, their keys are deleted
|
||||
stale = save(10)
|
||||
day_ago = time.time() - 86400
|
||||
os.utime(stale, (day_ago, day_ago))
|
||||
remove_stale_snapshots(base, time.time() - 3600, ks)
|
||||
self.ae((os.listdir(base), list(ks.keys)), (['11'], [read_key_id(path)]))
|
||||
# Nothing is saved if the key cannot be stored, for example because the keychain needs user interaction
|
||||
ks.fail = True
|
||||
with self.assertRaises(OSError):
|
||||
save(12)
|
||||
ks.fail = False
|
||||
self.ae(os.listdir(base), ['11'])
|
||||
|
||||
# Snapshots claimed by a running kitty instance are not claimed again, but those claimed by an instance that died are
|
||||
alive = {99}
|
||||
os.rename(path, os.path.join(base, '11.claimed-by-99'))
|
||||
self.ae(claim_snapshots(base, 1, ks, alive.__contains__), [])
|
||||
alive.clear()
|
||||
(snapshot,) = claim_snapshots(base, 1, ks, alive.__contains__)
|
||||
self.ae((snapshot.path, snapshot.process_state[:3]), (os.path.join(base, '11.claimed-by-1'), state[:3]))
|
||||
(s,) = load_snapshot(snapshot.path, opts, ks)
|
||||
# The scrollback is restored, without unsafe escape codes, followed by a line showing when it was saved
|
||||
restored = s.tabs[0].windows[0].restored_scrollback
|
||||
self.assertTrue(restored.startswith(b'seven\r\n'), restored)
|
||||
self.assertIn(b'Restored from', restored)
|
||||
# A snapshot that repeatedly fails to be restored, for example, because kitty crashes, is deleted, with its key
|
||||
self.ae(len(claim_snapshots(base, 2, ks, alive.__contains__)), 1)
|
||||
self.ae(claim_snapshots(base, 3, ks, alive.__contains__), [])
|
||||
self.ae((os.listdir(base), ks.keys), ([], {}))
|
||||
self.assertTrue(errors)
|
||||
|
||||
# Snapshots that cannot be decrypted are deleted: key not in the keychain, keychain needs user interaction, modified or
|
||||
# swapped files
|
||||
def modify(path: str) -> None:
|
||||
data = bytearray(raw(path, 'process.json'))
|
||||
data[-1] ^= 1
|
||||
with open(os.path.join(path, 'process.json'), 'wb') as f:
|
||||
f.write(data)
|
||||
|
||||
def swap(path: str) -> None:
|
||||
os.replace(os.path.join(path, 'session.kitty-session'), os.path.join(path, 'process.json'))
|
||||
|
||||
for name, damage, num_errors in (
|
||||
('missing key', lambda path: ks.keys.clear(), 1),
|
||||
# both reading the key and listing keys to remove orphans fail
|
||||
('keychain needs interaction', lambda path: setattr(ks, 'fail', True), 2),
|
||||
('modified', modify, 1),
|
||||
('swapped', swap, 1),
|
||||
):
|
||||
with self.subTest(name):
|
||||
errors.clear()
|
||||
damage(save(13))
|
||||
self.ae(claim_snapshots(base, 1, ks, alive.__contains__), [])
|
||||
ks.fail = False
|
||||
self.ae((os.listdir(base), len(errors)), ([], num_errors))
|
||||
|
||||
# Keys of snapshots deleted by something other than kitty are deleted, but not the keys of existing snapshots or keys
|
||||
# not created by kitty
|
||||
path = save(15)
|
||||
orphan, foreign = new_key_id(), 'some-other-item'
|
||||
ks.keys[orphan] = ks.keys[foreign] = ks.keys[read_key_id(path)]
|
||||
remove_orphaned_keys(base, ks)
|
||||
self.ae(sorted(ks.keys), sorted((read_key_id(path), foreign)))
|
||||
# Orphans are removed when saving and claiming, and all keys when all snapshots are removed
|
||||
ks.keys[orphan] = ks.keys[foreign]
|
||||
remove_stale_snapshots(base, 0, ks)
|
||||
self.assertNotIn(orphan, ks.keys)
|
||||
ks.keys[orphan] = ks.keys[foreign]
|
||||
self.ae(len(claim_snapshots(base, 1, ks, alive.__contains__)), 1)
|
||||
self.assertNotIn(orphan, ks.keys)
|
||||
# Failing to list the keys is logged, not raised
|
||||
errors.clear()
|
||||
ks.fail = True
|
||||
remove_orphaned_keys(base, ks)
|
||||
ks.fail = False
|
||||
self.ae(len(errors), 1)
|
||||
shutil.rmtree(base)
|
||||
ks.keys.clear()
|
||||
|
||||
# Files are bound to their names, so swapping the scrollback of two windows is detected
|
||||
path = save(14)
|
||||
os.rename(os.path.join(path, 'scrollback', '7'), os.path.join(path, 'scrollback', 'x'))
|
||||
os.rename(os.path.join(path, 'scrollback', '8'), os.path.join(path, 'scrollback', '7'))
|
||||
with self.assertRaises(Exception):
|
||||
load_snapshot(path, opts, ks)
|
||||
shutil.rmtree(base)
|
||||
ks.keys.clear()
|
||||
|
||||
# The snapshot of a kitty instance that is still running, for example, because the logout was cancelled, is not claimed,
|
||||
# even if a process with its pid is running, since pids are reused
|
||||
import kitty.logout_session as ls
|
||||
|
||||
path = save(16)
|
||||
lock_snapshot_for_saver(path)
|
||||
alive.add(16)
|
||||
self.ae(claim_snapshots(base, 1, ks, alive.__contains__), [])
|
||||
release_saver_lock(os.path.join(base, 'other'))
|
||||
self.ae(claim_snapshots(base, 1, ks, alive.__contains__), [])
|
||||
release_saver_lock(path)
|
||||
self.ae(len(claim_snapshots(base, 1, ks, alive.__contains__)), 1)
|
||||
alive.clear()
|
||||
# Deleting the snapshot of this instance, as when the logout is cancelled, releases its lock
|
||||
path = save(17)
|
||||
lock_snapshot_for_saver(path)
|
||||
delete_snapshot(path)
|
||||
self.assertIsNone(ls.saver_lock)
|
||||
shutil.rmtree(base)
|
||||
ks.keys.clear()
|
||||
|
||||
# Without a key store, as on Linux, snapshots are not encrypted and are readable only by the user
|
||||
path = save_snapshot(base, 31, session, {7: b'seven'}, state, None)
|
||||
self.ae((read_key_id(path), mode(path), mode(os.path.join(path, 'process.json'))), ('', 0o700, 0o600))
|
||||
self.assertIn(b'SECRET_VAR', raw(path, 'process.json'))
|
||||
(snapshot,) = claim_snapshots(base, 1, None, alive.__contains__)
|
||||
self.ae(snapshot.process_state[:3], state[:3])
|
||||
(s,) = load_snapshot(snapshot.path, opts, None)
|
||||
self.assertTrue(s.tabs[0].windows[0].restored_scrollback.startswith(b'seven\r\n'))
|
||||
finish_restore(snapshot.path)
|
||||
# An encrypted snapshot cannot be read without a key store and an unencrypted one is not accepted when there is a key store
|
||||
errors.clear()
|
||||
save_snapshot(base, 32, session, {}, state, None)
|
||||
self.ae(claim_snapshots(base, 1, ks, alive.__contains__), [])
|
||||
save(33)
|
||||
self.ae(claim_snapshots(base, 1, None, alive.__contains__), [])
|
||||
self.ae((os.listdir(base), len(errors)), ([], 2))
|
||||
remove_orphaned_keys(base, ks)
|
||||
self.ae(ks.keys, {})
|
||||
shutil.rmtree(base)
|
||||
ks.keys.clear()
|
||||
|
||||
# The snapshot of the kitty instance with the same command line is restored in this instance, others in new instances
|
||||
save(21, ('a',)), save(22, ('b',))
|
||||
started: list[str] = []
|
||||
with (
|
||||
patch('kitty.logout_session.snapshots_dir', return_value=base),
|
||||
patch('kitty.logout_session.get_key_store', return_value=ks),
|
||||
patch('kitty.logout_session.start_instance_for_snapshot', side_effect=lambda s: started.append(s.path)),
|
||||
):
|
||||
r = restore_snapshots(opts, ('b',))
|
||||
assert r is not None
|
||||
self.ae((os.path.basename(r.path), len(r.sessions)), (f'22.claimed-by-{os.getpid()}', 1))
|
||||
self.ae([os.path.basename(x) for x in started], [f'21.claimed-by-{os.getpid()}'])
|
||||
# Snapshots and their keys are deleted only once they have been restored
|
||||
self.assertTrue(os.path.exists(r.path))
|
||||
self.ae(len(ks.keys), 2)
|
||||
finish_restore(r.path)
|
||||
self.ae((os.listdir(base), list(ks.keys)), ([os.path.basename(started[0])], [read_key_id(started[0])]))
|
||||
self.assertIsNone(restore_snapshots(opts, ('b',)))
|
||||
remove_all_snapshots()
|
||||
self.assertFalse(os.path.exists(base))
|
||||
self.ae(ks.keys, {})
|
||||
self.assertIsNone(restore_snapshots(opts, ('b',)))
|
||||
|
||||
# On Linux, the snapshot is saved when the desktop portal says the session is about to end and is deleted if the logout is
|
||||
# cancelled
|
||||
from types import SimpleNamespace
|
||||
|
||||
from kitty.boss import Boss
|
||||
from kitty.logout_session import DESKTOP_SESSION_ENDING, DESKTOP_SESSION_QUERY_END, DESKTOP_SESSION_RUNNING
|
||||
|
||||
boss = SimpleNamespace(snapshot_saved_for_logout='', save_session_at_logout=lambda: save_snapshot(base, 41, session, {}, state, None))
|
||||
for new_state, expected in (
|
||||
(DESKTOP_SESSION_QUERY_END, ['41']),
|
||||
(DESKTOP_SESSION_RUNNING, []),
|
||||
(DESKTOP_SESSION_QUERY_END, ['41']),
|
||||
(DESKTOP_SESSION_ENDING, ['41']),
|
||||
):
|
||||
Boss.on_desktop_session_state_changed(boss, new_state) # type: ignore[arg-type]
|
||||
self.ae(os.listdir(base), expected)
|
||||
shutil.rmtree(base)
|
||||
|
||||
# Restored instances get variables that refer to the login session, such as the display, from the current login session and
|
||||
# never get single use startup tokens
|
||||
from kitty.logout_session import environment_for_snapshot
|
||||
|
||||
self.ae(
|
||||
environment_for_snapshot(
|
||||
{'HOME': '/h', 'WAYLAND_DISPLAY': 'wayland-1', 'XAUTHORITY': '/old', 'DISPLAY': ':1', 'XDG_ACTIVATION_TOKEN': 'x'},
|
||||
{'HOME': '/other', 'DISPLAY': ':0', 'XAUTHORITY': '/new', 'XDG_ACTIVATION_TOKEN': 'y'},
|
||||
),
|
||||
{'HOME': '/h', 'DISPLAY': ':0', 'XAUTHORITY': '/new'},
|
||||
)
|
||||
|
||||
# A quit confirmed long after the OS asked kitty to quit for a logout is an ordinary quit
|
||||
for requested_at, now, expected in ((-1, 10, False), (5, 10, True), (5, 6 + LOGOUT_CONFIRMATION_TIMEOUT, False)):
|
||||
with (
|
||||
patch('kitty.logout_session.application_logout_requested_at', return_value=requested_at),
|
||||
patch('kitty.logout_session.monotonic', return_value=now),
|
||||
):
|
||||
self.ae(is_logout_in_progress(), expected)
|
||||
@@ -0,0 +1,652 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2022, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import errno
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from functools import lru_cache, partial
|
||||
|
||||
from kitty.bash import decode_ansi_c_quoted_string
|
||||
from kitty.constants import is_macos, kitten_exe, kitty_base_dir, shell_integration_dir, terminfo_dir
|
||||
from kitty.fast_data_types import CURSOR_BEAM, CURSOR_BLOCK, CURSOR_UNDERLINE
|
||||
from kitty.shell_integration import setup_bash_env, setup_fish_env, setup_zsh_env
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
@lru_cache
|
||||
def bash_ok():
|
||||
v = shutil.which('bash')
|
||||
if not v:
|
||||
return False
|
||||
o = subprocess.check_output([v, '-c', 'echo "${BASH_VERSINFO[0]}\n${BASH_VERSINFO[4]}"']).decode('utf-8').splitlines()
|
||||
if not o:
|
||||
return False
|
||||
major_ver, relstatus = o[0], o[-1]
|
||||
return int(major_ver) >= 5 and relstatus == 'release'
|
||||
|
||||
|
||||
def run_interactive_bash(command: str, env: dict[str, str], cwd: str | None = None) -> 'subprocess.CompletedProcess[bytes]':
|
||||
"""Run an interactive bash without letting it touch our controlling terminal.
|
||||
|
||||
An interactive bash whose stderr is not a terminal falls back to opening
|
||||
/dev/tty to do job control on. That is the terminal the test suite is
|
||||
itself running in, and bash makes its own process group the foreground one
|
||||
on it for as long as it runs. When tests run in parallel, a second bash
|
||||
started in that window sees that it is not in the foreground process group
|
||||
and does kill(0, SIGTTIN), which stops the entire test run. Giving bash its
|
||||
own session leaves it with no controlling terminal, so it cannot interfere.
|
||||
"""
|
||||
return subprocess.run(['bash', '--noprofile', '--norc', '-ic', command], cwd=cwd, env=env, capture_output=True, start_new_session=True)
|
||||
|
||||
|
||||
def extract_block(content: str, opening: str, closing: str) -> str | None:
|
||||
"""Extract the block starting at the line opening and ending at closing with the same indentation."""
|
||||
lines = content.split('\n')
|
||||
start_idx = None
|
||||
indent_len = None
|
||||
for i, line in enumerate(lines):
|
||||
stripped = line.lstrip()
|
||||
if stripped == opening:
|
||||
start_idx = i
|
||||
indent_len = len(line) - len(stripped)
|
||||
break
|
||||
if start_idx is None:
|
||||
return None
|
||||
for i in range(start_idx + 1, len(lines)):
|
||||
line = lines[i]
|
||||
stripped = line.strip()
|
||||
if stripped == closing and (len(line) - len(line.lstrip())) == indent_len:
|
||||
return '\n'.join(lines[start_idx : i + 1])
|
||||
return None
|
||||
|
||||
|
||||
def extract_sudo_function(
|
||||
content: str, opening='sudo() {', closing='}', witht='command sudo TERMINFO="$TERMINFO" "$@";', without='command sudo "$@";'
|
||||
) -> str | None:
|
||||
"""Extract the sudo() function from bash/zsh shell integration content using indentation."""
|
||||
func = extract_block(content, opening, closing)
|
||||
if func is None:
|
||||
return None
|
||||
func = func.replace(witht, 'echo "with_terminfo";')
|
||||
return func.replace(without, 'echo "no_terminfo";')
|
||||
|
||||
|
||||
def basic_shell_env(home_dir):
|
||||
ans = {
|
||||
'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin'),
|
||||
'HOME': home_dir,
|
||||
'TERM': 'xterm-kitty',
|
||||
'TERMINFO': terminfo_dir,
|
||||
'KITTY_SHELL_INTEGRATION': 'enabled',
|
||||
'KITTY_INSTALLATION_DIR': kitty_base_dir,
|
||||
'BASH_SILENCE_DEPRECATION_WARNING': '1',
|
||||
'PYTHONDONTWRITEBYTECODE': '1',
|
||||
'WEZTERM_SHELL_SKIP_ALL': '1', # dont fail if WezTerm's system wide, default on (why?) shell integration is installed
|
||||
}
|
||||
for x in ('USER', 'LANG'):
|
||||
if os.environ.get(x):
|
||||
ans[x] = os.environ[x]
|
||||
return ans
|
||||
|
||||
|
||||
def safe_env_for_running_shell(argv, home_dir, rc='', shell='zsh', with_kitten=False):
|
||||
ans = basic_shell_env(home_dir)
|
||||
if shell == 'zsh':
|
||||
argv.insert(1, '--noglobalrcs')
|
||||
with open(os.path.join(home_dir, '.zshrc'), 'w') as f:
|
||||
print(rc + '\nZLE_RPROMPT_INDENT=0', file=f)
|
||||
setup_zsh_env(ans, argv)
|
||||
elif shell == 'fish':
|
||||
conf_dir = os.path.join(home_dir, '.config', 'fish')
|
||||
os.makedirs(conf_dir, exist_ok=True)
|
||||
# Avoid generating unneeded completion scripts
|
||||
os.makedirs(os.path.join(home_dir, '.local', 'share', 'fish', 'generated_completions'), exist_ok=True)
|
||||
with open(os.path.join(conf_dir, 'config.fish'), 'w') as f:
|
||||
print(rc + '\n', file=f)
|
||||
setup_fish_env(ans, argv)
|
||||
elif shell == 'bash':
|
||||
bashrc = os.path.join(home_dir, '.bashrc')
|
||||
if with_kitten:
|
||||
ans['KITTY_RUNNING_BASH_INTEGRATION_TEST'] = bashrc
|
||||
else:
|
||||
setup_bash_env(ans, argv)
|
||||
ans['KITTY_BASH_INJECT'] += ' posix'
|
||||
ans['KITTY_BASH_POSIX_ENV'] = bashrc
|
||||
with open(bashrc, 'w') as f:
|
||||
# ensure LINES and COLUMNS are kept up to date
|
||||
print('shopt -s checkwinsize', file=f)
|
||||
if rc:
|
||||
print(rc, file=f)
|
||||
return ans
|
||||
|
||||
|
||||
class ShellIntegration(BaseTest):
|
||||
with_kitten = False
|
||||
|
||||
@contextmanager
|
||||
def run_shell(self, shell='zsh', rc='', cmd='', setup_env=None, extra_env=None):
|
||||
home_dir = self.home_dir = os.path.realpath(tempfile.mkdtemp())
|
||||
needs_da1 = os.path.basename(shell) == 'fish'
|
||||
cmd = cmd or shell
|
||||
cmd = shlex.split(cmd.format(**locals()))
|
||||
env = (setup_env or safe_env_for_running_shell)(cmd, home_dir, rc=rc, shell=shell, with_kitten=self.with_kitten)
|
||||
env['KITTY_RUNNING_SHELL_INTEGRATION_TEST'] = '1'
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
try:
|
||||
if self.with_kitten:
|
||||
cmd = [kitten_exe(), 'run-shell', '--shell', shlex.join(cmd)]
|
||||
pty = self.create_pty(cmd, cwd=home_dir, env=env, cols=180, needs_da1=needs_da1)
|
||||
i = 10
|
||||
while i > 0 and not pty.screen_contents().strip():
|
||||
pty.process_input_from_child()
|
||||
i -= 1
|
||||
yield pty
|
||||
finally:
|
||||
while os.path.exists(home_dir):
|
||||
try:
|
||||
shutil.rmtree(home_dir)
|
||||
except OSError as e:
|
||||
# As of fish 4 fish runs a background daemon generating
|
||||
# completions.
|
||||
if e.errno == errno.ENOTEMPTY:
|
||||
continue
|
||||
raise
|
||||
|
||||
@unittest.skipUnless(shutil.which('zsh'), 'zsh not installed')
|
||||
def test_zsh_sudo_parser(self):
|
||||
if self.with_kitten:
|
||||
return
|
||||
src = os.path.join(shell_integration_dir, 'zsh', 'kitty-integration')
|
||||
with open(src) as f:
|
||||
func = extract_sudo_function(f.read())
|
||||
self.assertIsNotNone(func)
|
||||
self.sudo_parser_tests(['zsh', '--no-rcs', '-c'], func)
|
||||
|
||||
@unittest.skipUnless(bash_ok(), 'bash not installed, too old, or debug build')
|
||||
def test_bash_sudo_parser(self):
|
||||
if self.with_kitten:
|
||||
return
|
||||
src = os.path.join(shell_integration_dir, 'bash', 'kitty.bash')
|
||||
with open(src) as f:
|
||||
func = extract_sudo_function(f.read())
|
||||
self.assertIsNotNone(func)
|
||||
self.sudo_parser_tests(['bash', '--noprofile', '--norc', '-c'], func)
|
||||
|
||||
@unittest.skipUnless(bash_ok(), 'bash not installed, too old, or debug build')
|
||||
def test_bash_disabled_command_hook(self):
|
||||
if self.with_kitten:
|
||||
return
|
||||
integration_script = os.path.join(shell_integration_dir, 'bash', 'kitty.bash')
|
||||
command = 'PS0=original; source "$KITTY_BASH_INTEGRATION"; _ksi_prompt_command; printf %s "$PS0"'
|
||||
common_options = 'enabled no-cursor no-cwd no-complete no-sudo'
|
||||
for options, has_command_hook in (
|
||||
('no-title no-prompt-mark', False),
|
||||
('no-prompt-mark', True),
|
||||
('no-title', True),
|
||||
):
|
||||
with self.subTest(options=options), tempfile.TemporaryDirectory() as home_dir:
|
||||
env = basic_shell_env(home_dir)
|
||||
env['KITTY_BASH_INTEGRATION'] = integration_script
|
||||
env['KITTY_SHELL_INTEGRATION'] = f'{common_options} {options}'
|
||||
cp = run_interactive_bash(command, env)
|
||||
self.assertEqual(cp.returncode, 0, cp.stderr.decode())
|
||||
self.assertEqual(cp.stdout.decode() != 'original', has_command_hook)
|
||||
|
||||
@unittest.skipUnless(bash_ok(), 'bash not installed, too old, or debug build')
|
||||
def test_bash_ssh_hostname_fallback(self):
|
||||
if self.with_kitten:
|
||||
return
|
||||
integration_script = os.path.join(shell_integration_dir, 'bash', 'kitty.bash')
|
||||
command = 'PS1="prompt> "; source "$KITTY_BASH_INTEGRATION"; _ksi_prompt_command; printf %s "${PS1@P}"'
|
||||
with tempfile.TemporaryDirectory() as home_dir:
|
||||
home_dir = os.path.realpath(home_dir)
|
||||
who = os.path.join(home_dir, 'who')
|
||||
with open(who, 'w') as f:
|
||||
f.write("#!/bin/sh\nprintf '%s\\n' 'user pts/0 (192.0.2.1)'\n")
|
||||
os.chmod(who, 0o755)
|
||||
env = basic_shell_env(home_dir)
|
||||
env['KITTY_BASH_INTEGRATION'] = integration_script
|
||||
env['PATH'] = os.pathsep.join((home_dir, env['PATH']))
|
||||
cp = run_interactive_bash(command, env, cwd=home_dir)
|
||||
self.assertEqual(cp.returncode, 0, cp.stderr.decode())
|
||||
self.assertIn(': ~\x07', cp.stdout.decode())
|
||||
|
||||
@unittest.skipUnless(shutil.which('fish'), 'fish not installed')
|
||||
def test_fish_sudo_parser(self):
|
||||
if self.with_kitten:
|
||||
return
|
||||
src = os.path.join(shell_integration_dir, 'fish', 'vendor_conf.d', 'kitty-shell-integration.fish')
|
||||
with open(src) as f:
|
||||
func = extract_sudo_function(f.read(), opening='function sudo', closing='end', witht='sudo TERMINFO="$TERMINFO" $argv', without='sudo $argv')
|
||||
self.assertIsNotNone(func)
|
||||
self.sudo_parser_tests(['fish', '--no-config', '-c'], func)
|
||||
|
||||
def test_run0_wrapper(self):
|
||||
if self.with_kitten:
|
||||
return
|
||||
shells = (
|
||||
# shell, integration file, wrapper guard, set PATH, define a user run0 function
|
||||
('bash', ('bash', 'kitty.bash'), 'if builtin type -P run0 >/dev/null 2>&1; then', 'fi', 'PATH="{}"', ''),
|
||||
('zsh', ('zsh', 'kitty-integration'), 'if (( $+commands[run0] && ! $+functions[run0] )); then', 'fi', 'PATH="{}"', 'run0() { echo user; }'),
|
||||
(
|
||||
'fish',
|
||||
('fish', 'vendor_conf.d', 'kitty-shell-integration.fish'),
|
||||
'if test "file" = (type -t run0 2> /dev/null || echo "x")',
|
||||
'end',
|
||||
'set -gx PATH "{}"',
|
||||
'function run0; echo user; end',
|
||||
),
|
||||
)
|
||||
with tempfile.TemporaryDirectory() as bin_dir:
|
||||
with open(os.path.join(bin_dir, 'run0'), 'w') as f:
|
||||
f.write('#!/bin/sh\necho "$*"\n')
|
||||
os.chmod(os.path.join(bin_dir, 'run0'), 0o755)
|
||||
for shell, path, opening, closing, set_path, user_func in shells:
|
||||
exe = shutil.which(shell)
|
||||
if not exe:
|
||||
continue
|
||||
with self.subTest(shell=shell), open(os.path.join(shell_integration_dir, *path)) as f:
|
||||
block = extract_block(f.read(), opening, closing)
|
||||
self.assertIsNotNone(block)
|
||||
# The wrapper must not be defined when run0 is not installed
|
||||
script = [set_path.format('/nonexistent'), block, set_path.format(bin_dir), 'run0 -u root ls', block, 'run0 -u root ls', 'run0']
|
||||
expected = ['-u root ls', '--setenv=TERMINFO -u root ls', '--setenv=TERMINFO']
|
||||
if user_func:
|
||||
# The wrapper must not clobber a user defined run0 function
|
||||
script += [user_func, block, 'run0 -u root ls']
|
||||
expected.append('user')
|
||||
cp = subprocess.run([exe, '-c', '\n'.join(script)], capture_output=True, env={'HOME': bin_dir, 'TERMINFO': 'x'})
|
||||
self.assertEqual(cp.returncode, 0, f'{shell} failed with stderr: {cp.stderr.decode()}')
|
||||
self.assertEqual(expected, cp.stdout.decode().splitlines())
|
||||
|
||||
def sudo_parser_tests(self, shell: list[str], func: str) -> None:
|
||||
test_cases = [
|
||||
(['ls'], 'with_terminfo', 'simple command'),
|
||||
(['-e', 'file.txt'], 'no_terminfo', '-e flag'),
|
||||
(['--edit', 'file.txt'], 'no_terminfo', '--edit flag'),
|
||||
(['-v'], 'no_terminfo', '-v validate flag'),
|
||||
(['--validate'], 'no_terminfo', '--validate flag'),
|
||||
(['-nv'], 'no_terminfo', '-nv grouped flags'),
|
||||
(['-ne', 'file.txt'], 'no_terminfo', '-ne grouped flags'),
|
||||
(['-u', 'root', 'ls'], 'with_terminfo', '-u takes argument'),
|
||||
(['-u', 'root', '-v'], 'no_terminfo', '-u arg then -v'),
|
||||
(['--', '-v'], 'with_terminfo', '-- ends option processing'),
|
||||
(['TERM=xterm-kitty', 'ls'], 'with_terminfo', 'env var before command'),
|
||||
(['TERM=xterm-kitty', '-v', 'ls'], 'no_terminfo', 'env var before -v'),
|
||||
(['-g', 'wheel', '-v'], 'no_terminfo', '-g takes argument'),
|
||||
(['-D', '/tmp', '-e'], 'no_terminfo', '-D takes argument'),
|
||||
(['-R', '/chroot', '-e'], 'no_terminfo', '-R takes argument'),
|
||||
(['-h', 'localhost', '-v'], 'no_terminfo', '-h takes argument'),
|
||||
(['-uroot', '-v', 'ls'], 'with_terminfo', '-u with embedded argument'),
|
||||
(['--user', '-v', 'ls'], 'with_terminfo', '--user takes argument'),
|
||||
(['--user=root', '-v', 'ls'], 'no_terminfo', '--user=root self-contained'),
|
||||
]
|
||||
for cmd, expected, _ in test_cases:
|
||||
func += f'\n\nsudo {" ".join(cmd)}'
|
||||
cp = subprocess.run(shell + [func], capture_output=True)
|
||||
self.assertEqual(cp.returncode, 0, f'{shell[0]} failed with stderr: {cp.stderr.decode()}')
|
||||
for i, line in enumerate(cp.stdout.decode().splitlines()):
|
||||
line = line.strip()
|
||||
cmd, expected, desc = test_cases[i]
|
||||
self.assertEqual(expected, line, str(cmd))
|
||||
|
||||
@unittest.skipUnless(shutil.which('zsh'), 'zsh not installed')
|
||||
def test_zsh_integration(self):
|
||||
ps1, rps1 = 'left>', '<right'
|
||||
with self.run_shell(
|
||||
rc=f'''
|
||||
PS1="{ps1}"
|
||||
RPS1="{rps1}"
|
||||
'''
|
||||
) as pty:
|
||||
q = ps1 + ' ' * (pty.screen.columns - len(ps1) - len(rps1)) + rps1
|
||||
try:
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
except TimeoutError as e:
|
||||
raise AssertionError(f'Cursor was not changed to beam. Screen contents: {repr(pty.screen_contents())}') from e
|
||||
pty.wait_till(lambda: pty.screen_contents() == q)
|
||||
self.ae(pty.callbacks.titlebuf[-1], '~')
|
||||
pty.callbacks.clear()
|
||||
pty.send_cmd_to_child('mkdir test && ls -a')
|
||||
self.assert_command(pty)
|
||||
pty.wait_till(lambda: pty.screen_contents().count(rps1) == 2)
|
||||
self.ae(pty.callbacks.titlebuf[-2:], ['mkdir test && ls -a', '~'])
|
||||
q = '\n'.join(str(pty.screen.line(i)) for i in range(1, pty.screen.cursor.y))
|
||||
self.ae(pty.last_cmd_output(), q)
|
||||
# shrink the screen
|
||||
pty.write_to_child(r'echo $COLUMNS')
|
||||
pty.set_window_size(rows=20, columns=40)
|
||||
q = ps1 + 'echo $COLUMNS' + ' ' * (40 - len(ps1) - len(rps1) - len('echo $COLUMNS')) + rps1
|
||||
pty.process_input_from_child()
|
||||
|
||||
def redrawn():
|
||||
q = pty.screen_contents()
|
||||
return '$COLUMNS' in q and q.count(rps1) == 2 and q.count(ps1) == 2
|
||||
|
||||
pty.wait_till(redrawn)
|
||||
self.ae(q, str(pty.screen.line(pty.screen.cursor.y)))
|
||||
pty.write_to_child('\r')
|
||||
self.assert_command(pty, 'echo $COLUMNS')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(rps1) == 3)
|
||||
self.ae('40', str(pty.screen.line(pty.screen.cursor.y - 1)))
|
||||
self.ae(q, str(pty.screen.line(pty.screen.cursor.y - 2)))
|
||||
pty.send_cmd_to_child('clear')
|
||||
self.assert_command(pty)
|
||||
q = ps1 + ' ' * (pty.screen.columns - len(ps1) - len(rps1)) + rps1
|
||||
pty.wait_till(lambda: pty.screen_contents() == q)
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
pty.send_cmd_to_child('cat')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == 0)
|
||||
pty.write_to_child('\x04')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
self.assert_command(pty)
|
||||
# Check escaping of inputs
|
||||
pty.send_cmd_to_child('-f-this-command-must-not-exist')
|
||||
self.assert_command(pty, exit_status=127)
|
||||
with self.run_shell(rc=f'''PS1="{ps1}"''') as pty:
|
||||
pty.callbacks.clear()
|
||||
pty.send_cmd_to_child('printf "%s\x16\a%s" "a" "b"')
|
||||
pty.wait_till(lambda: 'ab' in pty.screen_contents())
|
||||
self.assertTrue(pty.screen.last_reported_cwd.decode().endswith(self.home_dir))
|
||||
self.assertIn('%s^G%s', pty.screen_contents())
|
||||
q = os.path.join(self.home_dir, 'testing-cwd-notification-🐱')
|
||||
os.mkdir(q)
|
||||
pty.send_cmd_to_child(f'cd {q}')
|
||||
pty.wait_till(lambda: pty.screen.last_reported_cwd.decode().endswith(q))
|
||||
if not is_macos: # Fails on older macOS like the one used to build kitty binary because of unicode encoding issues
|
||||
self.assert_command(pty)
|
||||
with self.run_shell(rc=f'''PS1="{ps1}"\nexport ES="a\n b c\nd"''') as pty:
|
||||
pty.callbacks.clear()
|
||||
pty.send_cmd_to_child('clone-in-kitty')
|
||||
pty.wait_till(lambda: len(pty.callbacks.clone_cmds) == 1)
|
||||
self.assert_command(pty)
|
||||
env = pty.callbacks.clone_cmds[0].env
|
||||
self.ae(env.get('ES'), 'a\n b c\nd')
|
||||
with self.run_shell(rc='PS1=XXX', extra_env={'KITTY_SI_RUN_COMMAND_AT_STARTUP': 'echo pre-start'}) as pty:
|
||||
pty.wait_till(lambda: 'XXX' in pty.screen_contents())
|
||||
self.assertIn('pre-start', pty.screen_contents())
|
||||
self.assertTrue(pty.screen_contents().startswith('pre-start'))
|
||||
# Interrupting the startup command must not leave integration half
|
||||
# initialized. The marker is printed by the child itself so that we
|
||||
# know it is the foreground job when we send SIGINT.
|
||||
with self.run_shell(rc='PS1=XXX', extra_env={'KITTY_SI_RUN_COMMAND_AT_STARTUP': "sh -c 'echo pre-start; exec sleep 100'"}) as pty:
|
||||
pty.wait_till(lambda: 'pre-start' in pty.screen_contents())
|
||||
pty.write_to_child('\x03')
|
||||
pty.wait_till(lambda: 'XXX' in pty.screen_contents())
|
||||
pty.send_cmd_to_child('echo ok1')
|
||||
pty.wait_till(lambda: '\nok1\n' in pty.screen_contents())
|
||||
pty.send_cmd_to_child('echo ok2')
|
||||
pty.wait_till(lambda: '\nok2\n' in pty.screen_contents())
|
||||
self.assertNotIn('FUNCNEST', pty.screen_contents())
|
||||
|
||||
@unittest.skipUnless(shutil.which('fish'), 'fish not installed')
|
||||
def test_fish_integration(self):
|
||||
fish_prompt, right_prompt = 'left>', '<right'
|
||||
completions_dir = os.path.join(kitty_base_dir, 'shell-integration', 'fish', 'vendor_completions.d')
|
||||
with self.run_shell(
|
||||
shell='fish',
|
||||
extra_env={'KITTY_SI_RUN_COMMAND_AT_STARTUP': 'echo XXX'},
|
||||
rc=f'''
|
||||
set -g fish_greeting
|
||||
function fish_prompt; echo -n "{fish_prompt}"; end
|
||||
function fish_right_prompt; echo -n "{right_prompt}"; end
|
||||
function _test_comp_path; contains "{completions_dir}" $fish_complete_path; and echo ok; end
|
||||
function _set_key; set -g fish_key_bindings fish_$argv[1]_key_bindings; end
|
||||
function _set_status_prompt; function fish_prompt; echo -n "$pipestatus $status {fish_prompt}"; end; end
|
||||
''',
|
||||
) as pty:
|
||||
q = 'XXX\n' + fish_prompt + ' ' * (pty.screen.columns - len(fish_prompt) - len(right_prompt)) + right_prompt
|
||||
pty.wait_till(lambda: pty.screen_contents().count(right_prompt) == 1)
|
||||
self.ae(pty.screen_contents(), q)
|
||||
|
||||
# shell integration dir must not be in XDG_DATA_DIRS
|
||||
cmd = f'string match -q -- "*{shell_integration_dir}*" "$XDG_DATA_DIRS" || echo "XDD_OK"'
|
||||
pty.send_cmd_to_child(cmd)
|
||||
pty.wait_till(lambda: 'XDD_OK' in pty.screen_contents())
|
||||
# self.assert_command(pty, cmd)
|
||||
|
||||
# CWD reporting
|
||||
self.assertTrue(pty.screen.last_reported_cwd.decode().endswith(self.home_dir))
|
||||
q = os.path.join(self.home_dir, 'testing-cwd-notification-🐱')
|
||||
os.mkdir(q)
|
||||
pty.send_cmd_to_child(f'cd {q}')
|
||||
# self.assert_command(pty)
|
||||
pty.wait_till(lambda: pty.screen.last_reported_cwd.decode().endswith(q))
|
||||
pty.send_cmd_to_child('cd -')
|
||||
pty.wait_till(lambda: pty.screen.last_reported_cwd.decode().endswith(self.home_dir))
|
||||
|
||||
# completion and prompt marking
|
||||
pty.wait_till(lambda: 'cd -' not in pty.screen_contents().splitlines()[-1])
|
||||
pty.send_cmd_to_child('clear')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(right_prompt) == 1)
|
||||
pty.send_cmd_to_child('_test_comp_path')
|
||||
# self.assert_command(pty)
|
||||
pty.wait_till(lambda: pty.screen_contents().count(right_prompt) == 2)
|
||||
q = '\n'.join(str(pty.screen.line(i)) for i in range(1, pty.screen.cursor.y))
|
||||
self.ae(q, 'ok')
|
||||
self.ae(pty.last_cmd_output(), q)
|
||||
|
||||
# resize and redraw (fish_handle_reflow)
|
||||
pty.write_to_child(r'echo $COLUMNS')
|
||||
pty.set_window_size(rows=20, columns=40)
|
||||
q = fish_prompt + 'echo $COLUMNS' + ' ' * (40 - len(fish_prompt) - len(right_prompt) - len('echo $COLUMNS')) + right_prompt
|
||||
pty.process_input_from_child()
|
||||
|
||||
def redrawn():
|
||||
q = pty.screen_contents()
|
||||
return '$COLUMNS' in q and q.count(right_prompt) == 2 and q.count(fish_prompt) == 2
|
||||
|
||||
pty.wait_till(redrawn)
|
||||
self.ae(q, str(pty.screen.line(pty.screen.cursor.y)))
|
||||
pty.write_to_child('\r')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(right_prompt) == 3)
|
||||
# self.assert_command(pty, 'echo $COLUMNS')
|
||||
self.ae('40', str(pty.screen.line(pty.screen.cursor.y - 1)))
|
||||
self.ae(q, str(pty.screen.line(pty.screen.cursor.y - 2)))
|
||||
|
||||
# cursor shapes
|
||||
pty.send_cmd_to_child('clear')
|
||||
q = fish_prompt + ' ' * (pty.screen.columns - len(fish_prompt) - len(right_prompt)) + right_prompt
|
||||
pty.wait_till(lambda: pty.screen_contents() == q)
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
pty.send_cmd_to_child('echo; cat')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == 0 and pty.screen.cursor.y > 1)
|
||||
pty.write_to_child('\x04')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
pty.send_cmd_to_child('_set_key vi')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(right_prompt) == 3)
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
pty.write_to_child('\x1b')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BLOCK)
|
||||
pty.write_to_child('r')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_UNDERLINE)
|
||||
pty.write_to_child('\x1b')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BLOCK)
|
||||
pty.write_to_child('i')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
pty.send_cmd_to_child('_set_key default')
|
||||
# self.assert_command(pty)
|
||||
pty.wait_till(lambda: pty.screen_contents().count(right_prompt) == 4)
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
|
||||
pty.send_cmd_to_child('exit')
|
||||
|
||||
def assert_command(self, pty, cmd='', exit_status=0):
|
||||
cmd = cmd or pty.last_cmd
|
||||
pty.wait_till(lambda: pty.callbacks.last_cmd_exit_status == exit_status, timeout_msg=lambda: f'{pty.callbacks.last_cmd_exit_status=} != {exit_status}')
|
||||
pty.wait_till(lambda: pty.callbacks.last_cmd_cmdline == cmd, timeout_msg=lambda: f'{pty.callbacks.last_cmd_cmdline=!r} != {cmd!r}')
|
||||
|
||||
@unittest.skipUnless(bash_ok(), 'bash not installed, too old, or debug build')
|
||||
def test_bash_integration(self):
|
||||
ps1 = 'prompt> '
|
||||
with self.run_shell(
|
||||
shell='bash',
|
||||
rc=f'''
|
||||
PS1="{ps1}"
|
||||
''',
|
||||
) as pty:
|
||||
try:
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
except TimeoutError as e:
|
||||
raise AssertionError(f'Cursor was not changed to beam. Screen contents: {repr(pty.screen_contents())}') from e
|
||||
pty.wait_till(lambda: pty.screen_contents().count(ps1) == 1)
|
||||
self.ae(pty.screen_contents(), ps1)
|
||||
pty.wait_till(lambda: pty.callbacks.titlebuf[-1:] == ['~'])
|
||||
self.ae(pty.callbacks.titlebuf[-1], '~')
|
||||
pty.callbacks.clear()
|
||||
cmd = 'mkdir test && ls -a'
|
||||
pty.send_cmd_to_child(cmd)
|
||||
pty.wait_till(lambda: pty.callbacks.titlebuf[-2:] == [cmd, '~'])
|
||||
pty.wait_till(lambda: pty.screen_contents().count(ps1) == 2)
|
||||
self.assert_command(pty, cmd)
|
||||
q = '\n'.join(str(pty.screen.line(i)) for i in range(1, pty.screen.cursor.y))
|
||||
self.ae(pty.last_cmd_output(), q)
|
||||
# shrink the screen
|
||||
pty.write_to_child(r'echo $COLUMNS')
|
||||
pty.set_window_size(rows=20, columns=40)
|
||||
pty.process_input_from_child()
|
||||
|
||||
def redrawn():
|
||||
q = pty.screen_contents()
|
||||
return '$COLUMNS' in q and q.count(ps1) == 2
|
||||
|
||||
pty.wait_till(redrawn)
|
||||
self.ae(ps1 + 'echo $COLUMNS', str(pty.screen.line(pty.screen.cursor.y)))
|
||||
pty.write_to_child('\r')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(ps1) == 3)
|
||||
self.ae('40', str(pty.screen.line(pty.screen.cursor.y - 1)))
|
||||
self.ae(ps1 + 'echo $COLUMNS', str(pty.screen.line(pty.screen.cursor.y - 2)))
|
||||
pty.send_cmd_to_child('clear')
|
||||
pty.wait_till(lambda: pty.screen_contents() == ps1)
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
pty.send_cmd_to_child('cat')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == 0)
|
||||
pty.write_to_child('\x04')
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM)
|
||||
pty.write_to_child('\x04')
|
||||
pty.send_cmd_to_child('clear')
|
||||
pty.wait_till(lambda: pty.callbacks.titlebuf)
|
||||
with self.run_shell(shell='bash', rc=f'''PS1="{ps1}"\ndeclare LOCAL_KSI_VAR=1''') as pty:
|
||||
pty.callbacks.clear()
|
||||
pty.send_cmd_to_child('declare')
|
||||
pty.wait_till(lambda: 'LOCAL_KSI_VAR' in pty.screen_contents())
|
||||
self.assert_command(pty, 'declare')
|
||||
with self.run_shell(shell='bash', rc=f'''PS1="{ps1}"''') as pty:
|
||||
pty.callbacks.clear()
|
||||
pty.send_cmd_to_child('printf "%s\x16\a%s" "a" "b"')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(ps1) == 2)
|
||||
self.ae(pty.screen_contents(), f'{ps1}printf "%s^G%s" "a" "b"\nab{ps1}')
|
||||
self.assertTrue(pty.screen.last_reported_cwd.decode().endswith(self.home_dir))
|
||||
pty.send_cmd_to_child('echo $HISTFILE')
|
||||
pty.wait_till(lambda: '.bash_history' in pty.screen_contents().replace('\n', ''))
|
||||
q = os.path.join(self.home_dir, 'testing-cwd-notification-🐱')
|
||||
os.mkdir(q)
|
||||
pty.send_cmd_to_child(f'cd {q}')
|
||||
pty.wait_till(lambda: pty.screen.last_reported_cwd.decode().endswith(q))
|
||||
|
||||
for ps1 in (
|
||||
'line1\\nline\\2\\prompt> ',
|
||||
'line1\nprompt> ',
|
||||
'line1\\nprompt> ',
|
||||
):
|
||||
with (
|
||||
self.subTest(ps1=ps1),
|
||||
self.run_shell(
|
||||
shell='bash',
|
||||
rc=f'''
|
||||
PS1="{ps1}"
|
||||
''',
|
||||
) as pty,
|
||||
):
|
||||
ps1 = ps1.replace('\\n', '\n')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(ps1) == 1)
|
||||
pty.send_cmd_to_child('echo test')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(ps1) == 2)
|
||||
self.ae(pty.screen_contents(), f'{ps1}echo test\ntest\n{ps1}')
|
||||
pty.write_to_child(r'echo $COLUMNS')
|
||||
pty.set_window_size(rows=20, columns=40)
|
||||
pty.process_input_from_child()
|
||||
pty.wait_till(redrawn)
|
||||
self.ae(ps1.splitlines()[-1] + 'echo $COLUMNS', str(pty.screen.line(pty.screen.cursor.y)))
|
||||
pty.write_to_child('\r')
|
||||
pty.wait_till(lambda: pty.screen_contents().count(ps1) == 3)
|
||||
self.ae('40', str(pty.screen.line(pty.screen.cursor.y - len(ps1.splitlines()))))
|
||||
self.ae(ps1.splitlines()[-1] + 'echo $COLUMNS', str(pty.screen.line(pty.screen.cursor.y - 1 - len(ps1.splitlines()))))
|
||||
self.assert_command(pty, 'echo $COLUMNS')
|
||||
|
||||
with self.run_shell(shell='bash', rc='PS1=XXX', extra_env={'KITTY_SI_RUN_COMMAND_AT_STARTUP': 'echo pre-start'}) as pty:
|
||||
pty.wait_till(lambda: 'XXX' in pty.screen_contents())
|
||||
self.assertIn('pre-start', pty.screen_contents())
|
||||
self.assertTrue(pty.screen_contents().startswith('pre-start'))
|
||||
# test startup file sourcing
|
||||
|
||||
def setup_env(excluded, argv, home_dir, rc='', shell='bash', with_kitten=self.with_kitten):
|
||||
ans = basic_shell_env(home_dir)
|
||||
if not with_kitten:
|
||||
setup_bash_env(ans, argv)
|
||||
for x in {'profile', 'bash.bashrc', '.bash_profile', '.bash_login', '.profile', '.bashrc', 'rcfile'} - excluded:
|
||||
with open(os.path.join(home_dir, x), 'w') as f:
|
||||
if x == '.bashrc' and rc:
|
||||
print(rc, file=f)
|
||||
else:
|
||||
print(f'echo [{x}]', file=f)
|
||||
ans['KITTY_BASH_ETC_LOCATION'] = home_dir
|
||||
ans['PS1'] = 'PROMPT $ '
|
||||
return ans
|
||||
|
||||
def run_test(argv, *expected, excluded=(), rc='', wait_string='PROMPT $', assert_not_in=False):
|
||||
with self.subTest(argv=argv), self.run_shell(shell='bash', setup_env=partial(setup_env, set(excluded)), cmd=argv, rc=rc) as pty:
|
||||
pty.wait_till(lambda: wait_string in pty.screen_contents())
|
||||
q = pty.screen_contents()
|
||||
for x in expected:
|
||||
if assert_not_in:
|
||||
self.assertNotIn(f'[{x}]', q)
|
||||
else:
|
||||
self.assertIn(f'[{x}]', q)
|
||||
|
||||
run_test('bash', 'bash.bashrc', '.bashrc')
|
||||
run_test('bash --rcfile rcfile', 'bash.bashrc', 'rcfile')
|
||||
run_test('bash --init-file rcfile', 'bash.bashrc', 'rcfile')
|
||||
run_test('bash --norc')
|
||||
run_test('bash -l', 'profile', '.bash_profile')
|
||||
run_test('bash --noprofile -l')
|
||||
run_test('bash -l', 'profile', '.bash_login', excluded=('.bash_profile',))
|
||||
run_test('bash -l', 'profile', '.profile', excluded=('.bash_profile', '.bash_login'))
|
||||
|
||||
# test argument parsing and non-interactive shell
|
||||
run_test('bash -s arg1 --rcfile rcfile', 'rcfile', rc='echo ok;read', wait_string='ok', assert_not_in=True)
|
||||
run_test('bash +O login_shell -ic "echo ok;read"', 'bash.bashrc', excluded=('.bash_profile'), wait_string='ok', assert_not_in=True)
|
||||
run_test('bash -l .bashrc', 'profile', rc='echo ok;read', wait_string='ok', assert_not_in=True)
|
||||
run_test('bash -il -- .bashrc', 'profile', rc='echo ok;read', wait_string='ok')
|
||||
|
||||
with self.run_shell(
|
||||
shell='bash', setup_env=partial(setup_env, set()), cmd='bash', rc=f'''PS1="{ps1}"\nexport ES=$'a\n `b` c\n$d'\nexport ES2="XXX" '''
|
||||
) as pty:
|
||||
pty.callbacks.clear()
|
||||
pty.send_cmd_to_child('clone-in-kitty')
|
||||
pty.wait_till(lambda: len(pty.callbacks.clone_cmds) == 1)
|
||||
env = pty.callbacks.clone_cmds[0].env
|
||||
self.ae(env.get('ES'), 'a\n `b` c\n$d', f'Screen contents: {pty.screen_contents()!r}')
|
||||
self.ae(env.get('ES2'), 'XXX', f'Screen contents: {pty.screen_contents()!r}')
|
||||
|
||||
for q, e in {
|
||||
'a': 'a',
|
||||
r'a\ab': 'a\ab',
|
||||
r'a\x7z': 'a\x07z',
|
||||
r'a\7b': 'a\007b',
|
||||
r'a\U1f345x': 'a🍅x',
|
||||
r'a\c b': 'a\0b',
|
||||
}.items():
|
||||
self.ae(decode_ansi_c_quoted_string(f"$'{q}'"), e, f'Failed to decode: {q!r}')
|
||||
|
||||
|
||||
class ShellIntegrationWithKitten(ShellIntegration):
|
||||
with_kitten = True
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2023, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
from kitty.constants import is_macos, kitten_exe
|
||||
from kitty.fast_data_types import shm_unlink
|
||||
from kitty.shm import SharedMemory
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class SHMTest(BaseTest):
|
||||
def test_shm_with_kitten(self):
|
||||
data = os.urandom(333)
|
||||
with SharedMemory(size=363) as shm:
|
||||
shm.write_data_with_size(data)
|
||||
cp = subprocess.run([kitten_exe(), '__pytest__', 'shm', 'read', shm.name], stdout=subprocess.PIPE)
|
||||
self.assertEqual(cp.returncode, 0)
|
||||
self.assertEqual(cp.stdout, data)
|
||||
self.assertRaises(FileNotFoundError, shm_unlink, shm.name)
|
||||
cp = subprocess.run([kitten_exe(), '__pytest__', 'shm', 'write'], input=data, stdout=subprocess.PIPE)
|
||||
self.assertEqual(cp.returncode, 0)
|
||||
name = cp.stdout.decode().strip()
|
||||
with SharedMemory(name=name, unlink_on_exit=True) as shm:
|
||||
q = shm.read_data_with_size()
|
||||
self.assertEqual(data, q)
|
||||
|
||||
def test_shm_ownership_verification(self):
|
||||
if is_macos:
|
||||
self.skipTest('macOS does not support fchmod() for shm files')
|
||||
with SharedMemory(size=64, unlink_on_exit=True) as shm:
|
||||
shm.verify_owner_and_mode()
|
||||
for mode in (0o644, 0o400, 0o660):
|
||||
os.fchmod(shm.fileno(), mode)
|
||||
with SharedMemory(name=shm.name, readonly=True) as shm2:
|
||||
self.assertRaises(ValueError, shm2.verify_owner_and_mode)
|
||||
os.fchmod(shm.fileno(), 0o600)
|
||||
with SharedMemory(name=shm.name, readonly=True) as shm2:
|
||||
shm2.verify_owner_and_mode()
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
from contextlib import closing
|
||||
|
||||
from kitty.constants import kitty_exe
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestSingleInstance(BaseTest):
|
||||
def test_single_instance_client(self):
|
||||
# Test that a client can talk to a single instance socket belonging to
|
||||
# the same user. The abstract socket namespace used below exists only
|
||||
# on Linux.
|
||||
if not sys.platform.startswith('linux'):
|
||||
self.skipTest('Abstract UNIX sockets are only available on Linux')
|
||||
group = f'test-{os.getpid()}'
|
||||
with closing(socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)) as server:
|
||||
server.bind('\0' + f'kitty-ipc-{os.geteuid()}-{group}')
|
||||
server.listen()
|
||||
env = os.environ.copy()
|
||||
env['KITTY_SINGLE_INSTANCE_TEST'] = 'xyz'
|
||||
p = subprocess.Popen(
|
||||
[kitty_exe(), '--single-instance', f'--instance-group={group}', '--title', 'si-test-title'],
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
try:
|
||||
with closing(server.accept()[0]) as peer:
|
||||
data = b''
|
||||
while True:
|
||||
d = peer.recv(8192)
|
||||
if not d:
|
||||
break
|
||||
data += d
|
||||
output = p.communicate(timeout=30)[0].decode()
|
||||
finally:
|
||||
if p.poll() is None:
|
||||
p.kill()
|
||||
p.wait()
|
||||
self.assertEqual(p.returncode, 0, f'kitty --single-instance failed with output: {output}')
|
||||
msg = json.loads(data.decode('utf-8'))
|
||||
self.assertEqual(msg['cmd'], 'new_instance')
|
||||
self.assertIn('si-test-title', msg['args'])
|
||||
self.assertEqual(msg['cwd'], os.getcwd())
|
||||
self.assertEqual(msg['environ'].get('KITTY_SINGLE_INSTANCE_TEST'), 'xyz')
|
||||
@@ -0,0 +1,981 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import hashlib
|
||||
import importlib.resources as ir
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.constants import slangc
|
||||
from kitty.shaders.slang import (
|
||||
EntryPoint,
|
||||
LoadShaderPrograms,
|
||||
SlangFile,
|
||||
SlangShaderQuery,
|
||||
Stage,
|
||||
apply_pipeline_specializations,
|
||||
build_custom_shader_pipeline_glsl,
|
||||
build_import_graph,
|
||||
cell_variant,
|
||||
cell_variations,
|
||||
clear_caches,
|
||||
custom_shader,
|
||||
defines_pointer_map,
|
||||
get_custom_pipeline_src,
|
||||
parse_pipeline_definition,
|
||||
parse_slang_declarations,
|
||||
parse_slang_text,
|
||||
parse_var_directive,
|
||||
pipeline_definition,
|
||||
pointer_map_shaders,
|
||||
slangc_version,
|
||||
text_contrast_is_identity,
|
||||
topological_layers,
|
||||
topological_sort,
|
||||
variant_name,
|
||||
)
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
_SUPPORT_SHADER_NAMES = frozenset(('types', 'pipeline'))
|
||||
|
||||
|
||||
class TestSlang(BaseTest):
|
||||
def test_animation_step_parsing(self):
|
||||
def step(val):
|
||||
return parse_pipeline_definition(['startgroup', f'animation_step {val}', 'shaders focus-highlight', 'endgroup'], 'test')['groups'][0][
|
||||
'animation_step'
|
||||
]
|
||||
|
||||
# 0 means "static effect, no periodic redraws" and must survive as 0
|
||||
self.ae(step(0), 0)
|
||||
self.ae(step(16), 16_000_000)
|
||||
self.assertRaises(ValueError, step, -1)
|
||||
|
||||
def test_custom_shader_redraw_logic(self):
|
||||
from kitty.fast_data_types import custom_shader_needs_render, simulate_custom_shader_render_ticks
|
||||
|
||||
NEVER = 2**63 - 1 # MONOTONIC_T_MAX, the "nothing scheduled" sentinel
|
||||
STEP = 50_000_000 # an animated group redrawing every 50ms
|
||||
NOW = 1_000_000_000
|
||||
|
||||
def needs_render(before, after, events=0, now=NOW):
|
||||
return custom_shader_needs_render(before, after, events, now)
|
||||
|
||||
idle = (False, NEVER, NEVER)
|
||||
static = (True, NEVER, NEVER)
|
||||
animating = (True, STEP, NEVER)
|
||||
|
||||
# Nothing active and nothing pending: the shader layer must not ask for frames.
|
||||
self.assertFalse(needs_render(idle, idle))
|
||||
self.assertFalse(needs_render(idle, idle, events=1))
|
||||
# A static group only redraws when an event may have changed its output.
|
||||
self.assertFalse(needs_render(static, static))
|
||||
self.assertTrue(needs_render(static, static, events=1))
|
||||
# An animated group redraws every tick...
|
||||
self.assertTrue(needs_render(animating, animating))
|
||||
# ...and gets one final frame after it stops, so the effect is cleared.
|
||||
self.assertTrue(needs_render(animating, static))
|
||||
self.assertTrue(needs_render(animating, idle))
|
||||
# Groups turning on or off is always a visible change.
|
||||
self.assertTrue(needs_render(idle, static))
|
||||
self.assertTrue(needs_render(static, idle))
|
||||
# The tick on which a duration bounded animation expires needs a frame,
|
||||
# earlier ticks do not.
|
||||
self.assertTrue(needs_render((True, NEVER, NOW), static))
|
||||
self.assertTrue(needs_render((True, NEVER, NOW - 1), static))
|
||||
self.assertFalse(needs_render((True, NEVER, NOW + 1), static))
|
||||
|
||||
# A window with no custom shaders configured must settle into asking for
|
||||
# no frames at all, otherwise an idle kitty redraws forever. Test both a
|
||||
# zero initialized window and one initialized the way add_os_window()
|
||||
# does it, since zero is not the MONOTONIC_T_MAX sentinel.
|
||||
self.ae(simulate_custom_shader_render_ticks(8, 0, True), [False] * 8)
|
||||
self.ae(simulate_custom_shader_render_ticks(8)[1:], [False] * 7)
|
||||
# Even a steady stream of shader events must not produce frames when
|
||||
# there are no shaders to draw.
|
||||
self.ae(simulate_custom_shader_render_ticks(8, 0xFF, True), [False] * 8)
|
||||
|
||||
def test_custom_shader_user_events(self):
|
||||
from kitty.fast_data_types import MAX_SHADER_ANIM_USER_EVENTS, fire_custom_shader_event, simulate_custom_shader_animation
|
||||
from kitty.options.utils import KeyAction, parse_key_action
|
||||
|
||||
def pipeline(*groups: str):
|
||||
lines = []
|
||||
for g in groups:
|
||||
lines.append('startgroup')
|
||||
lines.extend(g.splitlines())
|
||||
lines.append('shaders sample')
|
||||
lines.append('endgroup')
|
||||
return parse_pipeline_definition(lines, 'test')
|
||||
|
||||
# Parsing
|
||||
g = pipeline('animation_start user:find-cursor|tab-change\nanimation_stop user:x.y_z')['groups'][0]
|
||||
self.ae(g['animation_start'], ('user:find-cursor', 'tab-change'))
|
||||
self.ae(g['animation_end_events'], ('user:x.y_z',))
|
||||
# Trailing comments, including empty ones
|
||||
for comment in ('# ', '#', '# some comment', '\t#x'):
|
||||
g = pipeline(f'animation_toggle user:toggle-notch {comment}\nanimation_duration 600 {comment}')['groups'][0]
|
||||
self.ae(g['animation_toggle'], ('user:toggle-notch',))
|
||||
self.ae(g['animation_duration'], 600_000_000)
|
||||
for bad in ('user:', 'user:a/b', 'user:' + 'x' * 100, 'usr:a'):
|
||||
self.assertRaises(ValueError, pipeline, f'animation_start {bad}')
|
||||
# A toggled group stays on until toggled off unless told otherwise
|
||||
self.ae(pipeline('animation_toggle user:t')['groups'][0]['animation_end_duration'], 0)
|
||||
self.ae(pipeline('animation_toggle user:t\nanimation_stop 100')['groups'][0]['animation_end_duration'], 100_000_000)
|
||||
self.ae(pipeline('animation_start user:s\nanimation_toggle user:t')['groups'][0]['animation_end_duration'], -1)
|
||||
many = '|'.join(f'user:e{i}' for i in range(MAX_SHADER_ANIM_USER_EVENTS + 1))
|
||||
self.assertRaises(ValueError, pipeline, f'animation_start {many}')
|
||||
pipeline(f'animation_start {many.rpartition("|")[0]}')
|
||||
|
||||
# The action
|
||||
self.ae(parse_key_action('shader_event find-cursor'), KeyAction('shader_event', ('find-cursor', 'active')))
|
||||
self.ae(parse_key_action('shader_event user:notch ALL'), KeyAction('shader_event', ('notch', 'all')))
|
||||
for bad in ('a b c', 'a sideways', 'a/b'):
|
||||
self.assertRaises(ValueError, parse_key_action, f'shader_event {bad}')
|
||||
# Events not used by the current pipeline, here no pipeline at all, are ignored
|
||||
self.assertFalse(fire_custom_shader_event('find-cursor'))
|
||||
|
||||
# The animation state machine
|
||||
p = pipeline(
|
||||
'animation_toggle user:t',
|
||||
'animation_start user:s\nanimation_stop 20',
|
||||
'attach',
|
||||
'animation_start user:on\nanimation_toggle user:t\nanimation_stop user:off|0',
|
||||
'',
|
||||
)
|
||||
ticks = [(), ('user:t',), (), ('user:t',), ('user:s', 'user:unknown'), (), (), ('user:on',), ('user:t',), ('user:t', 'user:off'), ('user:on', 'user:t')]
|
||||
expected = [
|
||||
(False, False, False, False, True),
|
||||
(True, False, False, True, True), # toggled on
|
||||
(True, False, False, True, True), # toggles stay on
|
||||
(False, False, False, False, True), # toggled off
|
||||
(False, True, True, False, True), # started, with the attached group
|
||||
(False, True, True, False, True),
|
||||
(False, False, False, False, True), # duration expired
|
||||
(False, False, False, True, True),
|
||||
(True, False, False, False, True), # toggles flip each group's own state
|
||||
(False, False, False, True, True), # toggle wins over a simultaneous stop
|
||||
(True, False, False, False, True), # and over a simultaneous start
|
||||
]
|
||||
self.ae(simulate_custom_shader_animation(p, ticks), expected)
|
||||
|
||||
def test_custom_shader_animation_progress(self):
|
||||
from kitty.fast_data_types import simulate_custom_shader_animation
|
||||
|
||||
def pipeline(*groups: str):
|
||||
lines = []
|
||||
for g in groups:
|
||||
lines.append('startgroup')
|
||||
lines.extend(g.splitlines())
|
||||
lines.append('shaders sample')
|
||||
lines.append('endgroup')
|
||||
return parse_pipeline_definition(lines, 'test')
|
||||
|
||||
def group(spec: str):
|
||||
return pipeline(spec)['groups'][0]
|
||||
|
||||
def progress(spec: str, ticks: list[tuple[str, ...]]) -> list[float | None]:
|
||||
# The ticks are 10ms apart
|
||||
return [x[0] for x in simulate_custom_shader_animation(pipeline(spec, ''), ticks, True)]
|
||||
|
||||
# Parsing
|
||||
self.ae(group('')['animation_duration'], -1)
|
||||
self.ae(group('animation_duration 300')['animation_duration'], 300_000_000)
|
||||
self.ae(group('')['animation_reverse'], 0)
|
||||
self.ae(group('animation_reverse yes')['animation_reverse'], -1)
|
||||
self.ae(group('animation_reverse no')['animation_reverse'], 0)
|
||||
self.ae(group('animation_reverse 200')['animation_reverse'], 200_000_000)
|
||||
self.ae(group('')['animation_loops'], 1)
|
||||
self.ae(group('animation_reverse yes\nanimation_loops 3')['animation_loops'], 3)
|
||||
for bad in (
|
||||
'animation_duration -1',
|
||||
'animation_duration x',
|
||||
'animation_reverse -1',
|
||||
'animation_reverse maybe',
|
||||
'animation_reverse yes\nanimation_loops 0',
|
||||
'animation_loops 2',
|
||||
):
|
||||
self.assertRaises(ValueError, group, bad)
|
||||
|
||||
on, off, none = ('user:t',), ('user:off',), ()
|
||||
# Without animation_duration progress follows the stop duration, and a
|
||||
# group with no stop duration has no progress
|
||||
self.ae(progress('animation_start user:t\nanimation_stop 40', [on, none, none, none, none]), [0, 0.25, 0.5, 0.75, None])
|
||||
self.ae(progress('animation_toggle user:t', [on, none, none]), [0, 0, 0])
|
||||
# animation_duration makes progress rise to one and stay there
|
||||
self.ae(progress('animation_toggle user:t\nanimation_duration 40', [on] + [none] * 5 + [on, none]), [0, 0.25, 0.5, 0.75, 1, 1, None, None])
|
||||
# Reversing on toggle off, over animation_duration with yes
|
||||
self.ae(
|
||||
progress('animation_toggle user:t\nanimation_duration 40\nanimation_reverse yes', [on] + [none] * 4 + [on] + [none] * 4),
|
||||
[0, 0.25, 0.5, 0.75, 1, 1, 0.75, 0.5, 0.25, None],
|
||||
)
|
||||
# ...or over its own duration
|
||||
self.ae(
|
||||
progress('animation_toggle user:t\nanimation_duration 40\nanimation_reverse 20', [on] + [none] * 4 + [on, none, none]),
|
||||
[0, 0.25, 0.5, 0.75, 1, 1, 0.5, None],
|
||||
)
|
||||
# Stopping part way reverses from the current progress, and restarting
|
||||
# while reversing continues rising from there
|
||||
self.ae(
|
||||
progress('animation_toggle user:t\nanimation_duration 40\nanimation_reverse yes', [on, none, on, on, none, none, none]),
|
||||
[0, 0.25, 0.5, 0.25, 0.5, 0.75, 1],
|
||||
)
|
||||
# Stop events are ignored while reversing, start events restart
|
||||
self.ae(
|
||||
progress('animation_start user:t\nanimation_stop user:off\nanimation_duration 40\nanimation_reverse yes', [on] + [none] * 4 + [off, off, on, none]),
|
||||
[0, 0.25, 0.5, 0.75, 1, 1, 0.75, 0.5, 0.75],
|
||||
)
|
||||
# The stop duration ending also reverses, with progress having reached one
|
||||
self.ae(progress('animation_start user:t\nanimation_stop 40\nanimation_reverse yes', [on] + [none] * 8), [0, 0.25, 0.5, 0.75, 1, 0.75, 0.5, 0.25, None])
|
||||
# Loops play the animation forwards and in reverse again after the
|
||||
# first reverse, without holding, for example, to blink three times
|
||||
self.ae(
|
||||
progress('animation_start user:t\nanimation_stop 20\nanimation_duration 20\nanimation_reverse yes\nanimation_loops 3', [on] + [none] * 12),
|
||||
[0, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, None],
|
||||
)
|
||||
# Starting again while looping goes back to holding at one
|
||||
self.ae(
|
||||
progress(
|
||||
'animation_toggle user:t\nanimation_duration 20\nanimation_reverse yes\nanimation_loops 2', [on, none, none, on, none, none, on, none, none]
|
||||
),
|
||||
[0, 0.5, 1, 1, 0.5, 0, 0.5, 1, 1],
|
||||
)
|
||||
# Attached groups without their own events share the progress, including
|
||||
# the easing curve and reversal, of the group they are attached to
|
||||
p = pipeline('animation_toggle user:t\nanimation_duration 40\nanimation_curve ease-in\nanimation_reverse yes', 'attach', '')
|
||||
results = simulate_custom_shader_animation(p, [on] + [none] * 4 + [on] + [none] * 4, True)
|
||||
self.ae([r[0] for r in results], [r[1] for r in results])
|
||||
eased = results[2][0]
|
||||
assert eased is not None
|
||||
self.assertLess(eased, 0.5)
|
||||
self.ae([r[1] is None for r in results], [False] * 9 + [True])
|
||||
|
||||
def test_custom_shader_reenable(self):
|
||||
from kitty.fast_data_types import CUSTOM_END_PROGRAM
|
||||
from kitty.options.types import defaults
|
||||
|
||||
loader = LoadShaderPrograms()
|
||||
pipeline = parse_pipeline_definition(['startgroup', 'animation_step 0', 'shaders focus-highlight', 'endgroup'], 'test')
|
||||
self.ae(pipeline['groups'][0]['animation_step'], 0)
|
||||
with (
|
||||
patch('kitty.shaders.slang.parse_pipeline', return_value=pipeline),
|
||||
patch('kitty.shaders.slang.build_custom_shader_pipeline_glsl', return_value=('vertex', 'fragment', {})),
|
||||
patch('kitty.shaders.slang.compile_program') as compile_program,
|
||||
):
|
||||
for shaders in (('test',), (), ('test',)):
|
||||
loader.opts = defaults._replace(custom_shaders=shaders)
|
||||
loader.compile_custom_shaders(allow_recompile=True)
|
||||
operations = [c.args[1] for c in compile_program.call_args_list if c.args[0] == CUSTOM_END_PROGRAM]
|
||||
self.ae(operations, [('vertex',), (), ('vertex',)])
|
||||
|
||||
def test_slang_parser(self):
|
||||
def check(src: str, expected: SlangFile) -> None:
|
||||
actual = parse_slang_text(src)
|
||||
actual = actual._replace(text='')
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
# Basic vertex + fragment entry points
|
||||
check(
|
||||
"""
|
||||
[shader("vertex")]
|
||||
void drawTriangle(float4 pos : POSITION) {
|
||||
// vertex code
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
[numthreads(1, 1, 1)] // Handles intermediate attributes seamlessly
|
||||
float4 psMain() : SV_Target {
|
||||
return float4(1, 0, 0, 1);
|
||||
}
|
||||
""",
|
||||
SlangFile('', '', frozenset(), frozenset({EntryPoint(Stage.vertex, 'drawTriangle'), EntryPoint(Stage.fragment, 'psMain')})),
|
||||
)
|
||||
|
||||
# Empty source
|
||||
check('', SlangFile())
|
||||
|
||||
# Only line comments and block comments, no code
|
||||
check('// just a comment\n/* block comment */', SlangFile('', '', frozenset(), frozenset()))
|
||||
|
||||
# Module and import declarations
|
||||
check(
|
||||
"""
|
||||
module mymodule;
|
||||
import utils;
|
||||
import helpers;
|
||||
""",
|
||||
SlangFile('', '', frozenset({'utils', 'helpers'}), frozenset(), 'mymodule'),
|
||||
)
|
||||
|
||||
# pixel stage maps to Stage.fragment
|
||||
check(
|
||||
"""
|
||||
[shader("pixel")]
|
||||
float4 pixelMain() : SV_Target { return float4(0); }
|
||||
""",
|
||||
SlangFile('', '', frozenset(), frozenset({EntryPoint(Stage.fragment, 'pixelMain')})),
|
||||
)
|
||||
|
||||
# Block comment stripping removes multi-line comments before parsing
|
||||
check(
|
||||
"""
|
||||
/* This is a block comment
|
||||
spanning multiple lines */
|
||||
[shader("vertex")]
|
||||
void vertMain() {}
|
||||
""",
|
||||
SlangFile('', '', frozenset(), frozenset({EntryPoint(Stage.vertex, 'vertMain')})),
|
||||
)
|
||||
|
||||
# Block comment containing a shader attribute must not create a false entry point
|
||||
check(
|
||||
"""
|
||||
/* [shader("vertex")]
|
||||
void shouldNotBeDetected() {} */
|
||||
[shader("fragment")]
|
||||
void fragMain() {}
|
||||
""",
|
||||
SlangFile('', '', frozenset(), frozenset({EntryPoint(Stage.fragment, 'fragMain')})),
|
||||
)
|
||||
|
||||
# Multiple [attr] lines between [shader(...)] and the function declaration are skipped
|
||||
check(
|
||||
"""
|
||||
[shader("fragment")]
|
||||
[numthreads(4, 4, 1)]
|
||||
[SomeOtherAttribute]
|
||||
float4 fragMain() : SV_Target { return float4(0); }
|
||||
""",
|
||||
SlangFile('', '', frozenset(), frozenset({EntryPoint(Stage.fragment, 'fragMain')})),
|
||||
)
|
||||
|
||||
# Multiple entry points: vertex, pixel, and fragment stages
|
||||
check(
|
||||
"""
|
||||
[shader("vertex")]
|
||||
void vsMain(float4 pos : POSITION) {}
|
||||
|
||||
[shader("pixel")]
|
||||
float4 psMain() : SV_Target { return float4(0); }
|
||||
|
||||
[shader("fragment")]
|
||||
float4 fsMain() : SV_Target { return float4(0); }
|
||||
""",
|
||||
SlangFile(
|
||||
'',
|
||||
'',
|
||||
frozenset(),
|
||||
frozenset(
|
||||
{
|
||||
EntryPoint(Stage.vertex, 'vsMain'),
|
||||
EntryPoint(Stage.fragment, 'psMain'),
|
||||
EntryPoint(Stage.fragment, 'fsMain'),
|
||||
}
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
# module, imports and entry points together
|
||||
check(
|
||||
"""
|
||||
module myshader;
|
||||
import common;
|
||||
|
||||
[shader("vertex")]
|
||||
void vsMain() {}
|
||||
""",
|
||||
SlangFile('', '', frozenset({'common'}), frozenset({EntryPoint(Stage.vertex, 'vsMain')}), 'myshader'),
|
||||
)
|
||||
|
||||
# Autoformat style: return type on its own line before function name
|
||||
check(
|
||||
"""
|
||||
[shader("vertex")]
|
||||
VertexOutput
|
||||
vertex_main(uint vertex_id : SV_VertexID) {}
|
||||
""",
|
||||
SlangFile('', '', frozenset(), frozenset({EntryPoint(Stage.vertex, 'vertex_main')})),
|
||||
)
|
||||
|
||||
# Autoformat style: return type on own line, function name + open-paren on next, params on following lines
|
||||
check(
|
||||
"""
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(
|
||||
float2 texcoord : TEXCOORD
|
||||
) : SV_Target { return float4(0); }
|
||||
""",
|
||||
SlangFile('', '', frozenset(), frozenset({EntryPoint(Stage.fragment, 'fragment_main')})),
|
||||
)
|
||||
|
||||
# Autoformat style: attribute lines between [shader] and split return-type/name declaration
|
||||
check(
|
||||
"""
|
||||
[shader("fragment")]
|
||||
[numthreads(1, 1, 1)]
|
||||
float4
|
||||
psMain() : SV_Target { return float4(1, 0, 0, 1); }
|
||||
""",
|
||||
SlangFile('', '', frozenset(), frozenset({EntryPoint(Stage.fragment, 'psMain')})),
|
||||
)
|
||||
|
||||
# Autoformat style: vertex and fragment both split across lines
|
||||
check(
|
||||
"""
|
||||
[shader("vertex")]
|
||||
VertexOutput
|
||||
vsMain(uint id : SV_VertexID) {}
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fsMain(VertexOutput vo) : SV_Target { return float4(0); }
|
||||
""",
|
||||
SlangFile(
|
||||
'',
|
||||
'',
|
||||
frozenset(),
|
||||
frozenset({EntryPoint(Stage.vertex, 'vsMain'), EntryPoint(Stage.fragment, 'fsMain')}),
|
||||
),
|
||||
)
|
||||
|
||||
def test_slang_ordering(self):
|
||||
# Test topological_sort with a manually constructed linear chain: a <- b <- c
|
||||
graph: dict[str, SlangFile] = {
|
||||
'a': SlangFile('', '', frozenset(), frozenset(), 'a'),
|
||||
'b': SlangFile('', '', frozenset({'a'}), frozenset(), 'b'),
|
||||
'c': SlangFile('', '', frozenset({'b'}), frozenset(), 'c'),
|
||||
}
|
||||
order = topological_sort(graph)
|
||||
self.assertLess(order.index('a'), order.index('b'))
|
||||
self.assertLess(order.index('b'), order.index('c'))
|
||||
|
||||
# Diamond dependency: base <- left, base <- right, left + right <- top
|
||||
diamond: dict[str, SlangFile] = {
|
||||
'base': SlangFile('', '', frozenset(), frozenset(), 'base'),
|
||||
'left': SlangFile('', '', frozenset({'base'}), frozenset(), 'left'),
|
||||
'right': SlangFile('', '', frozenset({'base'}), frozenset(), 'right'),
|
||||
'top': SlangFile('', '', frozenset({'left', 'right'}), frozenset(), 'top'),
|
||||
}
|
||||
order2 = topological_sort(diamond)
|
||||
self.assertLess(order2.index('base'), order2.index('left'))
|
||||
self.assertLess(order2.index('base'), order2.index('right'))
|
||||
self.assertLess(order2.index('left'), order2.index('top'))
|
||||
self.assertLess(order2.index('right'), order2.index('top'))
|
||||
|
||||
# Node with an import not present in the graph is silently skipped
|
||||
partial: dict[str, SlangFile] = {
|
||||
'x': SlangFile('', '', frozenset({'missing'}), frozenset(), 'x'),
|
||||
}
|
||||
self.assertEqual(topological_sort(partial), ['x'])
|
||||
|
||||
# Empty graph
|
||||
self.assertEqual(topological_sort({}), [])
|
||||
|
||||
# build_import_graph reads .slang files from a directory tree and parses them
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
files = {
|
||||
'a': 'module a;\n',
|
||||
'b': 'module b;\nimport a;\n',
|
||||
'c': 'module c;\nimport b;\n',
|
||||
}
|
||||
for name, content in files.items():
|
||||
with open(os.path.join(tmpdir, name + '.slang'), 'w') as f:
|
||||
f.write(content)
|
||||
graph2 = build_import_graph(tmpdir)
|
||||
self.assertEqual(set(graph2.keys()), {'a', 'b', 'c'})
|
||||
self.assertEqual(graph2['a'].imports, frozenset())
|
||||
self.assertEqual(graph2['b'].imports, frozenset({'a'}))
|
||||
self.assertEqual(graph2['c'].imports, frozenset({'b'}))
|
||||
self.assertEqual(graph2['a'].module, 'a')
|
||||
|
||||
# Topological sort of file-based graph respects import dependencies
|
||||
order3 = topological_sort(graph2)
|
||||
self.assertLess(order3.index('a'), order3.index('b'))
|
||||
self.assertLess(order3.index('b'), order3.index('c'))
|
||||
|
||||
# Non-.slang files are ignored
|
||||
with open(os.path.join(tmpdir, 'ignored.txt'), 'w') as f:
|
||||
f.write('not a slang file\n')
|
||||
graph3 = build_import_graph(tmpdir)
|
||||
self.assertNotIn('ignored', graph3)
|
||||
|
||||
def test_topological_layers(self):
|
||||
# Linear chain a <- b <- c produces three layers
|
||||
graph: dict[str, SlangFile] = {
|
||||
'a': SlangFile('', '', frozenset(), frozenset(), 'a'),
|
||||
'b': SlangFile('', '', frozenset({'a'}), frozenset(), 'b'),
|
||||
'c': SlangFile('', '', frozenset({'b'}), frozenset(), 'c'),
|
||||
}
|
||||
layers = topological_layers(graph)
|
||||
self.assertEqual(len(layers), 3)
|
||||
self.assertIn('a', layers[0])
|
||||
self.assertIn('b', layers[1])
|
||||
self.assertIn('c', layers[2])
|
||||
|
||||
# Diamond: base <- left, base <- right, left+right <- top
|
||||
# base is layer 0, left and right are layer 1, top is layer 2
|
||||
diamond: dict[str, SlangFile] = {
|
||||
'base': SlangFile('', '', frozenset(), frozenset(), 'base'),
|
||||
'left': SlangFile('', '', frozenset({'base'}), frozenset(), 'left'),
|
||||
'right': SlangFile('', '', frozenset({'base'}), frozenset(), 'right'),
|
||||
'top': SlangFile('', '', frozenset({'left', 'right'}), frozenset(), 'top'),
|
||||
}
|
||||
layers2 = topological_layers(diamond)
|
||||
self.assertEqual(len(layers2), 3)
|
||||
self.assertIn('base', layers2[0])
|
||||
self.assertIn('left', layers2[1])
|
||||
self.assertIn('right', layers2[1])
|
||||
self.assertIn('top', layers2[2])
|
||||
|
||||
# Node with import not in graph is treated as layer 0
|
||||
partial: dict[str, SlangFile] = {
|
||||
'x': SlangFile('', '', frozenset({'missing'}), frozenset(), 'x'),
|
||||
}
|
||||
layers3 = topological_layers(partial)
|
||||
self.assertEqual(len(layers3), 1)
|
||||
self.assertIn('x', layers3[0])
|
||||
|
||||
# Empty graph
|
||||
self.assertEqual(topological_layers({}), [])
|
||||
|
||||
def test_parse_var_directive(self):
|
||||
self.assertEqual(parse_var_directive(['var', 'uint', 'algo', '=', '1']), ('uint', 'algo', '1'))
|
||||
self.assertEqual(parse_var_directive(['var', 'float', 'intensity', '=', '0.5']), ('float', 'intensity', '0.5'))
|
||||
self.assertEqual(parse_var_directive(['var', 'bool', 'flag', 'true']), ('bool', 'flag', 'true'))
|
||||
self.assertEqual(
|
||||
parse_var_directive(['var', 'float4', 'tint', '=', 'float4(0,', '0.6,', '0.8,', '1)']),
|
||||
('float4', 'tint', 'float4(0, 0.6, 0.8, 1)'),
|
||||
)
|
||||
self.assertRaises(ValueError, parse_var_directive, ['var', 'badtype', 'x', '=', '1'])
|
||||
self.assertRaises(ValueError, parse_var_directive, ['var', 'uint', '123bad', '=', '1'])
|
||||
self.assertRaises(ValueError, parse_var_directive, ['var', 'uint'])
|
||||
|
||||
def test_pointer_map_shaders(self):
|
||||
def pms(src: str) -> tuple[tuple[int, int], ...]:
|
||||
p = parse_pipeline_definition(src.splitlines(), 'test')
|
||||
return pointer_map_shaders(p, lambda g, s: p['groups'][g]['shaders'][s] == 'crt')
|
||||
|
||||
self.ae(pms('startgroup\nshaders crt\nendgroup'), ((0, 0),))
|
||||
self.ae(pms('startgroup\nshaders sample\nendgroup'), ())
|
||||
# The last shader to run is applied first
|
||||
self.ae(pms('startgroup\nshaders crt sample crt\nendgroup\nstartgroup\nshaders crt\nendgroup'), ((1, 0), (0, 2), (0, 0)))
|
||||
# Transient effects and passes that do not draw to the screen do not move pointer events
|
||||
self.ae(pms('startgroup\nanimation_start tab-change\nshaders crt\nendgroup'), ())
|
||||
self.ae(pms('startgroup\nanimation_start user:s\nanimation_stop 100\nshaders crt\nendgroup'), ())
|
||||
self.ae(pms('startgroup\nanimation_toggle user:t\nanimation_stop 100\nshaders crt\nendgroup'), ())
|
||||
# Effects that last until an event turns them off do
|
||||
self.ae(pms('startgroup\nanimation_toggle user:t\nshaders crt\nendgroup'), ((0, 0),))
|
||||
self.ae(pms('startgroup\nanimation_start user:s\nanimation_stop never\nshaders crt\nendgroup'), ((0, 0),))
|
||||
self.ae(pms('startgroup\nanimation_start user:s\nanimation_stop user:e\nshaders crt\nendgroup'), ((0, 0),))
|
||||
self.ae(pms('startgroup\nshaders sample\nendgroup\nstartgroup\nattach\nshaders crt\nendgroup'), ())
|
||||
self.ae(pms('textures a\nstartgroup\nshaders crt\noutput_texture a\nendgroup\nstartgroup\nshaders sample\nendgroup'), ())
|
||||
# Groups that draw only part of the screen do not move pointer events everywhere
|
||||
self.ae(pms('startgroup\nshaders crt\nviewport_size 0.5 1\nendgroup\nstartgroup\nshaders sample\nendgroup'), ())
|
||||
self.ae(pms('startgroup\nshaders crt\nviewport_pos 0.5 0\nendgroup\nstartgroup\nshaders sample\nendgroup'), ())
|
||||
|
||||
def test_slang_declarations(self):
|
||||
d = parse_slang_declarations("""
|
||||
#language slang 2026
|
||||
module m;
|
||||
import a.b;
|
||||
// float2 commented_out(float2 pos) { return pos; }
|
||||
/* float2 also_commented_out(float2 pos) */
|
||||
static const float4 TINT = float4(0, 0.8, // the tint
|
||||
0.6, 1);
|
||||
static const float ARR[2] = {1, 2};
|
||||
extern static const bool FLAG;
|
||||
struct S { float2 not_top_level(float2 p) { return p; } };
|
||||
public float2
|
||||
pointer_map(
|
||||
float2 pos, KittyCustomShaderData d) : SV_Target {
|
||||
static const float local = 1;
|
||||
return pos;
|
||||
}
|
||||
vector<float, 2> generic<T>(T x) { return float2(0); }
|
||||
float2 prototype(float2 p);
|
||||
[shader("fragment")] [numthreads(1, 1, 1)]
|
||||
float4 frag() { string s = "float2 in_string(float2 p) {}"; return float4(0); }
|
||||
""")
|
||||
self.ae(d.module, 'm')
|
||||
self.ae(d.imports, ('a.b',))
|
||||
self.ae([f.name for f in d.functions], ['pointer_map', 'generic', 'prototype', 'frag'])
|
||||
f = d.function('pointer_map')
|
||||
assert f is not None
|
||||
self.ae((f.return_type, f.modifiers, f.has_body), ('float2', frozenset({'public'}), True))
|
||||
self.ae(d.function('generic').return_type, 'vector<float,2>')
|
||||
self.assertFalse(d.function('prototype').has_body)
|
||||
self.ae(d.function('frag').attributes, (('shader', ('fragment',)), ('numthreads', ('1', '1', '1'))))
|
||||
self.ae(
|
||||
[(v.name, v.type, v.modifiers) for v in d.variables],
|
||||
[
|
||||
('TINT', 'float4', frozenset({'static', 'const'})),
|
||||
('ARR', 'float', frozenset({'static', 'const'})),
|
||||
('FLAG', 'bool', frozenset({'extern', 'static', 'const'})),
|
||||
],
|
||||
)
|
||||
self.ae(d.variable('FLAG').declaration, 'extern static const bool FLAG;')
|
||||
# # not at the start of a line is not a directive
|
||||
self.ae([f.name for f in parse_slang_declarations('float a = 1; # float2 f(float2 p) { return p; }').functions], ['f'])
|
||||
|
||||
def test_cell_contrast_variants(self):
|
||||
self.assertFalse(text_contrast_is_identity('legacy'))
|
||||
self.assertTrue(text_contrast_is_identity('1'))
|
||||
self.assertTrue(text_contrast_is_identity('1.0 0'))
|
||||
self.assertFalse(text_contrast_is_identity('1.7 30'))
|
||||
self.assertFalse(text_contrast_is_identity('2 0'))
|
||||
self.ae(text_contrast_is_identity('platform'), sys.platform != 'darwin')
|
||||
variants = cell_variations()
|
||||
self.ae(len(variants), 27)
|
||||
self.ae(sum(v['TEXT_NEW_GAMMA'] == 'false' for v in variants), 9)
|
||||
self.ae(sum(v['TEXT_CONTRAST_IDENTITY'] == 'true' for v in variants), 9)
|
||||
for v in variants:
|
||||
if v['TEXT_NEW_GAMMA'] == 'false':
|
||||
self.ae(v['TEXT_CONTRAST_IDENTITY'], 'false')
|
||||
default = cell_variant()
|
||||
names = [variant_name(dict(v), default) for v in variants]
|
||||
self.ae(len(names), len(set(names)))
|
||||
self.assertIn('', names)
|
||||
|
||||
def test_apply_pipeline_specializations(self):
|
||||
src = b"""static const float4 TINT = float4(0, 0.8,
|
||||
0.6, 1); // keep me
|
||||
// static const float SCAN = 0.5;
|
||||
static const float SCAN = 0.5; static const float WARP=1;
|
||||
extern static const bool FLAG = false;
|
||||
float f() { static const float SCAN = 2; return SCAN; }
|
||||
"""
|
||||
self.ae(apply_pipeline_specializations(src, {}), src)
|
||||
merged_vars = {'TINT': ('float3', '0.1'), 'SCAN': ('float', '1'), 'WARP': ('float', '2'), 'FLAG': ('bool', 'true')}
|
||||
self.ae(
|
||||
apply_pipeline_specializations(src, merged_vars).decode(),
|
||||
"""static const float3 TINT = 0.1; // keep me
|
||||
// static const float SCAN = 0.5;
|
||||
static const float SCAN = 1; static const float WARP = 2;
|
||||
extern static const bool FLAG = false;
|
||||
float f() { static const float SCAN = 2; return SCAN; }
|
||||
""",
|
||||
)
|
||||
|
||||
def test_shader_query(self):
|
||||
if not shutil.which(slangc()[0]):
|
||||
self.skipTest(f'slangc ({slangc()[0]}) not found in PATH')
|
||||
|
||||
def q(src: str) -> SlangShaderQuery:
|
||||
return SlangShaderQuery(src.encode(), 'test')
|
||||
|
||||
def has_pm(src: str) -> bool:
|
||||
return defines_pointer_map(q(src))
|
||||
|
||||
self.assertTrue(has_pm(custom_shader('crt')[2].decode()))
|
||||
self.assertFalse(has_pm(custom_shader('sample')[2].decode()))
|
||||
self.assertTrue(has_pm('public float2\npointer_map(float2 pos, KittyCustomShaderData d) { return pos; }'))
|
||||
self.assertTrue(has_pm('public vector<float, 2> pointer_map(float2 pos, KittyCustomShaderData d) { return pos; }'))
|
||||
# Comments, disabled code and strings do not count
|
||||
self.assertFalse(has_pm('// public float2 pointer_map(float2 pos, KittyCustomShaderData d) { return pos; }'))
|
||||
self.assertFalse(has_pm('#if 0\npublic float2 pointer_map(float2 pos, KittyCustomShaderData d) { return pos; }\n#endif'))
|
||||
self.assertFalse(has_pm('float2 f(float2 pos) { return pointer_map(pos); }'))
|
||||
# The preprocessor is applied
|
||||
self.assertTrue(has_pm('#define PM pointer_map\npublic float2 PM(float2 pos, KittyCustomShaderData d) { return pos; }'))
|
||||
# Mistakes are reported rather than ignored
|
||||
self.assertRaises(ValueError, has_pm, 'float2 pointer_map(float2 pos, KittyCustomShaderData d) { return pos; }')
|
||||
self.assertRaises(ValueError, has_pm, 'public float3 pointer_map(float2 pos, KittyCustomShaderData d) { return float3(pos, 0); }')
|
||||
# The preprocessor is run only when the answer could depend on it
|
||||
tracker: set[tuple[str, ...]] = set()
|
||||
self.assertIsNone(SlangShaderQuery(b'float4 f() { return float4(0); }', '', (), tracker).function('pointer_map'))
|
||||
self.assertFalse(tracker)
|
||||
|
||||
def test_sample_pointer_map(self):
|
||||
import struct
|
||||
|
||||
from kitty.fast_data_types import POINTER_MAP_SIZE, sample_pointer_map
|
||||
|
||||
def grid(f) -> bytes:
|
||||
last = POINTER_MAP_SIZE - 1
|
||||
vals = []
|
||||
for y in range(POINTER_MAP_SIZE):
|
||||
for x in range(POINTER_MAP_SIZE):
|
||||
vals.extend(f(x / last, y / last))
|
||||
return struct.pack(f'{len(vals)}f', *vals)
|
||||
|
||||
def ae(a, b):
|
||||
for x, y in zip(a, b):
|
||||
self.assertAlmostEqual(x, y, places=5)
|
||||
|
||||
identity = grid(lambda u, v: (u, v))
|
||||
for pos in ((0, 0), (1, 1), (0.5, 0.25), (0.123, 0.987), (1, 0)):
|
||||
ae(sample_pointer_map(identity, *pos), pos)
|
||||
# Positions outside the viewport are clamped to its edges
|
||||
ae(sample_pointer_map(identity, -0.5, 1.5), (0, 1))
|
||||
# Linear maps are reproduced exactly between grid points
|
||||
shrink = grid(lambda u, v: (0.1 + 0.8 * u, 1 - v))
|
||||
for u, v in ((0, 0), (0.3, 0.6), (1, 1)):
|
||||
ae(sample_pointer_map(shrink, u, v), (0.1 + 0.8 * u, 1 - v))
|
||||
self.assertRaises(ValueError, sample_pointer_map, b'', 0, 0)
|
||||
|
||||
def test_parse_pipeline_definition_vars(self):
|
||||
p = parse_pipeline_definition(
|
||||
"""
|
||||
var uint algo = 1
|
||||
var float intensity = 0.5
|
||||
startgroup
|
||||
shaders sample
|
||||
endgroup
|
||||
startgroup
|
||||
var uint algo = 2
|
||||
shaders sample
|
||||
endgroup
|
||||
""".splitlines(),
|
||||
'test',
|
||||
)
|
||||
self.assertEqual(p['vars'], {'algo': ('uint', '1'), 'intensity': ('float', '0.5')})
|
||||
self.assertEqual(p['groups'][0]['vars'], {})
|
||||
self.assertEqual(p['groups'][1]['vars'], {'algo': ('uint', '2')})
|
||||
# Groups still carry shaders correctly
|
||||
self.assertEqual(p['groups'][0]['shaders'], ('sample',))
|
||||
self.assertEqual(p['groups'][1]['shaders'], ('sample',))
|
||||
|
||||
def test_build_custom_shader_pipeline_glsl(self):
|
||||
if not shutil.which(slangc()[0]):
|
||||
self.skipTest(f'slangc ({slangc()[0]}) not found in PATH')
|
||||
|
||||
with tempfile.TemporaryDirectory() as cache_dir:
|
||||
# Clear the lru_cache so the temp cache_dir is actually used
|
||||
clear_caches()
|
||||
p = parse_pipeline_definition(
|
||||
"""
|
||||
startgroup
|
||||
shaders sample sample
|
||||
endgroup
|
||||
""".splitlines(),
|
||||
'test',
|
||||
)
|
||||
try:
|
||||
vert_src, frag_src, metadata = build_custom_shader_pipeline_glsl(p, cache_dir=cache_dir)
|
||||
invocation_tracker = set()
|
||||
build_custom_shader_pipeline_glsl(p, cache_dir=cache_dir, invocation_tracker=invocation_tracker)
|
||||
finally:
|
||||
clear_caches()
|
||||
|
||||
self.assertIsInstance(vert_src, str)
|
||||
self.assertIsInstance(frag_src, str)
|
||||
self.assertTrue(len(vert_src) > 0, 'vertex GLSL is empty')
|
||||
self.assertTrue(len(frag_src) > 0, 'fragment GLSL is empty')
|
||||
self.assertIsInstance(metadata, dict)
|
||||
self.assertFalse(metadata['has_pointer_map'])
|
||||
self.assertFalse(invocation_tracker)
|
||||
|
||||
with tempfile.TemporaryDirectory() as cache_dir:
|
||||
clear_caches()
|
||||
# pointer_map() of a group turned on and off by events applies only while it is active
|
||||
p = parse_pipeline_definition(
|
||||
[
|
||||
'startgroup',
|
||||
'shaders crt',
|
||||
'endgroup',
|
||||
'startgroup',
|
||||
'shaders sample',
|
||||
'endgroup',
|
||||
'startgroup',
|
||||
'animation_toggle user:t',
|
||||
'shaders crt',
|
||||
'endgroup',
|
||||
],
|
||||
'test',
|
||||
)
|
||||
try:
|
||||
_, pm_frag_src, pm_metadata = build_custom_shader_pipeline_glsl(p, cache_dir=cache_dir)
|
||||
finally:
|
||||
clear_caches()
|
||||
self.assertTrue(pm_metadata['has_pointer_map'])
|
||||
self.ae(pm_metadata['pointer_map_groups'], [0, 2])
|
||||
self.assertIn('active_groups', pm_frag_src)
|
||||
|
||||
if not shutil.which('glslangValidator'):
|
||||
return
|
||||
|
||||
for src, stage, ext in ((vert_src, 'vert', '.vert.glsl'), (frag_src, 'frag', '.frag.glsl')):
|
||||
with tempfile.NamedTemporaryFile(suffix=ext, mode='w', delete=False) as tf:
|
||||
tf.write(src)
|
||||
tf_path = tf.name
|
||||
try:
|
||||
cp = subprocess.run(
|
||||
['glslangValidator', '-S', stage, tf_path],
|
||||
capture_output=True,
|
||||
)
|
||||
self.assertEqual(
|
||||
cp.returncode,
|
||||
0,
|
||||
f'glslangValidator failed for {stage} shader:\n{cp.stdout.decode()}\n{cp.stderr.decode()}',
|
||||
)
|
||||
finally:
|
||||
os.unlink(tf_path)
|
||||
|
||||
def _content_hash(self) -> str:
|
||||
h = hashlib.md5(usedforsecurity=False)
|
||||
pkg = ir.files('kitty.shaders.custom')
|
||||
for entry in sorted(pkg.iterdir(), key=lambda x: x.name):
|
||||
if entry.name.endswith(('.slang', '.pipeline')):
|
||||
h.update(entry.name.encode())
|
||||
h.update(entry.read_bytes())
|
||||
h.update(slangc_version().encode())
|
||||
return h.hexdigest()
|
||||
|
||||
def test_all_custom_shaders_compile(self) -> None:
|
||||
if __file__ and os.path.isdir((local := os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.cache'))):
|
||||
cache_base = local
|
||||
else:
|
||||
cache_base = tempfile.gettempdir()
|
||||
cache_base = os.path.join(cache_base, 'kitty-test-cache')
|
||||
os.makedirs(cache_base, exist_ok=True)
|
||||
|
||||
_CACHE_FILE = os.path.join(cache_base, 'custom-shaders-test.json')
|
||||
if not shutil.which(slangc()[0]):
|
||||
self.skipTest(f'slangc ({slangc()[0]}) not found in PATH')
|
||||
|
||||
current_hash = self._content_hash()
|
||||
|
||||
try:
|
||||
with open(_CACHE_FILE) as f:
|
||||
if json.load(f).get('hash') == current_hash:
|
||||
return
|
||||
except (OSError, json.JSONDecodeError, KeyError):
|
||||
pass
|
||||
|
||||
pkg = ir.files('kitty.shaders.custom')
|
||||
shader_names = sorted(
|
||||
entry.name[: -len('.slang')]
|
||||
for entry in pkg.iterdir()
|
||||
if entry.name.endswith('.slang') and entry.name[: -len('.slang')] not in _SUPPORT_SHADER_NAMES
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as cache_dir:
|
||||
failures: list[str] = []
|
||||
clear_caches()
|
||||
for name in shader_names:
|
||||
pipeline = parse_pipeline_definition(
|
||||
['startgroup', f'shaders {name}', 'endgroup'],
|
||||
name,
|
||||
)
|
||||
try:
|
||||
vert_src, frag_src, _ = build_custom_shader_pipeline_glsl(pipeline, cache_dir=cache_dir)
|
||||
except Exception as e:
|
||||
failures.append(f'{name}: {e}')
|
||||
continue
|
||||
if not vert_src:
|
||||
failures.append(f'{name}: empty vertex GLSL')
|
||||
if not frag_src:
|
||||
failures.append(f'{name}: empty fragment GLSL')
|
||||
clear_caches()
|
||||
# Builtin pipelines can override constants with var and chain
|
||||
# shaders, so compile them as well
|
||||
pipeline_names = sorted(entry.name[: -len('.pipeline')] for entry in pkg.iterdir() if entry.name.endswith('.pipeline'))
|
||||
for name in pipeline_names:
|
||||
try:
|
||||
pipeline = parse_pipeline_definition(get_custom_pipeline_src(name).decode().splitlines(), name)
|
||||
build_custom_shader_pipeline_glsl(pipeline, cache_dir=cache_dir)
|
||||
except Exception as e:
|
||||
failures.append(f'{name}.pipeline: {e}')
|
||||
clear_caches()
|
||||
|
||||
if failures:
|
||||
self.fail('Custom shader compilation failures:\n' + '\n'.join(failures))
|
||||
|
||||
with open(_CACHE_FILE, 'w') as f:
|
||||
json.dump({'hash': current_hash}, f)
|
||||
|
||||
def test_builtin_pipelines_bundled(self) -> None:
|
||||
# Packaging code filters files by extension, ensure builtin pipelines
|
||||
# and the shaders they reference survive in all build types
|
||||
pkg = ir.files('kitty.shaders.custom')
|
||||
available = {entry.name for entry in pkg.iterdir()}
|
||||
pipelines = sorted(x[: -len('.pipeline')] for x in available if x.endswith('.pipeline'))
|
||||
self.assertIn('cursor-trail-default', pipelines)
|
||||
for name in pipelines:
|
||||
p = parse_pipeline_definition(get_custom_pipeline_src(name).decode().splitlines(), name)
|
||||
for group in p['groups']:
|
||||
for shader in group['shaders']:
|
||||
self.assertIn(f'{shader}.slang', available, f'Shader {shader} used by pipeline {name} is missing')
|
||||
|
||||
def test_pipeline_absolute_path(self) -> None:
|
||||
pipeline_content = 'startgroup\n shaders myshader\nendgroup\n'
|
||||
slang_content = b'// shader in pipeline dir\n'
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
pipeline_path = os.path.join(tmpdir, 'my.pipeline')
|
||||
with open(pipeline_path, 'w') as f:
|
||||
f.write(pipeline_content)
|
||||
with open(os.path.join(tmpdir, 'myshader.slang'), 'wb') as f:
|
||||
f.write(slang_content)
|
||||
|
||||
clear_caches()
|
||||
try:
|
||||
# Absolute path with .pipeline extension - used as-is
|
||||
lines, pipeline_dir = pipeline_definition(pipeline_path)
|
||||
self.assertEqual(pipeline_dir, tmpdir)
|
||||
self.assertIn('startgroup', lines)
|
||||
|
||||
# Absolute path without .pipeline extension - .pipeline is auto-appended
|
||||
clear_caches()
|
||||
lines2, pipeline_dir2 = pipeline_definition(pipeline_path[: -len('.pipeline')])
|
||||
self.assertEqual(pipeline_dir2, tmpdir)
|
||||
self.assertEqual(lines, lines2)
|
||||
|
||||
# Shader lookup finds the file in the pipeline directory first
|
||||
found_path, import_dir, src, _ = custom_shader('myshader', tmpdir)
|
||||
self.assertEqual(src, slang_content)
|
||||
self.assertEqual(import_dir, tmpdir)
|
||||
finally:
|
||||
clear_caches()
|
||||
|
||||
def test_custom_shader_discovery(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
pdir = os.path.join(tmpdir, 'pipelines')
|
||||
os.mkdir(pdir)
|
||||
|
||||
def w(path: str, data: str) -> str:
|
||||
path = os.path.join(tmpdir, path)
|
||||
with open(path, 'w') as f:
|
||||
f.write(data)
|
||||
return path
|
||||
|
||||
effect = w('effect.slang', '// effect shader\n')
|
||||
w('effect.pipeline', 'startgroup\n shaders effect\nendgroup\n')
|
||||
notch = w('notch.slang', '// notch shader\n')
|
||||
w('pipelines/other.slang', '// other\n')
|
||||
orig_home = os.environ.get('HOME')
|
||||
os.environ['HOME'] = tmpdir
|
||||
clear_caches()
|
||||
try:
|
||||
# absolute paths with the extension are not extended again
|
||||
self.assertEqual(custom_shader(effect)[0], effect)
|
||||
self.assertEqual(custom_shader(effect[: -len('.slang')])[0], effect)
|
||||
# ~ is expanded both at top level and inside a pipeline, even
|
||||
# when the pipeline is in the same directory as the shader
|
||||
self.assertEqual(custom_shader('~/effect.slang')[0], effect)
|
||||
self.assertEqual(custom_shader('~/notch', tmpdir)[0], notch)
|
||||
self.assertEqual(custom_shader('~/notch', pdir)[0], notch)
|
||||
self.assertEqual(custom_shader('other', pdir)[0], os.path.join(pdir, 'other.slang'))
|
||||
lines, pipeline_dir = pipeline_definition('~/effect')
|
||||
self.assertEqual(pipeline_dir, tmpdir)
|
||||
self.assertIn(' shaders effect', lines)
|
||||
# names ending with .slang never load pipelines
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
pipeline_definition('~/effect.slang')
|
||||
# builtins work with or without the extension
|
||||
self.assertEqual(custom_shader('crt.slang')[2], custom_shader('crt')[2])
|
||||
with self.assertRaises(FileNotFoundError) as cm:
|
||||
custom_shader('~/does-not-exist')
|
||||
self.assertIn(os.path.join(tmpdir, 'does-not-exist.slang'), str(cm.exception))
|
||||
finally:
|
||||
if orig_home is None:
|
||||
os.environ.pop('HOME', None)
|
||||
else:
|
||||
os.environ['HOME'] = orig_home
|
||||
clear_caches()
|
||||
@@ -0,0 +1,496 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
from contextlib import suppress
|
||||
from functools import lru_cache
|
||||
|
||||
from kittens.ssh.utils import get_connection_data
|
||||
from kitty.constants import is_macos, kitten_exe, kitty_base_dir, runtime_dir
|
||||
from kitty.fast_data_types import CURSOR_BEAM, shm_unlink
|
||||
from kitty.utils import SSHConnectionData
|
||||
|
||||
from .base import BaseTest, retry_on_failure
|
||||
from .shell_integration import bash_ok, basic_shell_env
|
||||
|
||||
|
||||
def make_writable(top):
|
||||
for dirpath, dirnames, filenames in os.walk(top):
|
||||
for x in dirnames:
|
||||
path = os.path.join(dirpath, x)
|
||||
if not os.path.islink(path):
|
||||
os.chmod(path, 0o700)
|
||||
|
||||
|
||||
def files_in(path):
|
||||
for record in os.walk(path):
|
||||
for f in record[-1]:
|
||||
yield os.path.relpath(os.path.join(record[0], f), path)
|
||||
|
||||
|
||||
class SSHKitten(BaseTest):
|
||||
@retry_on_failure()
|
||||
def test_basic_pty_operations(self):
|
||||
pty = self.create_pty('echo hello')
|
||||
pty.process_input_from_child()
|
||||
self.ae(pty.screen_contents(), 'hello')
|
||||
pty = self.create_pty(
|
||||
self.cmd_to_run_python_code("""\
|
||||
import array, fcntl, sys, termios
|
||||
buf = array.array('H', [0, 0, 0, 0])
|
||||
fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, buf)
|
||||
print(' '.join(map(str, buf)))"""),
|
||||
lines=13,
|
||||
cols=77,
|
||||
)
|
||||
pty.process_input_from_child()
|
||||
self.ae(pty.screen_contents(), '13 77 770 260')
|
||||
|
||||
@retry_on_failure()
|
||||
def test_ssh_connection_data(self):
|
||||
def t(cmdline, binary='ssh', host='main', port=None, identity_file='', extra_args=()):
|
||||
if identity_file:
|
||||
identity_file = os.path.abspath(identity_file)
|
||||
en = {f'{x[0]}' for x in extra_args}
|
||||
q = get_connection_data(cmdline.split(), extra_args=en)
|
||||
self.ae(q, SSHConnectionData(binary, host, port, identity_file, extra_args))
|
||||
|
||||
t('ssh main')
|
||||
t('ssh un@ip -i ident -p34', host='un@ip', port=34, identity_file='ident')
|
||||
t('ssh un@ip -iident -p34', host='un@ip', port=34, identity_file='ident')
|
||||
t('ssh -p 33 main', port=33)
|
||||
t('ssh -p 34 ssh://un@ip:33/', host='un@ip', port=34)
|
||||
t('ssh --kitten=one -p 12 --kitten two -ix main', identity_file='x', port=12, extra_args=(('--kitten', 'one'), ('--kitten', 'two')))
|
||||
self.assertTrue(runtime_dir())
|
||||
|
||||
@property
|
||||
@lru_cache
|
||||
def all_possible_sh(self):
|
||||
python = 'python3' if shutil.which('python3') else 'python'
|
||||
return tuple(filter(shutil.which, ('dash', 'zsh', 'bash', 'posh', 'sh', python)))
|
||||
|
||||
@retry_on_failure()
|
||||
def test_ssh_copy(self):
|
||||
simple_data = 'rkjlhfwf9whoaa'
|
||||
|
||||
def touch(p):
|
||||
with open(os.path.join(local_home, p), 'w') as f:
|
||||
f.write(simple_data)
|
||||
|
||||
for sh in self.all_possible_sh:
|
||||
with tempfile.TemporaryDirectory() as remote_home, tempfile.TemporaryDirectory() as local_home:
|
||||
tuple(map(touch, 'simple-file g.1 g.2'.split()))
|
||||
os.makedirs(f'{local_home}/d1/d2/d3')
|
||||
touch('d1/d2/x')
|
||||
touch('d1/d2/w.exclude')
|
||||
os.mkdir(f'{local_home}/d1/r')
|
||||
touch('d1/r/noooo')
|
||||
os.symlink('d2/x', f'{local_home}/d1/y')
|
||||
bad_link_name = '$(touch SHOULD_NOT_EXIST)'
|
||||
os.symlink('d2/x', os.path.join(local_home, 'd1', bad_link_name))
|
||||
os.symlink('-dash-target', os.path.join(local_home, 'd1', 'dash-target-link'))
|
||||
os.symlink('simple-file', f'{local_home}/s1')
|
||||
os.symlink('simple-file', f'{local_home}/s2')
|
||||
|
||||
conf = """\
|
||||
copy simple-file
|
||||
copy s1
|
||||
copy --symlink-strategy=keep-path s2
|
||||
copy --dest=a/sfa simple-file
|
||||
copy --glob g.*
|
||||
copy --exclude **/w.* --exclude **/r d1
|
||||
"""
|
||||
self.check_bootstrap(
|
||||
sh,
|
||||
remote_home,
|
||||
test_script='env; exit 0',
|
||||
SHELL_INTEGRATION_VALUE='',
|
||||
conf=conf,
|
||||
home=local_home,
|
||||
)
|
||||
tname = '.terminfo'
|
||||
if os.path.exists('/usr/share/misc/terminfo.cdb'):
|
||||
tname += '.cdb'
|
||||
self.assertTrue(os.path.lexists(f'{remote_home}/{tname}/78'))
|
||||
self.assertTrue(os.path.exists(f'{remote_home}/{tname}/78/xterm-kitty'))
|
||||
self.assertTrue(os.path.exists(f'{remote_home}/{tname}/x/xterm-kitty'))
|
||||
for w in ('simple-file', 'a/sfa', 's2'):
|
||||
with open(os.path.join(remote_home, w)) as f:
|
||||
self.ae(f.read(), simple_data)
|
||||
self.assertFalse(os.path.islink(f.name))
|
||||
self.assertTrue(os.path.lexists(f'{remote_home}/d1/y'))
|
||||
self.assertTrue(os.path.exists(f'{remote_home}/d1/y'))
|
||||
self.ae(os.readlink(f'{remote_home}/d1/y'), 'd2/x')
|
||||
self.assertTrue(os.path.lexists(os.path.join(remote_home, 'd1', bad_link_name)))
|
||||
self.assertFalse(os.path.exists(os.path.join(remote_home, 'SHOULD_NOT_EXIST')))
|
||||
self.ae(os.readlink(f'{remote_home}/d1/dash-target-link'), '-dash-target')
|
||||
self.ae(os.readlink(f'{remote_home}/s1'), 'simple-file')
|
||||
contents = set(files_in(remote_home))
|
||||
contents.discard('.zshrc') # added by check_bootstrap()
|
||||
# depending on platform one of these is a symlink and hence
|
||||
# isn't in contents
|
||||
contents.discard(f'{tname}/x/xterm-kitty')
|
||||
contents.discard(f'{tname}/78/xterm-kitty')
|
||||
self.ae(
|
||||
contents,
|
||||
{
|
||||
'g.1',
|
||||
'g.2',
|
||||
f'{tname}/kitty.terminfo',
|
||||
'simple-file',
|
||||
'd1/d2/x',
|
||||
'd1/y',
|
||||
f'd1/{bad_link_name}',
|
||||
'd1/dash-target-link',
|
||||
'a/sfa',
|
||||
's1',
|
||||
's2',
|
||||
'.local/share/kitty-ssh-kitten/kitty/version',
|
||||
'.local/share/kitty-ssh-kitten/kitty/bin/kitty',
|
||||
'.local/share/kitty-ssh-kitten/kitty/bin/kitten',
|
||||
},
|
||||
)
|
||||
self.ae(len(glob.glob(f'{remote_home}/{tname}/*/xterm-kitty')), 2)
|
||||
|
||||
def test_ssh_copy_home_prefix(self):
|
||||
for sh in self.all_possible_sh:
|
||||
with self.subTest(interpreter=sh):
|
||||
self.do_test_ssh_copy_home_prefix(sh)
|
||||
|
||||
@retry_on_failure()
|
||||
def do_test_ssh_copy_home_prefix(self, sh):
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
local_home = os.path.join(tdir, 'alice')
|
||||
remote_home = os.path.join(tdir, 'remote')
|
||||
sibling = local_home + '-backup'
|
||||
for d in (local_home, remote_home, sibling):
|
||||
os.mkdir(d)
|
||||
source = os.path.join(sibling, 'config')
|
||||
with open(source, 'w') as f:
|
||||
f.write('copied contents')
|
||||
# Remove the local file after creating the archive so that the
|
||||
# bootstrap must restore it at the same absolute path.
|
||||
launcher = os.path.join(tdir, 'launcher')
|
||||
with open(launcher, 'w') as f:
|
||||
f.write(f'#!/bin/sh\nrm -f {shlex.quote(source)} || exit 1\nexec sh "$@"\n')
|
||||
os.chmod(launcher, 0o755)
|
||||
self.check_bootstrap(
|
||||
sh,
|
||||
remote_home,
|
||||
test_script='env; exit 0',
|
||||
SHELL_INTEGRATION_VALUE='',
|
||||
conf=f'copy {shlex.quote(source)}',
|
||||
home=local_home,
|
||||
launcher=launcher,
|
||||
)
|
||||
with open(source) as f:
|
||||
self.ae(f.read(), 'copied contents')
|
||||
self.ae(glob.glob(os.path.join(remote_home, '.kitty-ssh-kitten-untar-*')), [])
|
||||
|
||||
def test_ssh_copy_directory_merge(self):
|
||||
bootstrap_utils = os.path.join(kitty_base_dir, 'shell-integration', 'ssh', 'bootstrap-utils.sh')
|
||||
for sh in self.all_possible_sh:
|
||||
if 'python' in sh:
|
||||
continue
|
||||
with self.subTest(shell=sh), tempfile.TemporaryDirectory() as tdir:
|
||||
src, dest = os.path.join(tdir, 'src'), os.path.join(tdir, 'dest')
|
||||
name = '-private dir'
|
||||
source, target = os.path.join(src, name), os.path.join(dest, name)
|
||||
os.makedirs(os.path.join(source, 'nested'))
|
||||
os.makedirs(target)
|
||||
with open(os.path.join(source, 'nested', 'file with spaces'), 'w') as f:
|
||||
f.write('copied contents')
|
||||
with open(os.path.join(target, 'existing'), 'w') as f:
|
||||
f.write('retained contents')
|
||||
os.chmod(os.path.join(source, 'nested'), 0o750)
|
||||
os.chmod(source, 0o500)
|
||||
os.chmod(target, 0o710)
|
||||
try:
|
||||
cp = subprocess.run(
|
||||
[sh, '-c', '. "$1"; mv_files_and_dirs "$2" "$3"', 'sh', bootstrap_utils, src, dest],
|
||||
stdin=subprocess.DEVNULL,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.ae(cp.returncode, 0, cp.stderr)
|
||||
self.ae(cp.stderr, '')
|
||||
self.ae(stat.S_IMODE(os.stat(target).st_mode), 0o710)
|
||||
self.ae(stat.S_IMODE(os.stat(os.path.join(target, 'nested')).st_mode), 0o750)
|
||||
for filename, data in (('nested/file with spaces', 'copied contents'), ('existing', 'retained contents')):
|
||||
with open(os.path.join(target, filename)) as f:
|
||||
self.ae(f.read(), data)
|
||||
finally:
|
||||
make_writable(tdir)
|
||||
|
||||
def test_ssh_copy_directory_permissions(self):
|
||||
dirs = {
|
||||
'': 0o750,
|
||||
'private': 0o700,
|
||||
'private/nested': 0o750,
|
||||
'.hidden': 0o700,
|
||||
'empty': 0o710,
|
||||
'space dir': 0o750,
|
||||
'readonly': 0o500,
|
||||
'readonly/sub': 0o500,
|
||||
'replaced': 0o750,
|
||||
}
|
||||
files = {'private/nested/file with spaces': 'one', 'readonly/f': 'two', 'readonly/sub/f': 'three'}
|
||||
existing = {'': 0o700, 'private': 0o710, 'readonly': 0o750}
|
||||
for sh in self.all_possible_sh:
|
||||
for umask in ('022', '077'):
|
||||
# Retry inside the subTest as subTest() swallows exceptions, so
|
||||
# decorating the test method itself would never retry.
|
||||
with self.subTest(interpreter=sh, umask=umask):
|
||||
self.do_test_ssh_copy_directory_permissions(sh, umask, dirs, files, existing)
|
||||
|
||||
@retry_on_failure()
|
||||
def do_test_ssh_copy_directory_permissions(self, sh, umask, dirs, files, existing):
|
||||
# Use fresh directories for every attempt
|
||||
with tempfile.TemporaryDirectory() as remote_home, tempfile.TemporaryDirectory() as local_home:
|
||||
try:
|
||||
self.check_ssh_copy_directory_permissions(sh, umask, remote_home, local_home, dirs, files, existing)
|
||||
finally:
|
||||
make_writable(remote_home)
|
||||
make_writable(local_home)
|
||||
|
||||
def check_ssh_copy_directory_permissions(self, sh, umask, remote_home, local_home, dirs, files, existing):
|
||||
tree = os.path.join(local_home, 'tree')
|
||||
for name in dirs:
|
||||
os.makedirs(os.path.join(tree, name), exist_ok=True)
|
||||
for name, data in files.items():
|
||||
with open(os.path.join(tree, name), 'w') as f:
|
||||
f.write(data)
|
||||
os.symlink('private/nested', os.path.join(tree, 'link'))
|
||||
os.symlink('missing', os.path.join(tree, 'broken'))
|
||||
for name, mode in sorted(dirs.items(), reverse=True):
|
||||
os.chmod(os.path.join(tree, name), mode)
|
||||
for name, mode in existing.items():
|
||||
path = os.path.join(remote_home, 'merged', name)
|
||||
os.mkdir(path, mode)
|
||||
os.chmod(path, mode)
|
||||
# a directory replacing a dangling symlink
|
||||
os.symlink('missing', os.path.join(remote_home, 'merged', 'replaced'))
|
||||
launcher = os.path.join(local_home, 'launcher')
|
||||
with open(launcher, 'w') as f:
|
||||
f.write(f'#!/bin/sh\numask {umask}\nexec sh "$@"\n')
|
||||
os.chmod(launcher, 0o755)
|
||||
self.check_bootstrap(
|
||||
sh,
|
||||
remote_home,
|
||||
test_script='env; exit 0',
|
||||
SHELL_INTEGRATION_VALUE='',
|
||||
conf='copy --dest=new tree\ncopy --dest=merged tree',
|
||||
home=local_home,
|
||||
launcher=launcher,
|
||||
)
|
||||
for target in ('new', 'merged'):
|
||||
dest = os.path.join(remote_home, target)
|
||||
for name, mode in dirs.items():
|
||||
# the ssh kitten ensures everything is readable and writable by the owner
|
||||
expected = existing.get(name, mode | 0o600) if target == 'merged' else mode | 0o600
|
||||
self.ae(stat.S_IMODE(os.lstat(os.path.join(dest, name)).st_mode), expected, (sh, umask, target, name))
|
||||
for name, data in files.items():
|
||||
with open(os.path.join(dest, name)) as f:
|
||||
self.ae(f.read(), data)
|
||||
self.ae(os.readlink(os.path.join(dest, 'link')), 'private/nested')
|
||||
self.ae(os.readlink(os.path.join(dest, 'broken')), 'missing')
|
||||
self.ae(glob.glob(os.path.join(remote_home, '.kitty-ssh-kitten-untar-*')), [])
|
||||
|
||||
@retry_on_failure()
|
||||
def test_ssh_env_vars(self):
|
||||
tset = '$A-$(echo no)-`echo no2` !Q5 "something else"'
|
||||
for sh in self.all_possible_sh:
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
os.mkdir(os.path.join(tdir, 'cwd'))
|
||||
conf = f"""
|
||||
cwd $HOME/cwd
|
||||
env A=AAA
|
||||
env TSET={tset}
|
||||
env COLORTERM
|
||||
"""
|
||||
pty = self.check_bootstrap(sh, tdir, test_script='env; pwd; exit 0', SHELL_INTEGRATION_VALUE='', conf=conf)
|
||||
# coreutils >= 9.12 has env(1) shell-quote values written to a terminal,
|
||||
# so accept both the raw and the shell-quoted form of the value.
|
||||
expected_tset = tset.replace('$A', 'AAA')
|
||||
pty.wait_till(lambda: f'TSET={expected_tset}' in pty.screen_contents() or f'TSET={shlex.quote(expected_tset)}' in pty.screen_contents())
|
||||
self.assertNotIn('COLORTERM', pty.screen_contents())
|
||||
pty.wait_till(lambda: '/cwd' in pty.screen_contents())
|
||||
self.assertTrue(pty.is_echo_on())
|
||||
|
||||
@retry_on_failure()
|
||||
def test_ssh_bootstrap_with_different_launchers(self):
|
||||
for launcher in self.all_possible_sh:
|
||||
if 'python' in launcher:
|
||||
continue
|
||||
for sh in self.all_possible_sh:
|
||||
if sh == 'sh' or 'python' in sh:
|
||||
q = shutil.which(launcher)
|
||||
if q:
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
self.check_bootstrap(sh, tdir, test_script='env; exit 0', SHELL_INTEGRATION_VALUE='', launcher=q)
|
||||
|
||||
@retry_on_failure()
|
||||
def test_ssh_leading_data(self):
|
||||
script = 'echo "ld:$leading_data"; exit 0'
|
||||
for sh in self.all_possible_sh:
|
||||
if 'python' in sh:
|
||||
script = 'print("ld:" + leading_data.decode("ascii")); raise SystemExit(0);'
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
pty = self.check_bootstrap(sh, tdir, test_script=script, SHELL_INTEGRATION_VALUE='', pre_data='before_tarfile')
|
||||
self.ae(pty.screen_contents(), 'UNTAR_DONE\nld:before_tarfile')
|
||||
|
||||
@retry_on_failure()
|
||||
def test_ssh_login_shell_detection(self):
|
||||
methods = []
|
||||
if shutil.which('python') or shutil.which('python3') or shutil.which('python2'):
|
||||
methods.append('using_python')
|
||||
if is_macos:
|
||||
methods += ['using_id']
|
||||
else:
|
||||
if shutil.which('getent'):
|
||||
methods.append('using_getent')
|
||||
if os.access('/etc/passwd', os.R_OK):
|
||||
methods.append('using_passwd')
|
||||
self.assertTrue(methods)
|
||||
import pwd
|
||||
|
||||
try:
|
||||
expected_login_shell = pwd.getpwuid(os.geteuid()).pw_shell
|
||||
except KeyError:
|
||||
self.skipTest('Skipping login shell detection as getpwuid() failed to read login shell')
|
||||
if os.path.basename(expected_login_shell) == 'nologin':
|
||||
self.skipTest('Skipping login shell detection as login shell is set to nologin')
|
||||
for m in methods:
|
||||
for sh in self.all_possible_sh:
|
||||
if 'python' in sh:
|
||||
continue
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
pty = self.check_bootstrap(sh, tdir, test_script=f'{m}; echo "$login_shell"; exit 0', SHELL_INTEGRATION_VALUE='')
|
||||
self.assertIn(expected_login_shell, pty.screen_contents())
|
||||
|
||||
def test_ssh_login_shell_fallback_quoting(self):
|
||||
bootstrap_utils = os.path.join(kitty_base_dir, 'shell-integration', 'ssh', 'bootstrap-utils.sh')
|
||||
python = shutil.which('python3') or shutil.which('python2') or shutil.which('python')
|
||||
if python is None:
|
||||
self.skipTest('Python executable not found')
|
||||
runners = [('execute_with_python', python, 'PYTHON_FOR_TEST')]
|
||||
if perl := shutil.which('perl'):
|
||||
runners.append(('execute_with_perl', perl, 'PERL_FOR_TEST'))
|
||||
script = """\
|
||||
. "$BOOTSTRAP_UTILS"
|
||||
detect_python() { python="$PYTHON_FOR_TEST"; return 0; }
|
||||
detect_perl() { perl="$PERL_FOR_TEST"; return 0; }
|
||||
login_shell=$LOGIN_SHELL
|
||||
shell_name=$(command basename "$login_shell")
|
||||
"$EXEC_FUNC"
|
||||
"""
|
||||
for func, executable, env_key in runners:
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
login_shell = os.path.join(tdir, "login shell's python")
|
||||
os.symlink(python, login_shell)
|
||||
env = {
|
||||
'PATH': os.environ.get('PATH', '/usr/bin:/bin'),
|
||||
'BOOTSTRAP_UTILS': bootstrap_utils,
|
||||
'EXEC_FUNC': func,
|
||||
'LOGIN_SHELL': login_shell,
|
||||
env_key: executable,
|
||||
}
|
||||
cp = subprocess.run(['sh', '-c', script], env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True)
|
||||
self.assertEqual(cp.returncode, 0, cp.stderr + cp.stdout)
|
||||
|
||||
@retry_on_failure()
|
||||
def test_ssh_shell_integration(self):
|
||||
available_login_shells = {'fish', 'zsh', 'bash'} & set(self.all_possible_sh)
|
||||
# Use one POSIX-shell bootstrap and one Python bootstrap as representatives.
|
||||
# Exhaustive bootstrap-shell compatibility is covered by
|
||||
# test_ssh_bootstrap_with_different_launchers; here we only need to verify
|
||||
# that both bootstrap code paths (sh and python) correctly deliver the
|
||||
# shell-integration files.
|
||||
sh_type = next((s for s in self.all_possible_sh if 'python' not in s), None)
|
||||
py_type = next((s for s in self.all_possible_sh if 'python' in s), None)
|
||||
test_interps = [s for s in (sh_type, py_type) if s is not None]
|
||||
|
||||
for sh in test_interps:
|
||||
for login_shell in available_login_shells:
|
||||
if login_shell == 'bash' and not bash_ok():
|
||||
continue
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
pty = self.check_bootstrap(sh, tdir, login_shell)
|
||||
if login_shell == 'bash':
|
||||
pty.send_cmd_to_child('echo $HISTFILE')
|
||||
pty.wait_till(lambda: '/.bash_history' in pty.screen_contents())
|
||||
elif login_shell == 'zsh':
|
||||
pty.send_cmd_to_child('echo "login_shell=$ZSH_NAME"')
|
||||
pty.wait_till(lambda: 'login_shell=zsh' in pty.screen_contents())
|
||||
self.assertIn(b'\x1b]133;', pty.received_bytes)
|
||||
|
||||
# Check that turning off shell integration works. Disabled integration is
|
||||
# a login-shell concern, so one representative bootstrap shell is enough;
|
||||
# we test all available bash/zsh login shells to cover both integrations.
|
||||
disabled_login_shells = available_login_shells & {'bash', 'zsh'}
|
||||
if disabled_login_shells and sh_type is not None:
|
||||
for val in ('', 'no-rc', 'enabled no-rc'):
|
||||
for login_shell in disabled_login_shells:
|
||||
if login_shell == 'bash' and not bash_ok():
|
||||
continue
|
||||
with tempfile.TemporaryDirectory() as tdir:
|
||||
pty = self.check_bootstrap(sh_type, tdir, login_shell, val)
|
||||
num_lines = len(pty.screen_contents().splitlines())
|
||||
pty.send_cmd_to_child('echo "$TERM=fruity"')
|
||||
pty.wait_till(lambda: 'kitty=fruity' in pty.screen_contents(), timeout=30)
|
||||
pty.wait_till(lambda: len(pty.screen_contents().splitlines()) >= num_lines + 2)
|
||||
self.assertEqual(pty.screen.cursor.shape, 0)
|
||||
self.assertNotIn(b'\x1b]133;', pty.received_bytes)
|
||||
|
||||
def check_bootstrap(self, sh, home_dir, login_shell='', SHELL_INTEGRATION_VALUE='enabled', test_script='', pre_data='', conf='', launcher='sh', home=''):
|
||||
if login_shell:
|
||||
conf += f'\nlogin_shell {login_shell}'
|
||||
if 'python' in sh:
|
||||
if test_script.startswith('env;'):
|
||||
test_script = f'os.execlp("sh", "sh", "-c", {test_script!r})'
|
||||
test_script = f'print("UNTAR_DONE", flush=True); {test_script}'
|
||||
else:
|
||||
test_script = f'echo "UNTAR_DONE"; {test_script}'
|
||||
conf += '\nshell_integration ' + (SHELL_INTEGRATION_VALUE or 'disabled')
|
||||
conf += '\ninterpreter ' + sh
|
||||
env = os.environ.copy()
|
||||
if home:
|
||||
env['HOME'] = home
|
||||
cp = subprocess.run([kitten_exe(), '__pytest__', 'ssh', test_script], env=env, stdout=subprocess.PIPE, input=conf.encode('utf-8'))
|
||||
self.assertEqual(cp.returncode, 0)
|
||||
self.rdata = json.loads(cp.stdout)
|
||||
del cp
|
||||
try:
|
||||
env = basic_shell_env(home_dir)
|
||||
# Avoid generating unneeded completion scripts
|
||||
os.makedirs(os.path.join(home_dir, '.local', 'share', 'fish', 'generated_completions'), exist_ok=True)
|
||||
# prevent newuser-install from running
|
||||
open(os.path.join(home_dir, '.zshrc'), 'w').close()
|
||||
pty = self.create_pty([launcher, '-c', ' '.join(self.rdata['cmd'])], cwd=home_dir, env=env)
|
||||
pty.turn_off_echo()
|
||||
if pre_data:
|
||||
pty.write_buf = pre_data.encode('utf-8')
|
||||
|
||||
def check_untar_or_fail():
|
||||
q = pty.screen_contents()
|
||||
return 'UNTAR_DONE' in q
|
||||
|
||||
pty.wait_till(check_untar_or_fail, timeout=60)
|
||||
self.assertTrue(os.path.exists(os.path.join(home_dir, '.terminfo/kitty.terminfo')))
|
||||
if SHELL_INTEGRATION_VALUE != 'enabled':
|
||||
pty.wait_till(lambda: len(pty.screen_contents().splitlines()) > 1, timeout=60)
|
||||
self.assertEqual(pty.screen.cursor.shape, 0)
|
||||
else:
|
||||
pty.wait_till(lambda: pty.screen.cursor.shape == CURSOR_BEAM, timeout=60)
|
||||
return pty
|
||||
finally:
|
||||
with suppress(FileNotFoundError):
|
||||
shm_unlink(self.rdata['shm_name'])
|
||||
@@ -0,0 +1,693 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from kitty.fast_data_types import LEFT_EDGE, Color, Region, Screen
|
||||
from kitty.options.utils import tab_title_wrap
|
||||
from kitty.tab_bar import CellRange, DrawData, ExtraData, TabBar, TabBarData, TabExtent, WindowDropTarget, as_rgb, powerline_symbols, truncate_line, wrap_title
|
||||
from kitty.utils import color_as_int
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
def region(left: int, top: int, right: int, bottom: int) -> Region:
|
||||
return Region((left, top, right, bottom, right - left, bottom - top))
|
||||
|
||||
|
||||
class DummyBoss:
|
||||
class mappings:
|
||||
current_keyboard_mode_name = ''
|
||||
|
||||
def tab_for_id(self, tab_id: int) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class TestTabBar(BaseTest):
|
||||
def test_tab_insertion_uses_nearest_boundary(self):
|
||||
tb = self.vertical_tab_bar()
|
||||
for vertical in (False, True):
|
||||
tb.is_vertical = vertical
|
||||
tb.screen.resize(50, 100)
|
||||
tb.cell_width, tb.cell_height = 10, 20
|
||||
tb.tab_extents = tuple(
|
||||
TabExtent(tid, CellRange(start, end), CellRange(start, end)) for tid, start, end in ((1, 2, 11), (2, 14, 23), (3, 26, 35), (-1, 38, 40))
|
||||
)
|
||||
cell_size = tb.cell_height if vertical else tb.cell_width
|
||||
for coordinate, before in ((0, 1), (6.99, 1), (7, 2), (13, 2), (18.99, 2), (19, 3), (31, 0), (40, 0)):
|
||||
pos = int(coordinate * cell_size)
|
||||
x, y = (5, pos) if vertical else (pos, 5)
|
||||
self.ae(tb.tab_insertion_target_at(x, y), before, (vertical, coordinate))
|
||||
|
||||
def test_vertical_insertion_marker_keeps_titles_visible(self):
|
||||
def marked(num_tabs: int, attr: str, before: int) -> tuple[list[str], list[str]]:
|
||||
tb = self.vertical_tab_bar(num_tabs)
|
||||
data, extents, original = tb.last_laid_out_tabs, tb.tab_extents, self.screen_lines(tb)
|
||||
with patch('kitty.tab_bar.update_tab_bar_edge_colors', return_value=None), patch('kitty.tab_bar.get_boss', return_value=DummyBoss()):
|
||||
setattr(tb, attr, before)
|
||||
tb.update(data)
|
||||
self.ae(tb.last_laid_out_tabs, data)
|
||||
self.ae(tb.tab_extents, extents)
|
||||
lines = self.screen_lines(tb)
|
||||
setattr(tb, attr, None)
|
||||
tb.update(data)
|
||||
self.ae(self.screen_lines(tb), original)
|
||||
return original, lines
|
||||
|
||||
line = '━' * 12
|
||||
for attr in ('tab_drop_insert_before', 'window_drop_insert_before'):
|
||||
# The marker uses the blank line between tabs, or after the last tab
|
||||
original, lines = marked(2, attr, 2)
|
||||
self.ae(original[:4], ['t0', '', 't1', ''])
|
||||
self.ae(lines[:4], ['t0', line, 't1', ''])
|
||||
self.ae(marked(2, attr, 0)[1][:4], ['t0', '', 't1', line])
|
||||
# Without a blank line before the first tab only its first cell is used
|
||||
self.ae(marked(2, attr, 1)[1][:3], ['▶0', '', 't1'])
|
||||
# Crowded tab bars have no blank lines between tabs
|
||||
original, lines = marked(8, attr, 3)
|
||||
self.ae(original[:4], ['t0', 't1', 't2', 't3'])
|
||||
self.ae(lines[:4], ['t0', 't1', '▶2', 't3'])
|
||||
|
||||
def test_window_drop_tab_edges_and_gaps(self):
|
||||
tb = self.vertical_tab_bar()
|
||||
for vertical in (False, True):
|
||||
with self.subTest(vertical=vertical):
|
||||
tb.is_vertical = vertical
|
||||
tb.screen.resize(50, 100)
|
||||
tb.cell_width, tb.cell_height = 10, 20
|
||||
tb.tab_extents = tuple(
|
||||
TabExtent(tid, CellRange(start, end), CellRange(start, end)) for tid, start, end in ((1, 2, 11), (2, 14, 23), (-1, 26, 28))
|
||||
)
|
||||
cell_size = tb.cell_height if vertical else tb.cell_width
|
||||
for coordinate, target in (
|
||||
(0, WindowDropTarget(before_tab_id=1)),
|
||||
(2.99, WindowDropTarget(before_tab_id=1)),
|
||||
(3, WindowDropTarget(tab_id=1)),
|
||||
(10.99, WindowDropTarget(tab_id=1)),
|
||||
(11, WindowDropTarget(before_tab_id=2)),
|
||||
(13, WindowDropTarget(before_tab_id=2)),
|
||||
(14.99, WindowDropTarget(before_tab_id=2)),
|
||||
(15, WindowDropTarget(tab_id=2)),
|
||||
(23, WindowDropTarget(before_tab_id=0)),
|
||||
(27, WindowDropTarget(before_tab_id=0)),
|
||||
(40, WindowDropTarget(before_tab_id=0)),
|
||||
):
|
||||
pos = int(coordinate * cell_size)
|
||||
x, y = (tb.window_geometry.left + 5, tb.window_geometry.top + pos) if vertical else (pos, 5)
|
||||
self.ae(tb.window_drop_target_at(x, y), target, (vertical, coordinate))
|
||||
|
||||
def test_window_drop_custom_full_width_tabs(self):
|
||||
tb = self.vertical_tab_bar()
|
||||
tb.is_vertical = False
|
||||
tb.screen.resize(1, 100)
|
||||
tb.cell_width = 10
|
||||
# A full-width custom renderer returns the cell after each tab, including the
|
||||
# first cell of its neighbor. The synthetic '+' is entirely off screen.
|
||||
tb.tab_extents = tuple(TabExtent(tid, CellRange(start, end)) for tid, start, end in ((1, 0, 50), (2, 50, 100), (-1, 100, 150)))
|
||||
for x, target in (
|
||||
(49, WindowDropTarget(before_tab_id=1)),
|
||||
(50, WindowDropTarget(tab_id=1)),
|
||||
(449, WindowDropTarget(tab_id=1)),
|
||||
(450, WindowDropTarget(before_tab_id=2)),
|
||||
(549, WindowDropTarget(before_tab_id=2)),
|
||||
(550, WindowDropTarget(tab_id=2)),
|
||||
(949, WindowDropTarget(tab_id=2)),
|
||||
(950, WindowDropTarget(before_tab_id=0)),
|
||||
(999, WindowDropTarget(before_tab_id=0)),
|
||||
):
|
||||
self.ae(tb.window_drop_target_at(x, 5), target, x)
|
||||
tb.window_drop_insert_before = 0
|
||||
tb.draw_drop_insert_marker()
|
||||
self.ae(str(tb.screen.line(0))[-1], '┃')
|
||||
|
||||
def test_vertical_tab_bar_hit_testing(self) -> None:
|
||||
self.set_options(
|
||||
{
|
||||
'tab_bar_edge': LEFT_EDGE,
|
||||
'tab_bar_style': 'separator',
|
||||
'tab_title_template': '{title}',
|
||||
}
|
||||
)
|
||||
central = region(120, 0, 400, 160)
|
||||
tab_bar = region(0, 0, 120, 160)
|
||||
geometries: list[tuple[int, int, int, int]] = []
|
||||
boss = DummyBoss()
|
||||
|
||||
with (
|
||||
patch('kitty.tab_bar.cell_size_for_window', return_value=(10, 20)),
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, 400, 160, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data', side_effect=lambda *args: geometries.append(args[2:6])),
|
||||
patch('kitty.tab_bar.get_boss', return_value=boss),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update(
|
||||
(
|
||||
TabBarData(title='one', tab_id=1, is_active=True),
|
||||
TabBarData(title='two', tab_id=2),
|
||||
TabBarData(title='three', tab_id=3),
|
||||
)
|
||||
)
|
||||
|
||||
self.assertTrue(tb.is_vertical)
|
||||
self.ae(geometries[-1], (0, 0, 120, 160))
|
||||
self.ae(tb.drag_axis_coordinate(5, 35), 35)
|
||||
# single line titles occupy one line each, separated by a blank line
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 0), CellRange(2, 2), CellRange(4, 4)))
|
||||
self.ae(tb.tab_id_at(5, 10), 1)
|
||||
self.ae(tb.tab_id_at(110, 10), 1)
|
||||
self.ae(tb.tab_id_at(60, 50), 2)
|
||||
self.ae(tb.tab_id_at(60, 90), 3)
|
||||
self.ae(tb.tab_id_at(60, 130), 0)
|
||||
self.ae(tb.tab_id_at(180, 10), 0)
|
||||
|
||||
def test_vertical_tab_bar_alignment(self) -> None:
|
||||
self.set_options(
|
||||
{
|
||||
'tab_bar_align': 'end',
|
||||
'tab_bar_edge': LEFT_EDGE,
|
||||
'tab_bar_style': 'separator',
|
||||
'tab_title_template': '{title}',
|
||||
}
|
||||
)
|
||||
central = region(120, 0, 400, 160)
|
||||
tab_bar = region(0, 0, 120, 160)
|
||||
boss = DummyBoss()
|
||||
|
||||
with (
|
||||
patch('kitty.tab_bar.cell_size_for_window', return_value=(10, 20)),
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, 400, 160, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.get_boss', return_value=boss),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update(
|
||||
(
|
||||
TabBarData(title='one', tab_id=1, is_active=True),
|
||||
TabBarData(title='two', tab_id=2),
|
||||
)
|
||||
)
|
||||
|
||||
# 8 lines available, two single line tabs plus a gap, aligned to the end
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(5, 5), CellRange(7, 7)))
|
||||
self.ae(tb.tab_id_at(5, 10), 0)
|
||||
self.ae(tb.tab_id_at(5, 110), 1)
|
||||
self.ae(tb.tab_id_at(5, 150), 2)
|
||||
|
||||
def vertical_tab_bar(self, num_tabs: int = 2, height: int = 160, width: int = 120, **opts: object) -> TabBar:
|
||||
self.set_options(
|
||||
{
|
||||
'tab_bar_edge': LEFT_EDGE,
|
||||
'tab_bar_style': 'separator',
|
||||
'tab_title_template': '{title}',
|
||||
**opts,
|
||||
}
|
||||
)
|
||||
central = region(width, 0, 400, height)
|
||||
tab_bar = region(0, 0, width, height)
|
||||
with (
|
||||
patch('kitty.tab_bar.cell_size_for_window', return_value=(10, 20)),
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, 400, height, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update(tuple(TabBarData(title=f't{i}', tab_id=i + 1, is_active=i == 0) for i in range(num_tabs)))
|
||||
return tb
|
||||
|
||||
def screen_lines(self, tb: TabBar) -> list[str]:
|
||||
s = tb.screen
|
||||
return [str(s.line(i)).rstrip() for i in range(s.lines)]
|
||||
|
||||
def test_vertical_tab_bar_narrow_powerline(self) -> None:
|
||||
# A short title fits in a narrow vertical tab bar, since the separator
|
||||
# is drawn in a column of its own
|
||||
sep = powerline_symbols['round'][0]
|
||||
tb = self.vertical_tab_bar(width=40, tab_bar_style='powerline', tab_powerline_style='round', tab_title_template='{index}', tab_title_max_length=1)
|
||||
self.ae(tb.screen.columns, 4)
|
||||
self.ae(self.screen_lines(tb)[:3], [f' 1 {sep}', '', f' 2 {sep}'])
|
||||
|
||||
def test_vertical_tab_bar_multiline_titles(self) -> None:
|
||||
# newlines are ignored unless tab_title_max_lines allows them, and the
|
||||
# dropped lines are marked with an ellipsis
|
||||
tb = self.vertical_tab_bar(tab_title_template='{title}\\nbr')
|
||||
self.ae(self.screen_lines(tb)[:4], ['t0…', '', 't1…', ''])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 0), CellRange(2, 2)))
|
||||
|
||||
# a newline now starts a new line at column zero, without staircasing,
|
||||
# and each tab occupies the two lines its title needs
|
||||
tb = self.vertical_tab_bar(tab_title_template='{title}\\nbr', tab_title_max_lines=2)
|
||||
self.ae(self.screen_lines(tb)[:6], ['t0', 'br', '', 't1', 'br', ''])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 1), CellRange(3, 4)))
|
||||
|
||||
# lines beyond the limit are dropped rather than bleeding into the next tab
|
||||
tb = self.vertical_tab_bar(tab_title_template='{title}\\nbr\\nextra', tab_title_max_lines=2)
|
||||
self.ae(self.screen_lines(tb)[:6], ['t0', 'br…', '', 't1', 'br…', ''])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 1), CellRange(3, 4)))
|
||||
|
||||
def test_vertical_tab_bar_mixed_title_heights(self) -> None:
|
||||
# a tab whose title has no newline stays one line tall even when the
|
||||
# limit is higher, so tabs pack according to what they actually use
|
||||
self.set_options(
|
||||
{
|
||||
'tab_bar_edge': LEFT_EDGE,
|
||||
'tab_bar_style': 'separator',
|
||||
'tab_title_template': '{title}',
|
||||
'tab_title_max_lines': 3,
|
||||
}
|
||||
)
|
||||
central = region(120, 0, 400, 160)
|
||||
tab_bar = region(0, 0, 120, 160)
|
||||
with (
|
||||
patch('kitty.tab_bar.cell_size_for_window', return_value=(10, 20)),
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, 400, 160, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update(
|
||||
(
|
||||
TabBarData(title='one\ntwo', tab_id=1, is_active=True),
|
||||
TabBarData(title='solo', tab_id=2),
|
||||
TabBarData(title='a\nb\nc', tab_id=3),
|
||||
)
|
||||
)
|
||||
self.ae(self.screen_lines(tb)[:8], ['one', 'two', '', 'solo', '', 'a', 'b', 'c'])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 1), CellRange(3, 3), CellRange(5, 7)))
|
||||
self.ae(tb.tab_id_at(5, 10), 1)
|
||||
self.ae(tb.tab_id_at(5, 30), 1)
|
||||
self.ae(tb.tab_id_at(5, 70), 2)
|
||||
self.ae(tb.tab_id_at(5, 110), 3)
|
||||
self.ae(tb.tab_id_at(5, 150), 3)
|
||||
|
||||
def test_vertical_tab_bar_tab_spacing(self) -> None:
|
||||
# a blank line is left between tabs while there is room for it, but not
|
||||
# above the first tab, and the gaps are not part of any tab's extent so
|
||||
# clicking one activates nothing
|
||||
tb = self.vertical_tab_bar(num_tabs=3)
|
||||
self.ae(self.screen_lines(tb)[:6], ['t0', '', 't1', '', 't2', ''])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 0), CellRange(2, 2), CellRange(4, 4)))
|
||||
self.ae(tb.tab_id_at(5, 10), 1)
|
||||
self.ae(tb.tab_id_at(5, 30), 0)
|
||||
self.ae(tb.tab_id_at(5, 50), 2)
|
||||
|
||||
# the gap uses the tab bar background, not the neighbouring tab's
|
||||
self.ae(int(tb.screen.line(1).cursor_from(0).bg), 0)
|
||||
|
||||
# spacing applies between multi-line tabs too
|
||||
tb = self.vertical_tab_bar(num_tabs=2, tab_title_max_lines=2, tab_title_template='{title}\\nbr')
|
||||
self.ae(self.screen_lines(tb)[:6], ['t0', 'br', '', 't1', 'br', ''])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 1), CellRange(3, 4)))
|
||||
|
||||
def test_vertical_tab_bar_tab_spacing_dropped_when_crowded(self) -> None:
|
||||
# once the tabs need the space the blank lines go away automatically,
|
||||
# rather than tabs being dropped in favour of keeping the gaps
|
||||
tb = self.vertical_tab_bar(num_tabs=8, height=160)
|
||||
self.ae(self.screen_lines(tb), [f't{i}' for i in range(8)])
|
||||
self.ae(len(tb.tab_extents), 8)
|
||||
|
||||
# exactly enough room for spacing: 4 tabs need 4 + 3 gaps == 7 lines
|
||||
tb = self.vertical_tab_bar(num_tabs=4, height=140)
|
||||
self.ae(self.screen_lines(tb), ['t0', '', 't1', '', 't2', '', 't3'])
|
||||
self.ae(len(tb.tab_extents), 4)
|
||||
|
||||
def test_vertical_tab_bar_fills_tab_width(self) -> None:
|
||||
# every line a tab occupies must be padded to the full width of the bar
|
||||
# in that tab's colors, otherwise uneven line lengths leave a ragged edge
|
||||
tb = self.vertical_tab_bar(tab_title_template='{title}\\nlonger-line', tab_title_max_lines=2)
|
||||
s = tb.screen
|
||||
self.ae([len(str(s.line(i))) for i in (0, 1, 3, 4)], [s.columns] * 4)
|
||||
|
||||
def bg_of(line: int, col: int) -> int:
|
||||
return int(s.line(line).cursor_from(col).bg)
|
||||
|
||||
# the padding after a short line uses the tab background, not the bar's
|
||||
for line in (0, 1):
|
||||
self.ae(bg_of(line, s.columns - 1), bg_of(line, 0))
|
||||
# and the two tabs still have distinct backgrounds
|
||||
self.assertNotEqual(bg_of(0, 0), bg_of(3, 0))
|
||||
|
||||
def test_vertical_tab_bar_title_taller_than_bar(self) -> None:
|
||||
# a title needing more lines than the bar has must be clipped from the
|
||||
# bottom rather than scrolling the tab bar and losing its first lines
|
||||
tb = self.vertical_tab_bar(num_tabs=1, height=60, tab_title_template='{title}\\na\\nb\\nc\\nd', tab_title_max_lines=5)
|
||||
self.ae(self.screen_lines(tb), ['t0', 'a', 'b…'])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 2),))
|
||||
|
||||
def test_vertical_tab_bar_multiline_overflow(self) -> None:
|
||||
# only 4 lines fit, so two 2-line tabs are drawn and the rest are
|
||||
# replaced by an ellipsis on the last line
|
||||
tb = self.vertical_tab_bar(num_tabs=6, height=100, tab_title_template='{title}\\nbr', tab_title_max_lines=2)
|
||||
self.ae(self.screen_lines(tb), ['t0', 'br', 't1', 'br', '…'])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 1), CellRange(2, 3)))
|
||||
|
||||
def test_wrap_title(self) -> None:
|
||||
self.ae(wrap_title('hello world foo', 6).split('\n'), ['hello ', 'world ', 'foo'])
|
||||
# a word longer than the width has to be broken mid-word
|
||||
self.ae(wrap_title('unbreakable', 4).split('\n'), ['unbr', 'eaka', 'ble'])
|
||||
# explicit newlines are preserved and each line wrapped independently
|
||||
self.ae(wrap_title('a\nbb ccc', 4).split('\n'), ['a', 'bb c', 'cc'])
|
||||
# SGR escapes are zero width, so they do not count towards the width and
|
||||
# are never split in half
|
||||
self.ae(wrap_title('\x1b[31mred text', 4).split('\n'), ['\x1b[31mred ', 'text'])
|
||||
# wide characters take two cells each
|
||||
self.ae(wrap_title('日本語', 4).split('\n'), ['日本', '語'])
|
||||
# a width of zero means no wrapping
|
||||
self.ae(wrap_title('abc', 0), 'abc')
|
||||
# fast path: a part that fits entirely is taken without grapheme splitting
|
||||
self.ae(wrap_title('abc def', 10).split('\n'), ['abc def'])
|
||||
# fast path: part fits exactly at the boundary
|
||||
self.ae(wrap_title('abcd', 4).split('\n'), ['abcd'])
|
||||
# fast path breaks down correctly when the second part overflows
|
||||
self.ae(wrap_title('abc defgh', 6).split('\n'), ['abc de', 'fgh'])
|
||||
# SGR escape followed by text that fits entirely (fast path with leading escape)
|
||||
self.ae(wrap_title('\x1b[1mhello', 10).split('\n'), ['\x1b[1mhello'])
|
||||
# mixed: first part fits (fast path), second part must be split
|
||||
self.ae(wrap_title('\x1b[1mab\x1b[0m cdefgh', 4).split('\n'), ['\x1b[1mab\x1b[0m c', 'defg', 'h'])
|
||||
# wide chars: part fits entirely (fast path)
|
||||
self.ae(wrap_title('日本', 4).split('\n'), ['日本'])
|
||||
# wide chars: part fits on new line after breaking
|
||||
self.ae(wrap_title('ab日本語', 4).split('\n'), ['ab日', '本語'])
|
||||
|
||||
def test_truncate_line(self) -> None:
|
||||
self.ae(truncate_line('abcdef', 4), 'abc…')
|
||||
self.ae(truncate_line('日本語', 4), '日…')
|
||||
# the ellipsis marks dropped content, so it is added even when the text
|
||||
# itself would have fit
|
||||
self.ae(truncate_line('ab', 4), 'ab…')
|
||||
self.ae(truncate_line('abcd', 4), 'abc…')
|
||||
# fast path: entire part fits within width-1 cells, ellipsis appended
|
||||
self.ae(truncate_line('abc', 6), 'abc…')
|
||||
# fast path: part exactly fills width-1 cells
|
||||
self.ae(truncate_line('abcde', 6), 'abcde…')
|
||||
# fast path taken for first part, overflow detected in second part
|
||||
self.ae(truncate_line('abc' + 'xyz', 5), 'abcx…')
|
||||
# SGR escapes are zero width, so they never consume cells (fast path still taken)
|
||||
self.ae(truncate_line('\x1b[1mabc\x1b[0m', 6), '\x1b[1mabc\x1b[0m…')
|
||||
# wide chars: fast path fits, ellipsis appended
|
||||
self.ae(truncate_line('日本', 6), '日本…')
|
||||
# empty line still gets ellipsis
|
||||
self.ae(truncate_line('', 4), '…')
|
||||
|
||||
def test_tab_title_wrap_option(self) -> None:
|
||||
for off in ('no', 'No', 'n', 'false', 'none', '0'):
|
||||
self.ae(tab_title_wrap(off), 0)
|
||||
for on in ('yes', 'y', 'true', 'YES'):
|
||||
self.ae(tab_title_wrap(on), -1)
|
||||
self.ae(tab_title_wrap('20'), 20)
|
||||
|
||||
def test_vertical_tab_bar_wrapping(self) -> None:
|
||||
# set_options bypasses the config parser, so these take parsed values:
|
||||
# -1 is 'yes' (wrap at the width of the tab bar), a positive int a width
|
||||
long_title = 'feature/some-really-long-branch'
|
||||
|
||||
def tb_with(**opts: object) -> list[str]:
|
||||
self.set_options(
|
||||
{
|
||||
'tab_bar_edge': LEFT_EDGE,
|
||||
'tab_bar_style': 'separator',
|
||||
'tab_title_template': '{title}',
|
||||
**opts,
|
||||
}
|
||||
)
|
||||
central, tab_bar = region(140, 0, 740, 240), region(0, 0, 140, 240)
|
||||
with (
|
||||
patch('kitty.tab_bar.cell_size_for_window', return_value=(10, 20)),
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, 740, 240, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update((TabBarData(title=long_title, tab_id=1, is_active=True),))
|
||||
return [line for line in self.screen_lines(tb) if line]
|
||||
|
||||
# off by default: the title is truncated onto a single line as before.
|
||||
# The trailing text is the tail the separator style draws past the
|
||||
# ellipsis, which predates wrapping.
|
||||
self.ae(tb_with(tab_title_max_lines=3), ['feature/som… h'])
|
||||
# 'yes' wraps at the width of the tab bar
|
||||
self.ae(tb_with(tab_title_max_lines=3, tab_title_wrap=-1), ['feature/some-', 'really-long-b', 'ranch'])
|
||||
# a number wraps at that many cells
|
||||
self.ae(tb_with(tab_title_max_lines=3, tab_title_wrap=8), ['feature/', 'some-rea', 'lly-lon…'])
|
||||
# wrapping needs more than one line to have any effect
|
||||
self.ae(tb_with(tab_title_max_lines=1, tab_title_wrap=-1), ['feature/som… h'])
|
||||
# when wrapping needs more lines than allowed, the last one is truncated
|
||||
self.ae(tb_with(tab_title_max_lines=2, tab_title_wrap=-1), ['feature/some-', 'really-long…'])
|
||||
# a wrap width wider than the bar is clamped to the bar, so the result
|
||||
# matches wrapping at the bar's width
|
||||
self.ae(tb_with(tab_title_max_lines=3, tab_title_wrap=99), ['feature/some-', 'really-long-b', 'ranch'])
|
||||
|
||||
def test_vertical_tab_bar_wrapping_with_newlines(self) -> None:
|
||||
# an explicit newline still breaks the line, and each resulting line is
|
||||
# wrapped independently
|
||||
tb = self.vertical_tab_bar(num_tabs=1, height=200, tab_title_max_lines=4, tab_title_wrap=-1, tab_title_template='a-really-long-first\\nshort')
|
||||
self.ae([line for line in self.screen_lines(tb) if line], ['a-really-lo', 'ng-first', 'short'])
|
||||
|
||||
def test_vertical_tab_bar_wrapping_overflow(self) -> None:
|
||||
# wrapped tabs are packed by the lines they use, and once they stop
|
||||
# fitting the remainder is replaced by the overflow ellipsis
|
||||
long_title = 'feature/really-long-branch-name'
|
||||
self.set_options(
|
||||
{
|
||||
'tab_bar_edge': LEFT_EDGE,
|
||||
'tab_bar_style': 'separator',
|
||||
'tab_title_template': '{title}',
|
||||
'tab_title_max_lines': 2,
|
||||
'tab_title_wrap': -1,
|
||||
}
|
||||
)
|
||||
central, tab_bar = region(140, 0, 740, 100), region(0, 0, 140, 100)
|
||||
with (
|
||||
patch('kitty.tab_bar.cell_size_for_window', return_value=(10, 20)),
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, 740, 100, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update(tuple(TabBarData(title=long_title, tab_id=i + 1, is_active=i == 0) for i in range(3)))
|
||||
self.ae(self.screen_lines(tb), ['feature/reall', 'y-long-bran…', 'feature/reall', 'y-long-bran…', '…'])
|
||||
self.ae(tuple(te.y for te in tb.tab_extents), (CellRange(0, 1), CellRange(2, 3)))
|
||||
|
||||
def test_vertical_tab_bar_fade_style(self) -> None:
|
||||
# Use fixed colors so every fade cell blends to the same midpoint
|
||||
# colour, making fade cells easy to identify by background.
|
||||
self.set_options(
|
||||
{
|
||||
'tab_bar_edge': LEFT_EDGE,
|
||||
'tab_bar_style': 'fade',
|
||||
'tab_title_template': '{title}',
|
||||
'active_tab_background': Color(200, 0, 0),
|
||||
'tab_bar_background': Color(0, 0, 100),
|
||||
'tab_fade': (0.5, 0.5, 0.5, 0.5),
|
||||
}
|
||||
)
|
||||
central = region(120, 0, 400, 160)
|
||||
tab_bar_r = region(0, 0, 120, 160)
|
||||
with (
|
||||
patch('kitty.tab_bar.cell_size_for_window', return_value=(10, 20)),
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar_r, 400, 160, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update((TabBarData(title='t0', tab_id=1, is_active=True),))
|
||||
|
||||
s = tb.screen
|
||||
# Screen: 12 columns (120px / 10px), max_tab_length = 11, 4 fade cells.
|
||||
# Title 't0' begins at col 4 (after 4 leading fades) and ends at col 6.
|
||||
# Trailing fades should occupy cols 8–11 (flush with the right edge).
|
||||
|
||||
def bg(col: int) -> int:
|
||||
return int(s.line(0).cursor_from(col).bg)
|
||||
|
||||
tab_bg = bg(4) # title cell: active_tab_background
|
||||
fade_bg = bg(0) # leading fade cell: midpoint blend
|
||||
|
||||
# Sanity: fade colour is distinct from plain tab colour.
|
||||
self.assertNotEqual(tab_bg, fade_bg)
|
||||
|
||||
# Issue 1: trailing fades flush with the right edge (cols 8–11), not right after the text.
|
||||
self.ae(bg(6), tab_bg) # col 6, right after 't0', must be plain tab bg
|
||||
self.ae(bg(8), fade_bg) # col 8, fade_start = 12 - 4, must be a fade cell
|
||||
|
||||
# Issue 2: no background-coloured separator after the trailing fades.
|
||||
self.ae(bg(11), fade_bg) # col 11, last trailing fade, must not be default_bg
|
||||
|
||||
def test_vertical_tab_bar_powerline_style(self) -> None:
|
||||
tb = self.vertical_tab_bar(
|
||||
num_tabs=3,
|
||||
tab_bar_style='powerline',
|
||||
tab_powerline_style='slanted',
|
||||
active_tab_background=Color(200, 0, 0),
|
||||
inactive_tab_background=Color(0, 200, 0),
|
||||
tab_bar_background=Color(0, 0, 100),
|
||||
)
|
||||
s = tb.screen
|
||||
separator, soft_separator = powerline_symbols['slanted']
|
||||
active_bg = as_rgb(color_as_int(Color(200, 0, 0)))
|
||||
inactive_bg = as_rgb(color_as_int(Color(0, 200, 0)))
|
||||
tab_bar_bg = as_rgb(color_as_int(Color(0, 0, 100)))
|
||||
for row, tab_bg in ((0, active_bg), (2, inactive_bg), (4, inactive_bg)):
|
||||
line = s.line(row)
|
||||
text = str(line)
|
||||
self.assertNotIn(soft_separator, text)
|
||||
self.ae(text.index(separator), s.columns - 1)
|
||||
self.ae(int(line.cursor_from(3).bg), tab_bg)
|
||||
sep = line.cursor_from(s.columns - 1)
|
||||
self.ae((int(sep.fg), int(sep.bg)), (tab_bg, tab_bar_bg))
|
||||
|
||||
tb = self.vertical_tab_bar(num_tabs=1, tab_bar_style='powerline', tab_powerline_style='slanted', tab_title_template='{title}-a-long-title')
|
||||
self.ae(str(tb.screen.line(0)), f' t0-a-lon… {separator}')
|
||||
|
||||
tb = self.vertical_tab_bar(num_tabs=1, tab_bar_style='powerline', tab_powerline_style='slanted', tab_title_template='abcdef', tab_title_max_length=3)
|
||||
self.ae(str(tb.screen.line(0)), f' ab… {separator}')
|
||||
|
||||
tb = self.vertical_tab_bar(
|
||||
num_tabs=1, tab_bar_style='powerline', tab_title_template='{fmt.fg.red}{title}{fmt.reset}', active_tab_background=Color(200, 0, 0)
|
||||
)
|
||||
line = tb.screen.line(0)
|
||||
self.ae({int(line.cursor_from(x).bg) for x in range(tb.screen.columns - 1)}, {active_bg})
|
||||
|
||||
def test_vertical_tab_bar_powerline_wrapped_titles(self) -> None:
|
||||
separator = powerline_symbols['slanted'][0]
|
||||
active_bg = as_rgb(color_as_int(Color(200, 0, 0)))
|
||||
tab_bar_bg = as_rgb(color_as_int(Color(0, 0, 100)))
|
||||
|
||||
def lines(**opts: object) -> list[str]:
|
||||
tb = self.vertical_tab_bar(
|
||||
num_tabs=1,
|
||||
height=200,
|
||||
tab_bar_style='powerline',
|
||||
tab_powerline_style='slanted',
|
||||
active_tab_background=Color(200, 0, 0),
|
||||
tab_bar_background=Color(0, 0, 100),
|
||||
**opts,
|
||||
)
|
||||
s = tb.screen
|
||||
ans = [str(s.line(i)) for i in range(s.lines)]
|
||||
# Every row of the tab has the separator in the last column, blending
|
||||
# into the tab bar background, with the tab background before it
|
||||
for y, text in enumerate(ans):
|
||||
if text:
|
||||
sep = s.line(y).cursor_from(s.columns - 1)
|
||||
self.ae((int(sep.fg), int(sep.bg)), (active_bg, tab_bar_bg))
|
||||
self.ae({int(s.line(y).cursor_from(x).bg) for x in range(s.columns - 1)}, {active_bg})
|
||||
return [x for x in ans if x]
|
||||
|
||||
# wrapped text stays clear of the last column
|
||||
self.ae(
|
||||
lines(tab_title_max_lines=3, tab_title_wrap=-1, tab_title_template='{title} abcdefgh ijklmnopq rs'),
|
||||
[f' t0 abcdefg{separator}', f'h ijklmnop {separator}', f'q rs {separator}'],
|
||||
)
|
||||
# the last kept line is truncated with an ellipsis
|
||||
self.ae(
|
||||
lines(tab_title_max_lines=2, tab_title_wrap=-1, tab_title_template='{title} abcdefgh ijklmnopq rs'),
|
||||
[f' t0 abcdefg{separator}', f'h ijklmno… {separator}'],
|
||||
)
|
||||
# an explicit wrap width narrower than the tab
|
||||
self.ae(
|
||||
lines(tab_title_max_lines=3, tab_title_wrap=4, tab_title_template='{title} abcdefgh'),
|
||||
[f' t0 a {separator}', f'bcde {separator}', f'fgh {separator}'],
|
||||
)
|
||||
# with wrapping disabled, over long lines are clipped by the separator
|
||||
self.ae(
|
||||
lines(tab_title_max_lines=3, tab_title_wrap=0, tab_title_template='{title}\\nabcdefghijklmnop\\nx'),
|
||||
[f' t0 {separator}', f'abcdefghijk{separator}', f'x {separator}'],
|
||||
)
|
||||
|
||||
def horizontal_tab_bar_line(self, titles: list[str], columns: int, **opts: object) -> str:
|
||||
self.set_options({'tab_title_template': '{title}', **opts})
|
||||
central = region(0, 0, columns * 10, 180)
|
||||
tab_bar = region(0, 180, columns * 10, 200)
|
||||
with (
|
||||
patch('kitty.tab_bar.cell_size_for_window', return_value=(10, 20)),
|
||||
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, columns * 10, 200, 10, 20)),
|
||||
patch('kitty.tab_bar.set_tab_bar_render_data'),
|
||||
patch('kitty.tab_bar.update_tab_bar_edge_colors', return_value=None),
|
||||
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
|
||||
):
|
||||
tb = TabBar(1)
|
||||
tb.layout()
|
||||
tb.update(tuple(TabBarData(title=t, tab_id=i + 1, is_active=i == 0) for i, t in enumerate(titles)))
|
||||
return str(tb.screen.line(0)).rstrip()
|
||||
|
||||
def test_horizontal_tab_bar_uses_free_space(self) -> None:
|
||||
line = self.horizontal_tab_bar_line
|
||||
# space not needed by short tabs goes to the long ones, instead of
|
||||
# being left unused at the end of the tab bar
|
||||
long_title = 'abcdefghijklmn'
|
||||
for style, columns, titles in (
|
||||
('fade', 25, ['1', long_title]),
|
||||
('fade', 35, ['1'] * 2 + [long_title]),
|
||||
('separator', 60, ['1'] * 8 + [long_title] * 2),
|
||||
('powerline', 80, ['1'] * 5 + [long_title] * 3),
|
||||
('slant', 126, ['1'] * 9 + [long_title] * 4),
|
||||
):
|
||||
text = line(titles, columns, tab_bar_style=style)
|
||||
self.ae(text.count(long_title), titles.count(long_title), (style, text))
|
||||
self.assertNotIn('…', text)
|
||||
|
||||
# tabs drawn more than one cell wider than their max length, by a wide
|
||||
# separator or the leading space of the powerline style, must still
|
||||
# fit, rather than the last one being replaced by the overflow marker
|
||||
for columns, titles, opts in (
|
||||
(10, ['x' * 10] * 3, {'tab_bar_style': 'separator', 'tab_separator': ' ||'}),
|
||||
(15, ['x' * 10, '~'], {'tab_bar_style': 'powerline'}),
|
||||
):
|
||||
text = line(titles, columns, **opts)
|
||||
self.assertFalse(text.endswith(' …'), (opts, text))
|
||||
|
||||
# no tabs
|
||||
self.ae(line([], 60, tab_bar_style='separator'), '')
|
||||
|
||||
def test_horizontal_tab_bar_custom_draw_func_margin(self) -> None:
|
||||
# a custom draw function may draw a wider overhang when given more
|
||||
# space than the default max length it is measured at, so it is left
|
||||
# some slack, rather than the last tab being replaced by the overflow marker
|
||||
def draw_tab(
|
||||
draw_data: DrawData, screen: Screen, tab: TabBarData, before: int, max_tab_length: int, index: int, is_last: bool, extra_data: ExtraData
|
||||
) -> int:
|
||||
screen.draw(tab.title[:max_tab_length])
|
||||
if len(tab.title) > max_tab_length and max_tab_length >= 8:
|
||||
screen.draw('»')
|
||||
end: int = screen.cursor.x
|
||||
if not is_last:
|
||||
screen.draw('|')
|
||||
return end
|
||||
|
||||
with patch('kitty.tab_bar.load_custom_draw_tab', return_value=draw_tab):
|
||||
for columns in (15, 16, 17):
|
||||
text = self.horizontal_tab_bar_line(['x' * 30] * 2, columns, tab_bar_style='custom')
|
||||
self.assertFalse(text.endswith(' …'), (columns, text))
|
||||
self.ae(text.count('|'), 1, text)
|
||||
|
||||
def test_tab_bar_title_cache(self) -> None:
|
||||
from contextlib import nullcontext
|
||||
|
||||
import kitty.tab_bar as tab_bar
|
||||
|
||||
titles = ['~', 'abcdefghijklmnopqrstuvwx'] * 4
|
||||
evaluate = tab_bar.evaluate_title_template
|
||||
for style in ('fade', 'separator', 'powerline', 'slant'):
|
||||
# titles are evaluated just once per tab in an update, though
|
||||
# laying out the tab bar draws them several times
|
||||
with patch('kitty.tab_bar.evaluate_title_template', wraps=evaluate) as ev:
|
||||
cached = self.horizontal_tab_bar_line(titles, 60, tab_bar_style=style)
|
||||
self.ae(ev.call_count, len(titles), style)
|
||||
self.assertIsNone(tab_bar.title_cache)
|
||||
with patch('kitty.tab_bar.caching_titles', nullcontext):
|
||||
self.ae(self.horizontal_tab_bar_line(titles, 60, tab_bar_style=style), cached, style)
|
||||
|
||||
# unless the title depends on the space available for it
|
||||
for template in ('{title[:max_title_length // 2]}', '{custom}'):
|
||||
with patch('kitty.tab_bar.evaluate_title_template', wraps=evaluate) as ev:
|
||||
cached = self.horizontal_tab_bar_line(titles, 60, tab_bar_style='separator', tab_title_template=template)
|
||||
with patch('kitty.tab_bar.caching_titles', nullcontext):
|
||||
self.ae(self.horizontal_tab_bar_line(titles, 60, tab_bar_style='separator', tab_title_template=template), cached, template)
|
||||
self.assertGreater(ev.call_count, len(titles), template)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, kitty contributors
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, Mock
|
||||
|
||||
from kitty.launch import find_existing, launch, parse_launch_args
|
||||
from kitty.options.utils import detach_window_parse
|
||||
from kitty.rc.base import MatchError, PayloadGetter
|
||||
from kitty.rc.detach_window import detach_window
|
||||
from kitty.tabs import index_for_new_tab
|
||||
from kitty.utils import natsort_ints, natsort_key
|
||||
from kitty.window import Window
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
def fake_window(wid: int, title: str = '', tab: object = None) -> MagicMock:
|
||||
w = MagicMock(spec=Window)
|
||||
w.id, w.title = wid, title
|
||||
w.child, w.ignore_focus_changes = None, False
|
||||
w.tabref = Mock(return_value=tab)
|
||||
return w
|
||||
|
||||
|
||||
class FakeTab:
|
||||
def __init__(self, tid: int, title: str, windows: tuple[MagicMock, ...] = ()):
|
||||
self.id, self.effective_title, self.windows = tid, title, windows
|
||||
self.active_window = windows[0] if windows else None
|
||||
self.tab_manager_ref = Mock(return_value=None)
|
||||
for w in windows:
|
||||
w.tabref.return_value = self
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.windows)
|
||||
|
||||
|
||||
class FakeBoss:
|
||||
def __init__(self, tabs: list[FakeTab], active_window: MagicMock | None = None):
|
||||
self.tabs = tabs
|
||||
self.active_window = self.active_window_for_cwd = active_window
|
||||
self.active_tab = tabs[0] if tabs else None
|
||||
# the tab bar of the active OS Window, shows all tabs unless a test hides some
|
||||
self.active_tab_manager = SimpleNamespace(tabs_to_be_shown_in_tab_bar=list(tabs))
|
||||
self.set_active_window = Mock()
|
||||
self.match_tabs = Mock(side_effect=lambda q: iter(()))
|
||||
self.match_windows = Mock(side_effect=lambda q, w=None: iter(()))
|
||||
self._move_window_to = Mock()
|
||||
|
||||
@property
|
||||
def all_tabs(self):
|
||||
return iter(self.tabs)
|
||||
|
||||
@property
|
||||
def all_windows(self):
|
||||
for t in self.tabs:
|
||||
yield from t.windows
|
||||
|
||||
|
||||
class TestTabWorkspaces(BaseTest):
|
||||
def test_index_for_new_tab(self):
|
||||
titles = ('a', 'c', 'e')
|
||||
for location, active, title, expected in (
|
||||
('last', 1, '', 3),
|
||||
('default', 1, '', 3),
|
||||
('first', 1, '', 0),
|
||||
('before', 1, '', 1),
|
||||
('after', 1, '', 2),
|
||||
('neighbor', 2, '', 3),
|
||||
('by-title', 0, 'b', 1),
|
||||
('by-title', 0, '0', 0),
|
||||
('by-title', 0, 'c', 2),
|
||||
('by-title', 0, 'z', 3),
|
||||
('by-title', 0, '', 3),
|
||||
):
|
||||
with self.subTest(location=location, active=active, title=title):
|
||||
self.ae(index_for_new_tab(titles, active, location, title), expected)
|
||||
self.ae(index_for_new_tab((), 0, 'by-title', 'x'), 0)
|
||||
self.ae(index_for_new_tab((), 0, 'after'), 0)
|
||||
# natural, case insensitive ordering
|
||||
titles = ('1', '2', '9', '10', 'apple', 'Banana', 'tab 2', 'tab 10')
|
||||
for title, expected in (('3', 2), ('11', 4), ('0', 0), ('avocado', 5), ('blueberry', 6), ('tab 3', 7), ('tab 11', 8), ('Apple', 4)):
|
||||
with self.subTest(title=title):
|
||||
self.ae(index_for_new_tab(titles, 0, 'by-title', title), expected)
|
||||
|
||||
def test_natsort(self):
|
||||
self.ae(natsort_ints(['10', '9', 'a2', 'a10', 'a1b', '²', '']), ['', '9', '10', 'a1b', 'a2', 'a10', '²'])
|
||||
self.ae(sorted(['b', 'A', 'a', 'B'], key=lambda x: (natsort_key(x, case_sensitive=False), x)), ['A', 'a', 'B', 'b'])
|
||||
|
||||
def test_find_existing(self):
|
||||
w1, w2 = fake_window(1, 'one'), fake_window(2, 'two')
|
||||
t1, t2 = FakeTab(1, 'x', (w1,)), FakeTab(2, 'y', (w2,))
|
||||
boss = FakeBoss([t1, t2], w1)
|
||||
|
||||
tm = boss.active_tab_manager
|
||||
|
||||
def opts(*args: str):
|
||||
return parse_launch_args(list(args))[0]
|
||||
|
||||
def find(*args: str):
|
||||
return find_existing(boss, opts(*args), None, tm) # type: ignore[arg-type]
|
||||
|
||||
self.assertIs(find('--type=tab', '--tab-title=y', '--focus-existing=@title'), t2)
|
||||
self.assertIsNone(find('--type=tab', '--tab-title=z', '--focus-existing=@title'))
|
||||
self.assertIs(find('--window-title=two', '--focus-existing=@title'), w2)
|
||||
self.assertIsNone(find('--window-title=tw', '--focus-existing=@title'))
|
||||
with self.assertRaises(ValueError):
|
||||
find('--type=tab', '--focus-existing=@title')
|
||||
with self.assertRaises(ValueError):
|
||||
find('--type=overlay', '--focus-existing=@title')
|
||||
# @title ignores tabs not shown in the tab bar, for example, ones hidden by tab_bar_filter
|
||||
tm.tabs_to_be_shown_in_tab_bar = [t1]
|
||||
self.assertIsNone(find('--type=tab', '--tab-title=y', '--focus-existing=@title'))
|
||||
self.assertIsNone(find('--window-title=two', '--focus-existing=@title'))
|
||||
# but os-window considers windows everywhere
|
||||
self.assertIs(find('--type=os-window', '--window-title=two', '--focus-existing=@title'), w2)
|
||||
tm.tabs_to_be_shown_in_tab_bar = [t1, t2]
|
||||
boss.match_tabs.side_effect = lambda q: iter((t1,))
|
||||
self.assertIs(find_existing(boss, opts('--type=tab', '--focus-existing=title:x')), t1)
|
||||
boss.match_tabs.assert_called_with('title:x')
|
||||
boss.match_windows.side_effect = lambda q, w=None: iter((w2,))
|
||||
self.assertIs(find_existing(boss, opts('--type=os-window', '--focus-existing=title:two')), w2)
|
||||
|
||||
def test_launch_focus_existing(self):
|
||||
w1, w2 = fake_window(1, 'one'), fake_window(2, 'two')
|
||||
t1, t2 = FakeTab(1, 'x', (w1,)), FakeTab(2, 'y', (w2,))
|
||||
boss = FakeBoss([t1, t2], w1)
|
||||
|
||||
def run(*args: str):
|
||||
boss.set_active_window.reset_mock()
|
||||
o, a = parse_launch_args(list(args))
|
||||
return launch(boss, o, a) # type: ignore[arg-type]
|
||||
|
||||
self.assertIs(run('--type=tab', '--tab-title=y', '--focus-existing=@title'), w2)
|
||||
boss.set_active_window.assert_called_once_with(w2, switch_os_window_if_needed=True)
|
||||
self.assertIs(run('--type=window', '--window-title=two', '--focus-existing=@title'), w2)
|
||||
boss.set_active_window.assert_called_once_with(w2, switch_os_window_if_needed=True)
|
||||
self.assertIs(run('--type=tab', '--tab-title=y', '--focus-existing=@title', '--keep-focus'), w2)
|
||||
boss.set_active_window.assert_not_called()
|
||||
# tab hidden from the tab bar is not focused, a new tab would be created instead
|
||||
boss.active_tab_manager.tabs_to_be_shown_in_tab_bar = [t1]
|
||||
o, _ = parse_launch_args(['--type=tab', '--tab-title=y', '--focus-existing=@title'])
|
||||
self.assertIsNone(find_existing(boss, o, None, boss.active_tab_manager)) # type: ignore[arg-type]
|
||||
|
||||
def test_detach_window_parse(self):
|
||||
self.ae(detach_window_parse('detach_window', 'new-tab'), ('detach_window', ('new-tab',)))
|
||||
self.ae(
|
||||
detach_window_parse('detach_window', '--target-tab=@title --tab-title="a b" --create-if-missing'),
|
||||
('detach_window', ['--target-tab=@title', '--tab-title=a b', '--create-if-missing']),
|
||||
)
|
||||
|
||||
def test_rc_detach_window_to_named_tab(self):
|
||||
w1, w2, w3 = fake_window(1), fake_window(2), fake_window(3)
|
||||
t1, t2 = FakeTab(1, 'x', (w1, w3)), FakeTab(2, 'y', (w2,))
|
||||
boss = FakeBoss([t1, t2], w1)
|
||||
|
||||
def run(**payload: object) -> None:
|
||||
boss._move_window_to.reset_mock()
|
||||
detach_window.response_from_kitty(boss, w1, PayloadGetter(detach_window, payload)) # type: ignore[arg-type]
|
||||
|
||||
run(target_tab='@title', tab_title='y')
|
||||
boss._move_window_to.assert_called_once_with(window=w1, target_tab_id=2, new_tab_title='y', new_tab_location='default')
|
||||
# tabs hidden from the tab bar are not targets for @title
|
||||
boss.active_tab_manager.tabs_to_be_shown_in_tab_bar = [t1]
|
||||
with self.assertRaisesRegex(MatchError, "No tab with the title 'y' exists"):
|
||||
run(target_tab='@title', tab_title='y')
|
||||
boss.active_tab_manager.tabs_to_be_shown_in_tab_bar = [t1, t2]
|
||||
# moving into the tab the window is already in is a no-op
|
||||
run(target_tab='@title', tab_title='x')
|
||||
boss._move_window_to.assert_not_called()
|
||||
with self.assertRaisesRegex(MatchError, "No tab with the title 'z' exists. Use --create-if-missing"):
|
||||
run(target_tab='@title', tab_title='z')
|
||||
with self.assertRaisesRegex(MatchError, "No tab matches the expression 'title:q'"):
|
||||
run(target_tab='title:q')
|
||||
with self.assertRaises(ValueError):
|
||||
run(target_tab='@title')
|
||||
run(target_tab='@title', tab_title='z', create_if_missing=True, location='by-title')
|
||||
boss._move_window_to.assert_called_once_with(window=w1, target_tab_id='new', new_tab_title='z', new_tab_location='by-title')
|
||||
|
||||
# when creating, later windows go into the newly created tab
|
||||
t3 = FakeTab(3, 'z')
|
||||
|
||||
def move(window, **kw):
|
||||
window.tabref.return_value = t3
|
||||
|
||||
boss._move_window_to.side_effect = move
|
||||
boss.match_windows.side_effect = lambda q, w=None: iter((w1, w3))
|
||||
run(match='all', target_tab='@title', tab_title='z', create_if_missing=True)
|
||||
self.ae([c.kwargs['target_tab_id'] for c in boss._move_window_to.call_args_list], ['new', 3])
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class TestTUI(BaseTest):
|
||||
def test_line_edit(self):
|
||||
from kittens.tui.line_edit import LineEdit
|
||||
|
||||
le = LineEdit()
|
||||
le.on_text('abcd', False)
|
||||
self.ae(le.cursor_pos, 4)
|
||||
for i in range(5):
|
||||
self.assertTrue(le.left()) if i < 4 else self.assertFalse(le.left())
|
||||
self.ae(le.cursor_pos, max(0, 3 - i))
|
||||
self.ae(le.pending_bell, True)
|
||||
le.clear()
|
||||
le.on_text('abcd', False), le.home()
|
||||
self.ae(le.cursor_pos, 0)
|
||||
for i in range(5):
|
||||
self.assertTrue(le.right()) if i < 4 else self.assertFalse(le.right())
|
||||
self.ae(le.cursor_pos, min(4, i + 1))
|
||||
self.ae(le.pending_bell, True)
|
||||
le.clear()
|
||||
le.on_text('abcd', False)
|
||||
self.ae(le.current_input, 'abcd')
|
||||
self.ae(le.cursor_pos, 4)
|
||||
self.ae(le.split_at_cursor(), ('abcd', ''))
|
||||
le.backspace()
|
||||
self.ae(le.current_input, 'abc')
|
||||
self.ae(le.cursor_pos, 3)
|
||||
self.assertFalse(le.pending_bell)
|
||||
le.backspace(num=2)
|
||||
self.ae(le.current_input, 'a')
|
||||
self.ae(le.cursor_pos, 1)
|
||||
self.assertFalse(le.pending_bell)
|
||||
le.backspace(num=2)
|
||||
self.ae(le.current_input, '')
|
||||
self.ae(le.cursor_pos, 0)
|
||||
le.backspace()
|
||||
self.assertTrue(le.pending_bell)
|
||||
|
||||
def test_multiprocessing_spawn(self):
|
||||
from kitty.multiprocessing import test_spawn
|
||||
|
||||
test_spawn()
|
||||
Binary file not shown.
@@ -0,0 +1,16 @@
|
||||
import subprocess
|
||||
|
||||
from kitty.fast_data_types import num_users
|
||||
|
||||
from .base import BaseTest
|
||||
|
||||
|
||||
class UTMPTest(BaseTest):
|
||||
def test_num_users(self):
|
||||
# who is the control
|
||||
try:
|
||||
expected = subprocess.check_output(['who']).decode('utf-8').count('\n')
|
||||
except FileNotFoundError:
|
||||
self.skipTest('No who executable cannot verify num_users')
|
||||
else:
|
||||
self.ae(num_users(), expected)
|
||||
Reference in new issue
Block a user