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
Whitespace-only changes.
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import (
|
||||
MATCH_WINDOW_OPTION,
|
||||
ArgsType,
|
||||
Boss,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
RemoteControlErrorWithoutTraceback,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import ActionRCOptions as CLIOptions
|
||||
|
||||
|
||||
class Action(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
action+/str: The action to perform. Of the form: action [optional args...]
|
||||
match_window/str: Window to run the action on
|
||||
self/bool: Whether to use the window this command is run in as the active window
|
||||
"""
|
||||
|
||||
short_desc = 'Run the specified mappable action'
|
||||
desc = (
|
||||
'Run the specified mappable action. For a list of all available mappable actions, see :doc:`actions`.'
|
||||
' Any arguments for ACTION should follow the action. Note that parsing of arguments is action dependent'
|
||||
' so for best results specify all arguments as single string on the command line in the same format as you would'
|
||||
' use for that action in kitty.conf.'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--self
|
||||
type=bool-set
|
||||
Run the action on the window this command is run in instead of the active window.
|
||||
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response indicating the success of the action. Note that
|
||||
using this option means that you will not be notified of failures.
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
)
|
||||
|
||||
args = RemoteCommand.Args(
|
||||
spec='ACTION [ARGS FOR ACTION...]',
|
||||
json_field='action',
|
||||
minimum_count=1,
|
||||
completion=RemoteCommand.CompletionSpec.from_string('type:special group:complete_actions'),
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'action': ' '.join(args), 'self': opts.self, 'match_window': opts.match}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
w = self.windows_for_match_payload(boss, window, payload_get, 'match_window')
|
||||
if w:
|
||||
window = w[0]
|
||||
ac = payload_get('action')
|
||||
if not ac:
|
||||
raise RemoteControlErrorWithoutTraceback('Must specify an action')
|
||||
|
||||
try:
|
||||
consumed = boss.combine(str(ac), window, raise_error=True)
|
||||
except (Exception, SystemExit) as e:
|
||||
raise RemoteControlErrorWithoutTraceback(str(e))
|
||||
|
||||
if not consumed:
|
||||
raise RemoteControlErrorWithoutTraceback(f'Unknown action: {ac}')
|
||||
return None
|
||||
|
||||
|
||||
action = Action()
|
||||
@@ -0,0 +1,486 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from io import BytesIO
|
||||
from typing import TYPE_CHECKING, Any, NoReturn, Optional, Union, cast
|
||||
|
||||
from kitty.cli import get_defaults_from_seq, parse_args
|
||||
from kitty.cli_stub import RCOptions as R
|
||||
from kitty.constants import list_kitty_resources, running_in_kitty
|
||||
from kitty.simple_cli_definitions import CompletionSpec, parse_option_spec
|
||||
from kitty.types import AsyncResponse
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.boss import Boss as B
|
||||
from kitty.tabs import Tab as T
|
||||
from kitty.window import Window as W
|
||||
|
||||
Window = W
|
||||
Boss = B
|
||||
Tab = T
|
||||
else:
|
||||
Boss = Window = Tab = object
|
||||
RCOptions = R
|
||||
|
||||
|
||||
class NoResponse:
|
||||
pass
|
||||
|
||||
|
||||
class RemoteControlError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class RemoteControlErrorWithoutTraceback(Exception):
|
||||
hide_traceback = True
|
||||
|
||||
|
||||
class MatchError(ValueError):
|
||||
hide_traceback = True
|
||||
|
||||
def __init__(self, expression: str, target: str = 'windows'):
|
||||
ValueError.__init__(self, f'No matching {target} for expression: {expression}')
|
||||
|
||||
|
||||
class OpacityError(ValueError):
|
||||
hide_traceback = True
|
||||
|
||||
|
||||
class UnknownLayout(ValueError):
|
||||
hide_traceback = True
|
||||
|
||||
|
||||
class StreamError(ValueError):
|
||||
hide_traceback = True
|
||||
|
||||
|
||||
class PayloadGetter:
|
||||
def __init__(self, cmd: 'RemoteCommand', payload: dict[str, Any]):
|
||||
self.payload = payload
|
||||
self.cmd = cmd
|
||||
|
||||
def __call__(self, key: str, opt_name: str | None = None, missing: Any = None) -> Any:
|
||||
ans = self.payload.get(key, payload_get)
|
||||
if ans is not payload_get:
|
||||
return ans
|
||||
return self.cmd.get_default(opt_name or key, missing=missing)
|
||||
|
||||
|
||||
no_response = NoResponse()
|
||||
payload_get = object()
|
||||
ResponseType = Union[bool, str, None, NoResponse, AsyncResponse]
|
||||
CmdReturnType = Union[dict[str, Any], list[Any], tuple[Any, ...], str, int, float, bool]
|
||||
CmdGenerator = Iterator[CmdReturnType]
|
||||
PayloadType = Optional[Union[CmdReturnType, CmdGenerator]]
|
||||
PayloadGetType = PayloadGetter
|
||||
ArgsType = list[str]
|
||||
ImageCompletion = CompletionSpec.from_string('type:file group:"Images" ext:png,jpg,jpeg,webp,gif,bmp,tiff')
|
||||
SUPPORTED_IMAGE_FORMATS = tuple(x.upper() for x in ImageCompletion.extensions if x != 'jpg')
|
||||
|
||||
|
||||
MATCH_WINDOW_OPTION = """\
|
||||
--match -m
|
||||
The window to match. Match specifications are of the form: :italic:`field:query`.
|
||||
Where :italic:`field` can be one of: :code:`id`, :code:`title`, :code:`pid`, :code:`cwd`, :code:`cmdline`, :code:`num`,
|
||||
:code:`env`, :code:`var`, :code:`state`, :code:`neighbor`, :code:`session` and :code:`recent`.
|
||||
:italic:`query` is the expression to match. Expressions can be either a number or a regular expression, and can be
|
||||
:ref:`combined using Boolean operators <search_syntax>`.
|
||||
|
||||
The special value :code:`all` matches all windows.
|
||||
|
||||
For numeric fields: :code:`id`, :code:`pid`, :code:`num` and :code:`recent`, the expression is interpreted as
|
||||
a number, not a regular expression. Negative values for :code:`id` match from the highest id number down, in particular,
|
||||
-1 is the most recently created window.
|
||||
|
||||
The field :code:`num` refers to the window position in the current tab, starting from zero and counting clockwise (this
|
||||
is the same as the order in which the windows are reported by the :ref:`kitten @ ls <at-ls>` command).
|
||||
|
||||
The window id of the current window is available as the :envvar:`KITTY_WINDOW_ID` environment variable.
|
||||
|
||||
The field :code:`recent` refers to recently active windows in the currently active tab, with zero being the currently
|
||||
active window, one being the previously active window and so on.
|
||||
|
||||
The field :code:`neighbor` refers to a neighbor of the active window in the specified direction, which can be:
|
||||
:code:`left`, :code:`right`, :code:`top` or :code:`bottom`.
|
||||
|
||||
The field :code:`session` matches windows that were created in the specified session.
|
||||
Use the expression :code:`^$` to match windows that were not created in a session and
|
||||
:code:`.` to match the currently active session and :code:`~` to match either the currently
|
||||
active session or the last active session when no session is active.
|
||||
|
||||
When using the :code:`env` field to match on environment variables, you can specify only the environment variable name
|
||||
or a name and value, for example, :code:`env:MY_ENV_VAR=2`.
|
||||
|
||||
Similarly, the :code:`var` field matches on user variables set on the window. You can specify name or name and value
|
||||
as with the :code:`env` field.
|
||||
|
||||
The field :code:`state` matches on the state of the window. Supported states
|
||||
are: :code:`active`, :code:`focused`, :code:`needs_attention`,
|
||||
:code:`parent_active`, :code:`parent_focused`, :code:`focused_os_window`,
|
||||
:code:`self`, :code:`overlay_parent`. Active windows are the windows that are
|
||||
active in their parent tab. There is only one focused window and it is the
|
||||
window to which keyboard events are delivered. If no window is focused, the
|
||||
last focused window is matched. The value :code:`focused_os_window` matches
|
||||
all windows in the currently focused OS window. The value :code:`self` matches
|
||||
the window in which the remote control command is run. The value
|
||||
:code:`overlay_parent` matches the window that is under the :code:`self`
|
||||
window, when the self window is an overlay.
|
||||
|
||||
Note that you can use the :ref:`kitten @ ls <at-ls>` command to get a list of windows.
|
||||
"""
|
||||
MATCH_TAB_OPTION = """\
|
||||
--match -m
|
||||
The tab to match. Match specifications are of the form: :italic:`field:query`.
|
||||
Where :italic:`field` can be one of: :code:`id`, :code:`index`, :code:`title`, :code:`window_id`, :code:`window_title`,
|
||||
:code:`pid`, :code:`cwd`, :code:`cmdline` :code:`env`, :code:`var`, :code:`state`, :code:`session` and :code:`recent`.
|
||||
:italic:`query` is the expression to match. Expressions can be either a number or a regular expression, and can be
|
||||
:ref:`combined using Boolean operators <search_syntax>`.
|
||||
|
||||
The special value :code:`all` matches all tabs.
|
||||
|
||||
For numeric fields: :code:`id`, :code:`index`, :code:`window_id`, :code:`pid` and :code:`recent`, the
|
||||
expression is interpreted as a number, not a regular expression. Negative values for :code:`id`/:code:`window_id` match
|
||||
from the highest id number down, in particular, -1 is the most recently created tab/window.
|
||||
|
||||
When using :code:`title` or :code:`id`, first a matching tab is looked for, and if not found a matching window is looked
|
||||
for, and the tab for that window is used.
|
||||
|
||||
You can also use :code:`window_id` and :code:`window_title` to match the tab that contains the window with the specified
|
||||
id or title.
|
||||
|
||||
The :code:`index` number is used to match the nth tab in the currently active OS window.
|
||||
The :code:`recent` number matches recently active tabs in the currently active OS window, with zero being the currently
|
||||
active tab, one the previously active tab and so on.
|
||||
|
||||
The field :code:`session` matches tabs that were created in the specified session.
|
||||
Use the expression :code:`^$` to match windows that were not created in a session and
|
||||
:code:`.` to match the currently active session and :code:`~` to match either the currently
|
||||
active session or the last active session when no session is active.
|
||||
|
||||
When using the :code:`env` field to match on environment variables, you can specify only the environment variable name
|
||||
or a name and value, for example, :code:`env:MY_ENV_VAR=2`. Tabs containing any window with the specified environment
|
||||
variables are matched. Similarly, :code:`var` matches tabs containing any window with the specified user variable.
|
||||
|
||||
The field :code:`state` matches on the state of the tab. Supported states are:
|
||||
:code:`active`, :code:`focused`, :code:`needs_attention`, :code:`parent_active`, :code:`parent_focused`
|
||||
and :code:`focused_os_window`.
|
||||
Active tabs are the tabs that are active in their parent OS window. There is only one focused tab
|
||||
and it is the tab to which keyboard events are delivered. If no tab is focused, the last focused tab is matched.
|
||||
The value :code:`focused_os_window` matches all tabs in the currently focused OS window.
|
||||
|
||||
Note that you can use the :ref:`kitten @ ls <at-ls>` command to get a list of tabs.
|
||||
"""
|
||||
|
||||
|
||||
class ParsingOfArgsFailed(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class AsyncResponder:
|
||||
def __init__(self, payload_get: PayloadGetType, window: Window | None) -> None:
|
||||
self.async_id: str = payload_get('async_id', missing='')
|
||||
self.peer_id: int = payload_get('peer_id', missing=0)
|
||||
self.window_id: int = getattr(window, 'id', 0)
|
||||
|
||||
def send_data(self, data: Any) -> None:
|
||||
from kitty.remote_control import send_response_to_client
|
||||
|
||||
send_response_to_client(data=data, peer_id=self.peer_id, window_id=self.window_id, async_id=self.async_id)
|
||||
|
||||
def send_error(self, error: str) -> None:
|
||||
from kitty.remote_control import send_response_to_client
|
||||
|
||||
send_response_to_client(error=error, peer_id=self.peer_id, window_id=self.window_id, async_id=self.async_id)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ArgsHandling:
|
||||
json_field: str = ''
|
||||
count: int | None = None
|
||||
spec: str = ''
|
||||
completion: CompletionSpec = field(default_factory=CompletionSpec)
|
||||
value_if_unspecified: tuple[str, ...] = ()
|
||||
minimum_count: int = -1
|
||||
first_rest: tuple[str, str] | None = None
|
||||
special_parse: str = ''
|
||||
args_choices: Callable[[], Iterable[str]] | None = None
|
||||
|
||||
@property
|
||||
def args_count(self) -> int | None:
|
||||
if not self.spec:
|
||||
return 0
|
||||
return self.count
|
||||
|
||||
def as_go_completion_code(self, go_name: str) -> Iterator[str]:
|
||||
c = self.args_count
|
||||
if c is not None:
|
||||
yield f'{go_name}.StopCompletingAtArg = {c}'
|
||||
if self.completion: # ty: ignore[redundant-condition]
|
||||
yield from self.completion.as_go_code(go_name + '.ArgCompleter', ' = ')
|
||||
|
||||
def as_go_code(self, cmd_name: str, field_types: dict[str, str], handled_fields: set[str]) -> Iterator[str]:
|
||||
c = self.args_count
|
||||
if c == 0:
|
||||
yield f'if len(args) != 0 {{ return fmt.Errorf("%s", "Unknown extra argument(s) supplied to {cmd_name}") }}'
|
||||
return
|
||||
if c is not None:
|
||||
yield f'if len(args) != {c} {{ return fmt.Errorf("%s", "Must specify exactly {c} argument(s) for {cmd_name}") }}'
|
||||
if self.value_if_unspecified:
|
||||
yield 'if len(args) == 0 {'
|
||||
for x in self.value_if_unspecified:
|
||||
yield f'args = append(args, "{x}")'
|
||||
yield '}'
|
||||
if self.minimum_count > -1:
|
||||
if self.minimum_count == 1:
|
||||
yield f'if len(args) < {self.minimum_count} {{ return fmt.Errorf("%s", "Must specify at least one argument to {cmd_name}") }}'
|
||||
else:
|
||||
yield f'if len(args) < {self.minimum_count} {{ return fmt.Errorf("%s", "Must specify at least {self.minimum_count} arguments to {cmd_name}") }}'
|
||||
if self.args_choices:
|
||||
achoices = tuple(self.args_choices())
|
||||
yield 'achoices := map[string]bool{' + ' '.join(f'"{x}":true,' for x in achoices) + '}'
|
||||
yield 'for _, a := range args {'
|
||||
yield 'if !achoices[a] { return fmt.Errorf("Not a valid choice: %s. Allowed values are: %s", a, "' + ', '.join(achoices) + '") }'
|
||||
yield '}'
|
||||
if self.json_field:
|
||||
jf = self.json_field
|
||||
dest = f'payload.{jf.capitalize()}'
|
||||
jt = field_types[jf]
|
||||
if self.first_rest:
|
||||
yield f'payload.{self.first_rest[0].capitalize()} = escaped_string(args[0])'
|
||||
yield f'payload.{self.first_rest[1].capitalize()} = escape_list_of_strings(args[1:])'
|
||||
handled_fields.add(self.first_rest[0])
|
||||
handled_fields.add(self.first_rest[1])
|
||||
return
|
||||
handled_fields.add(self.json_field)
|
||||
if self.special_parse:
|
||||
if self.special_parse.startswith('!'):
|
||||
yield f'io_data.multiple_payload_generator, err = {self.special_parse[1:]}'
|
||||
elif self.special_parse.startswith('+'):
|
||||
fields, sp = self.special_parse[1:].split(':', 1)
|
||||
handled_fields.update(set(fields.split(',')))
|
||||
if sp.startswith('!'):
|
||||
yield f'io_data.multiple_payload_generator, err = {sp[1:]}'
|
||||
else:
|
||||
yield f'err = {sp}'
|
||||
else:
|
||||
yield f'{dest}, err = {self.special_parse}'
|
||||
yield 'if err != nil { return err }'
|
||||
return
|
||||
if jt == 'list.str':
|
||||
yield f'{dest} = escape_list_of_strings(args)'
|
||||
return
|
||||
if jt == 'str':
|
||||
if c == 1:
|
||||
yield f'{dest} = escaped_string(args[0])'
|
||||
else:
|
||||
yield f'{dest} = escaped_string(strings.Join(args, " "))'
|
||||
return
|
||||
if jt.startswith('choices.'):
|
||||
yield f'if len(args) != 1 {{ return fmt.Errorf("%s", "Must specify exactly 1 argument for {cmd_name}") }}'
|
||||
choices = ', '.join(f'"{x}"' for x in jt.split('.')[1:])
|
||||
yield 'switch(args[0]) {'
|
||||
yield f'case {choices}:\n\t{dest} = args[0]'
|
||||
yield f'default: return fmt.Errorf("%s is not a valid choice. Allowed values: %s", args[0], `{choices}`)'
|
||||
yield '}'
|
||||
return
|
||||
if jt == 'dict.str':
|
||||
yield f'{dest} = parse_key_val_args(args)'
|
||||
return
|
||||
raise TypeError(f'Unknown args handling for cmd: {cmd_name}')
|
||||
|
||||
|
||||
class StreamInFlight:
|
||||
def __init__(self) -> None:
|
||||
self.stream_id = ''
|
||||
self.tempfile: BytesIO | None = None
|
||||
|
||||
def discard(self, stream_id: str) -> None:
|
||||
# Drop any data received for the specified stream, if it is in flight
|
||||
if stream_id and stream_id == self.stream_id:
|
||||
self.stream_id = ''
|
||||
if self.tempfile is not None:
|
||||
self.tempfile.close()
|
||||
self.tempfile = None
|
||||
|
||||
def handle_data(self, stream_id: str, data: bytes) -> AsyncResponse | BytesIO:
|
||||
from ..remote_control import close_active_stream
|
||||
|
||||
def abort_stream() -> None:
|
||||
close_active_stream(self.stream_id)
|
||||
self.discard(self.stream_id)
|
||||
|
||||
if stream_id != self.stream_id:
|
||||
abort_stream()
|
||||
self.stream_id = stream_id
|
||||
if self.tempfile is None:
|
||||
self.tempfile = BytesIO()
|
||||
t = self.tempfile
|
||||
if data:
|
||||
if (t.tell() + len(data)) > 128 * 1024 * 1024:
|
||||
abort_stream()
|
||||
raise StreamError('Too much data being sent')
|
||||
t.write(data)
|
||||
return AsyncResponse()
|
||||
close_active_stream(self.stream_id)
|
||||
self.stream_id = ''
|
||||
self.tempfile = None
|
||||
t.flush()
|
||||
return t
|
||||
|
||||
|
||||
class RemoteCommand:
|
||||
Args = ArgsHandling
|
||||
CompletionSpec = CompletionSpec
|
||||
|
||||
name: str = ''
|
||||
short_desc: str = ''
|
||||
desc: str = ''
|
||||
args: ArgsHandling = ArgsHandling()
|
||||
options_spec: str | None = None
|
||||
response_timeout: float = 10.0 # seconds
|
||||
string_return_is_error: bool = False
|
||||
defaults: dict[str, Any] | None = None
|
||||
is_asynchronous: bool = False
|
||||
options_class: type[RCOptions] = RCOptions
|
||||
protocol_spec: str = ''
|
||||
argspec = args_count = args_completion = ArgsHandling()
|
||||
field_to_option_map: dict[str, str] | None = None
|
||||
reads_streaming_data: bool = False
|
||||
disallow_responses: bool = False
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.desc = self.desc or self.short_desc
|
||||
self.name = self.__class__.__module__.split('.')[-1].replace('_', '-')
|
||||
self.stream_in_flight = StreamInFlight()
|
||||
|
||||
def fatal(self, msg: str) -> NoReturn:
|
||||
if running_in_kitty():
|
||||
raise RemoteControlError(msg)
|
||||
raise SystemExit(msg)
|
||||
|
||||
def get_default(self, name: str, missing: Any = None) -> Any:
|
||||
if self.options_spec:
|
||||
if self.defaults is None:
|
||||
self.defaults = get_defaults_from_seq(parse_option_spec(self.options_spec)[0])
|
||||
return self.defaults.get(name, missing)
|
||||
return missing
|
||||
|
||||
def windows_for_match_payload(self, boss: 'Boss', window: Optional['Window'], payload_get: PayloadGetType, match_name: str = 'match') -> list['Window']:
|
||||
if payload_get('all'):
|
||||
windows = list(boss.all_windows)
|
||||
else:
|
||||
self_window = window
|
||||
if payload_get('self') in (None, True):
|
||||
window = window or boss.active_window
|
||||
else:
|
||||
window = boss.active_window or window
|
||||
windows = [window] if window else []
|
||||
if match := payload_get(match_name):
|
||||
windows = list(boss.match_windows(match, self_window))
|
||||
if not windows:
|
||||
raise MatchError(match)
|
||||
return windows
|
||||
|
||||
def tabs_for_match_payload(self, boss: 'Boss', window: Optional['Window'], payload_get: PayloadGetType) -> list['Tab']:
|
||||
if payload_get('all'):
|
||||
return list(boss.all_tabs)
|
||||
match = payload_get('match')
|
||||
if match:
|
||||
tabs = list(boss.match_tabs(match))
|
||||
if not tabs:
|
||||
raise MatchError(match, 'tabs')
|
||||
return tabs
|
||||
if window and payload_get('self') in (None, True):
|
||||
if q := window.tabref():
|
||||
return [q]
|
||||
t = boss.active_tab
|
||||
if t:
|
||||
return [t]
|
||||
return []
|
||||
|
||||
def windows_for_payload(
|
||||
self,
|
||||
boss: 'Boss',
|
||||
window: Optional['Window'],
|
||||
payload_get: PayloadGetType,
|
||||
window_match_name: str = 'match_window',
|
||||
tab_match_name: str = 'match_tab',
|
||||
) -> list['Window']:
|
||||
if payload_get('all'):
|
||||
windows = list(boss.all_windows)
|
||||
else:
|
||||
window = window or boss.active_window
|
||||
windows = [window] if window else []
|
||||
if payload_get(window_match_name):
|
||||
windows = list(boss.match_windows(payload_get(window_match_name), window))
|
||||
if not windows:
|
||||
raise MatchError(payload_get(window_match_name))
|
||||
if payload_get(tab_match_name):
|
||||
tabs = tuple(boss.match_tabs(payload_get(tab_match_name)))
|
||||
if not tabs:
|
||||
raise MatchError(payload_get(tab_match_name), 'tabs')
|
||||
windows = []
|
||||
for tab in tabs:
|
||||
windows += list(tab)
|
||||
if payload_get('exclude_active'):
|
||||
windows = [w for w in windows if w is not boss.active_window]
|
||||
return windows
|
||||
|
||||
def create_async_responder(self, payload_get: PayloadGetType, window: Window | None) -> AsyncResponder:
|
||||
return AsyncResponder(payload_get, window)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: Any, args: ArgsType) -> PayloadType:
|
||||
raise NotImplementedError()
|
||||
|
||||
def response_from_kitty(self, boss: 'Boss', window: Optional['Window'], payload_get: PayloadGetType) -> ResponseType:
|
||||
raise NotImplementedError()
|
||||
|
||||
def cancel_async_request(self, boss: 'Boss', window: Optional['Window'], payload_get: PayloadGetType) -> None:
|
||||
pass
|
||||
|
||||
def handle_streamed_data(self, data: bytes, payload_get: PayloadGetType) -> BytesIO | AsyncResponse:
|
||||
stream_id = payload_get('stream_id')
|
||||
if not stream_id or not isinstance(stream_id, str):
|
||||
raise StreamError('No stream_id in rc payload')
|
||||
return self.stream_in_flight.handle_data(stream_id, data)
|
||||
|
||||
|
||||
def cli_params_for(command: RemoteCommand) -> tuple[Callable[[], str], str, str, str]:
|
||||
return (command.options_spec or '\n').format, command.args.spec, command.desc, f'kitten @ {command.name}'
|
||||
|
||||
|
||||
def parse_subcommand_cli(command: RemoteCommand, args: ArgsType) -> tuple[Any, ArgsType]:
|
||||
opts, items = parse_args(args[1:], *cli_params_for(command), result_class=command.options_class)
|
||||
if command.args.args_count is not None and command.args.args_count != len(items):
|
||||
if command.args.args_count == 0:
|
||||
raise SystemExit(f'Unknown extra argument(s) supplied to {command.name}')
|
||||
raise SystemExit(f'Must specify exactly {command.args.args_count} argument(s) for {command.name}')
|
||||
return opts, items
|
||||
|
||||
|
||||
def display_subcommand_help(func: RemoteCommand) -> None:
|
||||
with suppress(SystemExit):
|
||||
parse_args(['--help'], (func.options_spec or '\n').format, func.args.spec, func.desc, func.name)
|
||||
|
||||
|
||||
def command_for_name(cmd_name: str) -> RemoteCommand:
|
||||
from importlib import import_module
|
||||
|
||||
cmd_name = cmd_name.replace('-', '_')
|
||||
try:
|
||||
m = import_module(f'kitty.rc.{cmd_name}')
|
||||
except ImportError:
|
||||
raise KeyError(f'Unknown kitty remote control command: {cmd_name}')
|
||||
return cast(RemoteCommand, getattr(m, cmd_name))
|
||||
|
||||
|
||||
def all_command_names() -> frozenset[str]:
|
||||
|
||||
def ok(name: str) -> bool:
|
||||
root, _, ext = name.rpartition('.')
|
||||
return bool(ext in ('py', 'pyc', 'pyo') and root and root not in ('base', '__init__'))
|
||||
|
||||
return frozenset({x.rpartition('.')[0] for x in filter(ok, list_kitty_resources('kitty.rc'))})
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, MatchError, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import CloseTabRCOptions as CLIOptions
|
||||
|
||||
|
||||
class CloseTab(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which tab to close
|
||||
self/bool: Boolean indicating whether to close the tab of the window the command is run in
|
||||
ignore_no_match/bool: Boolean indicating whether no matches should be ignored or return an error
|
||||
"""
|
||||
|
||||
short_desc = 'Close the specified tabs'
|
||||
desc = """\
|
||||
Close an arbitrary set of tabs. The :code:`--match` option can be used to
|
||||
specify complex sets of tabs to close. For example, to close all non-focused
|
||||
tabs in the currently focused OS window, use::
|
||||
|
||||
kitten @ close-tab --match "not state:focused and state:parent_focused"
|
||||
"""
|
||||
options_spec = (
|
||||
MATCH_TAB_OPTION
|
||||
+ """\n
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response indicating the success of the action. Note that
|
||||
using this option means that you will not be notified of failures.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Close the tab of the window this command is run in, rather than the active tab.
|
||||
|
||||
|
||||
--ignore-no-match
|
||||
type=bool-set
|
||||
Do not return an error if no tabs are matched to be closed.
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'self': opts.self, 'ignore_no_match': opts.ignore_no_match}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
try:
|
||||
tabs = self.tabs_for_match_payload(boss, window, payload_get)
|
||||
except MatchError:
|
||||
if payload_get('ignore_no_match'):
|
||||
return None
|
||||
raise
|
||||
for tab in tuple(tabs):
|
||||
if tab:
|
||||
boss.close_tab_no_confirm(tab)
|
||||
return None
|
||||
|
||||
|
||||
close_tab = CloseTab()
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, MatchError, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import CloseWindowRCOptions as CLIOptions
|
||||
|
||||
|
||||
class CloseWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which window to close
|
||||
self/bool: Boolean indicating whether to close the window the command is run in
|
||||
ignore_no_match/bool: Boolean indicating whether no matches should be ignored or return an error
|
||||
"""
|
||||
|
||||
short_desc = 'Close the specified windows'
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response indicating the success of the action. Note that
|
||||
using this option means that you will not be notified of failures.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Close the window this command is run in, rather than the active window.
|
||||
|
||||
|
||||
--ignore-no-match
|
||||
type=bool-set
|
||||
Do not return an error if no windows are matched to be closed.
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'self': opts.self, 'ignore_no_match': opts.ignore_no_match}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
try:
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
except MatchError:
|
||||
if payload_get('ignore_no_match'):
|
||||
return None
|
||||
raise
|
||||
for window in tuple(windows):
|
||||
if window:
|
||||
boss.mark_window_for_close(window)
|
||||
return None
|
||||
|
||||
|
||||
close_window = CloseWindow()
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.options.utils import parse_marker_spec
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import CreateMarkerRCOptions as CLIOptions
|
||||
|
||||
|
||||
class CreateMarker(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which window to create the marker in
|
||||
self/bool: Boolean indicating whether to create marker in the window the command is run in
|
||||
marker_spec/list.str: A list or arguments that define the marker specification, for example: ['text', '1', 'ERROR']
|
||||
"""
|
||||
|
||||
short_desc = 'Create a marker that highlights specified text'
|
||||
desc = (
|
||||
'Create a marker which can highlight text in the specified window. For example: :code:`create_marker text 1 ERROR`. For full details see: :doc:`marks`'
|
||||
)
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--self
|
||||
type=bool-set
|
||||
Apply marker to the window this command is run in, rather than the active window.
|
||||
"""
|
||||
)
|
||||
args = RemoteCommand.Args(spec='MARKER SPECIFICATION', json_field='marker_spec', minimum_count=2)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if len(args) < 2:
|
||||
self.fatal('Invalid marker specification: {}'.format(' '.join(args)))
|
||||
try:
|
||||
parse_marker_spec(args[0], args[1:])
|
||||
except Exception as err:
|
||||
self.fatal(f'Failed to parse marker specification {" ".join(args)} with error: {err}')
|
||||
return {'match': opts.match, 'self': opts.self, 'marker_spec': args}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
args = payload_get('marker_spec')
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
window.set_marker(args)
|
||||
return None
|
||||
|
||||
|
||||
create_marker = CreateMarker()
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, MatchError, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import DetachTabRCOptions as CLIOptions
|
||||
|
||||
|
||||
class DetachTab(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which tab to detach
|
||||
target_tab/str: Which tab to move the detached tab to the OS window it is run in
|
||||
self/bool: Boolean indicating whether to detach the tab the command is run in
|
||||
"""
|
||||
|
||||
short_desc = 'Detach the specified tabs and place them in a different/new OS window'
|
||||
desc = (
|
||||
'Detach the specified tabs and either move them into a new OS window'
|
||||
' or add them to the OS window containing the tab specified by :option:`kitten @ detach-tab --target-tab`'
|
||||
)
|
||||
options_spec = (
|
||||
MATCH_TAB_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--target-tab -t')
|
||||
+ """\n
|
||||
--self
|
||||
type=bool-set
|
||||
Detach the tab this command is run in, rather than the active tab.
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'target_tab': opts.target_tab, 'self': opts.self}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
match = payload_get('target_tab')
|
||||
kwargs = {}
|
||||
if match:
|
||||
targets = tuple(boss.match_tabs(match))
|
||||
if not targets:
|
||||
raise MatchError(match, 'tabs')
|
||||
if targets[0]:
|
||||
kwargs['target_os_window_id'] = targets[0].os_window_id
|
||||
|
||||
for tab in self.tabs_for_match_payload(boss, window, payload_get):
|
||||
if tab:
|
||||
boss._move_tab_to(tab=tab, **kwargs)
|
||||
return None
|
||||
|
||||
|
||||
detach_tab = DetachTab()
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, MATCH_WINDOW_OPTION, ArgsType, Boss, MatchError, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import DetachWindowRCOptions as CLIOptions
|
||||
|
||||
|
||||
class TabNotFound(MatchError):
|
||||
def __init__(self, msg: str):
|
||||
ValueError.__init__(self, msg)
|
||||
|
||||
|
||||
class DetachWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which window to detach
|
||||
target_tab/str: Which tab to move the detached window to
|
||||
self/bool: Boolean indicating whether to detach the window the command is run in
|
||||
stay_in_tab/bool: Boolean indicating focus should remain in the active tab after windows are moved
|
||||
tab_title/str: Title for a newly created tab
|
||||
location/choices.first.after.before.neighbor.last.by-title.default: Where to place a newly created tab
|
||||
create_if_missing/bool: Boolean indicating a new tab should be created if no tab matches target_tab
|
||||
"""
|
||||
|
||||
short_desc = 'Detach the specified windows and place them in a different/new tab'
|
||||
desc = (
|
||||
'Detach the specified windows and either move them into a new tab, a new OS window'
|
||||
' or add them to the specified tab. Use the special value :code:`new` for :option:`kitten @ detach-window --target-tab`'
|
||||
' to move to a new tab. If no target tab is specified the windows are moved to a new OS window.'
|
||||
)
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--target-tab -t')
|
||||
+ """Use the special value :code:`new` to move to a new tab. The special value
|
||||
:code:`@title` selects the tab whose title is exactly the value of
|
||||
:option:`kitten @ detach-window --tab-title`, considering only the tabs shown
|
||||
in the tab bar of the active OS Window, so tabs hidden by :opt:`tab_bar_filter`
|
||||
are ignored.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Detach the window this command is run in, rather than the active window.
|
||||
|
||||
|
||||
--stay-in-tab
|
||||
type=bool-set
|
||||
Keep the focus on a window in the currently focused tab after moving the specified windows.
|
||||
|
||||
|
||||
--tab-title
|
||||
The title for the tab, when moving to a newly created tab.
|
||||
|
||||
|
||||
--location
|
||||
type=choices
|
||||
default=default
|
||||
choices=first,after,before,neighbor,last,by-title,default
|
||||
Where to place the newly created tab, when moving to a new tab. :code:`after`
|
||||
and :code:`before` place it next to the currently active tab, :code:`neighbor`
|
||||
is a synonym for :code:`after`. :code:`by-title` places the new tab before the
|
||||
first tab whose title sorts after :option:`kitten @ detach-window --tab-title`.
|
||||
The default is to place it at the end.
|
||||
|
||||
|
||||
--create-if-missing
|
||||
type=bool-set
|
||||
If no tab matches :option:`kitten @ detach-window --target-tab`, create a new tab
|
||||
and move the windows to it, instead of failing. Combined with :code:`@title`, this
|
||||
can be used to send windows to a named tab, creating it if needed. For example::
|
||||
|
||||
kitten @ detach-window --target-tab=@title --tab-title=1 --location=by-title --create-if-missing
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {
|
||||
'match': opts.match,
|
||||
'target_tab': opts.target_tab,
|
||||
'self': opts.self,
|
||||
'stay_in_tab': opts.stay_in_tab,
|
||||
'tab_title': opts.tab_title,
|
||||
'location': opts.location,
|
||||
'create_if_missing': opts.create_if_missing,
|
||||
}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
match = payload_get('target_tab')
|
||||
tab_title = payload_get('tab_title') or ''
|
||||
location = payload_get('location') or 'default'
|
||||
target_tab_id: str | int | None = None
|
||||
newval: str | int = 'new'
|
||||
create_tab = False
|
||||
if match:
|
||||
if match == 'new':
|
||||
target_tab_id = newval
|
||||
else:
|
||||
if match == '@title':
|
||||
if not tab_title:
|
||||
raise ValueError('--target-tab=@title requires --tab-title to also be specified')
|
||||
# only tabs visible in the tab bar of the active OS Window, so as to respect tab_bar_filter
|
||||
atm = boss.active_tab_manager
|
||||
tabs = tuple(t for t in (atm.tabs_to_be_shown_in_tab_bar if atm is not None else ()) if t.effective_title == tab_title)
|
||||
else:
|
||||
tabs = tuple(boss.match_tabs(match))
|
||||
if tabs:
|
||||
target_tab_id = tabs[0].id
|
||||
elif payload_get('create_if_missing'):
|
||||
target_tab_id = newval
|
||||
create_tab = True
|
||||
elif match == '@title':
|
||||
raise TabNotFound(f'No tab with the title {tab_title!r} exists. Use --create-if-missing to create it.')
|
||||
else:
|
||||
raise TabNotFound(f'No tab matches the expression {match!r}. Use --create-if-missing to create a new tab instead.')
|
||||
tab = boss.active_tab
|
||||
for window in windows:
|
||||
if not window:
|
||||
continue
|
||||
if target_tab_id is None:
|
||||
boss._move_window_to(window=window, target_os_window_id=newval, new_tab_title=tab_title)
|
||||
continue
|
||||
if (src_tab := window.tabref()) is not None and src_tab.id == target_tab_id:
|
||||
continue
|
||||
boss._move_window_to(window=window, target_tab_id=target_tab_id, new_tab_title=tab_title, new_tab_location=location)
|
||||
if create_tab and (created := window.tabref()) is not None:
|
||||
# move any remaining windows into the tab that was just created
|
||||
target_tab_id, create_tab = created.id, False
|
||||
if payload_get('stay_in_tab') and tab is not None:
|
||||
tab.make_active()
|
||||
return None
|
||||
|
||||
|
||||
detach_window = DetachWindow()
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import DisableLigaturesRCOptions as CLIOptions
|
||||
|
||||
|
||||
class DisableLigatures(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
strategy+/choices.never.always.cursor: One of :code:`never`, :code:`always` or :code:`cursor`
|
||||
match_window/str: Window to change opacity in
|
||||
match_tab/str: Tab to change opacity in
|
||||
all/bool: Boolean indicating operate on all windows
|
||||
"""
|
||||
|
||||
short_desc = 'Control ligature rendering'
|
||||
desc = (
|
||||
'Control ligature rendering for the specified windows/tabs (defaults to active window). The :italic:`STRATEGY`'
|
||||
' can be one of: :code:`never`, :code:`always`, :code:`cursor`.'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--all -a
|
||||
type=bool-set
|
||||
By default, ligatures are only affected in the active window. This option will
|
||||
cause ligatures to be changed in all windows.
|
||||
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
|
||||
)
|
||||
args = RemoteCommand.Args(spec='STRATEGY', count=1, json_field='strategy')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if not args:
|
||||
self.fatal('You must specify the STRATEGY for disabling ligatures, must be one of never, always or cursor')
|
||||
strategy = args[0]
|
||||
if strategy not in ('never', 'always', 'cursor'):
|
||||
self.fatal(f'{strategy} is not a valid disable_ligatures strategy')
|
||||
return {
|
||||
'strategy': strategy,
|
||||
'match_window': opts.match,
|
||||
'match_tab': opts.match_tab,
|
||||
'all': opts.all,
|
||||
}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
windows = self.windows_for_payload(boss, window, payload_get)
|
||||
boss.disable_ligatures_in(windows, payload_get('strategy'))
|
||||
return None
|
||||
|
||||
|
||||
# }}}
|
||||
|
||||
|
||||
disable_ligatures = DisableLigatures()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .base import ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
|
||||
class Env(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
env+/dict.str: Dictionary of environment variables to values. When a env var ends with = it is removed from the environment.
|
||||
"""
|
||||
|
||||
short_desc = 'Change environment variables seen by future children'
|
||||
desc = (
|
||||
'Change the environment variables that will be seen in newly launched windows.'
|
||||
' Similar to the :opt:`env` option in :file:`kitty.conf`, but affects running kitty instances.'
|
||||
' If no = is present, the variable is removed from the environment.'
|
||||
)
|
||||
args = RemoteCommand.Args(spec='env_var1=val env_var2=val ...', minimum_count=1, json_field='env')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: Any, args: ArgsType) -> PayloadType:
|
||||
if len(args) < 1:
|
||||
self.fatal('Must specify at least one env var to set')
|
||||
env = {}
|
||||
for x in args:
|
||||
if '=' in x:
|
||||
key, val = x.split('=', 1)
|
||||
env[key] = val
|
||||
else:
|
||||
env[x + '='] = ''
|
||||
return {'env': env}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
from kitty.child import default_env, set_default_env
|
||||
from kitty.utils import expandvars
|
||||
|
||||
new_env = payload_get('env') or {}
|
||||
env = default_env().copy()
|
||||
for k, v in new_env.items():
|
||||
if k.endswith('='):
|
||||
env.pop(k[:-1], None)
|
||||
else:
|
||||
env[k] = expandvars(v or '', env)
|
||||
set_default_env(env)
|
||||
return None
|
||||
|
||||
|
||||
env = Env()
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import FocusTabRCOptions as CLIOptions
|
||||
|
||||
|
||||
class FocusTab(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: The tab to focus
|
||||
"""
|
||||
|
||||
short_desc = 'Focus the specified tab'
|
||||
desc = 'The active window in the specified tab will be focused.'
|
||||
options_spec = (
|
||||
MATCH_TAB_OPTION
|
||||
+ """
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response indicating the success of the action. Note that
|
||||
using this option means that you will not be notified of failures.
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'no_response': opts.no_response}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
for tab in self.tabs_for_match_payload(boss, window, payload_get):
|
||||
if tab:
|
||||
window = tab.active_window
|
||||
if window:
|
||||
boss.set_active_window(window, switch_os_window_if_needed=True)
|
||||
else:
|
||||
boss.set_active_tab(tab)
|
||||
break
|
||||
return None
|
||||
|
||||
|
||||
focus_tab = FocusTab()
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import FocusWindowRCOptions as CLIOptions
|
||||
|
||||
|
||||
class FocusWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: The window to focus
|
||||
"""
|
||||
|
||||
short_desc = 'Focus the specified window'
|
||||
desc = 'Focus the specified window, if no window is specified, focus the window this command is run inside.'
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n\n
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response from kitty. This means that even if no matching window is found,
|
||||
the command will exit with a success code.
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
boss.set_active_window(window, switch_os_window_if_needed=True)
|
||||
break
|
||||
return None
|
||||
|
||||
|
||||
focus_window = FocusWindow()
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.fast_data_types import Color
|
||||
from kitty.rgb import color_as_sharp, color_from_int
|
||||
from kitty.utils import natsort_ints
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import GetColorsRCOptions as CLIOptions
|
||||
|
||||
|
||||
class GetColors(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: The window to get the colors for
|
||||
configured/bool: Boolean indicating whether to get configured or current colors
|
||||
"""
|
||||
|
||||
short_desc = 'Get terminal colors'
|
||||
desc = (
|
||||
'Get the terminal colors for the specified window (defaults to active window).'
|
||||
' Colors will be output to STDOUT in the same syntax as used for :file:`kitty.conf`.'
|
||||
'\n\nTo get a single color use:'
|
||||
'\n get-colors | grep "^background " | tr -s | cut -d" " -f2'
|
||||
'\n\nChange background above to whatever color you are interested in.'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--configured -c
|
||||
type=bool-set
|
||||
Instead of outputting the colors for the specified window, output the currently
|
||||
configured colors.
|
||||
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'configured': opts.configured, 'match': opts.match}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
from kitty.fast_data_types import get_options
|
||||
|
||||
opts = get_options()
|
||||
ans = {k: getattr(opts, k) for k in opts if isinstance(getattr(opts, k), Color)}
|
||||
if not payload_get('configured'):
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
if windows and windows[0]:
|
||||
for k, v in windows[0].current_colors.items():
|
||||
if v is None:
|
||||
ans.pop(k, None)
|
||||
elif isinstance(v, int):
|
||||
ans[k] = color_from_int(v)
|
||||
tab = windows[0].tabref()
|
||||
tm = None if tab is None else tab.tab_manager_ref()
|
||||
if tm is not None:
|
||||
ans.update(tm.tab_bar.current_colors)
|
||||
all_keys = natsort_ints(ans)
|
||||
maxlen = max(map(len, all_keys))
|
||||
return '\n'.join(('{:%ds} {}' % maxlen).format(key, color_as_sharp(ans[key])) for key in all_keys)
|
||||
|
||||
|
||||
# }}}
|
||||
|
||||
|
||||
get_colors = GetColors()
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import GetTextRCOptions as CLIOptions
|
||||
|
||||
|
||||
class GetText(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: The window to get text from
|
||||
extent/choices.screen.first_cmd_output_on_screen.last_cmd_output.last_visited_cmd_output.\
|
||||
last_non_empty_output.all.selection.alternate.alternate_scrollback: \
|
||||
One of :code:`screen`, :code:`first_cmd_output_on_screen`, :code:`last_cmd_output`, \
|
||||
:code:`last_visited_cmd_output`, :code:`last_non_empty_output`, :code:`all`, \
|
||||
:code:`selection`, :code:`alternate`, or :code:`alternate_scrollback`
|
||||
ansi/bool: Boolean, if True send ANSI formatting codes
|
||||
cursor/bool: Boolean, if True send cursor position/style as ANSI codes
|
||||
wrap_markers/bool: Boolean, if True add wrap markers to output
|
||||
clear_selection/bool: Boolean, if True clear the selection in the matched window
|
||||
self/bool: Boolean, if True use window the command was run in
|
||||
"""
|
||||
|
||||
short_desc = 'Get text from the specified window'
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--extent
|
||||
default=screen
|
||||
choices=screen, all, selection, first_cmd_output_on_screen, last_cmd_output, last_visited_cmd_output, last_non_empty_output, alternate, alternate_scrollback
|
||||
What text to get. The default of :code:`screen` means all text currently on the screen.
|
||||
:code:`all` means all the screen+scrollback and :code:`selection` means the
|
||||
currently selected text. :code:`first_cmd_output_on_screen` means the output of the first
|
||||
command that was run in the window on screen. :code:`last_cmd_output` means
|
||||
the output of the last command that was run in the window. :code:`last_visited_cmd_output` means
|
||||
the first command output below the last scrolled position via scroll_to_prompt.
|
||||
:code:`last_non_empty_output` is the output from the last command run in the window that had
|
||||
some non empty output. The last four require :ref:`shell_integration` to be enabled.
|
||||
:code:`alternate` means the text in the screen that is not currently visible (if the terminal
|
||||
is in the main screen this is the secondary/alternate screen and vice versa).
|
||||
:code:`alternate_scrollback` is the same but also includes the scrollback buffer (if any).
|
||||
|
||||
|
||||
--ansi
|
||||
type=bool-set
|
||||
By default, only plain text is returned. With this flag, the text will
|
||||
include the ANSI formatting escape codes for colors, bold, italic, etc.
|
||||
|
||||
|
||||
--add-cursor
|
||||
type=bool-set
|
||||
Add ANSI escape codes specifying the cursor position and style to the end of the text.
|
||||
|
||||
|
||||
--add-wrap-markers
|
||||
type=bool-set
|
||||
Add carriage returns at every line wrap location (where long lines are wrapped at
|
||||
screen edges).
|
||||
|
||||
|
||||
--clear-selection
|
||||
type=bool-set
|
||||
Clear the selection in the matched window, if any.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Get text from the window this command is run in, rather than the active window.
|
||||
"""
|
||||
)
|
||||
|
||||
field_to_option_map = {'wrap_markers': 'add_wrap_markers', 'cursor': 'add_cursor'}
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {
|
||||
'match': opts.match,
|
||||
'extent': opts.extent,
|
||||
'ansi': opts.ansi,
|
||||
'cursor': opts.add_cursor,
|
||||
'wrap_markers': opts.add_wrap_markers,
|
||||
'clear_selection': opts.clear_selection,
|
||||
'self': opts.self,
|
||||
}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
from kitty.window import CommandOutput
|
||||
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
if windows and windows[0]:
|
||||
window = windows[0]
|
||||
else:
|
||||
return None
|
||||
if payload_get('extent') == 'selection':
|
||||
ans = window.text_for_selection(as_ansi=payload_get('ansi'))
|
||||
elif payload_get('extent') == 'first_cmd_output_on_screen':
|
||||
ans = window.cmd_output(
|
||||
CommandOutput.first_on_screen,
|
||||
as_ansi=bool(payload_get('ansi')),
|
||||
add_wrap_markers=bool(payload_get('wrap_markers')),
|
||||
)
|
||||
elif payload_get('extent') == 'last_cmd_output':
|
||||
ans = window.cmd_output(
|
||||
CommandOutput.last_run,
|
||||
as_ansi=bool(payload_get('ansi')),
|
||||
add_wrap_markers=bool(payload_get('wrap_markers')),
|
||||
)
|
||||
elif payload_get('extent') == 'last_non_empty_output':
|
||||
ans = window.cmd_output(
|
||||
CommandOutput.last_non_empty,
|
||||
as_ansi=bool(payload_get('ansi')),
|
||||
add_wrap_markers=bool(payload_get('wrap_markers')),
|
||||
)
|
||||
elif payload_get('extent') == 'last_visited_cmd_output':
|
||||
ans = window.cmd_output(
|
||||
CommandOutput.last_visited,
|
||||
as_ansi=bool(payload_get('ansi')),
|
||||
add_wrap_markers=bool(payload_get('wrap_markers')),
|
||||
)
|
||||
elif payload_get('extent') in ('alternate', 'alternate_scrollback'):
|
||||
ans = window.as_text(
|
||||
as_ansi=bool(payload_get('ansi')),
|
||||
add_history=payload_get('extent') == 'alternate_scrollback',
|
||||
add_cursor=bool(payload_get('cursor')),
|
||||
add_wrap_markers=bool(payload_get('wrap_markers')),
|
||||
alternate_screen=True,
|
||||
)
|
||||
else:
|
||||
ans = window.as_text(
|
||||
as_ansi=bool(payload_get('ansi')),
|
||||
add_history=payload_get('extent') == 'all',
|
||||
add_cursor=bool(payload_get('cursor')),
|
||||
add_wrap_markers=bool(payload_get('wrap_markers')),
|
||||
)
|
||||
if payload_get('clear_selection'):
|
||||
window.clear_selection()
|
||||
return ans
|
||||
|
||||
|
||||
get_text = GetText()
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, UnknownLayout, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import GotoLayoutRCOptions as CLIOptions
|
||||
|
||||
|
||||
def layout_names() -> Iterable[str]:
|
||||
from kitty.layout.interface import all_layouts
|
||||
|
||||
return all_layouts.keys()
|
||||
|
||||
|
||||
class GotoLayout(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
layout+/str: The new layout name
|
||||
match/str: Which tab to change the layout of
|
||||
"""
|
||||
|
||||
short_desc = 'Set the window layout'
|
||||
desc = (
|
||||
'Set the window layout in the specified tabs (or the active tab if not specified).'
|
||||
' You can use special match value :code:`all` to set the layout in all tabs.'
|
||||
' In case there are multiple layouts with the same name but different options,'
|
||||
' specify the full layout definition or a unique prefix of the full definition.'
|
||||
)
|
||||
options_spec = MATCH_TAB_OPTION
|
||||
args = RemoteCommand.Args(
|
||||
spec='LAYOUT_NAME',
|
||||
count=1,
|
||||
json_field='layout',
|
||||
completion=RemoteCommand.CompletionSpec.from_string('type:keyword group:"Layout" kwds:' + ','.join(layout_names())),
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if len(args) != 1:
|
||||
self.fatal('Exactly one layout must be specified')
|
||||
return {'layout': args[0], 'match': opts.match}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
tabs = self.tabs_for_match_payload(boss, window, payload_get)
|
||||
for tab in tabs:
|
||||
if tab:
|
||||
try:
|
||||
tab.goto_layout(payload_get('layout'), raise_exception=True)
|
||||
except ValueError:
|
||||
raise UnknownLayout('The layout {} is unknown or disabled or the name is ambiguous'.format(payload_get('layout')))
|
||||
return None
|
||||
|
||||
|
||||
goto_layout = GotoLayout()
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import KittenRCOptions as CLIOptions
|
||||
|
||||
|
||||
class Kitten(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
kitten+/str: The name of the kitten to run
|
||||
args/list.str: Arguments to pass to the kitten as a list
|
||||
match/str: The window to run the kitten over
|
||||
"""
|
||||
|
||||
short_desc = 'Run a kitten'
|
||||
desc = (
|
||||
'Run a kitten over the specified windows (active window by default).'
|
||||
' The :italic:`kitten_name` can be either the name of a builtin kitten'
|
||||
' or the path to a Python file containing a custom kitten. If a relative path'
|
||||
' is used it is searched for in the :ref:`kitty config directory <confloc>`. If the kitten is a'
|
||||
' :italic:`no_ui` kitten and its handle response method returns a string or boolean, this'
|
||||
' is printed out to stdout.'
|
||||
)
|
||||
options_spec = MATCH_WINDOW_OPTION
|
||||
args = RemoteCommand.Args(spec='kitten_name', json_field='kitten', minimum_count=1, first_rest=('kitten', 'args'))
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if len(args) < 1:
|
||||
self.fatal('Must specify kitten name')
|
||||
return {'match': opts.match, 'args': list(args)[1:], 'kitten': args[0]}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
retval = None
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
retval = boss.run_kitten_with_metadata(payload_get('kitten'), args=tuple(payload_get('args') or ()), window=window)
|
||||
break
|
||||
if isinstance(retval, (str, bool)):
|
||||
return retval
|
||||
return None
|
||||
|
||||
|
||||
kitten = Kitten()
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import LastUsedLayoutRCOptions as CLIOptions
|
||||
|
||||
|
||||
class LastUsedLayout(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which tab to change the layout of
|
||||
all/bool: Boolean to match all tabs
|
||||
"""
|
||||
|
||||
short_desc = 'Switch to the last used layout'
|
||||
desc = 'Switch to the last used window layout in the specified tabs (or the active tab if not specified).'
|
||||
options_spec = (
|
||||
"""\
|
||||
--all -a
|
||||
type=bool-set
|
||||
Change the layout in all tabs.
|
||||
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response from kitty. This means that even if no matching tab is found,
|
||||
the command will exit with a success code.
|
||||
"""
|
||||
+ '\n\n\n'
|
||||
+ MATCH_TAB_OPTION
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'all': opts.all, 'no_response': opts.no_response}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
for tab in self.tabs_for_match_payload(boss, window, payload_get):
|
||||
if tab:
|
||||
tab.last_used_layout()
|
||||
return None
|
||||
|
||||
|
||||
last_used_layout = LastUsedLayout()
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import os
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.cli_stub import LaunchCLIOptions
|
||||
from kitty.launch import launch as do_launch
|
||||
from kitty.launch import options_spec as launch_options_spec
|
||||
from kitty.launch import parse_launch_args
|
||||
from kitty.types import AsyncResponse
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import LaunchRCOptions as CLIOptions
|
||||
|
||||
|
||||
class Launch(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
args+/list.str: The command line to run in the new window, as a list, use an empty list to run the default shell
|
||||
match/str: The tab to open the new window in
|
||||
next_to/str: The window next to which to create the new window or empty string to use active window
|
||||
source_window/str: The window to use as source for data or empty string to use active window
|
||||
window_title/str: Title for the new window
|
||||
cwd/str: Working directory for the new window
|
||||
add_to_session/str: Session name to add created window/tab to
|
||||
env/list.str: List of environment variables of the form NAME=VALUE
|
||||
var/list.str: List of user variables of the form NAME=VALUE
|
||||
os_panel/list.str: List of panel settings
|
||||
tab_title/str: Title for the new tab
|
||||
type/choices.window.window-dock.tab.tab-dock.os-window.os-panel.overlay.overlay-main.background.clipboard.primary: The type of window to open
|
||||
dock_edge/choices.left.top.right.bottom: The edge at which to place a docked window
|
||||
dock_size/str: The size of a docked window as a number of cells or a percentage
|
||||
dock_skip_focus/bool: Boolean indicating whether the docked window should never get keyboard focus
|
||||
keep_focus/bool: Boolean indicating whether the current window should retain focus or not
|
||||
focus_existing/str: Match expression for an existing window/tab to focus instead of launching
|
||||
copy_colors/bool: Boolean indicating whether to copy the colors from the current window
|
||||
copy_cmdline/bool: Boolean indicating whether to copy the cmdline from the current window
|
||||
copy_env/list.str=copy_local_env: List of strings representing the local env vars
|
||||
hold/bool: Boolean indicating whether to keep window open after cmd exits
|
||||
location/choices.first.after.before.neighbor.last.vsplit.hsplit.split.by-title.default: Where in the tab to open the new window
|
||||
allow_remote_control/bool: Boolean indicating whether to allow remote control from the new window
|
||||
remote_control_password/list.str: A list of remote control passwords
|
||||
stdin_source/choices.none.@selection.@screen.@screen_scrollback.@alternate.@alternate_scrollback.\
|
||||
@first_cmd_output_on_screen.@last_cmd_output.@last_visited_cmd_output: Where to get stdin for the process from
|
||||
stdin_add_formatting/bool: Boolean indicating whether to add formatting codes to stdin
|
||||
stdin_add_line_wrap_markers/bool: Boolean indicating whether to add line wrap markers to stdin
|
||||
spacing/list.str: A list of spacing specifications, see the docs for the set-spacing command
|
||||
marker/str: Specification for marker for new window, for example: "text 1 ERROR"
|
||||
logo/str: Path to window logo
|
||||
logo_position/str: Window logo position as string or empty string to use default
|
||||
logo_alpha/float: Window logo alpha or -1 to use default
|
||||
self/bool: Boolean, if True use tab the command was run in
|
||||
os_window_title/str: Title for OS Window
|
||||
os_window_name/str: WM_NAME for OS Window
|
||||
os_window_class/str: WM_CLASS for OS Window
|
||||
os_window_state/choices.normal.fullscreen.maximized.minimized: The initial state for OS Window
|
||||
os_window_position/str: The position for OS Window
|
||||
color/list.str: list of color specifications such as foreground=red
|
||||
watcher/list.str: list of paths to watcher files
|
||||
bias/float: The bias with which to create the new window in the current layout
|
||||
wait_for_child_to_exit/bool: Boolean indicating whether to wait and return child exit code
|
||||
hold_after_ssh/bool: Boolean indicating whether to run a local shell after exiting the ssh session cloned via cwd=current or similar
|
||||
"""
|
||||
|
||||
short_desc = 'Run an arbitrary process in a new window/tab'
|
||||
desc = (
|
||||
'Prints out the id of the newly opened window. Any command line arguments'
|
||||
' are assumed to be the command line used to run in the new window, if none'
|
||||
' are provided, the default shell is run. For example::\n\n'
|
||||
' kitten @ launch --title=Email mutt'
|
||||
)
|
||||
options_spec = (
|
||||
MATCH_TAB_OPTION
|
||||
+ '\n\n'
|
||||
+ """\
|
||||
--wait-for-child-to-exit
|
||||
type=bool-set
|
||||
Wait until the launched program exits and print out its exit code. The exit code is
|
||||
printed out instead of the window id. If the program exited normally its exit code is printed, which
|
||||
is always greater than or equal to zero. If the program was killed by a signal, the symbolic name
|
||||
of the SIGNAL is printed, if available, otherwise the signal number with a leading minus sign is printed.
|
||||
|
||||
|
||||
--response-timeout
|
||||
type=float
|
||||
default=86400
|
||||
The time in seconds to wait for the started process to exit, when using the :option:`--wait-for-child-to-exit`
|
||||
option. Defaults to one day.
|
||||
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
Do not print out the id of the newly created window.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
If specified the tab containing the window this command is run in is used
|
||||
instead of the active tab
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ launch_options_spec().replace(':option:`launch', ':option:`kitten @ launch')
|
||||
)
|
||||
args = RemoteCommand.Args(
|
||||
spec='[CMD ...]', json_field='args', completion=RemoteCommand.CompletionSpec.from_string('type:special group:cli.CompleteExecutableFirstArg')
|
||||
)
|
||||
is_asynchronous = True
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
ans = {'args': args or []}
|
||||
for attr, val in opts.__dict__.items():
|
||||
ans[attr] = val
|
||||
# ans['wait_for_child_to_exit'] = opts.wait_for_child_to_exit
|
||||
return ans
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
# responder.send_data(getattr(w, 'id', 0))
|
||||
default_opts = parse_launch_args()[0]
|
||||
opts = LaunchCLIOptions()
|
||||
for key, default_value in default_opts.__dict__.items():
|
||||
if key == 'copy_env':
|
||||
continue
|
||||
val = payload_get(key)
|
||||
if val is None:
|
||||
val = default_value
|
||||
setattr(opts, key, val)
|
||||
ceval = payload_get('copy_env')
|
||||
opts.copy_env = False
|
||||
base_env: dict[str, str] | None = None
|
||||
if ceval:
|
||||
if isinstance(ceval, list):
|
||||
base_env = {}
|
||||
for x in ceval:
|
||||
k, v = x.partition('=')[::2]
|
||||
base_env[k] = v
|
||||
elif isinstance(ceval, bool):
|
||||
opts.copy_env = ceval
|
||||
target_tab = None
|
||||
tabs = self.tabs_for_match_payload(boss, window, payload_get)
|
||||
if tabs and tabs[0]:
|
||||
target_tab = tabs[0]
|
||||
|
||||
# Create responder before defining callback to avoid closure issue
|
||||
responder = None
|
||||
if payload_get('wait_for_child_to_exit') and not payload_get('no_response'):
|
||||
responder = self.create_async_responder(payload_get, window)
|
||||
|
||||
def on_child_death(exit_status: int, exc: Exception | None) -> None:
|
||||
code = os.waitstatus_to_exitcode(exit_status)
|
||||
ans = str(code)
|
||||
if code < 0:
|
||||
try:
|
||||
from signal import Signals
|
||||
|
||||
ans = Signals(-code).name
|
||||
except ValueError:
|
||||
pass
|
||||
if responder is not None:
|
||||
responder.send_data(ans)
|
||||
|
||||
w = do_launch(
|
||||
boss,
|
||||
opts,
|
||||
payload_get('args') or [],
|
||||
target_tab=target_tab,
|
||||
rc_from_window=window,
|
||||
base_env=base_env,
|
||||
child_death_callback=on_child_death if payload_get('wait_for_child_to_exit') and not payload_get('no_response') else None,
|
||||
)
|
||||
if payload_get('no_response'):
|
||||
return None
|
||||
|
||||
if not payload_get('wait_for_child_to_exit'):
|
||||
return str(0 if w is None else w.id)
|
||||
|
||||
return AsyncResponse()
|
||||
|
||||
def cancel_async_request(self, boss: 'Boss', window: Window | None, payload_get: PayloadGetType) -> None:
|
||||
pass
|
||||
|
||||
|
||||
launch = Launch()
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.constants import appname
|
||||
|
||||
from .base import (
|
||||
ArgsType,
|
||||
Boss,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import LoadConfigRCOptions as CLIOptions
|
||||
|
||||
|
||||
class LoadConfig(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
paths/list.str: List of config file paths to load
|
||||
override/list.str: List of individual config overrides
|
||||
ignore_overrides/bool: Whether to apply previous overrides
|
||||
"""
|
||||
|
||||
short_desc = '(Re)load a config file'
|
||||
desc = (
|
||||
'(Re)load the specified kitty.conf config files(s). If no files are specified the previously specified config file is reloaded.'
|
||||
' Note that the specified paths must exist and be readable by the kitty process on the computer that process is running on.'
|
||||
' Relative paths are resolved with respect to the kitty config directory on the computer running kitty.'
|
||||
)
|
||||
options_spec = f"""\
|
||||
--ignore-overrides
|
||||
type=bool-set
|
||||
By default, any config overrides previously specified at the kitty invocation command line
|
||||
or a previous load-config-file command are respected. Use this option to have them ignored instead.
|
||||
|
||||
|
||||
--override -o
|
||||
type=list
|
||||
completion=type:special group:complete_kitty_override
|
||||
Override individual configuration options, can be specified multiple times.
|
||||
Syntax: :italic:`name=value`. For example: :option:`{appname} -o` font_size=20
|
||||
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response indicating the success of the action. Note that
|
||||
using this option means that you will not be notified of failures.
|
||||
"""
|
||||
|
||||
args = RemoteCommand.Args(
|
||||
spec='CONF_FILE ...', json_field='paths', completion=RemoteCommand.CompletionSpec.from_string('type:file group:"CONF files", ext:conf')
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'paths': args, 'override': opts.override, 'ignore_overrides': opts.ignore_overrides}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
from kitty.cli import parse_override
|
||||
from kitty.utils import resolve_abs_or_config_path
|
||||
|
||||
paths = tuple(map(resolve_abs_or_config_path, payload_get('paths', missing=())))
|
||||
boss.load_config_file(
|
||||
*paths,
|
||||
apply_overrides=not payload_get('ignore_overrides', missing=False),
|
||||
overrides=tuple(map(parse_override, payload_get('override', missing=()))),
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
load_config = LoadConfig()
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.constants import appname
|
||||
|
||||
from .base import MATCH_TAB_OPTION, MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Tab, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import LSRCOptions as CLIOptions
|
||||
|
||||
|
||||
class LS(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
all_env_vars/bool: Whether to send all environment variables for every window rather than just differing ones
|
||||
match/str: Window to change colors in
|
||||
match_tab/str: Tab to change colors in
|
||||
self/bool: Boolean indicating whether to list only the window the command is run in
|
||||
output_format/str: Output in json or session format
|
||||
"""
|
||||
|
||||
short_desc = 'List tabs/windows'
|
||||
desc = (
|
||||
'List windows. The list is returned as JSON tree. The top-level is a list of'
|
||||
f' operating system {appname} windows. Each OS window has an :italic:`id` and a list'
|
||||
' of :italic:`tabs`. Each tab has its own :italic:`id`, a :italic:`title` and a list of :italic:`windows`.'
|
||||
' Each window has an :italic:`id`, :italic:`title`, :italic:`current working directory`, :italic:`process id (PID)`,'
|
||||
' :italic:`command-line` and :italic:`environment` of the process running in the window. Additionally, when'
|
||||
' running the command inside a kitty window, that window can be identified by the :italic:`is_self` parameter.\n\n'
|
||||
'You can use these criteria to select windows/tabs for the other commands.\n\n'
|
||||
'You can limit the windows/tabs in the output by using the :option:`--match` and :option:`--match-tab` options.'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--all-env-vars
|
||||
type=bool-set
|
||||
Show all environment variables in output, not just differing ones.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Only list the window this command is run in.
|
||||
|
||||
|
||||
--output-format
|
||||
type=choices
|
||||
choices=json,session
|
||||
default=json
|
||||
Output in JSON or kitty session format
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t', 1)
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {
|
||||
'all_env_vars': opts.all_env_vars,
|
||||
'match': opts.match,
|
||||
'match_tab': opts.match_tab,
|
||||
'self': opts.self,
|
||||
'output_format': opts.output_format,
|
||||
}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
tab_filter: Callable[[Tab], bool] | None = None
|
||||
window_filter: Callable[[Window], bool] | None = None
|
||||
|
||||
if payload_get('self'):
|
||||
|
||||
def wf(w: Window) -> bool:
|
||||
return w is window
|
||||
|
||||
window_filter = wf
|
||||
elif payload_get('match') is not None or payload_get('match_tab') is not None:
|
||||
window_ids = frozenset(w.id for w in self.windows_for_payload(boss, window, payload_get, window_match_name='match'))
|
||||
|
||||
def wf(w: Window) -> bool:
|
||||
return w.id in window_ids
|
||||
|
||||
window_filter = wf
|
||||
elif payload_get('output_format') == 'session':
|
||||
return '\n'.join(boss.serialize_state_as_session())
|
||||
|
||||
data = list(boss.list_os_windows(window, tab_filter, window_filter))
|
||||
if not payload_get('all_env_vars'):
|
||||
all_env_blocks: list[dict[str, str]] = []
|
||||
common_env_vars: set[tuple[str, str]] = set()
|
||||
for osw in data:
|
||||
for tab in osw.get('tabs', ()):
|
||||
for w in tab.get('windows', ()):
|
||||
env: dict[str, str] = w.get('env', {})
|
||||
frozen_env = set(env.items())
|
||||
if all_env_blocks:
|
||||
common_env_vars &= frozen_env
|
||||
else:
|
||||
common_env_vars = frozen_env
|
||||
all_env_blocks.append(env)
|
||||
if common_env_vars and len(all_env_blocks) > 1:
|
||||
remove_env_vars = {k for k, v in common_env_vars}
|
||||
for env in all_env_blocks:
|
||||
for r in remove_env_vars:
|
||||
env.pop(r, None)
|
||||
return json.dumps(data, indent=2, sort_keys=True)
|
||||
|
||||
|
||||
ls = LS()
|
||||
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import NewWindowRCOptions as CLIOptions
|
||||
|
||||
|
||||
class NewWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
args+/list.str: The command line to run in the new window, as a list, use an empty list to run the default shell
|
||||
match/str: The tab to open the new window in
|
||||
title/str: Title for the new window
|
||||
cwd/str: Working directory for the new window
|
||||
keep_focus/bool: Boolean indicating whether the current window should retain focus or not
|
||||
window_type/choices.kitty.os: One of :code:`kitty` or :code:`os`
|
||||
new_tab/bool: Boolean indicating whether to open a new tab
|
||||
tab_title/str: Title for the new tab
|
||||
"""
|
||||
|
||||
short_desc = 'Open new window'
|
||||
desc = (
|
||||
'DEPRECATED: Use the :ref:`launch <at-launch>` command instead.\n\n'
|
||||
'Open a new window in the specified tab. If you use the :option:`kitten @ new-window --match` option'
|
||||
' the first matching tab is used. Otherwise the currently active tab is used.'
|
||||
' Prints out the id of the newly opened window'
|
||||
' (unless :option:`--no-response` is used). Any command line arguments'
|
||||
' are assumed to be the command line used to run in the new window, if none'
|
||||
' are provided, the default shell is run. For example::\n\n'
|
||||
' kitten @ new-window --title Email mutt'
|
||||
)
|
||||
options_spec = (
|
||||
MATCH_TAB_OPTION
|
||||
+ """\n
|
||||
--title
|
||||
The title for the new window. By default it will use the title set by the
|
||||
program running in it.
|
||||
|
||||
|
||||
--cwd
|
||||
The initial working directory for the new window. Defaults to whatever
|
||||
the working directory for the kitty process you are talking to is.
|
||||
|
||||
|
||||
--keep-focus --dont-take-focus
|
||||
type=bool-set
|
||||
Keep the current window focused instead of switching to the newly opened window.
|
||||
|
||||
|
||||
--window-type
|
||||
default=kitty
|
||||
choices=kitty,os
|
||||
What kind of window to open. A kitty window or a top-level OS window.
|
||||
|
||||
|
||||
--new-tab
|
||||
type=bool-set
|
||||
Open a new tab.
|
||||
|
||||
|
||||
--tab-title
|
||||
Set the title of the tab, when open a new tab.
|
||||
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response giving the id of the newly opened window. Note that
|
||||
using this option means that you will not be notified of failures and that
|
||||
the id of the new window will not be printed out.
|
||||
"""
|
||||
)
|
||||
args = RemoteCommand.Args(spec='[CMD ...]', json_field='args')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
ans = {'args': args or [], 'type': 'window'}
|
||||
for attr, val in opts.__dict__.items():
|
||||
if attr == 'new_tab':
|
||||
if val:
|
||||
ans['type'] = 'tab'
|
||||
elif attr == 'window_type':
|
||||
if val == 'os' and ans['type'] != 'tab':
|
||||
ans['type'] = 'os-window'
|
||||
else:
|
||||
ans[attr] = val
|
||||
return ans
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
from .launch import launch
|
||||
|
||||
return launch.response_from_kitty(boss, window, payload_get)
|
||||
|
||||
|
||||
new_window = NewWindow()
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import RemoveMarkerRCOptions as CLIOptions
|
||||
|
||||
|
||||
class RemoveMarker(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which window to remove the marker from
|
||||
self/bool: Boolean indicating whether to detach the window the command is run in
|
||||
"""
|
||||
|
||||
short_desc = 'Remove the currently set marker, if any.'
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--self
|
||||
type=bool-set
|
||||
Apply marker to the window this command is run in, rather than the active window.
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'self': opts.self}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
window.remove_marker()
|
||||
return None
|
||||
|
||||
|
||||
remove_marker = RemoveMarker()
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import (
|
||||
MATCH_WINDOW_OPTION,
|
||||
ArgsType,
|
||||
Boss,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
RemoteControlErrorWithoutTraceback,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import ResizeOSWindowRCOptions as CLIOptions
|
||||
|
||||
|
||||
class ResizeOSWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which window to resize
|
||||
self/bool: Boolean indicating whether to close the window the command is run in
|
||||
incremental/bool: Boolean indicating whether to adjust the size incrementally
|
||||
action/choices.resize.toggle-fullscreen.toggle-maximized.toggle-visibility.hide.show.os-panel: The action to perform
|
||||
unit/choices.cells.pixels: One of :code:`cells` or :code:`pixels`
|
||||
width/int: Integer indicating desired window width
|
||||
height/int: Integer indicating desired window height
|
||||
os_panel/list.str: Settings for modifying the OS Panel
|
||||
"""
|
||||
|
||||
short_desc = 'Resize/show/hide/etc. the specified OS Windows'
|
||||
desc = (
|
||||
'Resize (or other operations) on the specified OS Windows.'
|
||||
' Note that some window managers/environments do not allow applications to resize'
|
||||
' their windows, for example, tiling window managers.\n\nTo modify OS Panels created with the'
|
||||
' panel kitten, use :option:`--action`=:code:`os-panel`. Specify the modifications in the same syntax as used'
|
||||
' by the panel kitten, without the leading dashes. Use the :option:`--incremental` option to only change'
|
||||
' the specified panel settings. For example, move the panel to bottom edge and make it two lines tall:'
|
||||
' :code:`--action=os-panel --incremental lines=2 edge=bottom`'
|
||||
)
|
||||
args = RemoteCommand.Args(spec='[OS Panel settings ...]', json_field='os_panel', special_parse='escape_list_of_strings(args), nil')
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--action
|
||||
default=resize
|
||||
choices=resize,toggle-fullscreen,toggle-maximized,toggle-visibility,hide,show,os-panel
|
||||
The action to perform.
|
||||
|
||||
|
||||
--unit
|
||||
default=cells
|
||||
choices=cells,pixels
|
||||
The unit in which to interpret specified sizes.
|
||||
|
||||
|
||||
--width
|
||||
default=0
|
||||
type=int
|
||||
Change the width of the window. Zero leaves the width unchanged.
|
||||
|
||||
|
||||
--height
|
||||
default=0
|
||||
type=int
|
||||
Change the height of the window. Zero leaves the height unchanged.
|
||||
|
||||
|
||||
--incremental
|
||||
type=bool-set
|
||||
Treat the specified sizes as increments on the existing window size
|
||||
instead of absolute sizes. When using :option:`--action`=:code:`os-panel`,
|
||||
only the specified settings are changed, otherwise non-specified settings
|
||||
keep their current value.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Resize the window this command is run in, rather than the active window.
|
||||
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response indicating the success of the action. Note that
|
||||
using this option means that you will not be notified of failures.
|
||||
"""
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {
|
||||
'match': opts.match,
|
||||
'action': opts.action,
|
||||
'unit': opts.unit,
|
||||
'width': opts.width,
|
||||
'height': opts.height,
|
||||
'self': opts.self,
|
||||
'incremental': opts.incremental,
|
||||
'os_panel': args,
|
||||
}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
from kitty.fast_data_types import (
|
||||
get_os_window_size,
|
||||
layer_shell_config_for_os_window,
|
||||
set_layer_shell_config,
|
||||
toggle_fullscreen,
|
||||
toggle_os_window_visibility,
|
||||
)
|
||||
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
if windows:
|
||||
ac = payload_get('action')
|
||||
for os_window_id in {w.os_window_id for w in windows if w}:
|
||||
metrics = get_os_window_size(os_window_id)
|
||||
if metrics is None:
|
||||
raise RemoteControlErrorWithoutTraceback(f'The OS Window {os_window_id} does not exist')
|
||||
panels = payload_get('os_panel')
|
||||
is_panel = metrics['is_layer_shell']
|
||||
if ac == 'os-panel':
|
||||
if not is_panel:
|
||||
raise RemoteControlErrorWithoutTraceback(
|
||||
f'The OS Window {os_window_id} is not a panel you should not use the --action=resize option to resize it'
|
||||
)
|
||||
if not panels:
|
||||
raise RemoteControlErrorWithoutTraceback('Must specify at least one panel setting')
|
||||
if payload_get('incremental'):
|
||||
existing = layer_shell_config_for_os_window(os_window_id)
|
||||
if existing is None:
|
||||
raise RemoteControlErrorWithoutTraceback(f'The OS Window {os_window_id} has no panel configuration')
|
||||
from kittens.panel.main import incrementally_update_layer_shell_config
|
||||
|
||||
try:
|
||||
lsc = incrementally_update_layer_shell_config(existing, panels)
|
||||
except Exception as e:
|
||||
raise RemoteControlErrorWithoutTraceback(str(e))
|
||||
else:
|
||||
from kitty.launch import layer_shell_config_from_panel_opts
|
||||
|
||||
try:
|
||||
lsc = layer_shell_config_from_panel_opts(panels)
|
||||
except Exception as e:
|
||||
raise RemoteControlErrorWithoutTraceback(f'Invalid panel options specified: {e}')
|
||||
if not set_layer_shell_config(os_window_id, lsc):
|
||||
raise RemoteControlErrorWithoutTraceback(f'Failed to change panel configuration for OS Window {os_window_id}')
|
||||
elif ac == 'toggle-visibility':
|
||||
toggle_os_window_visibility(os_window_id)
|
||||
elif ac == 'hide':
|
||||
toggle_os_window_visibility(os_window_id, False)
|
||||
elif ac == 'show':
|
||||
toggle_os_window_visibility(os_window_id, True)
|
||||
elif ac == 'toggle-fullscreen':
|
||||
if not toggle_fullscreen(os_window_id):
|
||||
raise RemoteControlErrorWithoutTraceback(f'The OS Window {os_window_id} is a desktop panel that cannot be made fullscreen')
|
||||
elif is_panel:
|
||||
raise RemoteControlErrorWithoutTraceback(
|
||||
f'The OS Window {os_window_id} is a desktop panel, no actions other than resizing are supported for it'
|
||||
)
|
||||
elif ac == 'resize':
|
||||
boss.resize_os_window(
|
||||
os_window_id,
|
||||
width=payload_get('width'),
|
||||
height=payload_get('height'),
|
||||
unit=payload_get('unit'),
|
||||
incremental=payload_get('incremental'),
|
||||
metrics=metrics,
|
||||
)
|
||||
elif ac == 'toggle-maximized':
|
||||
boss.toggle_maximized(os_window_id)
|
||||
return None
|
||||
|
||||
|
||||
resize_os_window = ResizeOSWindow()
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from math import isfinite
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import ResizeWindowRCOptions as CLIOptions
|
||||
|
||||
|
||||
class ResizeWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which window to resize
|
||||
self/bool: Boolean indicating whether to resize the window the command is run in
|
||||
increment/int: Integer specifying the resize increment
|
||||
fraction/float: Fraction of the remaining resize steps to take, or zero for ordinary resizing
|
||||
axis/choices.horizontal.vertical.reset: One of :code:`horizontal, vertical` or :code:`reset`
|
||||
restore_entry_layout/bool: Restore an existing interactive Splits resize session on reset
|
||||
"""
|
||||
|
||||
short_desc = 'Resize the specified windows'
|
||||
desc = 'Resize the specified windows in the current layout. Note that not all layouts can resize all windows in all directions.'
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--increment -i
|
||||
type=int
|
||||
default=2
|
||||
The number of cells to change the size by, can be negative to decrease the size.
|
||||
|
||||
|
||||
--fraction
|
||||
type=float
|
||||
default=0
|
||||
Take this fraction of the remaining resize steps, rounding up. Must be between
|
||||
zero and one. Zero uses ordinary resizing. The increment sets the base step size.
|
||||
|
||||
|
||||
--axis -a
|
||||
type=choices
|
||||
choices=horizontal,vertical,reset
|
||||
default=horizontal
|
||||
The axis along which to resize. If :code:`horizontal`,
|
||||
it will make the window wider or narrower by the specified increment.
|
||||
If :code:`vertical`, it will make the window taller or shorter by the specified increment.
|
||||
The special value :code:`reset` will reset the layout to its default configuration.
|
||||
|
||||
|
||||
--restore-entry-layout
|
||||
type=bool-set
|
||||
With :code:`--axis=reset`, restore the proportions saved by the interactive
|
||||
resize page in Splits. When there is no such session, keep the default reset.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Resize the window this command is run in, rather than the active window.
|
||||
"""
|
||||
)
|
||||
string_return_is_error = True
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
self.validate_fraction(opts.fraction)
|
||||
return {
|
||||
'match': opts.match,
|
||||
'increment': opts.increment,
|
||||
'axis': opts.axis,
|
||||
'self': opts.self,
|
||||
'fraction': opts.fraction,
|
||||
'restore_entry_layout': opts.restore_entry_layout,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def validate_fraction(fraction: float) -> None:
|
||||
if not isfinite(fraction) or not 0 <= fraction <= 1:
|
||||
raise ValueError('Resize fraction must be between zero and one')
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
fraction = payload_get('fraction', missing=0)
|
||||
self.validate_fraction(fraction)
|
||||
resized: bool | None | str = False
|
||||
if windows and windows[0]:
|
||||
if payload_get('axis') == 'reset' and payload_get('restore_entry_layout', missing=False):
|
||||
from .resize_window_edge import resize_window_edge
|
||||
|
||||
err = resize_window_edge.restore_session(windows[0])
|
||||
if err is not None:
|
||||
return err or None
|
||||
resized = boss.resize_layout_window(
|
||||
windows[0],
|
||||
increment=payload_get('increment'),
|
||||
is_horizontal=payload_get('axis') == 'horizontal',
|
||||
reset=payload_get('axis') == 'reset',
|
||||
fraction=fraction,
|
||||
)
|
||||
return resized
|
||||
|
||||
|
||||
resize_window = ResizeWindow()
|
||||
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
from kitty.layout.splits import Pair, Splits
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
from .resize_window import resize_window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import ResizeWindowEdgeRCOptions as CLIOptions
|
||||
|
||||
|
||||
@dataclass
|
||||
class EdgeResizeSession:
|
||||
# None when resize mode opened in a layout other than Splits
|
||||
layout: Splits | None
|
||||
biases: tuple[tuple[Pair, float], ...]
|
||||
topology: tuple[tuple[int, bool, int, int], ...]
|
||||
selected: str = ''
|
||||
divider: Pair | None = None
|
||||
horizontal: bool | None = None
|
||||
|
||||
|
||||
def topology(layout: Splits) -> tuple[tuple[int, bool, int, int], ...]:
|
||||
def child_id(child: Pair | int | None) -> int:
|
||||
return id(child) if isinstance(child, Pair) else child or 0
|
||||
|
||||
return tuple((id(p), p.horizontal, child_id(p.one), child_id(p.two)) for p in layout.pairs_root.self_and_descendants())
|
||||
|
||||
|
||||
class ResizeWindowEdge(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: Which pane or resize overlay to use
|
||||
self/bool: Use the window in which this command is run
|
||||
operation/choices.start.state.select.move.reset: The resize session operation
|
||||
edge/choices.none.left.right.top.bottom: The edge to select or move
|
||||
increment/int: Number of cells to move, positive rightwards or downwards
|
||||
fraction/float: Fraction of remaining steps, or zero for ordinary steps
|
||||
divider/str: Optional divider identity returned by selection
|
||||
"""
|
||||
short_desc = 'Select and move an internal pane edge in the Splits layout'
|
||||
desc = (
|
||||
'Move a specific internal pane edge, keeping other same-axis dividers in place.'
|
||||
' Positive increments move rightwards or downwards; negative increments move leftwards or upwards.'
|
||||
' The resize-window kitten uses this command for its edge strategy.'
|
||||
' Start opens a session; reset restores its original divider proportions if the split structure has not changed.'
|
||||
)
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--operation
|
||||
type=choices
|
||||
choices=start,state,select,move,reset
|
||||
default=move
|
||||
Select a session operation. Start creates a session if needed, preserving an
|
||||
existing snapshot, and automatically selects a sole internal edge. State lists
|
||||
internal edges and clears the selection; select chooses an edge without moving
|
||||
it; move adjusts an edge; reset restores the session's original proportions.
|
||||
|
||||
|
||||
--edge
|
||||
type=choices
|
||||
choices=none,left,right,top,bottom
|
||||
default=none
|
||||
The pane edge. Outside edges cannot be selected or moved.
|
||||
|
||||
|
||||
--increment -i
|
||||
type=int
|
||||
default=2
|
||||
Number of cells to move the divider. Can be negative.
|
||||
|
||||
|
||||
--fraction
|
||||
type=float
|
||||
default=0
|
||||
Take this fraction of the remaining resize steps, rounding up. Zero uses an
|
||||
ordinary step. Must be between zero and one.
|
||||
|
||||
|
||||
--divider
|
||||
default=
|
||||
Only move the divider with this identity, as returned by select.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Use the window this command is run in, rather than the active window.
|
||||
"""
|
||||
)
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
# Each overlay has its own snapshot, released when that overlay closes.
|
||||
self.sessions: WeakKeyDictionary[Window, EdgeResizeSession] = WeakKeyDictionary()
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
resize_window.validate_fraction(opts.fraction)
|
||||
return {name: getattr(opts, name) for name in ('match', 'self', 'operation', 'edge', 'increment', 'fraction', 'divider')}
|
||||
|
||||
def start_session(self, window: Window, layout: object, existing: EdgeResizeSession | None = None) -> EdgeResizeSession:
|
||||
if existing is not None:
|
||||
session = existing
|
||||
session.selected, session.divider = '', None
|
||||
elif isinstance(layout, Splits):
|
||||
session = EdgeResizeSession(layout, tuple((p, p.bias) for p in layout.pairs_root.self_and_descendants()), topology(layout))
|
||||
else:
|
||||
# Record that there is no snapshot, so that one is not taken later
|
||||
# from sizes that may already have been changed.
|
||||
session = EdgeResizeSession(None, (), ())
|
||||
self.sessions[window] = session
|
||||
return session
|
||||
|
||||
def restore_session(self, window: Window) -> str | None:
|
||||
"""Restore the sizes from when resize mode opened, returning an error message, empty on success.
|
||||
Returns None when there is no snapshot for the current layout."""
|
||||
session = self.sessions.get(window)
|
||||
tab = window.tabref()
|
||||
if session is None or session.layout is None or tab is None or tab.current_layout is not session.layout:
|
||||
return None
|
||||
session.selected, session.divider = '', None
|
||||
if topology(session.layout) != session.topology:
|
||||
return 'Split structure changed; original sizes cannot be restored'
|
||||
for pair, bias in session.biases:
|
||||
pair.bias = bias
|
||||
tab.relayout()
|
||||
return ''
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
window = windows[0] if windows else None
|
||||
if window is None or (tab := window.tabref()) is None:
|
||||
raise ValueError('Window no longer exists')
|
||||
operation = payload_get('operation')
|
||||
edge = payload_get('edge')
|
||||
fraction = payload_get('fraction')
|
||||
resize_window.validate_fraction(fraction)
|
||||
if operation not in ('start', 'state', 'select', 'move', 'reset') or edge not in ('none', 'left', 'right', 'top', 'bottom'):
|
||||
raise ValueError('Invalid edge resize operation')
|
||||
layout = tab.current_layout
|
||||
if not isinstance(layout, Splits):
|
||||
return json.dumps({'edges': [], 'selected': '', 'divider': '', 'status': 'Edge resizing requires the Splits layout', 'failed': True})
|
||||
session = self.sessions.get(window)
|
||||
if session is None:
|
||||
# Used directly rather than from a resize overlay
|
||||
session = self.start_session(window, layout)
|
||||
status, failed = '', True
|
||||
if operation == 'reset':
|
||||
err = self.restore_session(window)
|
||||
if err is None:
|
||||
# No snapshot from when resize mode opened in this layout
|
||||
tab.reset_window_sizes()
|
||||
session.selected, session.divider = '', None
|
||||
status, failed = 'Reset to default sizes', False
|
||||
else:
|
||||
status, failed = (err, True) if err else ('Restored sizes from when resize mode opened', False)
|
||||
elif operation == 'state':
|
||||
session.selected, session.divider = '', None
|
||||
elif operation in ('select', 'move'):
|
||||
pair = layout.pair_for_window_edge(tab.windows, window.id, edge)
|
||||
if pair is None:
|
||||
session.selected, session.divider = '', None
|
||||
status = 'Outside edge: choose an internal edge'
|
||||
elif operation == 'select':
|
||||
session.selected, session.divider = edge, pair
|
||||
session.horizontal = pair.horizontal
|
||||
elif (token := payload_get('divider')) and (token != str(id(pair)) or session.divider is not pair or session.horizontal != pair.horizontal):
|
||||
session.selected, session.divider = '', None
|
||||
status = 'Layout changed; choose an edge again'
|
||||
else:
|
||||
session.selected, session.divider = edge, pair
|
||||
session.horizontal = pair.horizontal
|
||||
if layout.modify_size_of_window_edge(tab.windows, window.id, edge, payload_get('increment'), fraction):
|
||||
tab.relayout()
|
||||
else:
|
||||
status = 'At size limit; move the other way'
|
||||
edges = [e for e in ('left', 'bottom', 'top', 'right') if layout.pair_for_window_edge(tab.windows, window.id, e) is not None]
|
||||
if operation == 'start':
|
||||
session.selected, session.divider = '', None
|
||||
if len(edges) == 1:
|
||||
session.selected = edges[0]
|
||||
session.divider = layout.pair_for_window_edge(tab.windows, window.id, edges[0])
|
||||
assert session.divider is not None
|
||||
session.horizontal = session.divider.horizontal
|
||||
return json.dumps(
|
||||
{
|
||||
'edges': edges,
|
||||
'selected': session.selected,
|
||||
'divider': str(id(session.divider)) if session.divider is not None else '',
|
||||
'status': status,
|
||||
'failed': failed and bool(status),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
resize_window_edge = ResizeWindowEdge()
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from base64 import standard_b64decode, standard_b64encode
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.launch import env_docs, remote_control_password_docs
|
||||
from kitty.options.utils import env as parse_env
|
||||
from kitty.types import AsyncResponse
|
||||
|
||||
from .base import (
|
||||
ArgsType,
|
||||
Boss,
|
||||
ParsingOfArgsFailed,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import RunRCOptions as CLIOptions
|
||||
|
||||
|
||||
class Run(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
data+/str: Chunk of STDIN data, base64 encoded no more than 4096 bytes. Must send an empty chunk to indicate end of data.
|
||||
cmdline+/list.str: The command line to run
|
||||
env/list.str: List of environment variables of the form NAME=VALUE
|
||||
allow_remote_control/bool: A boolean indicating whether to allow remote control
|
||||
remote_control_password/list.str: A list of remote control passwords
|
||||
"""
|
||||
|
||||
short_desc = 'Run a program on the computer in which kitty is running and get the output'
|
||||
desc = (
|
||||
'Run the specified program on the computer in which kitty is running. When STDIN is not a TTY it is forwarded'
|
||||
' to the program as its STDIN. STDOUT and STDERR from the the program are forwarded here. The exit status of this'
|
||||
' invocation will be the exit status of the executed program. If you wish to just run a program without waiting for a response, '
|
||||
' use @ launch --type=background instead.'
|
||||
)
|
||||
|
||||
options_spec = f"""\n
|
||||
--env
|
||||
{env_docs}
|
||||
|
||||
|
||||
--allow-remote-control
|
||||
type=bool-set
|
||||
The executed program will have privileges to run remote control commands in kitty.
|
||||
|
||||
|
||||
--remote-control-password
|
||||
{remote_control_password_docs}
|
||||
"""
|
||||
args = RemoteCommand.Args(
|
||||
spec='CMD ...',
|
||||
json_field='data',
|
||||
special_parse='+cmdline:!read_run_data(io_data, args, &payload)',
|
||||
minimum_count=1,
|
||||
completion=RemoteCommand.CompletionSpec.from_string('type:special group:cli.CompleteExecutableFirstArg'),
|
||||
)
|
||||
reads_streaming_data = True
|
||||
is_asynchronous = True
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if not args:
|
||||
self.fatal('Must specify command to run')
|
||||
import secrets
|
||||
|
||||
ret = {
|
||||
'stream_id': secrets.token_urlsafe(),
|
||||
'cmdline': args,
|
||||
'env': opts.env,
|
||||
'allow_remote_control': opts.allow_remote_control,
|
||||
'remote_control_password': opts.remote_control_password,
|
||||
'data': '',
|
||||
}
|
||||
|
||||
# This is only used for remote_control mappings, where there is no
|
||||
# meaningful STDIN to forward (the kitten @ client is implemented in Go)
|
||||
return ret
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
data = payload_get('data')
|
||||
q = self.handle_streamed_data(standard_b64decode(data) if data else b'', payload_get)
|
||||
if isinstance(q, AsyncResponse):
|
||||
return q
|
||||
stdin_data = q.getvalue()
|
||||
from kitty.launch import parse_remote_control_passwords
|
||||
|
||||
cmdline = payload_get('cmdline')
|
||||
allow_remote_control = payload_get('allow_remote_control')
|
||||
pw = payload_get('remote_control_password')
|
||||
rcp = parse_remote_control_passwords(allow_remote_control, pw)
|
||||
if not cmdline:
|
||||
raise ParsingOfArgsFailed('No cmdline to run specified')
|
||||
responder = self.create_async_responder(payload_get, window)
|
||||
stdout, stderr = tempfile.TemporaryFile(), tempfile.TemporaryFile()
|
||||
|
||||
def on_death(exit_status: int, err: Exception | None) -> None:
|
||||
with stdout, stderr:
|
||||
if err:
|
||||
responder.send_error(f'Failed to run: {cmdline} with err: {err}')
|
||||
else:
|
||||
exit_code = os.waitstatus_to_exitcode(exit_status)
|
||||
stdout.seek(0)
|
||||
stderr.seek(0)
|
||||
responder.send_data(
|
||||
{
|
||||
'stdout': standard_b64encode(stdout.read()).decode('ascii'),
|
||||
'stderr': standard_b64encode(stderr.read()).decode('ascii'),
|
||||
'exit_code': exit_code,
|
||||
'exit_status': exit_status,
|
||||
}
|
||||
)
|
||||
|
||||
env: dict[str, str] = {}
|
||||
for x in payload_get('env') or ():
|
||||
for k, v in parse_env(x, env):
|
||||
env[k] = v
|
||||
|
||||
boss.run_background_process(
|
||||
cmdline,
|
||||
env=env,
|
||||
stdin=stdin_data,
|
||||
stdout=stdout.fileno(),
|
||||
stderr=stderr.fileno(),
|
||||
notify_on_death=on_death,
|
||||
remote_control_passwords=rcp,
|
||||
allow_remote_control=allow_remote_control,
|
||||
)
|
||||
return AsyncResponse()
|
||||
|
||||
|
||||
run = Run()
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2024, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
from base64 import standard_b64encode
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.fast_data_types import png_from_32bit_rgba_data
|
||||
from kitty.types import AsyncResponse
|
||||
|
||||
from .base import (
|
||||
MATCH_TAB_OPTION,
|
||||
MATCH_WINDOW_OPTION,
|
||||
ArgsType,
|
||||
Boss,
|
||||
MatchError,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
RemoteControlErrorWithoutTraceback,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import ScreenshotRCOptions as CLIOptions
|
||||
|
||||
|
||||
class Screenshot(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: The window to screenshot
|
||||
match_tab/str: The tab to screenshot
|
||||
output_path/str: Path to save the PNG image to, on the computer kitty is running on. Empty to return the image data instead.
|
||||
"""
|
||||
|
||||
short_desc = 'Take a screenshot of a kitty OS window, tab or window'
|
||||
desc = (
|
||||
'Take a screenshot, as a PNG image, of an entire kitty OS window. Restrict the screenshot to a single'
|
||||
' kitty window or tab with :option:`--match`/:option:`--match-tab`. The specified window/tab must be'
|
||||
' currently visible, i.e. it must be in the active tab of its OS window and, in the case of a window,'
|
||||
' not hidden behind another window by the layout, otherwise this command will fail.\n\n'
|
||||
'By default, the PNG image data is written to STDOUT. If instead a file path is specified, kitty itself'
|
||||
' (rather than this :program:`kitten` process) saves the screenshot to that path. Since kitty and the'
|
||||
' kitten are typically running on the same computer, this avoids copying the (potentially large)'
|
||||
' image data over the possibly slow remote control transport.'
|
||||
)
|
||||
options_spec = MATCH_WINDOW_OPTION + '\n\n' + MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
|
||||
args = RemoteCommand.Args(
|
||||
spec='[OUTPUT_FILE]',
|
||||
json_field='output_path',
|
||||
special_parse='!read_screenshot_args(io_data, args)',
|
||||
completion=RemoteCommand.CompletionSpec.from_string('type:file ext:png'),
|
||||
)
|
||||
is_asynchronous = True
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if len(args) > 1:
|
||||
self.fatal('Must specify at most one output file')
|
||||
return {
|
||||
'match': opts.match,
|
||||
'match_tab': opts.match_tab,
|
||||
'output_path': args[0] if args else '',
|
||||
}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
match = payload_get('match')
|
||||
match_tab = payload_get('match_tab')
|
||||
target_window_id = 0
|
||||
include_tab_bar = False
|
||||
|
||||
if match:
|
||||
windows = list(boss.match_windows(match, window))
|
||||
if not windows:
|
||||
raise MatchError(match)
|
||||
w = windows[0]
|
||||
tab = w.tabref()
|
||||
tm = tab.tab_manager_ref() if tab is not None else None
|
||||
if tab is None or tm is None or tm.active_tab is not tab or not w.is_visible_in_layout:
|
||||
raise RemoteControlErrorWithoutTraceback('The matched window is not currently visible, screenshots can only be taken of visible windows')
|
||||
os_window_id = w.os_window_id
|
||||
target_window_id = w.id
|
||||
elif match_tab:
|
||||
tabs = list(boss.match_tabs(match_tab))
|
||||
if not tabs:
|
||||
raise MatchError(match_tab, 'tabs')
|
||||
tab = tabs[0]
|
||||
tm = tab.tab_manager_ref()
|
||||
if tm is None or tm.active_tab is not tab:
|
||||
raise RemoteControlErrorWithoutTraceback('The matched tab is not currently visible, screenshots can only be taken of visible tabs')
|
||||
os_window_id = tab.os_window_id
|
||||
else:
|
||||
atm = boss.active_tab_manager
|
||||
if atm is None:
|
||||
raise RemoteControlErrorWithoutTraceback('There is no active OS window to screenshot')
|
||||
os_window_id = atm.os_window_id
|
||||
include_tab_bar = True
|
||||
|
||||
output_path = payload_get('output_path') or ''
|
||||
responder = self.create_async_responder(payload_get, window)
|
||||
|
||||
def callback(cb_os_window_id: int, cb_window_id: int, pixels: bytes, width: int, height: int) -> None:
|
||||
if not pixels:
|
||||
responder.send_error('Failed to take screenshot, the OS window may have been closed')
|
||||
return
|
||||
try:
|
||||
png_data = png_from_32bit_rgba_data(pixels, width, height, True)
|
||||
if output_path:
|
||||
with open(os.path.expanduser(output_path), 'wb') as f:
|
||||
f.write(png_data)
|
||||
responder.send_data(f'Screenshot saved to: {os.path.abspath(f.name)}')
|
||||
else:
|
||||
responder.send_data(standard_b64encode(png_data).decode('ascii'))
|
||||
except Exception as e:
|
||||
responder.send_error(f'Failed to save screenshot: {e}')
|
||||
|
||||
boss.request_thumbnail(os_window_id, callback, window_id=target_window_id, include_tab_bar=include_tab_bar, no_scaling=True)
|
||||
return AsyncResponse()
|
||||
|
||||
|
||||
screenshot = Screenshot()
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import ScrollWindowRCOptions as CLIOptions
|
||||
|
||||
|
||||
class ScrollWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
amount+/list.scroll_amount: The amount to scroll, a two item list with the first item being \
|
||||
either a number or the keywords, start and end. \
|
||||
And the second item being either 'p' for pages or 'l' for lines or 'u'
|
||||
for unscrolling by lines, or 'r' for scrolling to prompt.
|
||||
match/str: The window to scroll
|
||||
"""
|
||||
|
||||
short_desc = 'Scroll the specified windows'
|
||||
desc = (
|
||||
'Scroll the specified windows, if no window is specified, scroll the window this command is run inside.'
|
||||
' :italic:`SCROLL_AMOUNT` can be either the keywords :code:`start` or :code:`end` or an'
|
||||
' argument of the form :italic:`<number>[unit][+-]`. :code:`unit` can be :code:`l` for lines, :code:`p` for pages,'
|
||||
' :code:`u` for unscroll and :code:`r` for scroll to prompt. If unspecified, :code:`l` is the default.'
|
||||
' For example, :code:`30.5` will scroll down 30 and a half lines, :code:`2p-`'
|
||||
' will scroll up 2 pages and :code:`0.5p` will scroll down half page.'
|
||||
' :code:`3u` will *unscroll* by 3 lines, which means that 3 lines will move from the'
|
||||
' scrollback buffer onto the top of the screen. :code:`1r-` will scroll to the previous prompt and :code:`1r` to the next prompt.'
|
||||
' See :ac:`scroll_to_prompt` for details on how scrolling to prompt works.'
|
||||
)
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response indicating the success of the action. Note that
|
||||
using this option means that you will not be notified of failures.
|
||||
"""
|
||||
)
|
||||
args = RemoteCommand.Args(spec='SCROLL_AMOUNT', count=1, special_parse='parse_scroll_amount(args[0])', json_field='amount')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if len(args) < 1:
|
||||
self.fatal('Scroll amount must be specified')
|
||||
amt = args[0]
|
||||
amount: tuple[str | float, str | None] = (amt, None)
|
||||
if amt not in ('start', 'end'):
|
||||
pages = 'p' in amt
|
||||
unscroll = 'u' in amt
|
||||
prompt = 'r' in amt
|
||||
mult = -1 if amt.endswith('-') and not unscroll else 1
|
||||
q = float(amt.rstrip('+-plur'))
|
||||
if (unscroll or prompt) and not q.is_integer():
|
||||
self.fatal('The number must be an integer')
|
||||
amount = q * mult, 'p' if pages else ('u' if unscroll else ('r' if prompt else 'l'))
|
||||
|
||||
# defaults to scroll the window this command is run in
|
||||
return {'match': opts.match, 'amount': amount, 'self': True}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
vamt: tuple[int | float | Literal['start', 'end'], str] = payload_get('amount')
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
if vamt[0] in ('start', 'end'):
|
||||
(window.scroll_home if vamt[0] == 'start' else window.scroll_end)()
|
||||
else:
|
||||
amt, unit = vamt
|
||||
assert isinstance(amt, (int, float))
|
||||
match unit:
|
||||
case 'u':
|
||||
window.screen.reverse_scroll(int(abs(amt)), True)
|
||||
case 'r':
|
||||
window.scroll_to_prompt(int(amt))
|
||||
case 'l':
|
||||
window.scroll_fractional_lines(amt)
|
||||
case 'p':
|
||||
unit = 'page'
|
||||
if not isinstance(amt, int) and not amt.is_integer():
|
||||
amt = round(window.screen.lines * amt)
|
||||
unit = 'line'
|
||||
assert isinstance(amt, int)
|
||||
direction = 'up' if amt < 0 else 'down'
|
||||
func = getattr(window, f'scroll_{unit}_{direction}')
|
||||
for _ in range(int(abs(amt))):
|
||||
func()
|
||||
return None
|
||||
|
||||
|
||||
scroll_window = ScrollWindow()
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
from kitty.types import AsyncResponse
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.boss import VisualSelect
|
||||
from kitty.cli_stub import SelectWindowRCOptions as CLIOptions
|
||||
from kitty.tabs import Tab
|
||||
|
||||
|
||||
class SelectWindow(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
match/str: The tab to open the new window in
|
||||
self/bool: Boolean, if True use tab the command was run in
|
||||
title/str: A title for this selection
|
||||
exclude_active/bool: Exclude the currently active window from the list to pick
|
||||
reactivate_prev_tab/bool: Reactivate the previously activated tab when finished
|
||||
"""
|
||||
|
||||
short_desc = 'Visually select a window in the specified tab'
|
||||
desc = 'Prints out the id of the selected window. Other commands can then be chained to make use of it.'
|
||||
options_spec = (
|
||||
MATCH_TAB_OPTION
|
||||
+ '\n\n'
|
||||
+ """\
|
||||
--response-timeout
|
||||
type=float
|
||||
default=60
|
||||
The time in seconds to wait for the user to select a window.
|
||||
|
||||
|
||||
--self
|
||||
type=bool-set
|
||||
Select window from the tab containing the window this command is run in,
|
||||
instead of the active tab.
|
||||
|
||||
|
||||
--title
|
||||
A title that will be displayed to the user to describe what this selection is for.
|
||||
|
||||
|
||||
--exclude-active
|
||||
type=bool-set
|
||||
Exclude the currently active window from the list of windows to pick.
|
||||
|
||||
|
||||
--reactivate-prev-tab
|
||||
type=bool-set
|
||||
When the selection is finished, the tab in the same OS window that was activated
|
||||
before the selection will be reactivated. The last activated OS window will also
|
||||
be refocused.
|
||||
"""
|
||||
)
|
||||
is_asynchronous = True
|
||||
visual_selects: 'WeakValueDictionary[str, VisualSelect]' = WeakValueDictionary()
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
ans = {
|
||||
'self': opts.self,
|
||||
'match': opts.match,
|
||||
'title': opts.title,
|
||||
'exclude_active': opts.exclude_active,
|
||||
'reactivate_prev_tab': opts.reactivate_prev_tab,
|
||||
}
|
||||
return ans
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
responder = self.create_async_responder(payload_get, window)
|
||||
async_id: str = payload_get('async_id', missing='')
|
||||
|
||||
def callback(tab: Optional['Tab'], window: Window | None) -> None:
|
||||
self.visual_selects.pop(async_id, None)
|
||||
if window:
|
||||
responder.send_data(window.id)
|
||||
else:
|
||||
responder.send_error('No window selected')
|
||||
|
||||
for tab in self.tabs_for_match_payload(boss, window, payload_get):
|
||||
if tab:
|
||||
wids = tab.all_window_ids_except_active_window if payload_get('exclude_active') else None
|
||||
boss.visual_window_select_action(
|
||||
tab, callback, payload_get('title') or 'Choose window', only_window_ids=wids, reactivate_prev_tab=payload_get('reactivate_prev_tab')
|
||||
)
|
||||
if async_id and boss.current_visual_select is not None:
|
||||
self.visual_selects[async_id] = boss.current_visual_select
|
||||
break
|
||||
return AsyncResponse()
|
||||
|
||||
def cancel_async_request(self, boss: 'Boss', window: Optional['Window'], payload_get: PayloadGetType) -> None:
|
||||
# Cancellations are not authenticated, so only cancel the visual
|
||||
# select started by the request being cancelled, which requires
|
||||
# knowing its random async_id, never some other visual select.
|
||||
vs = self.visual_selects.pop(payload_get('async_id', missing=''), None)
|
||||
if vs is not None and vs is boss.current_visual_select:
|
||||
boss.cancel_current_visual_select()
|
||||
|
||||
|
||||
select_window = SelectWindow()
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import (
|
||||
MATCH_TAB_OPTION,
|
||||
MATCH_WINDOW_OPTION,
|
||||
ArgsType,
|
||||
Boss,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SendKeyRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SendKey(RemoteCommand):
|
||||
disallow_responses = True
|
||||
protocol_spec = __doc__ = """
|
||||
keys+/list.str: The keys to send
|
||||
match/str: A string indicating the window to send text to
|
||||
match_tab/str: A string indicating the tab to send text to
|
||||
all/bool: A boolean indicating all windows should be matched.
|
||||
exclude_active/bool: A boolean that prevents sending text to the active window
|
||||
"""
|
||||
short_desc = 'Send arbitrary key presses to the specified windows'
|
||||
desc = (
|
||||
'Send arbitrary key presses to specified windows. All specified keys are sent first as press events'
|
||||
' then as release events in reverse order. Keys are sent to the programs running in the windows.'
|
||||
' They are sent only if the current keyboard mode for the program supports the particular key.'
|
||||
' For example: send-key ctrl+a ctrl+b. Note that errors are not reported, for technical reasons,'
|
||||
' so send-key always succeeds, even if no key was sent to any window.'
|
||||
)
|
||||
# since send-key can send data over the tty to the window in which it was
|
||||
# run --no-reponse is always in effect for it, hence errors are not
|
||||
# reported.
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
|
||||
+ """\n
|
||||
--all
|
||||
type=bool-set
|
||||
Match all windows.
|
||||
|
||||
|
||||
--exclude-active
|
||||
type=bool-set
|
||||
Do not send text to the active window, even if it is one of the matched windows.
|
||||
"""
|
||||
)
|
||||
args = RemoteCommand.Args(spec='[KEYS TO SEND ...]', json_field='keys')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
ret = {'match': opts.match, 'keys': args, 'match_tab': opts.match_tab, 'all': opts.all, 'exclude_active': opts.exclude_active}
|
||||
return ret
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
windows = self.windows_for_payload(boss, None, payload_get, window_match_name='match')
|
||||
keys = payload_get('keys')
|
||||
for w in windows:
|
||||
w.send_key(*keys)
|
||||
return None
|
||||
|
||||
|
||||
send_key = SendKey()
|
||||
@@ -0,0 +1,267 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import base64
|
||||
import sys
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from kitty.fast_data_types import KeyEvent as WindowSystemKeyEvent
|
||||
from kitty.fast_data_types import get_boss
|
||||
from kitty.key_encoding import decode_key_event_as_window_system_key
|
||||
from kitty.options.utils import parse_send_text_bytes
|
||||
from kitty.utils import sanitize_for_bracketed_paste
|
||||
|
||||
from .base import (
|
||||
MATCH_TAB_OPTION,
|
||||
MATCH_WINDOW_OPTION,
|
||||
ArgsType,
|
||||
Boss,
|
||||
CmdGenerator,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SendTextRCOptions as CLIOptions
|
||||
|
||||
|
||||
class Session:
|
||||
id: str
|
||||
window_ids: set[int]
|
||||
|
||||
def __init__(self, id: str):
|
||||
self.id = id
|
||||
self.window_ids = set()
|
||||
|
||||
|
||||
sessions_map: dict[str, Session] = {}
|
||||
|
||||
|
||||
class SessionAction:
|
||||
def __init__(self, sid: str):
|
||||
self.sid = sid
|
||||
|
||||
|
||||
class ClearSession(SessionAction):
|
||||
def __call__(self, *a: Any) -> None:
|
||||
s = sessions_map.pop(self.sid, None)
|
||||
if s is not None:
|
||||
boss = get_boss()
|
||||
for wid in s.window_ids:
|
||||
qw = boss.window_id_map.get(wid)
|
||||
if qw is not None:
|
||||
qw.screen.render_unfocused_cursor = False
|
||||
|
||||
|
||||
class FocusChangedSession(SessionAction):
|
||||
def __call__(self, window: Window, focused: bool) -> None:
|
||||
s = sessions_map.get(self.sid)
|
||||
if s is not None:
|
||||
boss = get_boss()
|
||||
for wid in s.window_ids:
|
||||
qw = boss.window_id_map.get(wid)
|
||||
if qw is not None:
|
||||
qw.screen.render_unfocused_cursor = focused
|
||||
|
||||
|
||||
class SendText(RemoteCommand):
|
||||
disallow_responses = True
|
||||
protocol_spec = __doc__ = """
|
||||
data+/str: The data being sent. Can be either: text: followed by text or base64: followed by standard base64 encoded bytes
|
||||
match/str: A string indicating the window to send text to
|
||||
match_tab/str: A string indicating the tab to send text to
|
||||
all/bool: A boolean indicating all windows should be matched.
|
||||
exclude_active/bool: A boolean that prevents sending text to the active window
|
||||
session_id/str: A string that identifies a "broadcast session"
|
||||
bracketed_paste/choices.disable.auto.enable: Whether to wrap the text in bracketed paste escape codes
|
||||
"""
|
||||
short_desc = 'Send arbitrary text to specified windows'
|
||||
desc = (
|
||||
'Send arbitrary text to specified windows. The text follows Python'
|
||||
' escaping rules. So you can use :link:`escapes <https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html>`'
|
||||
" like :code:`'\\\\e'` to send control codes"
|
||||
" and :code:`'\\\\u21fa'` to send Unicode characters. Remember to use single-quotes otherwise"
|
||||
' the backslash is interpreted as a shell escape character. If you use the :option:`kitten @ send-text --match` option'
|
||||
' the text will be sent to all matched windows. By default, text is sent to'
|
||||
' only the currently active window. Note that errors are not reported, for technical reasons,'
|
||||
' so send-text always succeeds, even if no text was sent to any window.'
|
||||
)
|
||||
# since send-text can send data over the tty to the window in which it was
|
||||
# run --no-reponse is always in effect for it, hence errors are not
|
||||
# reported.
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
|
||||
+ """\n
|
||||
--all
|
||||
type=bool-set
|
||||
Match all windows.
|
||||
|
||||
|
||||
--exclude-active
|
||||
type=bool-set
|
||||
Do not send text to the active window, even if it is one of the matched windows.
|
||||
|
||||
|
||||
--stdin
|
||||
type=bool-set
|
||||
Read the text to be sent from :italic:`stdin`. Note that in this case the text is sent as is,
|
||||
not interpreted for escapes. If stdin is a terminal, you can press :kbd:`Ctrl+D` to end reading.
|
||||
|
||||
|
||||
--from-file
|
||||
Path to a file whose contents you wish to send. Note that in this case the file contents
|
||||
are sent as is, not interpreted for escapes.
|
||||
|
||||
|
||||
--bracketed-paste
|
||||
choices=disable,auto,enable
|
||||
default=disable
|
||||
When sending text to a window, wrap the text in bracketed paste escape codes. The default is to not do this.
|
||||
A value of :code:`auto` means, bracketed paste will be used only if the program running in the window has turned
|
||||
on bracketed paste mode.
|
||||
"""
|
||||
)
|
||||
args = RemoteCommand.Args(spec='[TEXT TO SEND]', json_field='data', special_parse='+session_id:parse_send_text(io_data, args)')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
limit = 1024
|
||||
ret = {
|
||||
'match': opts.match,
|
||||
'data': '',
|
||||
'match_tab': opts.match_tab,
|
||||
'all': opts.all,
|
||||
'exclude_active': opts.exclude_active,
|
||||
'bracketed_paste': opts.bracketed_paste,
|
||||
}
|
||||
|
||||
def pipe() -> CmdGenerator:
|
||||
if sys.stdin.isatty():
|
||||
ret['exclude_active'] = True
|
||||
keep_going = True
|
||||
from kitty.utils import TTYIO
|
||||
|
||||
with TTYIO(read_with_timeout=False) as tty:
|
||||
while keep_going:
|
||||
if not tty.wait_till_read_available():
|
||||
break
|
||||
data = tty.read(limit)
|
||||
if not data:
|
||||
break
|
||||
decoded_data = data.decode('utf-8')
|
||||
if '\x04' in decoded_data:
|
||||
decoded_data = decoded_data[: decoded_data.index('\x04')]
|
||||
keep_going = False
|
||||
ret['data'] = f'text:{decoded_data}'
|
||||
yield ret
|
||||
else:
|
||||
while True:
|
||||
data = sys.stdin.buffer.read(limit)
|
||||
if not data:
|
||||
break
|
||||
ret['data'] = f'base64:{base64.standard_b64encode(data).decode("ascii")}'
|
||||
yield ret
|
||||
|
||||
def chunks(text: str) -> CmdGenerator:
|
||||
data = parse_send_text_bytes(text)
|
||||
while data:
|
||||
b = base64.standard_b64encode(data[:limit]).decode('ascii')
|
||||
ret['data'] = f'base64:{b}'
|
||||
yield ret
|
||||
data = data[limit:]
|
||||
|
||||
def file_pipe(path: str) -> CmdGenerator:
|
||||
with open(path, 'rb') as f:
|
||||
while True:
|
||||
data = f.read(limit)
|
||||
if not data:
|
||||
break
|
||||
ret['data'] = f'base64:{base64.standard_b64encode(data).decode("ascii")}'
|
||||
yield ret
|
||||
|
||||
sources = []
|
||||
if opts.stdin:
|
||||
sources.append(pipe())
|
||||
|
||||
if opts.from_file:
|
||||
sources.append(file_pipe(opts.from_file))
|
||||
|
||||
text = ' '.join(args)
|
||||
sources.append(chunks(text))
|
||||
|
||||
def chain() -> CmdGenerator:
|
||||
for src in sources:
|
||||
yield from src
|
||||
|
||||
return chain()
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
sid = payload_get('session_id', '')
|
||||
windows = self.windows_for_payload(boss, window, payload_get, window_match_name='match')
|
||||
pdata: str = payload_get('data')
|
||||
encoding, _, q = pdata.partition(':')
|
||||
session = ''
|
||||
if encoding == 'text':
|
||||
data: bytes | WindowSystemKeyEvent = q.encode('utf-8')
|
||||
elif encoding == 'base64':
|
||||
data = base64.standard_b64decode(q)
|
||||
elif encoding == 'kitty-key':
|
||||
bdata = base64.standard_b64decode(q)
|
||||
candidate = decode_key_event_as_window_system_key(bdata.decode('ascii'))
|
||||
if candidate is None:
|
||||
raise ValueError(f'Could not decode window system key: {q}')
|
||||
data = candidate
|
||||
elif encoding == 'session':
|
||||
session = q
|
||||
else:
|
||||
raise TypeError(f'Invalid encoding for send-text data: {encoding}')
|
||||
|
||||
def create_or_update_session() -> Session:
|
||||
s = sessions_map.setdefault(sid, Session(sid))
|
||||
return s
|
||||
|
||||
if session == 'end':
|
||||
s = create_or_update_session()
|
||||
for w in windows:
|
||||
w.screen.render_unfocused_cursor = False
|
||||
s.window_ids.discard(w.id)
|
||||
ClearSession(sid)()
|
||||
elif session == 'start':
|
||||
s = create_or_update_session()
|
||||
if window is not None:
|
||||
|
||||
def is_ok(x: Any) -> bool:
|
||||
return not isinstance(x, SessionAction) or x.sid != sid
|
||||
|
||||
window.actions_on_removal = list(filter(is_ok, window.actions_on_removal))
|
||||
window.actions_on_focus_change = list(filter(is_ok, window.actions_on_focus_change))
|
||||
window.actions_on_removal.append(ClearSession(sid))
|
||||
window.actions_on_focus_change.append(FocusChangedSession(sid))
|
||||
for w in windows:
|
||||
w.screen.render_unfocused_cursor = True
|
||||
s.window_ids.add(w.id)
|
||||
else:
|
||||
bp = payload_get('bracketed_paste')
|
||||
if sid:
|
||||
s = create_or_update_session()
|
||||
for w in windows:
|
||||
if sid:
|
||||
w.screen.render_unfocused_cursor = True
|
||||
s.window_ids.add(w.id)
|
||||
if isinstance(data, WindowSystemKeyEvent):
|
||||
kdata = w.encoded_key(data)
|
||||
if kdata:
|
||||
w.write_to_child(kdata)
|
||||
else:
|
||||
if bp == 'enable' or (bp == 'auto' and w.screen.in_bracketed_paste_mode):
|
||||
data = b'\x1b[200~' + sanitize_for_bracketed_paste(data) + b'\x1b[201~'
|
||||
w.write_to_child(data)
|
||||
return None
|
||||
|
||||
|
||||
send_text = SendText()
|
||||
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
from base64 import standard_b64decode, standard_b64encode
|
||||
from io import BytesIO
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.types import AsyncResponse
|
||||
from kitty.utils import is_png
|
||||
|
||||
from .base import (
|
||||
MATCH_WINDOW_OPTION,
|
||||
SUPPORTED_IMAGE_FORMATS,
|
||||
ArgsType,
|
||||
Boss,
|
||||
CmdGenerator,
|
||||
ImageCompletion,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetBackgroundImageRCOptions as CLIOptions
|
||||
|
||||
|
||||
layout_choices = 'tiled,scaled,mirror-tiled,clamped,centered,cscaled,configured'
|
||||
|
||||
|
||||
class SetBackgroundImage(RemoteCommand):
|
||||
protocol_spec = __doc__ = f"""
|
||||
data+/str: Chunk of at most 512 bytes of PNG data, base64 encoded. Must send an empty chunk to indicate end of image. \
|
||||
Or the special value - to indicate image must be removed. Or the value index:idx to change image.
|
||||
match/str: Window to change opacity in
|
||||
layout/choices.{layout_choices.replace(',', '.')}: The image layout
|
||||
all/bool: Boolean indicating operate on all windows
|
||||
configured/bool: Boolean indicating if the configured value should be changed
|
||||
"""
|
||||
|
||||
short_desc = 'Set the background image'
|
||||
desc = (
|
||||
'Set the background image for the specified OS windows. You must specify the path to an image that'
|
||||
' will be used as the background. If you specify the special value :code:`none` then any existing image will'
|
||||
' be removed.'
|
||||
f' Supported image formats are: {", ".join(SUPPORTED_IMAGE_FORMATS)}'
|
||||
'\n\n'
|
||||
'You can also specify an index to change the background image to one of the pre-configured set of background images.'
|
||||
' The index is either a number, or a number preceded by the plus or minus sign which acts as an increment.'
|
||||
' If the index falls outside the range of configured images, the first configured image is used.'
|
||||
' For example: set-background -- -1 or set-background 3'
|
||||
)
|
||||
options_spec = (
|
||||
f"""\
|
||||
--all -a
|
||||
type=bool-set
|
||||
By default, background image is only changed for the currently active OS window. This option will
|
||||
cause the image to be changed in all windows.
|
||||
|
||||
|
||||
--configured -c
|
||||
type=bool-set
|
||||
Change the configured background image which is used for new OS windows. Note that an index with this option
|
||||
is not supported. Specifying :code:`none` will erase *all* configured background images.
|
||||
|
||||
|
||||
--layout
|
||||
type=choices
|
||||
choices={layout_choices}
|
||||
default=configured
|
||||
How the image should be displayed. A value of :code:`configured` will use the configured value.
|
||||
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response from kitty. This means that even if setting the background image
|
||||
failed, the command will exit with a success code.
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
)
|
||||
args = RemoteCommand.Args(
|
||||
spec='PATH_TO_IMAGE_OR_INDEX', count=1, json_field='data', special_parse='!read_background_image(io_data, args[0])', completion=ImageCompletion
|
||||
)
|
||||
reads_streaming_data = True
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if len(args) != 1:
|
||||
self.fatal('Must specify path to exactly one PNG image')
|
||||
path = os.path.expanduser(args[0])
|
||||
import secrets
|
||||
|
||||
ret = {
|
||||
'match': opts.match,
|
||||
'configured': opts.configured,
|
||||
'layout': opts.layout,
|
||||
'all': opts.all,
|
||||
'stream_id': secrets.token_urlsafe(),
|
||||
}
|
||||
if path.lower() == 'none':
|
||||
ret['data'] = '-'
|
||||
return ret
|
||||
import re
|
||||
|
||||
if re.match(r'[+-]?\d+$', path) is not None:
|
||||
ret['data'] = f'index:{path}'
|
||||
return ret
|
||||
if not is_png(path):
|
||||
self.fatal(f'{path} is not a PNG image')
|
||||
|
||||
def file_pipe(path: str) -> CmdGenerator:
|
||||
with open(path, 'rb') as f:
|
||||
while True:
|
||||
data = f.read(512)
|
||||
if not data:
|
||||
break
|
||||
ret['data'] = standard_b64encode(data).decode('ascii')
|
||||
yield ret
|
||||
ret['data'] = ''
|
||||
yield ret
|
||||
|
||||
return file_pipe(path)
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
data = payload_get('data')
|
||||
path = None
|
||||
global_index = -1
|
||||
is_increment = False
|
||||
if data == '-':
|
||||
tfile = BytesIO()
|
||||
elif data and data.startswith('index:'):
|
||||
if payload_get('configured'):
|
||||
ex = ValueError('Cannot use --configured with an image index')
|
||||
ex.hide_traceback = True # type: ignore
|
||||
raise ex
|
||||
tfile = BytesIO()
|
||||
data = data[len('index:') :]
|
||||
global_index = int(data)
|
||||
is_increment = data[0] in '+-'
|
||||
else:
|
||||
q = self.handle_streamed_data(standard_b64decode(data) if data else b'', payload_get)
|
||||
if isinstance(q, AsyncResponse):
|
||||
return q
|
||||
path = '/image/from/remote/control'
|
||||
tfile = q
|
||||
|
||||
windows = self.windows_for_payload(boss, window, payload_get, window_match_name='match')
|
||||
os_windows = tuple({w.os_window_id for w in windows if w})
|
||||
layout = payload_get('layout')
|
||||
if layout == 'configured':
|
||||
layout = None
|
||||
try:
|
||||
boss.set_background_image(
|
||||
path, os_windows, payload_get('configured'), layout, tfile.getvalue(), global_index=global_index, is_increment=is_increment
|
||||
)
|
||||
except ValueError as err:
|
||||
err.hide_traceback = True # type: ignore
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
set_background_image = SetBackgroundImage()
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import math
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import (
|
||||
MATCH_TAB_OPTION,
|
||||
MATCH_WINDOW_OPTION,
|
||||
ArgsType,
|
||||
Boss,
|
||||
OpacityError,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetBackgroundOpacityRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SetBackgroundOpacity(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
opacity+/float: A number between 0 and 1
|
||||
match_window/str: Window to change opacity in
|
||||
match_tab/str: Tab to change opacity in
|
||||
all/bool: Boolean indicating operate on all windows
|
||||
toggle/bool: Boolean indicating if opacity should be toggled between the default and the specified value
|
||||
"""
|
||||
|
||||
short_desc = 'Set the background opacity'
|
||||
desc = (
|
||||
'Set the background opacity for the specified windows. This will only work if you have turned on'
|
||||
' :opt:`dynamic_background_opacity` in :file:`kitty.conf`. The background opacity affects all kitty windows in a'
|
||||
' single OS window. For example::\n\n'
|
||||
' kitten @ set-background-opacity 0.5'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--all -a
|
||||
type=bool-set
|
||||
By default, background opacity are only changed for the currently active OS window. This option will
|
||||
cause background opacity to be changed in all windows.
|
||||
|
||||
|
||||
--toggle
|
||||
type=bool-set
|
||||
When specified, the background opacity for the matching OS windows will be reset to default if it is currently
|
||||
equal to the specified value, otherwise it will be set to the specified value.
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
|
||||
)
|
||||
args = RemoteCommand.Args(spec='OPACITY', count=1, json_field='opacity', special_parse='parse_opacity(args[0])')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
opacity = float(args[0])
|
||||
if math.isnan(opacity):
|
||||
raise ValueError(f'Invalid opacity {args[0]!r}: must be a number between 0 and 1')
|
||||
opacity = max(0, min(opacity, 1))
|
||||
return {
|
||||
'opacity': opacity,
|
||||
'match_window': opts.match,
|
||||
'all': opts.all,
|
||||
'match_tab': opts.match_tab,
|
||||
'toggle': opts.toggle,
|
||||
}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
from kitty.fast_data_types import background_opacity_of, get_options
|
||||
|
||||
opts = get_options()
|
||||
if not opts.dynamic_background_opacity:
|
||||
raise OpacityError('You must turn on the dynamic_background_opacity option in kitty.conf to be able to set background opacity')
|
||||
windows = self.windows_for_payload(boss, window, payload_get)
|
||||
for os_window_id in {w.os_window_id for w in windows if w}:
|
||||
val: float = payload_get('opacity') or 0.0
|
||||
if payload_get('toggle'):
|
||||
current = background_opacity_of(os_window_id)
|
||||
# GLFW represents opacity as a float internally, but python's
|
||||
# "float" type has double precision, so we can't rely on precise
|
||||
# equality here
|
||||
if current is not None and abs(current - val) <= 0.0001:
|
||||
val = opts.background_opacity
|
||||
boss._set_os_window_background_opacity(os_window_id, val)
|
||||
return None
|
||||
|
||||
|
||||
set_background_opacity = SetBackgroundOpacity()
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.cli import emph
|
||||
|
||||
from .base import (
|
||||
MATCH_TAB_OPTION,
|
||||
MATCH_WINDOW_OPTION,
|
||||
ArgsType,
|
||||
Boss,
|
||||
ParsingOfArgsFailed,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
RemoteControlErrorWithoutTraceback,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetColorsRCOptions as CLIOptions
|
||||
from kitty.colors import TransparentBackgroundColors
|
||||
|
||||
|
||||
class SetColors(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
colors+/dict.colors: Map of names to 24-bit RGB ints or null for nullable colors. transparent_background_colors is a string, empty to clear, absent to keep.
|
||||
match_window/str: Window to change colors in
|
||||
match_tab/str: Tab to change colors in
|
||||
all/bool: Boolean indicating change colors everywhere or not
|
||||
configured/bool: Boolean indicating whether to change the configured colors. Must be True if reset is True
|
||||
reset/bool: Boolean indicating colors should be reset to startup values
|
||||
"""
|
||||
|
||||
short_desc = 'Set terminal colors'
|
||||
desc = (
|
||||
'Set the terminal colors for the specified windows/tabs (defaults to active window).'
|
||||
' You can either specify the path to a conf file'
|
||||
' (in the same format as :file:`kitty.conf`) to read the colors from or you can specify individual colors,'
|
||||
' for example::\n\n'
|
||||
' kitten @ set-colors foreground=red background=white'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--all -a
|
||||
type=bool-set
|
||||
By default, colors are only changed for the currently active window. This option will
|
||||
cause colors to be changed in all windows.
|
||||
|
||||
|
||||
--configured -c
|
||||
type=bool-set
|
||||
Also change the configured colors (i.e. the colors kitty will use for new
|
||||
windows or after a reset).
|
||||
|
||||
|
||||
--reset
|
||||
type=bool-set
|
||||
Restore all colors to the values they had at kitty startup. Note that if you specify
|
||||
this option, any color arguments are ignored and :option:`kitten @ set-colors --configured` and :option:`kitten @ set-colors --all` are implied.
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
|
||||
)
|
||||
args = RemoteCommand.Args(
|
||||
spec='COLOR_OR_FILE ...',
|
||||
json_field='colors',
|
||||
special_parse='+all,configured,reset:parse_colors_and_files(args, options_set_colors, &payload)',
|
||||
completion=RemoteCommand.CompletionSpec.from_string('type:file group:"CONF files", ext:conf'),
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
final_colors: dict[str, int | None | str] = {}
|
||||
transparent_background_colors: 'TransparentBackgroundColors | None' = None
|
||||
from kitty.colors import parse_colors
|
||||
|
||||
if not opts.reset:
|
||||
try:
|
||||
fc, transparent_background_colors = parse_colors(args)
|
||||
except FileNotFoundError as err:
|
||||
raise ParsingOfArgsFailed(f'The colors configuration file {emph(err.filename)} was not found.') from err
|
||||
except Exception as err:
|
||||
raise ParsingOfArgsFailed(str(err)) from err
|
||||
final_colors.update(fc)
|
||||
if transparent_background_colors is not None:
|
||||
final_colors['transparent_background_colors'] = ' '.join(f'{c.as_sharp}@{f}' for c, f in transparent_background_colors)
|
||||
ans = {
|
||||
'match_window': opts.match,
|
||||
'match_tab': opts.match_tab,
|
||||
'all': opts.all or opts.reset,
|
||||
'configured': opts.configured or opts.reset,
|
||||
'colors': final_colors,
|
||||
'reset': opts.reset,
|
||||
}
|
||||
return ans
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
from kitty.colors import patch_colors
|
||||
|
||||
colors: dict[str, int | None] = {}
|
||||
tbc: TransparentBackgroundColors | None = None
|
||||
# reset implies all and configured, enforce it here as not all clients set them
|
||||
reset = bool(payload_get('reset'))
|
||||
configured = reset or bool(payload_get('configured'))
|
||||
windows = list(boss.all_windows) if reset else self.windows_for_payload(boss, window, payload_get)
|
||||
if reset:
|
||||
colors = {k: None if v is None else int(v) for k, v in boss.color_settings_at_startup.items()}
|
||||
tbc = boss.transparent_background_colors_at_startup
|
||||
else:
|
||||
payload_colors: dict[str, int | str | None] = payload_get('colors') or {}
|
||||
for k, v in payload_colors.items():
|
||||
if k == 'transparent_background_colors':
|
||||
tbc = self.parse_transparent_background_colors(v)
|
||||
elif isinstance(v, str):
|
||||
raise RemoteControlErrorWithoutTraceback(f'The color {k} must be an integer or null, not a string')
|
||||
else:
|
||||
colors[k] = v
|
||||
patch_colors(colors, tbc, configured, windows=windows, replace_window_colors=True)
|
||||
return None
|
||||
|
||||
def parse_transparent_background_colors(self, spec: int | str | None) -> 'TransparentBackgroundColors':
|
||||
from kitty.options.utils import transparent_background_colors
|
||||
|
||||
if not isinstance(spec, str):
|
||||
raise RemoteControlErrorWithoutTraceback('transparent_background_colors must be a string')
|
||||
try:
|
||||
return transparent_background_colors(spec)
|
||||
except ValueError as err:
|
||||
raise RemoteControlErrorWithoutTraceback(f'Invalid transparent_background_colors: {spec!r} with error: {err}') from err
|
||||
|
||||
|
||||
set_colors = SetColors()
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.fast_data_types import get_options
|
||||
from kitty.options.utils import parse_layout_names
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetEnabledLayoutsRCOptions as CLIOptions
|
||||
|
||||
|
||||
def layout_names() -> Iterable[str]:
|
||||
from kitty.layout.interface import all_layouts
|
||||
|
||||
return all_layouts.keys()
|
||||
|
||||
|
||||
class SetEnabledLayouts(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
layouts+/list.str: The list of layout names
|
||||
match/str: Which tab to change the layout of
|
||||
configured/bool: Boolean indicating whether to change the configured value
|
||||
"""
|
||||
|
||||
short_desc = 'Set the enabled layouts in tabs'
|
||||
desc = (
|
||||
'Set the enabled layouts in the specified tabs (or the active tab if not specified).'
|
||||
' You can use special match value :code:`all` to set the enabled layouts in all tabs. If the'
|
||||
' current layout of the tab is not included in the enabled layouts, its layout is changed'
|
||||
' to the first enabled layout.'
|
||||
)
|
||||
options_spec = (
|
||||
MATCH_TAB_OPTION
|
||||
+ """\n\n
|
||||
--configured
|
||||
type=bool-set
|
||||
Change the default enabled layout value so that the new value takes effect for all newly created tabs
|
||||
as well.
|
||||
"""
|
||||
)
|
||||
args = RemoteCommand.Args(
|
||||
spec='LAYOUT ...',
|
||||
minimum_count=1,
|
||||
json_field='layouts',
|
||||
completion=RemoteCommand.CompletionSpec.from_string('type:keyword group:"Layout" kwds:' + ','.join(layout_names())),
|
||||
args_choices=layout_names,
|
||||
)
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if len(args) < 1:
|
||||
self.fatal('At least one layout must be specified')
|
||||
a: list[str] = []
|
||||
for x in args:
|
||||
a.extend(y.strip() for y in x.split(','))
|
||||
try:
|
||||
layouts = parse_layout_names(a)
|
||||
except ValueError as err:
|
||||
self.fatal(str(err))
|
||||
return {'layouts': layouts, 'match': opts.match, 'configured': opts.configured}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
tabs = self.tabs_for_match_payload(boss, window, payload_get)
|
||||
layouts = parse_layout_names(payload_get('layouts'))
|
||||
if payload_get('configured'):
|
||||
get_options().enabled_layouts = list(layouts)
|
||||
for tab in tabs:
|
||||
if tab:
|
||||
tab.set_enabled_layouts(layouts)
|
||||
return None
|
||||
|
||||
|
||||
set_enabled_layouts = SetEnabledLayouts()
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from math import isfinite
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.options.utils import parse_font_size_change
|
||||
|
||||
from .base import ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, RemoteControlErrorWithoutTraceback, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetFontSizeRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SetFontSize(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
size+/float: The new font size in pts (a positive number). If absent is assumed to be zero which means reset to default.
|
||||
all/bool: Boolean whether to change font size in the current window or all windows
|
||||
increment_op/choices.+.-.*./: The string ``+``, ``-``, ``*`` or ``/`` to interpret size as an increment
|
||||
"""
|
||||
|
||||
short_desc = 'Set the font size in the active top-level OS window'
|
||||
desc = (
|
||||
'Sets the font size to the specified size, in pts. Note'
|
||||
' that in kitty all sub-windows in the same OS window'
|
||||
' must have the same font size. A value of zero'
|
||||
' resets the font size to default. Prefixing the value'
|
||||
' with a :code:`+`, :code:`-`, :code:`*` or :code:`/` changes the font size by the specified'
|
||||
' amount. Use -- before using - to have it not mistaken for a option. For example:'
|
||||
' kitten @ set-font-size -- -2'
|
||||
)
|
||||
args = RemoteCommand.Args(spec='FONT_SIZE', count=1, special_parse='+increment_op:parse_set_font_size(args[0], &payload)', json_field='size')
|
||||
options_spec = """\
|
||||
--all -a
|
||||
type=bool-set
|
||||
By default, the font size is only changed in the active OS window,
|
||||
this option will cause it to be changed in all OS windows. It also changes
|
||||
the font size for any newly created OS Windows in the future.
|
||||
"""
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if not args:
|
||||
self.fatal('No font size specified')
|
||||
try:
|
||||
inc, size = parse_font_size_change(args[0])
|
||||
except ValueError as e:
|
||||
self.fatal(f'Invalid font size: {args[0]}: {e}')
|
||||
return {'size': size, 'all': opts.all, 'increment_op': inc}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
size = payload_get('size') or 0
|
||||
inc = payload_get('increment_op')
|
||||
if not isfinite(size) or size < 0 or (inc and size == 0):
|
||||
raise RemoteControlErrorWithoutTraceback(f'Invalid font size: {inc or ""}{size}, must be a positive number')
|
||||
boss.change_font_size(payload_get('all'), inc, size)
|
||||
return None
|
||||
|
||||
|
||||
set_font_size = SetFontSize()
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.fast_data_types import set_os_window_title as set_os_window_title_impl
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetOsWindowTitleRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SetOsWindowTitle(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
title/str: The new title
|
||||
match/str: Which OS windows to change, matched via their contained windows
|
||||
"""
|
||||
|
||||
short_desc = 'Set the OS window title'
|
||||
desc = (
|
||||
'Set the title for the OS windows containing the specified windows. If you use the '
|
||||
':option:`kitten @ set-os-window-title --match` option the title will be set for all matched OS windows. '
|
||||
'By default, only the OS window in which the command is run is affected. If you do not specify a title, the '
|
||||
'title of the currently active window in each OS window is used.'
|
||||
)
|
||||
options_spec = MATCH_WINDOW_OPTION
|
||||
args = RemoteCommand.Args(spec='[TITLE ...]', json_field='title', special_parse='expand_ansi_c_escapes_in_args(args...)')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
ans = {'match': opts.match, 'self': True}
|
||||
title = ' '.join(args)
|
||||
if title:
|
||||
ans['title'] = title
|
||||
return ans
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
title = payload_get('title') or ''
|
||||
for os_window_id in {w.os_window_id for w in self.windows_for_match_payload(boss, window, payload_get) if w}:
|
||||
set_os_window_title_impl(os_window_id, title)
|
||||
return None
|
||||
|
||||
|
||||
set_os_window_title = SetOsWindowTitle()
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetSpacingRCOptions as CLIOptions
|
||||
from kitty.options.types import Options
|
||||
|
||||
|
||||
def patch_window_edges(w: Window, s: dict[str, float | None]) -> None:
|
||||
for k, v in s.items():
|
||||
which, edge = k.lower().split('-', 1)
|
||||
if edge == 'left':
|
||||
w.patch_edge_width(which, 'left', v)
|
||||
elif edge == 'right':
|
||||
w.patch_edge_width(which, 'right', v)
|
||||
elif edge == 'top':
|
||||
w.patch_edge_width(which, 'top', v)
|
||||
elif edge == 'bottom':
|
||||
w.patch_edge_width(which, 'bottom', v)
|
||||
|
||||
|
||||
def patch_configured_edges(opts: 'Options', s: dict[str, float | None]) -> None:
|
||||
for k, val in s.items():
|
||||
if val is None:
|
||||
continue
|
||||
which, edge = k.lower().split('-', 1)
|
||||
q = f'window_{which}_width'
|
||||
new_edges = getattr(opts, q)._replace(**{edge: val})
|
||||
setattr(opts, q, new_edges)
|
||||
|
||||
|
||||
def spacing_edge_map() -> dict[str, tuple[str, ...]]:
|
||||
# This is the single source of truth for the edge names accepted when
|
||||
# setting spacing, it is also used to generate the Go parser's map.
|
||||
ans: dict[str, tuple[str, ...]] = {}
|
||||
for q in ('margin', 'padding'):
|
||||
ans[q] = tuple(f'{q}-{edge}' for edge in ('left', 'top', 'right', 'bottom'))
|
||||
ans[f'{q}-h'] = ans[f'{q}-horizontal'] = (f'{q}-left', f'{q}-right')
|
||||
ans[f'{q}-v'] = ans[f'{q}-vertical'] = (f'{q}-top', f'{q}-bottom')
|
||||
for edge in ('left', 'top', 'right', 'bottom'):
|
||||
ans[f'{q}-{edge}'] = (f'{q}-{edge}',)
|
||||
return ans
|
||||
|
||||
|
||||
SPACING_SETTINGS_DOC = (
|
||||
'For example: :code:`margin=20` or :code:`padding-left=10` or :code:`margin-h=30`. The shorthand form sets'
|
||||
' all values, the :code:`*-h` (or :code:`*-horizontal`) and :code:`*-v` (or :code:`*-vertical`) variants'
|
||||
' set horizontal and vertical values. The special value :code:`default` resets to using the default value.'
|
||||
)
|
||||
|
||||
|
||||
def parse_spacing_settings(args: Iterable[str]) -> dict[str, float | None]:
|
||||
mapper = spacing_edge_map()
|
||||
settings: dict[str, float | None] = {}
|
||||
for spec in args:
|
||||
parts = spec.split('=', 1)
|
||||
if len(parts) != 2:
|
||||
raise ValueError(f'{spec} is not a valid setting')
|
||||
which = mapper.get(parts[0].lower())
|
||||
if not which:
|
||||
raise ValueError(f'{parts[0]} is not a valid edge specification')
|
||||
if parts[1].lower() == 'default':
|
||||
val = None
|
||||
else:
|
||||
try:
|
||||
val = float(parts[1])
|
||||
except Exception:
|
||||
raise ValueError(f'{parts[1]} is not a number')
|
||||
for q in which:
|
||||
settings[q] = val
|
||||
return settings
|
||||
|
||||
|
||||
class SetSpacing(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
settings+/dict.spacing: An object mapping margins/paddings using canonical form {'margin-top': 50, 'padding-left': null} etc
|
||||
match_window/str: Window to change paddings and margins in
|
||||
match_tab/str: Tab to change paddings and margins in
|
||||
all/bool: Boolean indicating change paddings and margins everywhere or not
|
||||
configured/bool: Boolean indicating whether to change the configured paddings and margins. Must be True if reset is True
|
||||
"""
|
||||
|
||||
short_desc = 'Set window paddings and margins'
|
||||
desc = (
|
||||
'Set the paddings and margins for the specified windows (defaults to active window). '
|
||||
+ SPACING_SETTINGS_DOC
|
||||
+ ' If you specify a tab rather than a window, all windows in that tab are affected.'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--all -a
|
||||
type=bool-set
|
||||
By default, settings are only changed for the currently active window. This option will
|
||||
cause paddings and margins to be changed in all windows.
|
||||
|
||||
|
||||
--configured -c
|
||||
type=bool-set
|
||||
Also change the configured paddings and margins (i.e. the settings kitty will use for new
|
||||
windows).
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
+ '\n\n'
|
||||
+ MATCH_TAB_OPTION.replace('--match -m', '--match-tab -t')
|
||||
)
|
||||
args = RemoteCommand.Args(spec='MARGIN_OR_PADDING ...', minimum_count=1, json_field='settings', special_parse='parse_set_spacing(args)')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if not args:
|
||||
self.fatal('At least one setting must be specified')
|
||||
try:
|
||||
settings = parse_spacing_settings(args)
|
||||
except Exception as e:
|
||||
self.fatal(str(e))
|
||||
ans = {'match_window': opts.match, 'match_tab': opts.match_tab, 'all': opts.all, 'configured': opts.configured, 'settings': settings}
|
||||
return ans
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
windows = self.windows_for_payload(boss, window, payload_get)
|
||||
settings: dict[str, float | None] = payload_get('settings')
|
||||
dirtied_tabs = {}
|
||||
from kitty.fast_data_types import get_options
|
||||
|
||||
if payload_get('configured'):
|
||||
patch_configured_edges(get_options(), settings)
|
||||
|
||||
for w in windows:
|
||||
if w:
|
||||
patch_window_edges(w, settings)
|
||||
tab = w.tabref()
|
||||
if tab is not None:
|
||||
dirtied_tabs[tab.id] = tab
|
||||
|
||||
for tab in dirtied_tabs.values():
|
||||
tab.relayout()
|
||||
return None
|
||||
|
||||
|
||||
set_spacing = SetSpacing()
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.rgb import to_color
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, ParsingOfArgsFailed, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetTabColorRCOptions as CLIOptions
|
||||
|
||||
|
||||
valid_color_names = frozenset('active_fg active_bg inactive_fg inactive_bg'.split())
|
||||
|
||||
|
||||
def parse_colors(args: ArgsType) -> dict[str, int | None]:
|
||||
ans: dict[str, int | None] = {}
|
||||
for spec in args:
|
||||
key, val = spec.split('=', 1)
|
||||
key = key.lower()
|
||||
if key.lower() not in valid_color_names:
|
||||
raise KeyError(f'{key} is not a valid color name')
|
||||
if val.lower() == 'none':
|
||||
col: int | None = None
|
||||
else:
|
||||
q = to_color(val, validate=True)
|
||||
if q is not None:
|
||||
col = int(q)
|
||||
ans[key.lower()] = col
|
||||
return ans
|
||||
|
||||
|
||||
class SetTabColor(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
colors+/dict.colors: An object mapping names to colors as 24-bit RGB integers. A color value of null indicates it should be unset.
|
||||
match/str: Which tab to change the color of
|
||||
self/bool: Boolean indicating whether to use the tab of the window the command is run in
|
||||
"""
|
||||
|
||||
short_desc = 'Change the color of the specified tabs in the tab bar'
|
||||
desc = f"""
|
||||
{short_desc}
|
||||
|
||||
The foreground and background colors when active and inactive can be overridden using this command. \
|
||||
The syntax for specifying colors is: active_fg=color active_bg=color inactive_fg=color \
|
||||
inactive_bg=color. Where color can be either a color name or a value of the form #rrggbb or \
|
||||
the keyword NONE to revert to using the default colors.
|
||||
"""
|
||||
options_spec = (
|
||||
MATCH_TAB_OPTION
|
||||
+ """\n
|
||||
--self
|
||||
type=bool-set
|
||||
Close the tab this command is run in, rather than the active tab.
|
||||
"""
|
||||
)
|
||||
args = RemoteCommand.Args(spec='COLORS', json_field='colors', minimum_count=1, special_parse='parse_tab_colors(args)')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
try:
|
||||
colors = parse_colors(args)
|
||||
except Exception as err:
|
||||
raise ParsingOfArgsFailed(str(err)) from err
|
||||
if not colors:
|
||||
raise ParsingOfArgsFailed('No colors specified')
|
||||
return {'match': opts.match, 'self': opts.self, 'colors': colors}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
colors = payload_get('colors')
|
||||
s = {k: None if colors[k] is None else int(colors[k]) for k in valid_color_names if k in colors}
|
||||
for tab in self.tabs_for_match_payload(boss, window, payload_get):
|
||||
if tab:
|
||||
for k, v in s.items():
|
||||
setattr(tab, k, v)
|
||||
tab.mark_tab_bar_dirty()
|
||||
return None
|
||||
|
||||
|
||||
set_tab_color = SetTabColor()
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_TAB_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetTabTitleRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SetTabTitle(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
title+/str: The new title
|
||||
match/str: Which tab to change the title of
|
||||
"""
|
||||
|
||||
short_desc = 'Set the tab title'
|
||||
desc = (
|
||||
'Set the title for the specified tabs. If you use the :option:`kitten @ set-tab-title --match` option'
|
||||
' the title will be set for all matched tabs. By default, only the tab'
|
||||
' in which the command is run is affected. If you do not specify a title, the'
|
||||
' title of the currently active window in the tab is used.'
|
||||
)
|
||||
options_spec = MATCH_TAB_OPTION
|
||||
args = RemoteCommand.Args(spec='TITLE ...', json_field='title', special_parse='expand_ansi_c_escapes_in_args(args...)')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'title': ' '.join(args), 'match': opts.match}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
for tab in self.tabs_for_match_payload(boss, window, payload_get):
|
||||
if tab:
|
||||
tab.set_title(payload_get('title'))
|
||||
return None
|
||||
|
||||
|
||||
set_tab_title = SetTabTitle()
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetUserVarsRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SetUserVars(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
var/list.str: List of user variables of the form NAME=VALUE
|
||||
match/str: Which windows to change the title in
|
||||
"""
|
||||
|
||||
short_desc = 'Set user variables on a window'
|
||||
desc = (
|
||||
'Set user variables for the specified windows. If you use the :option:`kitten @ set-user-vars --match` option'
|
||||
' the variables will be set for all matched windows. By default, only the window'
|
||||
' in which the command is run is affected. If you do not specify any variables, the'
|
||||
' current variables are printed out, one per line. To unset a variable specify just its name.'
|
||||
)
|
||||
options_spec = MATCH_WINDOW_OPTION
|
||||
args = RemoteCommand.Args(json_field='var', spec='[NAME=VALUE ...]')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'var': args, 'self': True}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
val = {}
|
||||
for x in payload_get('var') or ():
|
||||
a, sep, b = x.partition('=')
|
||||
if sep:
|
||||
val[a] = b
|
||||
else:
|
||||
val[a] = None
|
||||
lines = []
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
if val:
|
||||
for k, v in val.items():
|
||||
window.set_user_var(k, v)
|
||||
else:
|
||||
lines.append('\n'.join(f'{k}={v}' for k, v in window.user_vars.items()))
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
set_user_vars = SetUserVars()
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
from base64 import standard_b64decode, standard_b64encode
|
||||
from io import BytesIO
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from kitty.types import AsyncResponse
|
||||
from kitty.utils import is_png
|
||||
|
||||
from .base import (
|
||||
MATCH_WINDOW_OPTION,
|
||||
SUPPORTED_IMAGE_FORMATS,
|
||||
ArgsType,
|
||||
Boss,
|
||||
CmdGenerator,
|
||||
ImageCompletion,
|
||||
PayloadGetType,
|
||||
PayloadType,
|
||||
RCOptions,
|
||||
RemoteCommand,
|
||||
ResponseType,
|
||||
Window,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetWindowLogoRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SetWindowLogo(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
data+/str: Chunk of PNG data, base64 encoded no more than 2048 bytes. Must send an empty chunk to indicate end of image. \
|
||||
Or the special value :code:`-` to indicate image must be removed.
|
||||
position/str: The logo position as a string, empty string means default
|
||||
alpha/float: The logo alpha between :code:`0` and :code:`1`. :code:`-1` means use default
|
||||
match/str: Which window to change the logo in
|
||||
self/bool: Boolean indicating whether to act on the window the command is run in
|
||||
"""
|
||||
|
||||
short_desc = 'Set the window logo'
|
||||
desc = (
|
||||
'Set the logo image for the specified windows. You must specify the path to an image that'
|
||||
' will be used as the logo. If you specify the special value :code:`none` then any existing logo will'
|
||||
' be removed. Supported image formats are: '
|
||||
) + ', '.join(SUPPORTED_IMAGE_FORMATS)
|
||||
|
||||
options_spec = (
|
||||
MATCH_WINDOW_OPTION
|
||||
+ """\n
|
||||
--self
|
||||
type=bool-set
|
||||
Act on the window this command is run in, rather than the active window.
|
||||
|
||||
|
||||
--position
|
||||
The position for the window logo. See :opt:`window_logo_position`.
|
||||
|
||||
|
||||
--alpha
|
||||
type=float
|
||||
default=-1
|
||||
The amount the window logo should be faded into the background.
|
||||
See :opt:`window_logo_position`.
|
||||
|
||||
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response from kitty. This means that even if setting the image
|
||||
failed, the command will exit with a success code.
|
||||
"""
|
||||
)
|
||||
args = RemoteCommand.Args(
|
||||
spec='PATH_TO_PNG_IMAGE', count=1, json_field='data', special_parse='!read_window_logo(io_data, args[0])', completion=ImageCompletion
|
||||
)
|
||||
reads_streaming_data = True
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
if len(args) != 1:
|
||||
self.fatal('Must specify path to exactly one PNG image')
|
||||
path = os.path.expanduser(args[0])
|
||||
import secrets
|
||||
|
||||
ret = {
|
||||
'match': opts.match,
|
||||
'self': opts.self,
|
||||
'alpha': opts.alpha,
|
||||
'position': opts.position,
|
||||
'stream_id': secrets.token_urlsafe(),
|
||||
}
|
||||
if path.lower() == 'none':
|
||||
ret['data'] = '-'
|
||||
return ret
|
||||
if not is_png(path):
|
||||
self.fatal(f'{path} is not a PNG image')
|
||||
|
||||
def file_pipe(path: str) -> CmdGenerator:
|
||||
with open(path, 'rb') as f:
|
||||
while True:
|
||||
data = f.read(512)
|
||||
if not data:
|
||||
break
|
||||
ret['data'] = standard_b64encode(data).decode('ascii')
|
||||
yield ret
|
||||
ret['data'] = ''
|
||||
yield ret
|
||||
|
||||
return file_pipe(path)
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
data = payload_get('data')
|
||||
alpha = float(payload_get('alpha', '-1'))
|
||||
position = payload_get('position') or ''
|
||||
if data == '-':
|
||||
path = ''
|
||||
tfile = BytesIO()
|
||||
else:
|
||||
q = self.handle_streamed_data(standard_b64decode(data) if data else b'', payload_get)
|
||||
if isinstance(q, AsyncResponse):
|
||||
return q
|
||||
import hashlib
|
||||
|
||||
path = '/from/remote/control/' + hashlib.sha1(q.getvalue()).hexdigest()
|
||||
tfile = q
|
||||
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
window.set_logo(path, position, alpha, tfile.getvalue())
|
||||
return None
|
||||
|
||||
|
||||
set_window_logo = SetWindowLogo()
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SetWindowTitleRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SetWindowTitle(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
title/str: The new title
|
||||
match/str: Which windows to change the title in
|
||||
temporary/bool: Boolean indicating if the change is temporary or permanent
|
||||
"""
|
||||
|
||||
short_desc = 'Set the window title'
|
||||
desc = (
|
||||
'Set the title for the specified windows. If you use the :option:`kitten @ set-window-title --match` option'
|
||||
' the title will be set for all matched windows. By default, only the window'
|
||||
' in which the command is run is affected. If you do not specify a title, the'
|
||||
' last title set by the child process running in the window will be used.'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--temporary
|
||||
type=bool-set
|
||||
By default, the title will be permanently changed and programs running in the window will not be able to change it
|
||||
again. If you want to allow other programs to change it afterwards, use this option.
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
)
|
||||
args = RemoteCommand.Args(json_field='title', spec='[TITLE ...]', special_parse='expand_ansi_c_escapes_in_args(args...)')
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
ans = {'match': opts.match, 'temporary': opts.temporary}
|
||||
title = ' '.join(args)
|
||||
if title:
|
||||
ans['title'] = title
|
||||
# defaults to set the window title this command is run in
|
||||
ans['self'] = True
|
||||
return ans
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
title: str | None = payload_get('title')
|
||||
btitle: memoryview | None = None
|
||||
if payload_get('temporary') and title is not None:
|
||||
btitle = memoryview(title.encode('utf-8'))
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
if payload_get('temporary'):
|
||||
window.override_title = None
|
||||
window.title_changed(btitle)
|
||||
else:
|
||||
window.set_title(title)
|
||||
return None
|
||||
|
||||
|
||||
set_window_title = SetWindowTitle()
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from kitty.cli_stub import SignalChildRCOptions as CLIOptions
|
||||
|
||||
|
||||
class SignalChild(RemoteCommand):
|
||||
protocol_spec = __doc__ = """
|
||||
signals+/list.str: The signals, a list of names, such as :code:`SIGTERM`, :code:`SIGKILL`, :code:`SIGUSR1`, etc.
|
||||
match/str: Which windows to send the signals to
|
||||
"""
|
||||
|
||||
short_desc = 'Send a signal to the foreground process in the specified windows'
|
||||
desc = (
|
||||
'Send one or more signals to the foreground process in the specified windows.'
|
||||
' If you use the :option:`kitten @ signal-child --match` option'
|
||||
' the signal will be sent for all matched windows. By default, only the active'
|
||||
' window is affected. If you do not specify any signals, :code:`SIGINT` is sent by default.'
|
||||
' You can also map :ac:`signal_child` to a shortcut in :file:`kitty.conf`, for example::\n\n'
|
||||
' map f1 signal_child SIGTERM'
|
||||
)
|
||||
options_spec = (
|
||||
"""\
|
||||
--no-response
|
||||
type=bool-set
|
||||
default=false
|
||||
Don't wait for a response indicating the success of the action. Note that
|
||||
using this option means that you will not be notified of failures.
|
||||
"""
|
||||
+ '\n\n'
|
||||
+ MATCH_WINDOW_OPTION
|
||||
)
|
||||
args = RemoteCommand.Args(json_field='signals', spec='[SIGNAL_NAME ...]', value_if_unspecified=('SIGINT',))
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
# defaults to signal the window this command is run in
|
||||
return {'match': opts.match, 'self': True, 'signals': [x.upper() for x in args] or ['SIGINT']}
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
import signal
|
||||
|
||||
signals = tuple(getattr(signal, x) for x in payload_get('signals'))
|
||||
for window in self.windows_for_match_payload(boss, window, payload_get):
|
||||
if window:
|
||||
window.signal_child(*signals)
|
||||
return None
|
||||
|
||||
|
||||
signal_child = SignalChild()
|
||||
Reference in new issue
Block a user