2021-03-11 19:16:15 +01:00
|
|
|
"""Integrated command-line implementation."""
|
2021-03-13 16:31:11 +01:00
|
|
|
|
2021-02-12 23:29:51 +01:00
|
|
|
import curses
|
2021-03-13 16:31:11 +01:00
|
|
|
import curses.ascii
|
2021-02-12 23:29:51 +01:00
|
|
|
import curses.textpad
|
2021-04-17 21:54:11 +02:00
|
|
|
import os
|
|
|
|
import tempfile
|
2021-05-12 22:29:03 +02:00
|
|
|
from typing import Optional
|
2021-03-13 16:31:11 +01:00
|
|
|
|
2021-04-17 21:54:11 +02:00
|
|
|
from bebop.external import open_external_program
|
2021-03-13 16:31:11 +01:00
|
|
|
from bebop.links import Links
|
2021-02-12 23:29:51 +01:00
|
|
|
|
|
|
|
|
|
|
|
class CommandLine:
|
2021-04-17 21:54:11 +02:00
|
|
|
"""Basic and flaky command-line à la Vim, using curses module's Textbox.
|
|
|
|
|
|
|
|
I don't understand how to get proper pad-like behaviour, e.g. to scroll past
|
|
|
|
the window's right border when writing more content than the width allows.
|
|
|
|
Therefore I just added the M-e keybind to call an external editor and use
|
|
|
|
its content as result.
|
2021-04-19 00:28:20 +02:00
|
|
|
|
|
|
|
Attributes:
|
|
|
|
- window: curses window to use for the command line and Textbox.
|
|
|
|
- editor_command: external command to use to edit content externally.
|
|
|
|
- textbox: Textbox object handling user input.
|
2021-04-17 21:54:11 +02:00
|
|
|
"""
|
2021-02-12 23:29:51 +01:00
|
|
|
|
2021-04-19 00:28:20 +02:00
|
|
|
CHAR_COMMAND = ":"
|
|
|
|
CHAR_DIGIT = "&"
|
|
|
|
CHAR_TEXT = ">"
|
|
|
|
|
2021-04-18 02:27:05 +02:00
|
|
|
def __init__(self, window, editor_command):
|
2021-02-12 23:29:51 +01:00
|
|
|
self.window = window
|
2021-04-18 02:27:05 +02:00
|
|
|
self.editor_command = editor_command
|
2021-04-19 00:28:20 +02:00
|
|
|
self.textbox = curses.textpad.Textbox(self.window)
|
2021-02-12 23:29:51 +01:00
|
|
|
|
|
|
|
def clear(self):
|
2021-03-13 16:31:11 +01:00
|
|
|
"""Clear command-line contents."""
|
2021-02-12 23:29:51 +01:00
|
|
|
self.window.clear()
|
|
|
|
self.window.refresh()
|
|
|
|
|
2021-05-12 22:29:03 +02:00
|
|
|
def gather(self) -> str:
|
2021-04-19 00:28:20 +02:00
|
|
|
"""Return the string currently written by the user in command line.
|
|
|
|
|
|
|
|
This doesn't count the command char used, but it includes then prefix.
|
|
|
|
Trailing whitespace is trimmed.
|
|
|
|
"""
|
|
|
|
return self.textbox.gather()[1:].rstrip()
|
|
|
|
|
2021-05-12 22:29:03 +02:00
|
|
|
def focus(
|
|
|
|
self,
|
|
|
|
command_char,
|
|
|
|
validator=None,
|
|
|
|
prefix="",
|
|
|
|
escape_to_none=False
|
|
|
|
) -> Optional[str]:
|
2021-02-12 23:29:51 +01:00
|
|
|
"""Give user focus to the command bar.
|
|
|
|
|
|
|
|
Show the command char and give focus to the command textbox. The
|
|
|
|
validator function is passed to the textbox.
|
|
|
|
|
|
|
|
Arguments:
|
2021-03-13 16:31:11 +01:00
|
|
|
- command_char: char to display before the command line; it must be an
|
|
|
|
str of length 1, else the return value of `gather` might be wrong.
|
|
|
|
- validator: function to use to validate the input chars; if omitted,
|
|
|
|
`validate_common_input` is used.
|
2021-02-12 23:29:51 +01:00
|
|
|
- prefix: string to insert before the cursor in the command line.
|
2021-05-12 22:29:03 +02:00
|
|
|
- escape_to_none: if True, an escape interruption returns None instead
|
|
|
|
of an empty string.
|
2021-02-12 23:29:51 +01:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
User input as string. The string will be empty if the validator raised
|
2021-05-12 22:29:03 +02:00
|
|
|
an EscapeInterrupt, unless `escape_to_none` is True.
|
2021-02-12 23:29:51 +01:00
|
|
|
"""
|
2021-04-19 00:28:20 +02:00
|
|
|
validator = validator or self._validate_common_input
|
2021-02-12 23:29:51 +01:00
|
|
|
self.window.clear()
|
|
|
|
self.window.refresh()
|
|
|
|
self.window.addstr(command_char + prefix)
|
|
|
|
curses.curs_set(1)
|
|
|
|
try:
|
2021-04-19 00:28:20 +02:00
|
|
|
command = self.textbox.edit(validator)
|
2021-02-12 23:29:51 +01:00
|
|
|
except EscapeCommandInterrupt:
|
2021-05-12 22:29:03 +02:00
|
|
|
command = "" if not escape_to_none else None
|
2021-02-12 23:29:51 +01:00
|
|
|
except TerminateCommandInterrupt as exc:
|
|
|
|
command = exc.command
|
2021-03-14 00:04:55 +01:00
|
|
|
else:
|
|
|
|
command = command[1:].rstrip()
|
2021-02-12 23:29:51 +01:00
|
|
|
curses.curs_set(0)
|
2021-03-13 16:31:11 +01:00
|
|
|
self.clear()
|
2021-02-12 23:29:51 +01:00
|
|
|
return command
|
|
|
|
|
2021-04-19 00:28:20 +02:00
|
|
|
def _validate_common_input(self, ch: int):
|
2021-03-13 16:31:11 +01:00
|
|
|
"""Generic input validator, handles a few more cases than default.
|
|
|
|
|
|
|
|
This validator can be used as a default validator as it handles, on top
|
|
|
|
of the Textbox defaults:
|
|
|
|
- Erasing the first command char, i.e. clearing the line, cancels the
|
|
|
|
command input.
|
|
|
|
- Pressing ESC also cancels the input.
|
|
|
|
|
|
|
|
This validator can be safely called at the beginning of other validators
|
|
|
|
to handle the keys above.
|
|
|
|
"""
|
|
|
|
if ch == curses.KEY_BACKSPACE: # Cancel input if all line is cleaned.
|
|
|
|
text = self.gather()
|
|
|
|
if len(text) == 0:
|
|
|
|
raise EscapeCommandInterrupt()
|
|
|
|
elif ch == curses.ascii.ESC: # Could be ESC or ALT
|
|
|
|
self.window.nodelay(True)
|
|
|
|
ch = self.window.getch()
|
|
|
|
if ch == -1:
|
|
|
|
raise EscapeCommandInterrupt()
|
2021-04-17 21:54:11 +02:00
|
|
|
else: # ALT keybinds.
|
|
|
|
if ch == ord("e"):
|
|
|
|
self.open_editor(self.gather())
|
2021-03-13 16:31:11 +01:00
|
|
|
self.window.nodelay(False)
|
|
|
|
return ch
|
|
|
|
|
|
|
|
def focus_for_link_navigation(self, init_char: int, links: Links):
|
|
|
|
"""Handle a initial digit input by the user.
|
|
|
|
|
|
|
|
When a digit key is pressed, the user intents to visit a link (or
|
|
|
|
dropped something on the numpad). To reduce the number of key types
|
|
|
|
needed, Bebop uses the following algorithm:
|
|
|
|
- If the current user input identifies a link without ambiguity, it is
|
|
|
|
used directly.
|
|
|
|
- If it is ambiguous, the user either inputs as many digits required
|
|
|
|
to disambiguate the link ID, or press enter to validate her input.
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
- I have 3 links. Pressing "2" takes me to link 2.
|
|
|
|
- I have 15 links. Pressing "3" takes me to link 3 (no ambiguity).
|
|
|
|
- I have 15 links. Pressing "1" and "2" takes me to link 12.
|
|
|
|
- I have 456 links. Pressing "1", "2" and Enter takes me to link 12.
|
|
|
|
- I have 456 links. Pressing "1", "2" and "6" takes me to link 126.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
- init_char: the first char (code) being pressed.
|
|
|
|
- links: accessible Links.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The tuple (error, value); if error is 0, value is the link ID to use; if
|
|
|
|
error is 1, discard value and do nothing; if error is 2, value is an
|
|
|
|
error than can be showed to the user.
|
|
|
|
"""
|
|
|
|
digit = init_char & 0xf
|
|
|
|
num_links = len(links)
|
|
|
|
# If there are less than 10 links, just open it now.
|
|
|
|
if num_links < 10:
|
|
|
|
return 0, digit
|
|
|
|
# Else check if the digit alone is sufficient.
|
|
|
|
digit = chr(init_char)
|
|
|
|
max_digits = 0
|
|
|
|
while num_links:
|
|
|
|
max_digits += 1
|
|
|
|
num_links //= 10
|
|
|
|
candidates = links.disambiguate(digit, max_digits)
|
|
|
|
if len(candidates) == 1:
|
|
|
|
return 0, candidates[0]
|
|
|
|
# Else, focus the command line to let the user input more digits.
|
2021-04-19 00:28:20 +02:00
|
|
|
validator = lambda ch: self._validate_link_digit(ch, links, max_digits)
|
|
|
|
link_input = self.focus(CommandLine.CHAR_DIGIT, validator, digit)
|
2021-03-13 16:31:11 +01:00
|
|
|
if not link_input:
|
|
|
|
return 1, None
|
|
|
|
try:
|
|
|
|
link_id = int(link_input)
|
2021-03-13 20:38:19 +01:00
|
|
|
except ValueError:
|
2021-03-13 16:31:11 +01:00
|
|
|
return 2, f"Invalid link ID {link_input}."
|
|
|
|
return 0, link_id
|
|
|
|
|
2021-04-19 00:28:20 +02:00
|
|
|
def _validate_link_digit(self, ch: int, links: Links, max_digits: int):
|
2021-03-13 16:31:11 +01:00
|
|
|
"""Handle input chars to be used as link ID."""
|
|
|
|
# Handle common chars.
|
2021-04-19 00:28:20 +02:00
|
|
|
ch = self._validate_common_input(ch)
|
2021-03-13 16:31:11 +01:00
|
|
|
# Only accept digits. If we reach the amount of required digits, open
|
|
|
|
# link now and leave command line. Else just process it.
|
|
|
|
if curses.ascii.isdigit(ch):
|
|
|
|
digits = self.gather() + chr(ch)
|
|
|
|
candidates = links.disambiguate(digits, max_digits)
|
|
|
|
if len(candidates) == 1:
|
2021-03-13 18:57:37 +01:00
|
|
|
raise TerminateCommandInterrupt(candidates[0])
|
2021-03-13 16:31:11 +01:00
|
|
|
return ch
|
|
|
|
# If not a digit but a printable character, ignore it.
|
|
|
|
if curses.ascii.isprint(ch):
|
|
|
|
return 0
|
|
|
|
# Everything else could be a control character and should be processed.
|
|
|
|
return ch
|
|
|
|
|
2021-04-17 21:54:11 +02:00
|
|
|
def open_editor(self, existing_content=None):
|
|
|
|
"""Open an external editor and raise termination interrupt."""
|
|
|
|
try:
|
|
|
|
with tempfile.NamedTemporaryFile("w+t", delete=False) as temp_file:
|
|
|
|
if existing_content:
|
|
|
|
temp_file.write(existing_content)
|
|
|
|
temp_filepath = temp_file.name
|
|
|
|
except OSError:
|
|
|
|
return
|
|
|
|
|
2021-04-18 02:27:40 +02:00
|
|
|
command = self.editor_command + [temp_filepath]
|
2021-04-17 21:54:11 +02:00
|
|
|
open_external_program(command)
|
|
|
|
|
|
|
|
try:
|
|
|
|
with open(temp_filepath, "rt") as temp_file:
|
2021-04-18 02:27:40 +02:00
|
|
|
content = temp_file.read().rstrip("\r\n")
|
2021-04-17 21:54:11 +02:00
|
|
|
os.unlink(temp_filepath)
|
|
|
|
except OSError:
|
|
|
|
return
|
|
|
|
raise TerminateCommandInterrupt(content)
|
|
|
|
|
2021-04-19 00:28:20 +02:00
|
|
|
def prompt_key(self, keys):
|
|
|
|
"""Focus the command line and wait for the user """
|
|
|
|
validator = lambda ch: self._validate_prompt(ch, keys)
|
|
|
|
key = self.focus(CommandLine.CHAR_TEXT, validator)
|
|
|
|
return key if key in keys else ""
|
|
|
|
|
|
|
|
def _validate_prompt(self, ch: int, keys):
|
|
|
|
"""Handle input chars and raise a terminate interrupt on a valid key."""
|
|
|
|
# Handle common keys.
|
|
|
|
ch = self._validate_common_input(ch)
|
2021-04-19 02:04:18 +02:00
|
|
|
try:
|
|
|
|
char = chr(ch)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if char in keys:
|
|
|
|
raise TerminateCommandInterrupt(char)
|
2021-04-19 00:28:20 +02:00
|
|
|
return 0
|
|
|
|
|
2021-02-12 23:29:51 +01:00
|
|
|
|
|
|
|
class EscapeCommandInterrupt(Exception):
|
|
|
|
"""Signal that ESC has been pressed during command line."""
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class TerminateCommandInterrupt(Exception):
|
2021-02-13 23:34:45 +01:00
|
|
|
"""Signal that validation ended command line input early.
|
2021-02-12 23:29:51 +01:00
|
|
|
|
2021-02-13 23:34:45 +01:00
|
|
|
The value to use is stored in the command attribute. This value can be of
|
|
|
|
any type: str for common commands but also int for ID input, etc.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, command, *args, **kwargs):
|
2021-02-12 23:29:51 +01:00
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.command = command
|