""" ChaosCrypt interactive terminal UI. A dependency-free menu-driven interface, intended for people who would rather not memorise command line flags. English is the default language; the menu can switch to Chinese at runtime. Running ``chaoscrypt`` with no arguments launches this UI. The module is imported lazily so that library users never pay for it. """ from __future__ import annotations import os import sys from typing import Optional from . import DEFAULT_KEY_FILE, __version__, ChaosCrypt from .errors import ChaosCryptError from .i18n import DEFAULT_LANG, LANG_NAMES, t __all__ = ["run_tui", "TUI"] WIDTH = 66 # ANSI styling; degrades to plain text when the terminal cannot handle it. _C = { "reset": "\033[0m", "bold": "\033[1m", "dim": "\033[2m", "cyan": "\033[36m", "green": "\033[32m", "yellow": "\033[33m", "red": "\033[31m", "magenta": "\033[35m", } def _supports_color() -> bool: """Whether the attached stdout can render ANSI colour.""" if os.environ.get("NO_COLOR"): return False if not sys.stdout.isatty(): return False if os.name == "nt": try: import ctypes kernel32 = ctypes.windll.kernel32 kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7) return True except Exception: return False return True _COLOR = _supports_color() def c(text: str, *styles: str) -> str: """Wrap ``text`` in ANSI styles, or return it unchanged.""" if not _COLOR or not styles: return text return "".join(_C.get(s, "") for s in styles) + text + _C["reset"] # --------------------------------------------------------------------------- # Input helpers # --------------------------------------------------------------------------- class _Abort(Exception): """Raised when the user asks to return to the main menu.""" def _ask(prompt: str, default: Optional[str] = None) -> str: suffix = f" [{default}]" if default else "" try: val = input(f"{c('>', 'cyan')} {prompt}{suffix}: ").strip() except (EOFError, KeyboardInterrupt): print() raise _Abort() if not val and default is not None: return default return val def _ask_secret(prompt: str) -> str: """Read a password without echoing it when possible. Interactive terminals use ``getpass`` so the input is not shown. Piped or redirected input cannot use ``getpass``, so it falls back to ``input``, which keeps the UI scriptable. """ label = f"{c('>', 'cyan')} {prompt}: " if sys.stdin is not None and sys.stdin.isatty(): try: import getpass return getpass.getpass(label) except (EOFError, KeyboardInterrupt): print() raise _Abort() except Exception: pass # Fall through to the non-echoing fallback below. try: return input(label).strip() except (EOFError, KeyboardInterrupt): print() raise _Abort() def _ask_yes_no(prompt: str, lang: str) -> bool: try: val = input(f"{c('>', 'cyan')} {prompt} [y/n]: ").strip().lower() except (EOFError, KeyboardInterrupt): print() raise _Abort() return val in ("y", "yes") def _pause(lang: str) -> None: try: input(c(f" {t('press_enter', lang)}", "dim")) except (EOFError, KeyboardInterrupt): print() def _rule() -> str: return "-" * WIDTH # --------------------------------------------------------------------------- # TUI # --------------------------------------------------------------------------- class TUI: """Menu-driven bilingual interface over :class:`~chaoscrypt.ChaosCrypt`.""" def __init__(self, lang: str = DEFAULT_LANG, key_file: str = DEFAULT_KEY_FILE) -> None: self.lang = lang if lang in LANG_NAMES else DEFAULT_LANG self.key_file = key_file self.cc = ChaosCrypt() self.key_password: Optional[str] = None # ------------------------------------------------------------------ view def _tr(self, key: str) -> str: return t(key, self.lang) def banner(self) -> None: print() print(c("+" + "=" * (WIDTH - 2) + "+", "magenta")) title = f" {self._tr('app_title')} v{__version__}" print(c("|", "magenta") + c(title.ljust(WIDTH - 2), "bold", "cyan") + c("|", "magenta")) print(c("+" + "=" * (WIDTH - 2) + "+", "magenta")) for line in self._tr("warn_banner").split("\n"): print(c(line, "yellow")) shown = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE state = ( c("[*] " + self._tr("key_loaded"), "green") if self.cc.loaded else c("[ ] " + self._tr("no_key_loaded"), "red") ) print(f"\n{state} {c(shown, 'dim')}") def _print_error(self, exc: Exception) -> None: """Render a unified error, with a hint where one applies.""" print() print(c("+" + "-" * (WIDTH - 2) + "+", "red")) print(c("| ", "red") + c(f"{self._tr('err_prefix')}: {exc}", "red", "bold")) print(c("+" + "-" * (WIDTH - 2) + "+", "red")) msg = str(exc) if "_E011" in msg or "_E003" in msg: print(c(" " + self._tr("err_hint_password"), "dim")) elif "_E004" in msg or "_E001" in msg: print(c(" " + self._tr("err_hint_key_required"), "dim")) # ------------------------------------------------------------------ menu def menu(self) -> str: items = [ ("1", "menu_encrypt"), ("2", "menu_decrypt"), ("3", "menu_encrypt_file"), ("4", "menu_decrypt_file"), ("5", "menu_keygen"), ("6", "menu_loadkey"), ("7", "menu_keyinfo"), ("8", "menu_chpwd"), ("9", "menu_lang"), ("a", "menu_about"), ("q", "menu_quit"), ] print() print(c(_rule(), "dim")) print(c(" " + self._tr("menu_choose"), "bold")) print(c(_rule(), "dim")) for key, label in items: print(f" {c('[' + key + ']', 'cyan')} {self._tr(label)}") print(c(_rule(), "dim")) return _ask(self._tr("menu_prompt")).lower() # ------------------------------------------------------------ key state def _ensure_key(self) -> bool: """Make sure a key is loaded, offering to create one if none exists. Searches the instance's loaded key, then the remembered file, then the default name. """ if self.cc.loaded: return True path = ( self.cc.key_file or self.key_file or DEFAULT_KEY_FILE ) self.key_file = path if not os.path.exists(path): if _ask_yes_no(self._tr("prompt_create_if_missing"), self.lang): return self.action_keygen() return False try: pwd = self.key_password or _ask_secret(self._tr("prompt_key_password")) self.cc.load(path, pwd) self.key_password = pwd print(c(f"{self._tr('key_loaded')}: {path}", "green")) return True except ChaosCryptError as exc: self._print_error(exc) return False # ---------------------------------------------------------------- actions def action_encrypt(self) -> None: if not self._ensure_key(): return text = _ask(self._tr("prompt_plaintext")) if not text: print(c(" " + self._tr("cancelled"), "dim")) return pwd = _ask_secret(self._tr("prompt_user_password")) try: ct = self.cc.encrypt(text, pwd) print() print(c(f"{self._tr('result_ciphertext')}:", "green", "bold")) print(c(ct, "cyan")) except ChaosCryptError as exc: self._print_error(exc) def action_decrypt(self) -> None: if not self._ensure_key(): return text = _ask(self._tr("prompt_ciphertext")) if not text: print(c(" " + self._tr("cancelled"), "dim")) return pwd = _ask_secret(self._tr("prompt_user_password")) try: pt = self.cc.decrypt(text, pwd) print() print(c(f"{self._tr('result_plaintext')}:", "green", "bold")) print(c(pt, "cyan")) except ChaosCryptError as exc: self._print_error(exc) def action_encrypt_file(self) -> None: if not self._ensure_key(): return src = _ask(self._tr("prompt_src_file")) if not src or not os.path.exists(src): print(c(f" {self._tr('failed')}: {src}", "red")) return dst = _ask(self._tr("prompt_dst_file")) or None pwd = _ask_secret(self._tr("prompt_user_password")) try: out = self.cc.encrypt_file(src, pwd, dst) print(c(f"{self._tr('file_written')}: {out}", "green")) except ChaosCryptError as exc: self._print_error(exc) def action_decrypt_file(self) -> None: if not self._ensure_key(): return src = _ask(self._tr("prompt_src_file")) if not src or not os.path.exists(src): print(c(f" {self._tr('failed')}: {src}", "red")) return dst = _ask(self._tr("prompt_dst_file")) or None pwd = _ask_secret(self._tr("prompt_user_password")) try: out = self.cc.decrypt_file(src, pwd, dst) print(c(f"{self._tr('file_written')}: {out}", "green")) except ChaosCryptError as exc: self._print_error(exc) def action_keygen(self) -> bool: default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE path = _ask(self._tr("prompt_key_file"), default) overwrite = False if os.path.exists(path): if not _ask_yes_no(self._tr("prompt_overwrite"), self.lang): print(c(" " + self._tr("cancelled"), "dim")) return False overwrite = True pwd = _ask_secret(self._tr("prompt_key_password_new")) if not pwd: print(c(" " + self._tr("failed"), "red")) return False confirm = _ask_secret(self._tr("prompt_key_password_confirm")) if pwd != confirm: print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red")) return False try: out = self.cc.create_key(pwd, path, overwrite=overwrite) self.key_file = out self.key_password = pwd print(c(f"{self._tr('key_saved')}: {out}", "green")) return True except ChaosCryptError as exc: self._print_error(exc) return False def action_loadkey(self) -> None: default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE path = _ask(self._tr("prompt_key_file"), default) pwd = _ask_secret(self._tr("prompt_key_password")) try: self.cc.load(path, pwd) self.key_file = path self.key_password = pwd print(c(f"{self._tr('key_loaded')}: {path}", "green")) except ChaosCryptError as exc: self._print_error(exc) def action_keyinfo(self) -> None: if not self._ensure_key(): return try: info = self.cc.info() except ChaosCryptError as exc: self._print_error(exc) return rows = [ ("info_key_file", info["key_file"]), ("info_version", info["version"]), ("info_upper", info["upper_mapping"]), ("info_lower", info["lower_mapping"]), ("info_digit", "".join(info["digit_mapping"].values())), ("info_equal", "".join(info["equal_mapping"].values())), ("info_flip", info["flip_pattern"]), ("info_long_key", f"{info['long_key_length']} {self._tr('characters')}"), ("info_short_key", f"{info['short_key_length']} {self._tr('characters')}"), ("info_loaded", self._tr("yes")), ] print() print(c(_rule(), "dim")) for key, val in rows: print(f" {c(self._tr(key), 'bold'):<38} {val}") print(c(_rule(), "dim")) def action_chpwd(self) -> None: default = self.cc.key_file or self.key_file or DEFAULT_KEY_FILE path = _ask(self._tr("prompt_key_file"), default) if not os.path.exists(path): print(c(" ChaosCrypt_ERR_KeyFileNotFound_E001", "red")) return old = _ask_secret(self._tr("prompt_key_password_old")) new = _ask_secret(self._tr("prompt_key_password_new")) confirm = _ask_secret(self._tr("prompt_key_password_confirm")) if new != confirm: print(c(" ChaosCrypt_ERR_PasswordMismatch_E007", "red")) return try: out = self.cc.change_key_password(old, new, path) self.key_password = new print(c(f"{self._tr('key_password_changed')}: {out}", "green")) except ChaosCryptError as exc: self._print_error(exc) def action_lang(self) -> None: codes = list(LANG_NAMES.keys()) print() for i, (code, name) in enumerate(LANG_NAMES.items(), 1): mark = "*" if code == self.lang else " " print(f" {c('[' + str(i) + ']', 'cyan')} {mark} {name} ({code})") default_index = str(codes.index(self.lang) + 1) if self.lang in codes else "1" choice = _ask("Language", default_index) try: idx = int(choice) - 1 if 0 <= idx < len(codes): self.lang = codes[idx] except ValueError: if choice in codes: self.lang = choice print(c(f" -> {LANG_NAMES[self.lang]}", "green")) def action_about(self) -> None: print() print(c(self._tr("about_body"), "cyan")) # ------------------------------------------------------------- main loop def run(self) -> int: while True: self.banner() try: choice = self.menu() except _Abort: print() print(c(self._tr("bye"), "green")) return 0 try: if choice == "1": self.action_encrypt() elif choice == "2": self.action_decrypt() elif choice == "3": self.action_encrypt_file() elif choice == "4": self.action_decrypt_file() elif choice == "5": self.action_keygen() elif choice == "6": self.action_loadkey() elif choice == "7": self.action_keyinfo() elif choice == "8": self.action_chpwd() elif choice == "9": self.action_lang() elif choice in ("a", "about"): self.action_about() elif choice in ("q", "quit", "exit"): print() print(c(self._tr("bye"), "green")) return 0 else: print(c(" " + self._tr("menu_invalid"), "yellow")) continue except _Abort: print(c(" " + self._tr("cancelled"), "dim")) continue except KeyboardInterrupt: print() print(c(self._tr("bye"), "green")) return 0 _pause(self.lang) def run_tui(lang: str = DEFAULT_LANG, key_file: str = DEFAULT_KEY_FILE) -> int: """Launch the interactive UI and return the process exit code.""" try: return TUI(lang=lang, key_file=key_file).run() except KeyboardInterrupt: print() return 0 if __name__ == "__main__": # pragma: no cover sys.exit(run_tui())