Files

92 lines
2.1 KiB
Python

# A simple menu system for T-DeckARD
# Created by Luxferre in 2025, released into public domain
from deck.input import input
_idx_map = {
'1': 0, 'q': 0,
'2': 1, 'w': 1,
'3': 2, 'e': 2,
'4': 3, 'r': 3,
'5': 4, 't': 4,
'6': 5, 'y': 5,
'7': 6, 'u': 6,
'8': 7, 'i': 7,
'9': 8, 'o': 8,
'0': 9, 'p': 9
}
def confirm(msg, yes='y', no='n', alt_prompt=None):
prompt=f' ({yes}/{no}) '
yes = yes.lower()
no = no.lower()
if alt_prompt is not None:
prompt = alt_prompt
final_prompt = msg + prompt
while True:
choice = input(final_prompt).strip().lower()
if choice == yes:
return True
elif choice == no:
return False
def menu(choices, max_size = 10):
"""
Presents a menu of choices and prompts for numeric or
alphabetical input
Accepts a list of (id, label) tuples (up to 10 items)
Returns the associated id of the selected menu items
"""
cnum = 1
for (cid, clbl) in choices:
try:
cletter = 'qwertyuiop'[cnum - 1]
print(f'[{cletter}] {cnum % 10}. {clbl}')
except:
print(f'{cnum % 10} {clbl}')
cnum += 1
if cnum > max_size:
break
sel = ''
while len(sel) < 1:
sel = input('Your choice (c to cancel): ').strip().lower()
sel = str(sel[0])
if sel == 'c':
print('Selection canceled')
return '' # empty label denotes canceled operation
elif sel in _idx_map:
idx = _idx_map[sel]
if idx < len(choices):
return choices[idx][0]
else:
print('Invalid choice!')
return menu(choices)
else:
print('Invalid choice!')
return menu(choices)
def shortmenu(choices, suffix=': '):
letters = {}
cmap = []
for c in choices:
l = '?'
cl = len(c)
i = 0
while i < cl:
l = c[i].lower()
if l not in letters:
break
i += 1
if i == 0:
letters[l] = (c, l + ')' + c[1:])
cmap.append(letters[l][1])
elif i < cl:
letters[l] = (c, c[0:i] + '(' + l + ')' + c[i+1:])
cmap.append(letters[l][1])
prompt = ' '.join(cmap) + suffix
res = input(prompt).strip()[0].lower()
if res in letters:
return (res, letters[res][0])
else:
return ('', '')