view.py 27 KB

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