view.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. tw.view: base class for tracking wallet view classes
  20. """
  21. import sys, time, asyncio
  22. from collections import namedtuple
  23. from ..cfg import gv
  24. from ..objmethods import MMGenObject
  25. from ..obj import get_obj, MMGenIdx, MMGenList
  26. from ..color import nocolor, yellow, green, red, blue
  27. from ..util import msg, msg_r, fmt, die, capfirst, make_timestr
  28. from ..rpc import rpc_init
  29. from ..base_obj import AsyncInit
  30. # these are replaced by fake versions in overlay:
  31. CUR_HOME = '\033[H'
  32. CUR_UP = lambda n: f'\033[{n}A'
  33. CUR_DOWN = lambda n: f'\033[{n}B'
  34. ERASE_ALL = '\033[0J'
  35. # decorator for action.run():
  36. def enable_echo(orig_func):
  37. async def f(self, parent, action_method):
  38. if parent.scroll:
  39. parent.term.set('echo')
  40. ret = await orig_func(self, parent, action_method)
  41. if parent.scroll:
  42. parent.term.set('noecho')
  43. return ret
  44. return f
  45. # base class for TwUnspentOutputs, TwAddresses, TwTxHistory:
  46. class TwView(MMGenObject, metaclass=AsyncInit):
  47. class display_type:
  48. class squeezed:
  49. detail = False
  50. fmt_method = 'gen_squeezed_display'
  51. line_fmt_method = 'squeezed_format_line'
  52. subhdr_fmt_method = 'gen_subheader'
  53. colhdr_fmt_method = 'squeezed_col_hdr'
  54. need_column_widths = True
  55. item_separator = '\n'
  56. print_header = '[screen print truncated to width {}]\n'
  57. class detail:
  58. detail = True
  59. fmt_method = 'gen_detail_display'
  60. line_fmt_method = 'detail_format_line'
  61. subhdr_fmt_method = 'gen_subheader'
  62. colhdr_fmt_method = 'detail_col_hdr' # set to None to disable
  63. need_column_widths = True
  64. item_separator = '\n'
  65. print_header = ''
  66. class line_processing:
  67. class print:
  68. @staticmethod
  69. def do(method, data, cw, fs, color, fmt_method):
  70. return [l.rstrip() for l in method(data, cw, fs, color, fmt_method)]
  71. has_wallet = True
  72. has_amt2 = False
  73. dates_set = False
  74. reverse = False
  75. group = False
  76. use_cached = False
  77. txid_w = 64
  78. sort_key = 'age'
  79. display_hdr = ()
  80. display_body = ()
  81. prompt_fs_repl = {}
  82. nodata_msg = '[no data for requested parameters]'
  83. cols = 0
  84. term_height = 0
  85. term_width = 0
  86. scrollable_height = 0
  87. min_scrollable_height = 5
  88. addr_view_pref = 0
  89. pos = 0
  90. filters = ()
  91. fp = namedtuple('fs_params', ['fs_key', 'hdr_fs_repl', 'fs_repl', 'hdr_fs', 'fs'])
  92. fs_params = {
  93. 'num': fp('n', True, True, ' {n:>%s}', ' {n:>%s}'),
  94. 'txid': fp('t', True, False, ' {t:%s}', ' {t}'),
  95. 'vout': fp('v', True, False, '{v:%s}', '{v}'),
  96. 'used': fp('u', True, False, ' {u:%s}', ' {u}'),
  97. 'addr': fp('a', True, False, ' {a:%s}', ' {a}'),
  98. 'mmid': fp('m', True, False, ' {m:%s}', ' {m}'),
  99. 'comment': fp('c', True, False, ' {c:%s}', ' {c}'),
  100. 'amt': fp('A', True, False, ' {A:%s}', ' {A}'),
  101. 'amt2': fp('B', True, False, ' {B:%s}', ' {B}'),
  102. 'date': fp('d', True, True, ' {d:%s}', ' {d:<%s}'),
  103. 'date_time': fp('D', True, True, ' {D:%s}', ' {D:%s}'),
  104. 'block': fp('b', True, True, ' {b:%s}', ' {b:<%s}'),
  105. 'inputs': fp('i', True, False, ' {i:%s}', ' {i}'),
  106. 'outputs': fp('o', True, False, ' {o:%s}', ' {o}'),
  107. }
  108. age_fmts = ('confs', 'block', 'days', 'date', 'date_time')
  109. age_fmts_date_dependent = ('days', 'date', 'date_time')
  110. _age_fmt = 'confs'
  111. bch_addr_fmts = ('cashaddr', 'legacy')
  112. age_col_params = {
  113. 'confs': (7, 'Confs'),
  114. 'block': (8, 'Block'),
  115. 'days': (6, 'Age(d)'),
  116. 'date': (8, 'Date'),
  117. 'date_time': (16, 'Date/Time'),
  118. }
  119. date_formatter = {
  120. 'days': lambda rpc, secs: (rpc.cur_date - secs) // 86400 if secs else 0,
  121. 'date': (
  122. lambda rpc, secs: '{}-{:02}-{:02}'.format(*time.gmtime(secs)[:3])[2:]
  123. if secs else '- '),
  124. 'date_time': (
  125. lambda rpc, secs: '{}-{:02}-{:02} {:02}:{:02}'.format(*time.gmtime(secs)[:5])
  126. if secs else '- '),
  127. }
  128. twidth_diemsg = """
  129. --columns or MMGEN_COLUMNS value ({}) is too small to display the {}
  130. Minimum value for this configuration: {}
  131. """
  132. twidth_errmsg = """
  133. Screen is too narrow to display the {} with current configuration
  134. Please resize your screen to at least {} characters and hit any key:
  135. """
  136. theight_errmsg = """
  137. Terminal window is too small to display the {} with current configuration
  138. Please resize it to at least {} lines and hit any key:
  139. """
  140. squeezed_format_line = None
  141. detail_format_line = None
  142. scroll_keys = {
  143. 'vi': {
  144. 'k': 'm_cursor_up',
  145. 'j': 'm_cursor_down',
  146. 'b': 'm_pg_up',
  147. 'f': 'm_pg_down',
  148. 'g': 'm_top',
  149. 'G': 'm_bot',
  150. },
  151. 'linux': {
  152. '\x1b[A': 'm_cursor_up',
  153. '\x1b[B': 'm_cursor_down',
  154. '\x1b[5~': 'm_pg_up',
  155. '\x1b[6~': 'm_pg_down',
  156. '\x1b[7~': 'm_top',
  157. '\x1b[8~': 'm_bot',
  158. },
  159. 'win32': {
  160. '\xe0H': 'm_cursor_up',
  161. '\xe0P': 'm_cursor_down',
  162. '\xe0I': 'm_pg_up',
  163. '\xe0Q': 'm_pg_down',
  164. '\xe0G': 'm_top',
  165. '\xe0O': 'm_bot',
  166. }
  167. }
  168. scroll_keys['darwin'] = scroll_keys['linux']
  169. def __new__(cls, cfg, proto, *args, **kwargs):
  170. return MMGenObject.__new__(proto.base_proto_subclass(cls, cls.mod_subpath))
  171. async def __init__(self, cfg, proto):
  172. self.cfg = cfg
  173. self.proto = proto
  174. self.rpc = await rpc_init(cfg, proto)
  175. if self.has_wallet:
  176. from .ctl import TwCtl
  177. self.twctl = await TwCtl(cfg, proto, mode='w')
  178. self.amt_keys = {'amt':'iwidth', 'amt2':'iwidth2'} if self.has_amt2 else {'amt':'iwidth'}
  179. if repl := self.prompt_fs_repl.get(self.proto.coin):
  180. self.prompt_fs_in[repl[0]] = repl[1]
  181. self.prompt_fs = '\n'.join(self.prompt_fs_in)
  182. if self.proto.coin == 'BCH':
  183. self.key_mappings.update({'h': 'd_addr_view_pref'})
  184. self.addr_view_pref = 1 if not self.cfg.cashaddr else not self.proto.cashaddr
  185. @property
  186. def age_w(self):
  187. return self.age_col_params[self.age_fmt][0]
  188. @property
  189. def age_hdr(self):
  190. return self.age_col_params[self.age_fmt][1]
  191. @property
  192. def age_fmt(self):
  193. return self._age_fmt
  194. @age_fmt.setter
  195. def age_fmt(self, val):
  196. if val not in self.age_fmts:
  197. die('BadAgeFormat', f'{val!r}: invalid age format (must be one of {self.age_fmts!r})')
  198. self._age_fmt = val
  199. def age_disp(self, o, age_fmt):
  200. if age_fmt == 'confs':
  201. return o.confs or '-'
  202. elif age_fmt == 'block':
  203. return self.rpc.blockcount + 1 - o.confs if o.confs else '-'
  204. else:
  205. return self.date_formatter[age_fmt](self.rpc, o.date)
  206. def get_disp_prec(self, wide):
  207. return self.proto.coin_amt.max_prec
  208. sort_disp = {
  209. 'addr': 'Addr',
  210. 'age': 'Age',
  211. 'amt': 'Amt',
  212. 'txid': 'TxID',
  213. 'twmmid': 'MMGenID',
  214. }
  215. sort_funcs = {
  216. 'addr': lambda i: '{} {:010} {:024.12f}'.format(i.addr, 0xffffffff - abs(i.confs), i.amt),
  217. 'age': lambda i: '{:010} {:024.12f}'.format(0xffffffff - abs(i.confs), i.amt),
  218. 'amt': lambda i: '{:024.12f} {:010} {}'.format(i.amt, 0xffffffff - abs(i.confs), i.addr),
  219. 'txid': lambda i: f'{i.txid} {i.vout:04}',
  220. 'twmmid': lambda i: '{} {:010} {:024.12f}'.format(i.twmmid.sort_key, 0xffffffff - abs(i.confs), i.amt)
  221. }
  222. def sort_info(self, include_group=True):
  223. ret = ([], ['Reverse'])[self.reverse]
  224. ret.append(self.sort_disp[self.sort_key])
  225. if include_group and self.group and (self.sort_key in ('addr', 'txid', 'twmmid')):
  226. ret.append('Grouped')
  227. return ret
  228. def do_sort(self, key=None, reverse=False):
  229. key = key or self.sort_key
  230. if key not in self.sort_funcs:
  231. die(1, f'{key!r}: invalid sort key. Valid options: {" ".join(self.sort_funcs)}')
  232. self.sort_key = key
  233. assert isinstance(reverse, bool)
  234. save = self.data.copy()
  235. self.data.sort(key=self.sort_funcs[key], reverse=reverse or self.reverse)
  236. if self.data != save:
  237. self.pos = 0
  238. async def get_data(self, sort_key=None, reverse_sort=False):
  239. rpc_data = await self.get_rpc_data()
  240. if not rpc_data:
  241. die(1, fmt(self.no_rpcdata_errmsg).strip())
  242. lbl_id = ('account', 'label')['label_api' in self.rpc.caps]
  243. res = self.gen_data(rpc_data, lbl_id)
  244. self.data = MMGenList(await res if type(res).__name__ == 'coroutine' else res)
  245. self.disp_data = list(self.filter_data())
  246. if not self.data:
  247. die(1, self.no_data_errmsg)
  248. self.do_sort(key=sort_key, reverse=reverse_sort)
  249. # get_data() is immediately followed by display header, and get_rpc_data() produces output,
  250. # so add NL here (' ' required because CUR_HOME erases preceding blank lines)
  251. msg(' ')
  252. def get_term_dimensions(self, min_cols, min_lines=None):
  253. from ..term import get_terminal_size, get_char_raw, _term_dimensions
  254. user_resized = False
  255. while True:
  256. ts = get_terminal_size()
  257. cols = self.cfg.columns or ts.width
  258. lines = ts.height
  259. if cols >= min_cols and (min_lines is None or lines >= min_lines):
  260. if user_resized:
  261. msg_r(CUR_HOME + ERASE_ALL)
  262. return _term_dimensions(cols, ts.height)
  263. if sys.stdout.isatty():
  264. if self.cfg.columns and cols < min_cols:
  265. die(1, '\n'+fmt(self.twidth_diemsg.format(self.cfg.columns, self.desc, min_cols), indent=' '))
  266. else:
  267. m, dim = (self.twidth_errmsg, min_cols) if cols < min_cols else (self.theight_errmsg, min_lines)
  268. get_char_raw(CUR_HOME + ERASE_ALL + fmt(m.format(self.desc, dim), append=''))
  269. user_resized = True
  270. else:
  271. return _term_dimensions(min_cols, ts.height)
  272. def compute_column_widths(self, widths, maxws, minws, maxws_nice, wide, interactive):
  273. def do_ret(freews):
  274. widths.update({k:minws[k] + freews.get(k, 0) for k in minws})
  275. widths.update({ikey: widths[key] - self.disp_prec - 1 for key, ikey in self.amt_keys.items()})
  276. return namedtuple('column_widths', widths.keys())(*widths.values())
  277. def do_ret_max():
  278. widths.update({k:max(minws[k], maxws[k]) for k in minws})
  279. widths.update({ikey: widths[key] - self.disp_prec - 1 for key, ikey in self.amt_keys.items()})
  280. return namedtuple('column_widths', widths.keys())(*widths.values())
  281. def get_freews(cols, varws, varw, minw):
  282. freew = cols - minw
  283. if freew and varw:
  284. x = freew / varw
  285. freews = {k:int(varws[k] * x) for k in varws}
  286. remainder = freew - sum(freews.values())
  287. for k in varws:
  288. if not remainder:
  289. break
  290. if freews[k] < varws[k]:
  291. freews[k] += 1
  292. remainder -= 1
  293. return freews
  294. else:
  295. return {k:0 for k in varws}
  296. varws = {k:maxws[k] - minws[k] for k in maxws if maxws[k] > minws[k]}
  297. minw = sum(widths.values()) + sum(minws.values())
  298. varw = sum(varws.values())
  299. self.min_term_width = 40 if wide else max(self.prompt_width, minw) if interactive else minw
  300. td = self.get_term_dimensions(self.min_term_width)
  301. self.term_height = td.height
  302. self.term_width = td.width
  303. self.cols = min(self.term_width, minw + varw)
  304. if wide or self.cols == minw + varw:
  305. return do_ret_max()
  306. if maxws_nice:
  307. # compute high-priority widths:
  308. varws_hp = {k: maxws_nice[k] - minws[k] if k in maxws_nice else varws[k] for k in varws}
  309. varw_hp = sum(varws_hp.values())
  310. widths_hp = get_freews(
  311. min(self.term_width, minw + varw_hp),
  312. varws_hp,
  313. varw_hp,
  314. minw)
  315. # compute low-priority (nice) widths:
  316. varws_lp = {k: varws[k] - varws_hp[k] for k in maxws_nice if k in varws}
  317. widths_lp = get_freews(
  318. self.cols,
  319. varws_lp,
  320. sum(varws_lp.values()),
  321. minw + sum(widths_hp.values()))
  322. # sum the two for each field:
  323. return do_ret({k:widths_hp[k] + widths_lp.get(k, 0) for k in varws})
  324. else:
  325. return do_ret(get_freews(self.cols, varws, varw, minw))
  326. def gen_subheader(self, cw, color):
  327. return ()
  328. def gen_footer(self, color):
  329. if hasattr(self, 'total'):
  330. yield 'TOTAL: {} {}'.format(self.total.hl(color=color), self.proto.dcoin)
  331. def set_amt_widths(self, data):
  332. # width of amts column: min(7, width of integer part) + len('.') + width of fractional part
  333. self.amt_widths = {
  334. k:min(7, max(len(str(getattr(d, k).to_integral_value())) for d in data)) + 1 + self.disp_prec
  335. for k in self.amt_keys}
  336. async def format(
  337. self,
  338. display_type,
  339. color = True,
  340. interactive = False,
  341. line_processing = None,
  342. scroll = False):
  343. def make_display():
  344. def gen_hdr():
  345. Blue, Green = (blue, green) if color else (nocolor, nocolor)
  346. Yes, No, All = (green('yes'), red('no'), yellow('all')) if color else ('yes', 'no', 'all')
  347. sort_info = ' '.join(self.sort_info())
  348. def fmt_filter(k):
  349. return '{}:{}'.format(k, {0:No, 1:Yes, 2:All}[getattr(self, k)])
  350. yield '{} (sort order: {}){}'.format(
  351. self.hdr_lbl.upper(),
  352. Blue(sort_info),
  353. ' ' * (self.cols - len(f'{self.hdr_lbl} (sort order: {sort_info})')))
  354. if self.filters:
  355. yield 'Filters: {}{}'.format(
  356. ' '.join(map(fmt_filter, self.filters)),
  357. ' ' * len(self.filters))
  358. yield 'Network: {}'.format(Green(
  359. self.proto.coin + ' ' + self.proto.chain_name.upper()))
  360. yield 'Block {} [{}]'.format(
  361. self.rpc.blockcount.hl(color=color),
  362. make_timestr(self.rpc.cur_date))
  363. if hasattr(self, 'total'):
  364. yield 'Total {}: {}'.format(self.proto.dcoin, self.total.hl(color=color))
  365. yield from getattr(self, dt.subhdr_fmt_method)(cw, color)
  366. yield ' ' * self.term_width
  367. if data and dt.colhdr_fmt_method:
  368. col_hdr = getattr(self, dt.colhdr_fmt_method)(cw, hdr_fs, color)
  369. yield col_hdr.rstrip() if line_processing == 'print' else col_hdr
  370. def get_body(method):
  371. if line_processing:
  372. return getattr(self.line_processing, line_processing).do(
  373. method, data, cw, fs, color, getattr(self, dt.line_fmt_method))
  374. else:
  375. return method(data, cw, fs, color, getattr(self, dt.line_fmt_method))
  376. if data and dt.need_column_widths:
  377. self.set_amt_widths(data)
  378. cw = self.get_column_widths(data, wide=dt.detail, interactive=interactive)
  379. cwh = cw._asdict()
  380. fp = self.fs_params
  381. rfill = ' ' * (self.term_width - self.cols) if scroll else ''
  382. hdr_fs = ''.join(fp[name].hdr_fs % ((), cwh[name])[fp[name].hdr_fs_repl]
  383. for name in dt.cols if cwh[name]) + rfill
  384. fs = ''.join(fp[name].fs % ((), cwh[name])[fp[name].fs_repl]
  385. for name in dt.cols if cwh[name]) + rfill
  386. else:
  387. cw = hdr_fs = fs = None
  388. return (
  389. tuple(gen_hdr()),
  390. tuple(
  391. get_body(getattr(self, dt.fmt_method)) if data else
  392. [(nocolor, yellow)[color](self.nodata_msg.ljust(self.term_width))])
  393. )
  394. if not gv.stdout.isatty():
  395. line_processing = 'print'
  396. dt = getattr(self.display_type, display_type)
  397. if self.use_cached:
  398. self.use_cached = False
  399. display_hdr = self.display_hdr
  400. display_body = self.display_body
  401. else:
  402. self.disp_prec = self.get_disp_prec(wide=dt.detail)
  403. if self.has_age and (self.age_fmt in self.age_fmts_date_dependent or dt.detail):
  404. await self.set_dates(self.data)
  405. dsave = self.disp_data
  406. data = self.disp_data = list(self.filter_data()) # method could be a generator
  407. if data != dsave:
  408. self.pos = 0
  409. display_hdr, display_body = make_display()
  410. if scroll:
  411. fixed_height = len(display_hdr) + self.prompt_height + 1
  412. if self.term_height - fixed_height < self.min_scrollable_height:
  413. td = self.get_term_dimensions(
  414. self.min_term_width,
  415. min_lines = self.min_scrollable_height + fixed_height)
  416. self.term_height = td.height
  417. self.term_width = td.width
  418. display_hdr, display_body = make_display()
  419. self.scrollable_height = self.term_height - fixed_height
  420. self.max_pos = max(0, len(display_body) - self.scrollable_height)
  421. self.pos = min(self.pos, self.max_pos)
  422. if not dt.detail:
  423. self.display_hdr = display_hdr
  424. self.display_body = display_body
  425. if scroll:
  426. top = self.pos
  427. bot = self.pos + self.scrollable_height
  428. fill = ('\n' + ''.ljust(self.term_width)) * (self.scrollable_height - len(display_body))
  429. else:
  430. top, bot, fill = (None, None, '')
  431. if interactive:
  432. footer = ''
  433. else:
  434. footer = '\n'.join(self.gen_footer(color))
  435. footer = ('\n\n' + footer if footer else '') + '\n'
  436. return (
  437. '\n'.join(display_hdr) + '\n'
  438. + dt.item_separator.join(display_body[top:bot])
  439. + fill
  440. + footer
  441. )
  442. async def view_filter_and_sort(self):
  443. action_map = {
  444. 'a_': 'action',
  445. 's_': 'sort_action',
  446. 'd_': 'display_action',
  447. 'm_': 'scroll_action',
  448. 'i_': 'item_action',
  449. }
  450. def make_key_mappings(scroll):
  451. if scroll:
  452. for k in self.scroll_keys['vi']:
  453. assert k not in self.key_mappings, f'{k!r} is in key_mappings'
  454. self.key_mappings.update(self.scroll_keys['vi'])
  455. self.key_mappings.update(self.scroll_keys[sys.platform])
  456. return self.key_mappings
  457. scroll = self.scroll = self.cfg.scroll
  458. key_mappings = make_key_mappings(scroll)
  459. action_classes = {k: getattr(self, action_map[v[:2]])() for k, v in key_mappings.items()}
  460. action_methods = {k: getattr(v, key_mappings[k]) for k, v in action_classes.items()}
  461. prompt = self.prompt_fs.strip().format(
  462. s='\nScrolling: k=up, j=down, b=pgup, f=pgdown, g=top, G=bottom' if scroll else '')
  463. self.prompt_width = max(len(l) for l in prompt.split('\n'))
  464. self.prompt_height = len(prompt.split('\n'))
  465. self.oneshot_msg = ''
  466. prompt += '\b'
  467. clear_screen = '\n\n' if self.cfg.no_blank else CUR_HOME + ('' if scroll else ERASE_ALL)
  468. from ..term import get_term, get_char, get_char_raw
  469. if scroll:
  470. self.term = get_term()
  471. self.term.register_cleanup()
  472. self.term.set('noecho')
  473. get_char = get_char_raw
  474. msg_r(CUR_HOME + ERASE_ALL)
  475. while True:
  476. if self.oneshot_msg and scroll:
  477. msg_r(self.blank_prompt + self.oneshot_msg + ' ') # oneshot_msg must be a one-liner
  478. await asyncio.sleep(2)
  479. msg_r('\r' + ''.ljust(self.term_width))
  480. reply = get_char(
  481. clear_screen
  482. + await self.format('squeezed', interactive=True, scroll=scroll)
  483. + '\n\n'
  484. + (self.oneshot_msg + '\n\n' if self.oneshot_msg and not scroll else '')
  485. + prompt,
  486. immed_chars = key_mappings)
  487. self.oneshot_msg = ''
  488. if reply in key_mappings:
  489. ret = action_classes[reply].run(self, action_methods[reply])
  490. if type(ret).__name__ == 'coroutine':
  491. await ret
  492. elif reply == 'q':
  493. msg('')
  494. if self.scroll:
  495. self.term.set('echo')
  496. return
  497. else:
  498. if not scroll:
  499. msg_r('\ninvalid keypress ')
  500. await asyncio.sleep(0.3)
  501. @property
  502. def blank_prompt(self):
  503. return CUR_HOME + CUR_DOWN(self.term_height - self.prompt_height) + ERASE_ALL
  504. def keypress_confirm(self, *args, **kwargs):
  505. from ..ui import keypress_confirm
  506. if keypress_confirm(self.cfg, *args, no_nl=self.scroll, **kwargs):
  507. return True
  508. else:
  509. if self.scroll:
  510. msg_r('\r'+''.ljust(self.term_width)+'\r'+yellow('Canceling! '))
  511. return False
  512. class action:
  513. @enable_echo
  514. async def run(self, parent, action_method):
  515. return await action_method(parent)
  516. async def a_print_detail(self, parent):
  517. return await self._print(parent, output_type='detail')
  518. async def a_print_squeezed(self, parent):
  519. return await self._print(parent, output_type='squeezed')
  520. async def _print(self, parent, output_type):
  521. if not parent.disp_data:
  522. return None
  523. outfile = '{a}{b}-{c}{d}[{e}].out'.format(
  524. a = parent.dump_fn_pfx,
  525. b = f'-{output_type}' if len(parent.print_output_types) > 1 else '',
  526. c = parent.proto.dcoin,
  527. d = ('' if parent.proto.network == 'mainnet' else '-'+parent.proto.network.upper()),
  528. e = ','.join(parent.sort_info(include_group=False)).replace(' ', ''))
  529. print_hdr = getattr(parent.display_type, output_type).print_header.format(parent.cols)
  530. msg_r(parent.blank_prompt if parent.scroll else '\n')
  531. from ..fileutil import write_data_to_file
  532. from ..exception import UserNonConfirmation
  533. try:
  534. write_data_to_file(
  535. cfg = parent.cfg,
  536. outfile = outfile,
  537. data = print_hdr + await parent.format(
  538. display_type = output_type,
  539. line_processing = 'print',
  540. color = False),
  541. desc = f'{parent.desc} listing')
  542. except UserNonConfirmation:
  543. parent.oneshot_msg = yellow(f'File {outfile!r} not overwritten by user request')
  544. else:
  545. parent.oneshot_msg = green(f'Data written to {outfile!r}')
  546. async def a_view(self, parent):
  547. from ..ui import do_pager
  548. parent.use_cached = True
  549. msg_r(CUR_HOME)
  550. do_pager(await parent.format('squeezed', color=True))
  551. async def a_view_detail(self, parent):
  552. from ..ui import do_pager
  553. msg_r(CUR_HOME)
  554. do_pager(await parent.format('detail', color=True))
  555. class item_action:
  556. @enable_echo
  557. async def run(self, parent, action_method):
  558. if not parent.disp_data:
  559. return
  560. from ..ui import line_input
  561. while True:
  562. msg_r(parent.blank_prompt if parent.scroll else '\n')
  563. ret = line_input(
  564. parent.cfg,
  565. f'Enter {parent.item_desc} number (or ENTER to return to main menu): ')
  566. if ret == '':
  567. if parent.scroll:
  568. msg_r(CUR_UP(1) + '\r' + ''.ljust(parent.term_width))
  569. return
  570. idx = get_obj(MMGenIdx, n=ret, silent=True)
  571. if not idx or idx < 1 or idx > len(parent.disp_data):
  572. msg_r(
  573. 'Choice must be a single number between 1 and {n}{s}'.format(
  574. n = len(parent.disp_data),
  575. s = ' ' if parent.scroll else ''))
  576. if parent.scroll:
  577. await asyncio.sleep(1.5)
  578. msg_r(CUR_UP(1) + '\r' + ERASE_ALL)
  579. else:
  580. # action return values:
  581. # True: action successfully performed
  582. # None: action aborted by user or no action performed
  583. # False: an error occurred
  584. # 'redo': user will be re-prompted for item number
  585. ret = await action_method(parent, idx)
  586. if ret != 'redo':
  587. break
  588. await asyncio.sleep(0.5)
  589. if parent.scroll and ret is False:
  590. # error messages could leave screen in messy state, so do complete redraw:
  591. msg_r(
  592. CUR_HOME + ERASE_ALL +
  593. await parent.format(display_type='squeezed', interactive=True, scroll=True))
  594. async def i_balance_refresh(self, parent, idx):
  595. if not parent.keypress_confirm(
  596. f'Refreshing tracking wallet {parent.item_desc} #{idx}. Is this what you want?'):
  597. return 'redo'
  598. await parent.twctl.get_balance(parent.disp_data[idx-1].addr, force_rpc=True)
  599. await parent.get_data()
  600. parent.oneshot_msg = yellow(f'{parent.proto.dcoin} balance for account #{idx} refreshed')
  601. async def i_addr_delete(self, parent, idx):
  602. if not parent.keypress_confirm(
  603. 'Removing {} {} from tracking wallet. Is this what you want?'.format(
  604. parent.item_desc, red(f'#{idx}'))):
  605. return 'redo'
  606. if await parent.twctl.remove_address(parent.disp_data[idx-1].addr):
  607. await parent.get_data()
  608. parent.oneshot_msg = yellow(f'{capfirst(parent.item_desc)} #{idx} removed')
  609. return True
  610. else:
  611. await asyncio.sleep(3)
  612. parent.oneshot_msg = red('Address could not be removed')
  613. return False
  614. async def i_comment_add(self, parent, idx):
  615. async def do_comment_add(comment):
  616. if await parent.twctl.set_comment(
  617. addrspec = None,
  618. comment = comment,
  619. trusted_pair = (entry.twmmid, entry.addr),
  620. silent = parent.scroll):
  621. entry.comment = comment
  622. edited = cur_comment and comment
  623. parent.oneshot_msg = (green if comment else yellow)('Label {a} {b}{c}'.format(
  624. a = 'for' if edited else 'added to' if comment else 'removed from',
  625. b = desc,
  626. c = ' edited' if edited else ''))
  627. return True
  628. else:
  629. await asyncio.sleep(3)
  630. parent.oneshot_msg = red('Label for {desc} could not be {action}'.format(
  631. desc = desc,
  632. action = 'edited' if cur_comment and comment else 'added' if comment else 'removed'
  633. ))
  634. return False
  635. entry = parent.disp_data[idx-1]
  636. desc = f'{parent.item_desc} #{idx}'
  637. cur_comment = parent.disp_data[idx-1].comment
  638. msg('Current label: {}'.format(cur_comment.hl() if cur_comment else '(none)'))
  639. from ..ui import line_input
  640. res = line_input(
  641. parent.cfg,
  642. 'Enter label text for {} {}: '.format(parent.item_desc, red(f'#{idx}')),
  643. insert_txt = cur_comment)
  644. if res == cur_comment:
  645. parent.oneshot_msg = yellow(f'Label for {desc} unchanged')
  646. return None
  647. elif res == '':
  648. if not parent.keypress_confirm(f'Removing label for {desc}. Is this what you want?'):
  649. return 'redo'
  650. return await do_comment_add(res)
  651. class scroll_action:
  652. def run(self, parent, action_method):
  653. self.use_cached = True
  654. return action_method(parent)
  655. def m_cursor_up(self, parent):
  656. parent.pos -= min(parent.pos - 0, 1)
  657. def m_cursor_down(self, parent):
  658. parent.pos += min(parent.max_pos - parent.pos, 1)
  659. def m_pg_up(self, parent):
  660. parent.pos -= min(parent.scrollable_height, parent.pos - 0)
  661. def m_pg_down(self, parent):
  662. parent.pos += min(parent.scrollable_height, parent.max_pos - parent.pos)
  663. def m_top(self, parent):
  664. parent.pos = 0
  665. def m_bot(self, parent):
  666. parent.pos = parent.max_pos
  667. class sort_action:
  668. def run(self, parent, action_method):
  669. return action_method(parent)
  670. def s_addr(self, parent):
  671. parent.do_sort('addr')
  672. def s_age(self, parent):
  673. parent.do_sort('age')
  674. def s_amt(self, parent):
  675. parent.do_sort('amt')
  676. def s_txid(self, parent):
  677. parent.do_sort('txid')
  678. def s_twmmid(self, parent):
  679. parent.do_sort('twmmid')
  680. def s_reverse(self, parent):
  681. parent.data.reverse()
  682. parent.reverse = not parent.reverse
  683. class display_action:
  684. def run(self, parent, action_method):
  685. return action_method(parent)
  686. def d_days(self, parent):
  687. af = parent.age_fmts
  688. parent.age_fmt = af[(af.index(parent.age_fmt) + 1) % len(af)]
  689. if parent.update_widths_on_age_toggle: # TODO
  690. pass
  691. def d_redraw(self, parent):
  692. msg_r(CUR_HOME + ERASE_ALL)
  693. def d_addr_view_pref(self, parent):
  694. parent.addr_view_pref = (parent.addr_view_pref + 1) % len(parent.bch_addr_fmts)