From d21965438759cdee7d5ca1f3529ead51e65b7e6b Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Sat, 22 Jan 2022 12:27:20 +0530 Subject: [PATCH] Use a dedicated choose() method matching confirm() --- kitty/boss.py | 16 ++++++++++++++++ kitty/window.py | 15 +++++---------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/kitty/boss.py b/kitty/boss.py index c5ddabb6e..3776ec9c7 100644 --- a/kitty/boss.py +++ b/kitty/boss.py @@ -680,6 +680,22 @@ class Boss: self._run_kitten('ask', ['--type=yesno', '--message', msg, '--default', 'y' if confirm_on_accept else 'n'], window=window, custom_callback=callback_, default_data={'response': 'y' if confirm_on_cancel else 'n'}) + def choose( + self, msg: str, # can contain newlines and ANSI formatting + callback: Callable[..., None], # called with the choice or empty string when aborted + *choices: str, # The choices, see the help for the ask kitten for format of a choice + window: Optional[Window] = None, # the window associated with the confirmation + default: str = '', # the default choice when the user presses Enter + ) -> None: + def callback_(res: Dict[str, Any], x: int, boss: Boss) -> None: + callback(res.get('response') or '') + cmd = ['--type=choices', '--message', msg] + if default: + cmd += ['-d', default] + for c in choices: + cmd += ['-c', c] + self._run_kitten('ask', cmd, window=window, custom_callback=callback_, default_data={'response': ''}) + def confirm_tab_close(self, tab: Tab) -> None: x = get_options().confirm_os_window_close num = tab.number_of_windows_with_running_programs if x < 0 else len(tab) diff --git a/kitty/window.py b/kitty/window.py index b4f0cec21..c11ae0408 100644 --- a/kitty/window.py +++ b/kitty/window.py @@ -649,21 +649,16 @@ class Window: url = urlunparse(purl._replace(netloc='')) if opts.allow_hyperlinks & 0b10: from kittens.tui.operations import styled - get_boss()._run_kitten('ask', ['--type=choices', '--message', _( - 'What would you like to do with this URL:\n') + - styled(unquote(url), fg='yellow'), - '--choice=o:Open', '--choice=c:Copy to clipboard', '--choice=n;red:Nothing', - '--default=o' - ], + get_boss().choose( + 'What would you like to do with this URL:\n' + styled(unquote(url), fg='yellow'), + partial(self.hyperlink_open_confirmed, url, cwd), + 'o:Open', 'c:Copy to clipboard', 'n;red:Nothing', default='o', window=self, - custom_callback=partial(self.hyperlink_open_confirmed, url, cwd), - default_data={'response': ''} ) return get_boss().open_url(url, cwd=cwd) - def hyperlink_open_confirmed(self, url: str, cwd: Optional[str], data: Dict[str, Any], *a: Any) -> None: - q = data.get('response', '') + def hyperlink_open_confirmed(self, url: str, cwd: Optional[str], q: str) -> None: if q == 'o': get_boss().open_url(url, cwd=cwd) elif q == 'c':