Improve Linux terminal input and interactive path prompts
This commit is contained in:
1 parent
eb5937a629
commit
ad2b15994f
5 files changed
+190
-22
No files matched your search
Regular → Executable
+3
-1
@@ -11,7 +11,7 @@ from __future__ import annotations
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from tools.console import pause_if_interactive, prompt_input
|
from tools.console import launch_terminal_if_needed, pause_if_interactive, prompt_input
|
||||||
from tools.exiftool import require_exiftool
|
from tools.exiftool import require_exiftool
|
||||||
from tools.metadata_copy import copy_meaningful_metadata
|
from tools.metadata_copy import copy_meaningful_metadata
|
||||||
|
|
||||||
@@ -93,6 +93,8 @@ def run(argv: list[str]) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def main(argv: list[str]) -> int:
|
def main(argv: list[str]) -> int:
|
||||||
|
if launch_terminal_if_needed(argv):
|
||||||
|
return 0
|
||||||
try:
|
try:
|
||||||
return run(argv)
|
return run(argv)
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
+63
-7
@@ -3,12 +3,14 @@ from __future__ import annotations
|
|||||||
import os
|
import os
|
||||||
import select
|
import select
|
||||||
import shutil
|
import shutil
|
||||||
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import textwrap
|
import textwrap
|
||||||
import time
|
import time
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from math import floor, log10
|
from math import floor, log10
|
||||||
|
from pathlib import Path
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
|
|
||||||
|
|
||||||
@@ -44,6 +46,26 @@ def pause_if_interactive() -> None:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def launch_terminal_if_needed(argv: list[str]) -> bool:
|
||||||
|
"""Relaunch an interactive script when a desktop starts it without a terminal."""
|
||||||
|
if os.name == "nt" or (stream_is_interactive(sys.stdin) and stream_is_interactive(sys.stdout)):
|
||||||
|
return False
|
||||||
|
if not (os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")):
|
||||||
|
return False
|
||||||
|
|
||||||
|
terminals = (("konsole", "-e"), ("gnome-terminal", "--"), ("x-terminal-emulator", "-e"))
|
||||||
|
for name, separator in terminals:
|
||||||
|
executable = shutil.which(name)
|
||||||
|
if executable:
|
||||||
|
script = Path(argv[0]).resolve()
|
||||||
|
subprocess.Popen(
|
||||||
|
[executable, separator, sys.executable, str(script), *argv[1:]],
|
||||||
|
cwd=script.parent,
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def supports_color() -> bool:
|
def supports_color() -> bool:
|
||||||
return not os.environ.get("NO_COLOR") and supports_ansi()
|
return not os.environ.get("NO_COLOR") and supports_ansi()
|
||||||
|
|
||||||
@@ -117,7 +139,7 @@ def raw_key_input():
|
|||||||
fd = sys.stdin.fileno()
|
fd = sys.stdin.fileno()
|
||||||
settings = termios.tcgetattr(fd)
|
settings = termios.tcgetattr(fd)
|
||||||
try:
|
try:
|
||||||
tty.setraw(fd)
|
tty.setcbreak(fd)
|
||||||
yield read_key
|
yield read_key
|
||||||
finally:
|
finally:
|
||||||
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
|
termios.tcsetattr(fd, termios.TCSADRAIN, settings)
|
||||||
@@ -129,13 +151,47 @@ def read_key() -> str:
|
|||||||
|
|
||||||
key = msvcrt.getwch()
|
key = msvcrt.getwch()
|
||||||
if key in {"\x00", "\xe0"}:
|
if key in {"\x00", "\xe0"}:
|
||||||
return {"H": "up", "P": "down", "K": "left", "M": "right"}.get(msvcrt.getwch(), "")
|
return {"H": "up", "P": "down", "K": "left", "M": "right", "S": "delete"}.get(msvcrt.getwch(), "")
|
||||||
else:
|
else:
|
||||||
key = sys.stdin.read(1)
|
fd = sys.stdin.fileno()
|
||||||
if key == "\x1b" and select.select([sys.stdin], [], [], 0.03)[0]:
|
key = _read_unix_character(fd)
|
||||||
key += sys.stdin.read(2)
|
if key == "\x1b":
|
||||||
return {"\x1b[A": "up", "\x1b[B": "down", "\x1b[D": "left", "\x1b[C": "right"}.get(key, "esc")
|
return _read_escape_sequence(fd)
|
||||||
return {"\r": "enter", "\n": "enter", "\x1b": "esc", "\x08": "backspace", "\x7f": "backspace", " ": "space"}.get(key, key)
|
return {"\r": "enter", "\n": "enter", "\t": "tab", "\x1b": "esc", "\x08": "backspace", "\x7f": "backspace", " ": "space"}.get(key, key)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_unix_character(fd: int) -> str:
|
||||||
|
data = os.read(fd, 1)
|
||||||
|
first = data[0]
|
||||||
|
length = 1 if first < 0x80 else 2 if first < 0xE0 else 3 if first < 0xF0 else 4
|
||||||
|
while len(data) < length:
|
||||||
|
data += os.read(fd, length - len(data))
|
||||||
|
return data.decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _read_escape_sequence(fd: int) -> str:
|
||||||
|
if not select.select([fd], [], [], 0.1)[0]:
|
||||||
|
return "esc"
|
||||||
|
sequence = "\x1b" + _read_unix_character(fd)
|
||||||
|
if sequence[1:] in {"[", "O"}:
|
||||||
|
for _ in range(6):
|
||||||
|
if not select.select([fd], [], [], 0.1)[0]:
|
||||||
|
break
|
||||||
|
character = _read_unix_character(fd)
|
||||||
|
sequence += character
|
||||||
|
if character.isalpha() or character == "~":
|
||||||
|
break
|
||||||
|
return {
|
||||||
|
"\x1b[A": "up",
|
||||||
|
"\x1b[B": "down",
|
||||||
|
"\x1b[D": "left",
|
||||||
|
"\x1b[C": "right",
|
||||||
|
"\x1bOA": "up",
|
||||||
|
"\x1bOB": "down",
|
||||||
|
"\x1bOD": "left",
|
||||||
|
"\x1bOC": "right",
|
||||||
|
"\x1b[3~": "delete",
|
||||||
|
}.get(sequence, "")
|
||||||
|
|
||||||
|
|
||||||
def draw_screen(lines: list[str]) -> None:
|
def draw_screen(lines: list[str]) -> None:
|
||||||
|
|||||||
@@ -1,7 +1,102 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import glob
|
||||||
import os
|
import os
|
||||||
|
from contextlib import contextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from urllib.parse import unquote, urlparse
|
||||||
|
|
||||||
|
from tools.console import prompt_input
|
||||||
|
|
||||||
|
|
||||||
|
def entered_path(value: str) -> Path:
|
||||||
|
text = value.strip()
|
||||||
|
if len(text) > 1 and text[0] == text[-1] and text[0] in "\"'":
|
||||||
|
text = text[1:-1]
|
||||||
|
if text.startswith("file://"):
|
||||||
|
text = unquote(urlparse(text).path)
|
||||||
|
return Path(text).expanduser()
|
||||||
|
|
||||||
|
|
||||||
|
def path_completions(text: str, base: Path | None = None) -> list[str]:
|
||||||
|
quote = text[0] if text[:1] in {"\"", "'"} else ""
|
||||||
|
value = text[1:] if quote else text
|
||||||
|
if quote and value.endswith(quote):
|
||||||
|
value = value[:-1]
|
||||||
|
expanded = os.path.expanduser(value)
|
||||||
|
relative = base is not None and not Path(expanded).is_absolute()
|
||||||
|
search = os.path.join(str(base), expanded) if relative else expanded
|
||||||
|
found = sorted(glob.glob(glob.escape(search) + "*"), key=str.casefold)
|
||||||
|
matches = [os.path.relpath(match, base) for match in found] if relative else found.copy()
|
||||||
|
if value.startswith("~"):
|
||||||
|
home = str(Path.home())
|
||||||
|
matches = ["~" + match[len(home):] if match.startswith(home) else match for match in matches]
|
||||||
|
return [
|
||||||
|
quote + match + (os.sep if Path(found[index]).is_dir() else "")
|
||||||
|
for index, match in enumerate(matches)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def complete_path(text: str, base: Path | None = None) -> str:
|
||||||
|
matches = path_completions(text, base)
|
||||||
|
return os.path.commonprefix(matches) if matches else text
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def path_completion(candidates=path_completions):
|
||||||
|
try:
|
||||||
|
import readline
|
||||||
|
except ImportError:
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
|
||||||
|
previous = readline.get_completer(), readline.get_completer_delims()
|
||||||
|
matches: list[str] = []
|
||||||
|
|
||||||
|
def complete(text: str, state: int) -> str | None:
|
||||||
|
nonlocal matches
|
||||||
|
if state == 0:
|
||||||
|
matches = candidates(text)
|
||||||
|
return matches[state] if state < len(matches) else None
|
||||||
|
|
||||||
|
readline.set_completer(complete)
|
||||||
|
readline.set_completer_delims("\n")
|
||||||
|
readline.parse_and_bind("tab: complete")
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
readline.set_completer(previous[0])
|
||||||
|
readline.set_completer_delims(previous[1])
|
||||||
|
|
||||||
|
|
||||||
|
def prompt_existing_paths() -> list[str]:
|
||||||
|
print("Enter one file or directory per line. Leave the path empty when finished.")
|
||||||
|
paths: list[str] = []
|
||||||
|
with path_completion():
|
||||||
|
while True:
|
||||||
|
value = prompt_input("Path: ").strip()
|
||||||
|
if not value:
|
||||||
|
return paths
|
||||||
|
path = entered_path(value)
|
||||||
|
if not path.exists():
|
||||||
|
print("Path not found. Try again.")
|
||||||
|
continue
|
||||||
|
paths.append(str(path.resolve()))
|
||||||
|
|
||||||
|
|
||||||
|
def input_paths(argv: list[str]) -> list[str]:
|
||||||
|
return argv[1:] or prompt_existing_paths()
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_output_directory(value: str, default: Path) -> Path:
|
||||||
|
if not value.strip():
|
||||||
|
return default
|
||||||
|
path = entered_path(value)
|
||||||
|
path = path if path.is_absolute() else default / path
|
||||||
|
path = path.resolve()
|
||||||
|
if path.exists() and not path.is_dir():
|
||||||
|
raise ValueError("The output path exists but is not a directory.")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
def existing_input_paths(args: list[str], *, print_missing: bool = False) -> list[Path]:
|
def existing_input_paths(args: list[str], *, print_missing: bool = False) -> list[Path]:
|
||||||
|
|||||||
Regular → Executable
+16
-8
@@ -27,9 +27,15 @@ from tools.avisynth_workspace import (
|
|||||||
workspace_root,
|
workspace_root,
|
||||||
write_workspace,
|
write_workspace,
|
||||||
)
|
)
|
||||||
from tools.console import ProgressView, pause_if_interactive, prompt_input, prompt_yes_no
|
from tools.console import (
|
||||||
|
ProgressView,
|
||||||
|
launch_terminal_if_needed,
|
||||||
|
pause_if_interactive,
|
||||||
|
prompt_input,
|
||||||
|
prompt_yes_no,
|
||||||
|
)
|
||||||
from tools.exiftool import require_exiftool, run_exiftool_json
|
from tools.exiftool import require_exiftool, run_exiftool_json
|
||||||
from tools.filesystem import determine_working_dir
|
from tools.filesystem import determine_working_dir, input_paths
|
||||||
from tools.video_batch_encode import encode_validated_video_only
|
from tools.video_batch_encode import encode_validated_video_only
|
||||||
from tools.video_inputs import VideoInput, collect_video_inputs
|
from tools.video_inputs import VideoInput, collect_video_inputs
|
||||||
from tools.video_options import (
|
from tools.video_options import (
|
||||||
@@ -43,13 +49,13 @@ from tools.video_validation_workflow import run_validations
|
|||||||
|
|
||||||
|
|
||||||
def run(argv: list[str]) -> int:
|
def run(argv: list[str]) -> int:
|
||||||
if len(argv) < 2:
|
|
||||||
print("Usage: python3 video_encode.py path/to/file/or/directory [...]")
|
|
||||||
return 2
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
working_dir = determine_working_dir(argv[1:])
|
args = input_paths(argv)
|
||||||
inputs = collect_video_inputs(argv[1:])
|
if not args:
|
||||||
|
print("No inputs selected.")
|
||||||
|
return 0
|
||||||
|
working_dir = determine_working_dir(args)
|
||||||
|
inputs = collect_video_inputs(args)
|
||||||
except RuntimeError as exc:
|
except RuntimeError as exc:
|
||||||
print(exc)
|
print(exc)
|
||||||
return 1
|
return 1
|
||||||
@@ -364,6 +370,8 @@ def wait_for_script_edits() -> str | None:
|
|||||||
|
|
||||||
|
|
||||||
def main(argv: list[str]) -> int:
|
def main(argv: list[str]) -> int:
|
||||||
|
if launch_terminal_if_needed(argv):
|
||||||
|
return 0
|
||||||
try:
|
try:
|
||||||
return run(argv)
|
return run(argv)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
|
|||||||
Regular → Executable
+13
-6
@@ -13,9 +13,9 @@ from __future__ import annotations
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from tools.console import pause_if_interactive
|
from tools.console import launch_terminal_if_needed, pause_if_interactive
|
||||||
from tools.exiftool import require_exiftool, run_exiftool_command
|
from tools.exiftool import require_exiftool, run_exiftool_command
|
||||||
from tools.filesystem import first_file_from_path
|
from tools.filesystem import first_file_from_path, input_paths
|
||||||
|
|
||||||
|
|
||||||
def choose_file(args: list[str]) -> Path | None:
|
def choose_file(args: list[str]) -> Path | None:
|
||||||
@@ -27,9 +27,14 @@ def choose_file(args: list[str]) -> Path | None:
|
|||||||
|
|
||||||
|
|
||||||
def run(argv: list[str]) -> int:
|
def run(argv: list[str]) -> int:
|
||||||
if len(argv) < 2:
|
try:
|
||||||
print("Usage: python3 view_metadata.py path/to/file/or/directory [...]")
|
args = input_paths(argv)
|
||||||
return 2
|
except RuntimeError as exc:
|
||||||
|
print(exc)
|
||||||
|
return 1
|
||||||
|
if not args:
|
||||||
|
print("No inputs selected.")
|
||||||
|
return 0
|
||||||
|
|
||||||
try:
|
try:
|
||||||
exiftool = require_exiftool()
|
exiftool = require_exiftool()
|
||||||
@@ -37,7 +42,7 @@ def run(argv: list[str]) -> int:
|
|||||||
print(exc)
|
print(exc)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
file_path = choose_file(argv[1:])
|
file_path = choose_file(args)
|
||||||
if file_path is None:
|
if file_path is None:
|
||||||
print("No file found.")
|
print("No file found.")
|
||||||
return 1
|
return 1
|
||||||
@@ -55,6 +60,8 @@ def run(argv: list[str]) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def main(argv: list[str]) -> int:
|
def main(argv: list[str]) -> int:
|
||||||
|
if launch_terminal_if_needed(argv):
|
||||||
|
return 0
|
||||||
try:
|
try:
|
||||||
return run(argv)
|
return run(argv)
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
Reference in new issue
Block a user