ui.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2023 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen
  9. # https://gitlab.com/mmgen/mmgen
  10. """
  11. ui: Interactive user interface functions for the MMGen suite
  12. """
  13. import sys,os
  14. from .globalvars import g
  15. from .opts import opt
  16. from .util import msg,msg_r,Msg,dmsg,die
  17. def confirm_or_raise(message,action,expect='YES',exit_msg='Exiting at user request'):
  18. if message:
  19. msg(message)
  20. if line_input(
  21. (f'{action} ' if action[0].isupper() else f'Are you sure you want to {action}?\n') +
  22. f'Type uppercase {expect!r} to confirm: '
  23. ).strip() != expect:
  24. die( 'UserNonConfirmation', exit_msg )
  25. def get_words_from_user(prompt):
  26. words = line_input(prompt, echo=opt.echo_passphrase).split()
  27. if g.debug:
  28. msg('Sanitized input: [{}]'.format(' '.join(words)))
  29. return words
  30. def get_data_from_user(desc='data'): # user input MUST be UTF-8
  31. data = line_input(f'Enter {desc}: ',echo=opt.echo_passphrase)
  32. if g.debug:
  33. msg(f'User input: [{data}]')
  34. return data
  35. def line_input(prompt,echo=True,insert_txt='',hold_protect=True):
  36. """
  37. multi-line prompts OK
  38. one-line prompts must begin at beginning of line
  39. empty prompts forbidden due to interactions with readline
  40. """
  41. assert prompt,'calling line_input() with an empty prompt forbidden'
  42. def get_readline():
  43. try:
  44. import readline
  45. return readline
  46. except ImportError:
  47. return False
  48. if not sys.stdout.isatty():
  49. msg_r(prompt)
  50. prompt = ''
  51. if hold_protect:
  52. from .term import kb_hold_protect
  53. kb_hold_protect()
  54. if g.test_suite_popen_spawn:
  55. msg(prompt)
  56. sys.stderr.flush()
  57. reply = os.read(0,4096).decode().rstrip('\n') # strip NL to mimic behavior of input()
  58. elif echo or not sys.stdin.isatty():
  59. readline = insert_txt and sys.stdin.isatty() and get_readline()
  60. if readline:
  61. readline.set_startup_hook(lambda: readline.insert_text(insert_txt))
  62. reply = input(prompt)
  63. if readline:
  64. readline.set_startup_hook(lambda: readline.insert_text(''))
  65. else:
  66. from getpass import getpass
  67. reply = getpass(prompt)
  68. if hold_protect:
  69. kb_hold_protect()
  70. return reply.strip()
  71. def keypress_confirm(
  72. prompt,
  73. default_yes = False,
  74. verbose = False,
  75. no_nl = False,
  76. complete_prompt = False ):
  77. if not complete_prompt:
  78. prompt = '{} {}: '.format( prompt, '(Y/n)' if default_yes else '(y/N)' )
  79. nl = f'\r{" "*len(prompt)}\r' if no_nl else '\n'
  80. if g.accept_defaults:
  81. msg(prompt)
  82. return default_yes
  83. from .term import get_char
  84. while True:
  85. reply = get_char(prompt,immed_chars='yYnN').strip('\n\r')
  86. if not reply:
  87. msg_r(nl)
  88. return True if default_yes else False
  89. elif reply in 'yYnN':
  90. msg_r(nl)
  91. return True if reply in 'yY' else False
  92. else:
  93. msg_r('\nInvalid reply\n' if verbose else '\r')
  94. def do_pager(text):
  95. pagers = ['less','more']
  96. end_msg = '\n(end of text)\n\n'
  97. # --- Non-MSYS Windows code deleted ---
  98. # raw, chop, horiz scroll 8 chars, disable buggy line chopping in MSYS
  99. os.environ['LESS'] = (('--shift 8 -RS'),('--shift 16 -RS'))[g.platform=='win']
  100. if 'PAGER' in os.environ and os.environ['PAGER'] != pagers[0]:
  101. pagers = [os.environ['PAGER']] + pagers
  102. from subprocess import run
  103. from .color import set_vt100
  104. for pager in pagers:
  105. try:
  106. m = text + ('' if pager == 'less' else end_msg)
  107. p = run([pager],input=m.encode(),check=True)
  108. msg_r('\r')
  109. except:
  110. pass
  111. else:
  112. break
  113. else:
  114. Msg(text+end_msg)
  115. set_vt100()
  116. def do_license_msg(immed=False):
  117. if opt.quiet or g.no_license or opt.yes or not g.stdin_tty:
  118. return
  119. import mmgen.contrib.license as gpl
  120. msg(gpl.warning)
  121. from .term import get_char
  122. prompt = "Press 'w' for conditions and warranty info, or 'c' to continue: "
  123. while True:
  124. reply = get_char(prompt, immed_chars=('','wc')[bool(immed)])
  125. if reply == 'w':
  126. do_pager(gpl.conditions)
  127. elif reply == 'c':
  128. msg('')
  129. break
  130. else:
  131. msg_r('\r')
  132. msg('')