_termui_impl.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. """
  2. This module contains implementations for the termui module. To keep the
  3. import time of Click down, some infrequently used functionality is
  4. placed in this module and only imported as needed.
  5. """
  6. from __future__ import annotations
  7. import collections.abc as cabc
  8. import contextlib
  9. import math
  10. import os
  11. import shlex
  12. import sys
  13. import time
  14. import typing as t
  15. from gettext import gettext as _
  16. from io import StringIO
  17. from pathlib import Path
  18. from shutil import which
  19. from types import TracebackType
  20. from ._compat import _default_text_stdout
  21. from ._compat import CYGWIN
  22. from ._compat import get_best_encoding
  23. from ._compat import isatty
  24. from ._compat import open_stream
  25. from ._compat import strip_ansi
  26. from ._compat import term_len
  27. from ._compat import WIN
  28. from .exceptions import ClickException
  29. from .utils import echo
  30. V = t.TypeVar("V")
  31. if os.name == "nt":
  32. BEFORE_BAR = "\r"
  33. AFTER_BAR = "\n"
  34. else:
  35. BEFORE_BAR = "\r\033[?25l"
  36. AFTER_BAR = "\033[?25h\n"
  37. class ProgressBar(t.Generic[V]):
  38. def __init__(
  39. self,
  40. iterable: cabc.Iterable[V] | None,
  41. length: int | None = None,
  42. fill_char: str = "#",
  43. empty_char: str = " ",
  44. bar_template: str = "%(bar)s",
  45. info_sep: str = " ",
  46. hidden: bool = False,
  47. show_eta: bool = True,
  48. show_percent: bool | None = None,
  49. show_pos: bool = False,
  50. item_show_func: t.Callable[[V | None], str | None] | None = None,
  51. label: str | None = None,
  52. file: t.TextIO | None = None,
  53. color: bool | None = None,
  54. update_min_steps: int = 1,
  55. width: int = 30,
  56. ) -> None:
  57. self.fill_char = fill_char
  58. self.empty_char = empty_char
  59. self.bar_template = bar_template
  60. self.info_sep = info_sep
  61. self.hidden = hidden
  62. self.show_eta = show_eta
  63. self.show_percent = show_percent
  64. self.show_pos = show_pos
  65. self.item_show_func = item_show_func
  66. self.label: str = label or ""
  67. if file is None:
  68. file = _default_text_stdout()
  69. # There are no standard streams attached to write to. For example,
  70. # pythonw on Windows.
  71. if file is None:
  72. file = StringIO()
  73. self.file = file
  74. self.color = color
  75. self.update_min_steps = update_min_steps
  76. self._completed_intervals = 0
  77. self.width: int = width
  78. self.autowidth: bool = width == 0
  79. if length is None:
  80. from operator import length_hint
  81. length = length_hint(iterable, -1)
  82. if length == -1:
  83. length = None
  84. if iterable is None:
  85. if length is None:
  86. raise TypeError("iterable or length is required")
  87. iterable = t.cast("cabc.Iterable[V]", range(length))
  88. self.iter: cabc.Iterable[V] = iter(iterable)
  89. self.length = length
  90. self.pos: int = 0
  91. self.avg: list[float] = []
  92. self.last_eta: float
  93. self.start: float
  94. self.start = self.last_eta = time.time()
  95. self.eta_known: bool = False
  96. self.finished: bool = False
  97. self.max_width: int | None = None
  98. self.entered: bool = False
  99. self.current_item: V | None = None
  100. self._is_atty = isatty(self.file)
  101. self._last_line: str | None = None
  102. def __enter__(self) -> ProgressBar[V]:
  103. self.entered = True
  104. self.render_progress()
  105. return self
  106. def __exit__(
  107. self,
  108. exc_type: type[BaseException] | None,
  109. exc_value: BaseException | None,
  110. tb: TracebackType | None,
  111. ) -> None:
  112. self.render_finish()
  113. def __iter__(self) -> cabc.Iterator[V]:
  114. if not self.entered:
  115. raise RuntimeError("You need to use progress bars in a with block.")
  116. self.render_progress()
  117. return self.generator()
  118. def __next__(self) -> V:
  119. # Iteration is defined in terms of a generator function,
  120. # returned by iter(self); use that to define next(). This works
  121. # because `self.iter` is an iterable consumed by that generator,
  122. # so it is re-entry safe. Calling `next(self.generator())`
  123. # twice works and does "what you want".
  124. return next(iter(self))
  125. def render_finish(self) -> None:
  126. if self.hidden or not self._is_atty:
  127. return
  128. self.file.write(AFTER_BAR)
  129. self.file.flush()
  130. @property
  131. def pct(self) -> float:
  132. if self.finished:
  133. return 1.0
  134. return min(self.pos / (float(self.length or 1) or 1), 1.0)
  135. @property
  136. def time_per_iteration(self) -> float:
  137. if not self.avg:
  138. return 0.0
  139. return sum(self.avg) / float(len(self.avg))
  140. @property
  141. def eta(self) -> float:
  142. if self.length is not None and not self.finished:
  143. return self.time_per_iteration * (self.length - self.pos)
  144. return 0.0
  145. def format_eta(self) -> str:
  146. if self.eta_known:
  147. t = int(self.eta)
  148. seconds = t % 60
  149. t //= 60
  150. minutes = t % 60
  151. t //= 60
  152. hours = t % 24
  153. t //= 24
  154. if t > 0:
  155. return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"
  156. else:
  157. return f"{hours:02}:{minutes:02}:{seconds:02}"
  158. return ""
  159. def format_pos(self) -> str:
  160. pos = str(self.pos)
  161. if self.length is not None:
  162. pos += f"/{self.length}"
  163. return pos
  164. def format_pct(self) -> str:
  165. return f"{int(self.pct * 100): 4}%"[1:]
  166. def format_bar(self) -> str:
  167. if self.length is not None:
  168. bar_length = int(self.pct * self.width)
  169. bar = self.fill_char * bar_length
  170. bar += self.empty_char * (self.width - bar_length)
  171. elif self.finished:
  172. bar = self.fill_char * self.width
  173. else:
  174. chars = list(self.empty_char * (self.width or 1))
  175. if self.time_per_iteration != 0:
  176. chars[
  177. int(
  178. (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)
  179. * self.width
  180. )
  181. ] = self.fill_char
  182. bar = "".join(chars)
  183. return bar
  184. def format_progress_line(self) -> str:
  185. show_percent = self.show_percent
  186. info_bits = []
  187. if self.length is not None and show_percent is None:
  188. show_percent = not self.show_pos
  189. if self.show_pos:
  190. info_bits.append(self.format_pos())
  191. if show_percent:
  192. info_bits.append(self.format_pct())
  193. if self.show_eta and self.eta_known and not self.finished:
  194. info_bits.append(self.format_eta())
  195. if self.item_show_func is not None:
  196. item_info = self.item_show_func(self.current_item)
  197. if item_info is not None:
  198. info_bits.append(item_info)
  199. return (
  200. self.bar_template
  201. % {
  202. "label": self.label,
  203. "bar": self.format_bar(),
  204. "info": self.info_sep.join(info_bits),
  205. }
  206. ).rstrip()
  207. def render_progress(self) -> None:
  208. import shutil
  209. if self.hidden:
  210. return
  211. if not self._is_atty:
  212. # Only output the label once if the output is not a TTY.
  213. if self._last_line != self.label:
  214. self._last_line = self.label
  215. echo(self.label, file=self.file, color=self.color)
  216. return
  217. buf = []
  218. # Update width in case the terminal has been resized
  219. if self.autowidth:
  220. old_width = self.width
  221. self.width = 0
  222. clutter_length = term_len(self.format_progress_line())
  223. new_width = max(0, shutil.get_terminal_size().columns - clutter_length)
  224. if new_width < old_width and self.max_width is not None:
  225. buf.append(BEFORE_BAR)
  226. buf.append(" " * self.max_width)
  227. self.max_width = new_width
  228. self.width = new_width
  229. clear_width = self.width
  230. if self.max_width is not None:
  231. clear_width = self.max_width
  232. buf.append(BEFORE_BAR)
  233. line = self.format_progress_line()
  234. line_len = term_len(line)
  235. if self.max_width is None or self.max_width < line_len:
  236. self.max_width = line_len
  237. buf.append(line)
  238. buf.append(" " * (clear_width - line_len))
  239. line = "".join(buf)
  240. # Render the line only if it changed.
  241. if line != self._last_line:
  242. self._last_line = line
  243. echo(line, file=self.file, color=self.color, nl=False)
  244. self.file.flush()
  245. def make_step(self, n_steps: int) -> None:
  246. self.pos += n_steps
  247. if self.length is not None and self.pos >= self.length:
  248. self.finished = True
  249. if (time.time() - self.last_eta) < 1.0:
  250. return
  251. self.last_eta = time.time()
  252. # self.avg is a rolling list of length <= 7 of steps where steps are
  253. # defined as time elapsed divided by the total progress through
  254. # self.length.
  255. if self.pos:
  256. step = (time.time() - self.start) / self.pos
  257. else:
  258. step = time.time() - self.start
  259. self.avg = self.avg[-6:] + [step]
  260. self.eta_known = self.length is not None
  261. def update(self, n_steps: int, current_item: V | None = None) -> None:
  262. """Update the progress bar by advancing a specified number of
  263. steps, and optionally set the ``current_item`` for this new
  264. position.
  265. :param n_steps: Number of steps to advance.
  266. :param current_item: Optional item to set as ``current_item``
  267. for the updated position.
  268. .. versionchanged:: 8.0
  269. Added the ``current_item`` optional parameter.
  270. .. versionchanged:: 8.0
  271. Only render when the number of steps meets the
  272. ``update_min_steps`` threshold.
  273. """
  274. if current_item is not None:
  275. self.current_item = current_item
  276. self._completed_intervals += n_steps
  277. if self._completed_intervals >= self.update_min_steps:
  278. self.make_step(self._completed_intervals)
  279. self.render_progress()
  280. self._completed_intervals = 0
  281. def finish(self) -> None:
  282. self.eta_known = False
  283. self.current_item = None
  284. self.finished = True
  285. def generator(self) -> cabc.Iterator[V]:
  286. """Return a generator which yields the items added to the bar
  287. during construction, and updates the progress bar *after* the
  288. yielded block returns.
  289. """
  290. # WARNING: the iterator interface for `ProgressBar` relies on
  291. # this and only works because this is a simple generator which
  292. # doesn't create or manage additional state. If this function
  293. # changes, the impact should be evaluated both against
  294. # `iter(bar)` and `next(bar)`. `next()` in particular may call
  295. # `self.generator()` repeatedly, and this must remain safe in
  296. # order for that interface to work.
  297. if not self.entered:
  298. raise RuntimeError("You need to use progress bars in a with block.")
  299. if not self._is_atty:
  300. yield from self.iter
  301. else:
  302. for rv in self.iter:
  303. self.current_item = rv
  304. # This allows show_item_func to be updated before the
  305. # item is processed. Only trigger at the beginning of
  306. # the update interval.
  307. if self._completed_intervals == 0:
  308. self.render_progress()
  309. yield rv
  310. self.update(1)
  311. self.finish()
  312. self.render_progress()
  313. def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:
  314. """Decide what method to use for paging through text."""
  315. stdout = _default_text_stdout()
  316. # There are no standard streams attached to write to. For example,
  317. # pythonw on Windows.
  318. if stdout is None:
  319. stdout = StringIO()
  320. if not isatty(sys.stdin) or not isatty(stdout):
  321. return _nullpager(stdout, generator, color)
  322. # Split and normalize the pager command into parts.
  323. pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False)
  324. if pager_cmd_parts:
  325. if WIN:
  326. if _tempfilepager(generator, pager_cmd_parts, color):
  327. return
  328. elif _pipepager(generator, pager_cmd_parts, color):
  329. return
  330. if os.environ.get("TERM") in ("dumb", "emacs"):
  331. return _nullpager(stdout, generator, color)
  332. if (WIN or sys.platform.startswith("os2")) and _tempfilepager(
  333. generator, ["more"], color
  334. ):
  335. return
  336. if _pipepager(generator, ["less"], color):
  337. return
  338. import tempfile
  339. fd, filename = tempfile.mkstemp()
  340. os.close(fd)
  341. try:
  342. if _pipepager(generator, ["more"], color):
  343. return
  344. return _nullpager(stdout, generator, color)
  345. finally:
  346. os.unlink(filename)
  347. def _pipepager(
  348. generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None
  349. ) -> bool:
  350. """Page through text by feeding it to another program. Invoking a
  351. pager through this might support colors.
  352. Returns `True` if the command was found, `False` otherwise and thus another
  353. pager should be attempted.
  354. """
  355. # Split the command into the invoked CLI and its parameters.
  356. if not cmd_parts:
  357. return False
  358. cmd = cmd_parts[0]
  359. cmd_params = cmd_parts[1:]
  360. cmd_filepath = which(cmd)
  361. if not cmd_filepath:
  362. return False
  363. # Resolves symlinks and produces a normalized absolute path string.
  364. cmd_path = Path(cmd_filepath).resolve()
  365. cmd_name = cmd_path.name
  366. import subprocess
  367. # Make a local copy of the environment to not affect the global one.
  368. env = dict(os.environ)
  369. # If we're piping to less and the user hasn't decided on colors, we enable
  370. # them by default we find the -R flag in the command line arguments.
  371. if color is None and cmd_name == "less":
  372. less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"
  373. if not less_flags:
  374. env["LESS"] = "-R"
  375. color = True
  376. elif "r" in less_flags or "R" in less_flags:
  377. color = True
  378. c = subprocess.Popen(
  379. [str(cmd_path)] + cmd_params,
  380. shell=True,
  381. stdin=subprocess.PIPE,
  382. env=env,
  383. errors="replace",
  384. text=True,
  385. )
  386. assert c.stdin is not None
  387. try:
  388. for text in generator:
  389. if not color:
  390. text = strip_ansi(text)
  391. c.stdin.write(text)
  392. except BrokenPipeError:
  393. # In case the pager exited unexpectedly, ignore the broken pipe error.
  394. pass
  395. except Exception as e:
  396. # In case there is an exception we want to close the pager immediately
  397. # and let the caller handle it.
  398. # Otherwise the pager will keep running, and the user may not notice
  399. # the error message, or worse yet it may leave the terminal in a broken state.
  400. c.terminate()
  401. raise e
  402. finally:
  403. # We must close stdin and wait for the pager to exit before we continue
  404. try:
  405. c.stdin.close()
  406. # Close implies flush, so it might throw a BrokenPipeError if the pager
  407. # process exited already.
  408. except BrokenPipeError:
  409. pass
  410. # Less doesn't respect ^C, but catches it for its own UI purposes (aborting
  411. # search or other commands inside less).
  412. #
  413. # That means when the user hits ^C, the parent process (click) terminates,
  414. # but less is still alive, paging the output and messing up the terminal.
  415. #
  416. # If the user wants to make the pager exit on ^C, they should set
  417. # `LESS='-K'`. It's not our decision to make.
  418. while True:
  419. try:
  420. c.wait()
  421. except KeyboardInterrupt:
  422. pass
  423. else:
  424. break
  425. return True
  426. def _tempfilepager(
  427. generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None
  428. ) -> bool:
  429. """Page through text by invoking a program on a temporary file.
  430. Returns `True` if the command was found, `False` otherwise and thus another
  431. pager should be attempted.
  432. """
  433. # Split the command into the invoked CLI and its parameters.
  434. if not cmd_parts:
  435. return False
  436. cmd = cmd_parts[0]
  437. cmd_filepath = which(cmd)
  438. if not cmd_filepath:
  439. return False
  440. # Resolves symlinks and produces a normalized absolute path string.
  441. cmd_path = Path(cmd_filepath).resolve()
  442. import subprocess
  443. import tempfile
  444. fd, filename = tempfile.mkstemp()
  445. # TODO: This never terminates if the passed generator never terminates.
  446. text = "".join(generator)
  447. if not color:
  448. text = strip_ansi(text)
  449. encoding = get_best_encoding(sys.stdout)
  450. with open_stream(filename, "wb")[0] as f:
  451. f.write(text.encode(encoding))
  452. try:
  453. subprocess.call([str(cmd_path), filename])
  454. except OSError:
  455. # Command not found
  456. pass
  457. finally:
  458. os.close(fd)
  459. os.unlink(filename)
  460. return True
  461. def _nullpager(
  462. stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None
  463. ) -> None:
  464. """Simply print unformatted text. This is the ultimate fallback."""
  465. for text in generator:
  466. if not color:
  467. text = strip_ansi(text)
  468. stream.write(text)
  469. class Editor:
  470. def __init__(
  471. self,
  472. editor: str | None = None,
  473. env: cabc.Mapping[str, str] | None = None,
  474. require_save: bool = True,
  475. extension: str = ".txt",
  476. ) -> None:
  477. self.editor = editor
  478. self.env = env
  479. self.require_save = require_save
  480. self.extension = extension
  481. def get_editor(self) -> str:
  482. if self.editor is not None:
  483. return self.editor
  484. for key in "VISUAL", "EDITOR":
  485. rv = os.environ.get(key)
  486. if rv:
  487. return rv
  488. if WIN:
  489. return "notepad"
  490. for editor in "sensible-editor", "vim", "nano":
  491. if which(editor) is not None:
  492. return editor
  493. return "vi"
  494. def edit_files(self, filenames: cabc.Iterable[str]) -> None:
  495. import subprocess
  496. editor = self.get_editor()
  497. environ: dict[str, str] | None = None
  498. if self.env:
  499. environ = os.environ.copy()
  500. environ.update(self.env)
  501. exc_filename = " ".join(f'"{filename}"' for filename in filenames)
  502. try:
  503. c = subprocess.Popen(
  504. args=f"{editor} {exc_filename}", env=environ, shell=True
  505. )
  506. exit_code = c.wait()
  507. if exit_code != 0:
  508. raise ClickException(
  509. _("{editor}: Editing failed").format(editor=editor)
  510. )
  511. except OSError as e:
  512. raise ClickException(
  513. _("{editor}: Editing failed: {e}").format(editor=editor, e=e)
  514. ) from e
  515. @t.overload
  516. def edit(self, text: bytes | bytearray) -> bytes | None: ...
  517. # We cannot know whether or not the type expected is str or bytes when None
  518. # is passed, so str is returned as that was what was done before.
  519. @t.overload
  520. def edit(self, text: str | None) -> str | None: ...
  521. def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None:
  522. import tempfile
  523. if text is None:
  524. data = b""
  525. elif isinstance(text, (bytes, bytearray)):
  526. data = text
  527. else:
  528. if text and not text.endswith("\n"):
  529. text += "\n"
  530. if WIN:
  531. data = text.replace("\n", "\r\n").encode("utf-8-sig")
  532. else:
  533. data = text.encode("utf-8")
  534. fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)
  535. f: t.BinaryIO
  536. try:
  537. with os.fdopen(fd, "wb") as f:
  538. f.write(data)
  539. # If the filesystem resolution is 1 second, like Mac OS
  540. # 10.12 Extended, or 2 seconds, like FAT32, and the editor
  541. # closes very fast, require_save can fail. Set the modified
  542. # time to be 2 seconds in the past to work around this.
  543. os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))
  544. # Depending on the resolution, the exact value might not be
  545. # recorded, so get the new recorded value.
  546. timestamp = os.path.getmtime(name)
  547. self.edit_files((name,))
  548. if self.require_save and os.path.getmtime(name) == timestamp:
  549. return None
  550. with open(name, "rb") as f:
  551. rv = f.read()
  552. if isinstance(text, (bytes, bytearray)):
  553. return rv
  554. return rv.decode("utf-8-sig").replace("\r\n", "\n")
  555. finally:
  556. os.unlink(name)
  557. def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
  558. import subprocess
  559. def _unquote_file(url: str) -> str:
  560. from urllib.parse import unquote
  561. if url.startswith("file://"):
  562. url = unquote(url[7:])
  563. return url
  564. if sys.platform == "darwin":
  565. args = ["open"]
  566. if wait:
  567. args.append("-W")
  568. if locate:
  569. args.append("-R")
  570. args.append(_unquote_file(url))
  571. null = open("/dev/null", "w")
  572. try:
  573. return subprocess.Popen(args, stderr=null).wait()
  574. finally:
  575. null.close()
  576. elif WIN:
  577. if locate:
  578. url = _unquote_file(url)
  579. args = ["explorer", f"/select,{url}"]
  580. else:
  581. args = ["start"]
  582. if wait:
  583. args.append("/WAIT")
  584. args.append("")
  585. args.append(url)
  586. try:
  587. return subprocess.call(args)
  588. except OSError:
  589. # Command not found
  590. return 127
  591. elif CYGWIN:
  592. if locate:
  593. url = _unquote_file(url)
  594. args = ["cygstart", os.path.dirname(url)]
  595. else:
  596. args = ["cygstart"]
  597. if wait:
  598. args.append("-w")
  599. args.append(url)
  600. try:
  601. return subprocess.call(args)
  602. except OSError:
  603. # Command not found
  604. return 127
  605. try:
  606. if locate:
  607. url = os.path.dirname(_unquote_file(url)) or "."
  608. else:
  609. url = _unquote_file(url)
  610. c = subprocess.Popen(["xdg-open", url])
  611. if wait:
  612. return c.wait()
  613. return 0
  614. except OSError:
  615. if url.startswith(("http://", "https://")) and not locate and not wait:
  616. import webbrowser
  617. webbrowser.open(url)
  618. return 0
  619. return 1
  620. def _translate_ch_to_exc(ch: str) -> None:
  621. if ch == "\x03":
  622. raise KeyboardInterrupt()
  623. if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
  624. raise EOFError()
  625. if ch == "\x1a" and WIN: # Windows, Ctrl+Z
  626. raise EOFError()
  627. return None
  628. if sys.platform == "win32":
  629. import msvcrt
  630. @contextlib.contextmanager
  631. def raw_terminal() -> cabc.Iterator[int]:
  632. yield -1
  633. def getchar(echo: bool) -> str:
  634. # The function `getch` will return a bytes object corresponding to
  635. # the pressed character. Since Windows 10 build 1803, it will also
  636. # return \x00 when called a second time after pressing a regular key.
  637. #
  638. # `getwch` does not share this probably-bugged behavior. Moreover, it
  639. # returns a Unicode object by default, which is what we want.
  640. #
  641. # Either of these functions will return \x00 or \xe0 to indicate
  642. # a special key, and you need to call the same function again to get
  643. # the "rest" of the code. The fun part is that \u00e0 is
  644. # "latin small letter a with grave", so if you type that on a French
  645. # keyboard, you _also_ get a \xe0.
  646. # E.g., consider the Up arrow. This returns \xe0 and then \x48. The
  647. # resulting Unicode string reads as "a with grave" + "capital H".
  648. # This is indistinguishable from when the user actually types
  649. # "a with grave" and then "capital H".
  650. #
  651. # When \xe0 is returned, we assume it's part of a special-key sequence
  652. # and call `getwch` again, but that means that when the user types
  653. # the \u00e0 character, `getchar` doesn't return until a second
  654. # character is typed.
  655. # The alternative is returning immediately, but that would mess up
  656. # cross-platform handling of arrow keys and others that start with
  657. # \xe0. Another option is using `getch`, but then we can't reliably
  658. # read non-ASCII characters, because return values of `getch` are
  659. # limited to the current 8-bit codepage.
  660. #
  661. # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`
  662. # is doing the right thing in more situations than with `getch`.
  663. if echo:
  664. func = t.cast(t.Callable[[], str], msvcrt.getwche)
  665. else:
  666. func = t.cast(t.Callable[[], str], msvcrt.getwch)
  667. rv = func()
  668. if rv in ("\x00", "\xe0"):
  669. # \x00 and \xe0 are control characters that indicate special key,
  670. # see above.
  671. rv += func()
  672. _translate_ch_to_exc(rv)
  673. return rv
  674. else:
  675. import termios
  676. import tty
  677. @contextlib.contextmanager
  678. def raw_terminal() -> cabc.Iterator[int]:
  679. f: t.TextIO | None
  680. fd: int
  681. if not isatty(sys.stdin):
  682. f = open("/dev/tty")
  683. fd = f.fileno()
  684. else:
  685. fd = sys.stdin.fileno()
  686. f = None
  687. try:
  688. old_settings = termios.tcgetattr(fd)
  689. try:
  690. tty.setraw(fd)
  691. yield fd
  692. finally:
  693. termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
  694. sys.stdout.flush()
  695. if f is not None:
  696. f.close()
  697. except termios.error:
  698. pass
  699. def getchar(echo: bool) -> str:
  700. with raw_terminal() as fd:
  701. ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
  702. if echo and isatty(sys.stdout):
  703. sys.stdout.write(ch)
  704. _translate_ch_to_exc(ch)
  705. return ch