]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Make menus more logical
[lightcards.git] / lightcards / display.py
1 # Display card output and retreive input
2 # Armaan Bhojwani 2021
3
4 import curses
5 import curses.panel
6 from random import shuffle
7 import sys
8 import textwrap
9
10 from . import runner, progress
11
12
13 class Display:
14     def __init__(self, stack, headers, obj):
15         self.stack = stack
16         self.headers = headers
17         self.obj = obj
18
19     def run(self, stdscr):
20         """Set important options that require stdscr before starting"""
21         self.win = stdscr
22         (mlines, mcols) = self.win.getmaxyx()
23         curses.curs_set(0)  # Hide cursor
24         curses.use_default_colors()  # Allow transparency
25         curses.init_pair(1, curses.COLOR_CYAN, -1)
26         curses.init_pair(2, curses.COLOR_RED, -1)
27         curses.init_pair(3, curses.COLOR_YELLOW, -1)
28
29         (self.main_win, self.main_panel) = self.panel_create(mlines, mcols)
30         self.menu_init()
31         self.help_init()
32
33         self.get_key()
34
35     def panel_create(self, x, y):
36         """Create popup panels to a certain scale"""
37         win = curses.newwin(x, y)
38         panel = curses.panel.new_panel(win)
39         win.erase()
40         return (win, panel)
41
42     def panel_up(self):
43         """Update panel and window contents"""
44         curses.panel.update_panels()
45         self.win.refresh()
46
47     def leave(self):
48         """Pickle stack before quitting"""
49         if self.obj.getIdx() + 1 == len(self.stack):
50             self.obj.setIdx(0)
51
52         progress.dump(self.stack, runner.get_orig()[1])
53         sys.exit(0)
54
55     def ntotal(self):
56         """Get total number of starred cards"""
57         return [card for card in self.stack if card.getStar()]
58
59     def disp_bar(self):
60         """
61         Display the statusbar at the bottom of the screen with progress, star
62         status, and card side.
63         """
64         (mlines, mcols) = self.win.getmaxyx()
65
66         # Calculate percent done
67         if len(self.stack) <= 1:
68             percent = "100"
69         else:
70             percent = str(
71                 round(self.obj.getIdx() / (len(self.stack) - 1) * 100)
72             ).zfill(2)
73
74         # Print yellow if starred
75         if self.current_card().getStar():
76             star_color = curses.color_pair(3)
77         else:
78             star_color = curses.color_pair(1)
79
80         # Create bar component
81         bar_start = "["
82         bar_middle = self.current_card().printStar()
83         bar_end = (
84             f"] [{len(self.ntotal())}/{str(len(self.stack))} starred] "
85             f"[{percent}% ("
86             f"{str(self.obj.getIdx()).zfill(len(str(len(self.stack))))}"
87             f"/{str(len(self.stack))})] ["
88             f"{self.headers[self.current_card().getSide()]} ("
89             f"{str(int(self.current_card().getSide()) + 1)})]"
90         )
91
92         # Put it all togethor
93         self.win.addstr(mlines - 1, 0, bar_start, curses.color_pair(1))
94         self.win.addstr(mlines - 1, len(bar_start), bar_middle, star_color)
95         self.win.addstr(
96             mlines - 1,
97             len(bar_start + bar_middle),
98             bar_end,
99             curses.color_pair(1),
100         )
101
102     def menu_print(self, string, err=False):
103         """Print messages on the menu screen"""
104         if err:
105             color = curses.color_pair(2)
106         else:
107             color = curses.color_pair(1)
108
109         for i in range(42):
110             self.menu_win.addch(15, i + 1, " ")
111
112         self.menu_win.addstr(15, 1, string, color)
113         self.panel_up()
114         self.menu_grab()
115
116     def menu_grab(self):
117         """Grab keypresses on the menu screen"""
118         while True:
119             key = self.win.getkey()
120             if key in ["r", "m"]:
121                 self.menu_panel.hide()
122                 self.panel_up()
123                 self.get_key()
124             elif key == "q":
125                 self.leave()
126             elif key == "y":
127                 self.stack = runner.get_orig()[1]
128                 self.menu_print("Stack reset!")
129             elif key == "a":
130                 self.stack.sort()
131                 self.menu_print("Stack alphabetized!")
132             elif key == "u":
133                 [x.unStar() for x in self.stack]
134                 self.menu_print("All unstarred!")
135             elif key == "d":
136                 [x.star() for x in self.stack]
137                 self.menu_print("All starred!")
138             elif key == "t":
139                 self.stack.reverse()
140                 self.menu_print("Stack reversed!")
141             elif key == "z":
142                 shuffle(self.stack)
143                 self.menu_print("Stack shuffled!")
144             elif key == "f":
145                 for x in self.stack:
146                     x[0], x[1] = x[1], x[0]
147                 (self.headers[0], self.headers[1]) = (
148                     self.headers[1],
149                     self.headers[0],
150                 )
151                 self.menu_print("Cards flipped!")
152             elif key == "s":
153                 # Check if there are any starred cards before proceeding, and
154                 # if not, don't allow to proceed and show an error message
155                 cont = False
156                 for x in self.stack:
157                     if x.getStar():
158                         cont = True
159                         break
160
161                 if cont:
162                     self.stack = [x for x in self.stack if x.getStar()]
163                     self.menu_print("Stars only!")
164                 else:
165                     self.menu_print("ERR: None are starred!", err=True)
166             elif key in ["h", "KEY_LEFT"]:
167                 self.obj.setIdx(len(self.stack) - 1)
168                 self.get_key()
169             elif key == "r":
170                 self.obj.setIdx(0)
171                 self.get_key()
172
173     def menu_init(self):
174         """Initialize the menu with content"""
175         (self.menu_win, self.menu_panel) = self.panel_create(17, 44)
176         self.menu_panel.top()
177         self.menu_panel.hide()
178
179         self.menu_win.addstr(
180             1, 1, "LIGHTCARDS MENU", curses.color_pair(1) + curses.A_BOLD
181         )
182         self.menu_win.hline(2, 1, curses.ACS_HLINE, 15)
183         text = [
184             "[y]: reset stack to original state",
185             "[a]: alphabetize stack",
186             "[z]: shuffle stack",
187             "[f]: flip all cards in stack",
188             "[t]: reverse stack order",
189             "[u]: unstar all",
190             "[d]: star all",
191             "[s]: update stack to include starred only",
192             "",
193             "[r]: restart",
194             "[m]: close menu",
195         ]
196
197         for t in enumerate(text):
198             self.menu_win.addstr(t[0] + 3, 1, t[1])
199
200         self.menu_win.box()
201         self.panel_up()
202
203     def disp_menu(self, keygrab=True):
204         """
205         Display a menu offering multiple options on how to manipulate the deck
206         and to continue
207         """
208         (mlines, mcols) = self.win.getmaxyx()
209         self.menu_win.mvwin(int(mlines / 2) - 9, int(mcols / 2) - 22)
210         self.menu_panel.show()
211         self.panel_up()
212
213         if keygrab:
214             self.menu_grab()
215
216     def wrap_width(self):
217         """Calculate the width at which the body text should wrap"""
218         (_, mcols) = self.win.getmaxyx()
219         wrap_width = mcols - 20
220         if wrap_width > 80:
221             wrap_width = 80
222         return wrap_width
223
224     def disp_card(self):
225         """
226         Display the contents of the card.
227         Shows a header, a horizontal line, and the contents of the current
228         side.
229         """
230         (mlines, mcols) = self.win.getmaxyx()
231         self.main_panel.bottom()
232         self.main_win.clear()
233         # If on the back of the card, show the content of the front side in
234         # the header
235         num_done = str(self.obj.getIdx() + 1).zfill(len(str(len(self.stack))))
236         if self.current_card().getSide() == 0:
237             top = (
238                 num_done + " | " + self.headers[self.current_card().getSide()]
239             )
240         else:
241             top = (
242                 num_done
243                 + " | "
244                 + self.headers[self.current_card().getSide()]
245                 + ' | "'
246                 + str(self.current_card().getFront())
247                 + '"'
248             )
249         header_width = mcols
250         if mcols > 80:
251             header_width = 80
252
253         self.main_win.addstr(
254             0,
255             0,
256             textwrap.shorten(top, width=header_width, placeholder="…"),
257             curses.A_BOLD,
258         )
259
260         # Add horizontal line
261         lin_width = header_width
262         if len(top) < header_width:
263             lin_width = len(top)
264         self.main_win.hline(1, 0, curses.ACS_HLINE, lin_width)
265
266         # Show current side
267         self.main_win.addstr(
268             2,
269             0,
270             textwrap.fill(
271                 self.current_card().get(),
272                 width=self.wrap_width(),
273             ),
274         )
275         self.panel_up()
276         self.disp_bar()
277         self.disp_sidebar()
278         self.win.hline(mlines - 2, 0, 0, mcols)
279
280     def help_init(self):
281         """Initialize help screen"""
282         (self.help_win, self.help_panel) = self.panel_create(20, 52)
283         self.help_panel.top()
284         self.help_panel.hide()
285         self.help_win.clear()
286         self.help_win.addstr(
287             1, 1, "LIGHTCARDS HELP", curses.color_pair(1) + curses.A_BOLD
288         )
289         self.help_win.hline(2, 1, curses.ACS_HLINE, 15)
290         text = [
291             "Welcome to runner. Here are some keybindings",
292             "to get you started:",
293             "",
294             "h, left          previous card",
295             "l, right         next card",
296             "j, k, up, down   flip card",
297             "i, /             star card",
298             "0, ^, home       go to the start of the deck",
299             "$, end           go to the end of the deck",
300             "H, ?             open this screen",
301             "e                open the input file in $EDITOR",
302             "m                open the control menu",
303             "",
304             "More information can be found in the man page, or",
305             "by running `lightcards --help`.",
306             "",
307             "Press [H], or [?] to go back.",
308         ]
309
310         for t in enumerate(text):
311             self.help_win.addstr(t[0] + 3, 1, t[1])
312
313         self.help_win.box()
314
315     def disp_help(self):
316         """Display help screen"""
317         (mlines, mcols) = self.win.getmaxyx()
318         self.help_win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 26)
319         self.panel_up()
320         self.help_panel.show()
321         while True:
322             key = self.help_win.getkey()
323             if key == "q":
324                 self.leave()
325             elif key in ["H", "?"]:
326                 self.help_panel.hide()
327                 self.get_key()
328
329     def current_card(self):
330         """Get current card object"""
331         return self.stack[self.obj.getIdx()]
332
333     def get_key(self):
334         """
335         Display a card and wait for the input.
336         Used as a general way of getting back into the card flow from a menu
337         """
338         self.disp_card()
339         while True:
340             key = self.win.getkey()
341             if key == "q":
342                 self.leave()
343             elif key in ["h", "KEY_LEFT"]:
344                 self.obj.back()
345                 self.current_card().setSide(0)
346                 self.disp_card()
347             elif key in ["l", "KEY_RIGHT"]:
348                 if self.obj.getIdx() + 1 == len(self.stack):
349                     self.disp_menu()
350                 else:
351                     self.obj.forward(self.stack)
352                     self.current_card().setSide(0)
353                     self.disp_card()
354             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"]:
355                 self.current_card().flip()
356                 self.disp_card()
357             elif key in ["i", "/"]:
358                 self.current_card().toggleStar()
359                 self.disp_card()
360             elif key in ["0", "^", "KEY_HOME"]:
361                 self.obj.setIdx(0)
362                 self.current_card().setSide(0)
363                 self.disp_card()
364             elif key in ["$", "KEY_END"]:
365                 self.obj.setIdx(len(self.stack) - 1)
366                 self.current_card().setSide(0)
367                 self.disp_card()
368             elif key in ["H", "?"]:
369                 self.disp_help()
370             elif key == "m":
371                 self.disp_menu()
372             elif key == "e":
373                 (self.headers, self.stack) = runner.reparse()
374                 self.get_key()
375
376     def disp_sidebar(self):
377         """Display a sidebar with the starred terms"""
378         (mlines, mcols) = self.win.getmaxyx()
379         left = mcols - 19
380
381         self.win.addstr(
382             0,
383             mcols - 16,
384             "STARRED CARDS",
385             curses.color_pair(3) + curses.A_BOLD,
386         )
387         self.win.vline(0, mcols - 20, 0, mlines - 2)
388         self.win.hline(1, left, 0, mlines)
389
390         i = 0
391         # TODO: Fix this, some off by one error
392         newntotal = self.ntotal()
393         if mlines - 5 < len(self.ntotal()):
394             newntotal = self.ntotal()[: mlines - 4]
395         elif mlines - 5 == len(self.ntotal()):
396             newntotal = self.ntotal()[: mlines - 3]
397
398         for _ in newntotal:
399             for i, card in enumerate(newntotal):
400                 term = card.getFront()
401                 if len(term) > 18:
402                     term = term + "…"
403                 self.win.addstr(2 + i, left, term)
404             if not newntotal == self.ntotal():
405                 self.win.addstr(
406                     mlines - 3,
407                     left,
408                     f"({len(self.ntotal()) - len(newntotal)} more)",
409                 )
410                 break
411
412         if len(self.ntotal()) == 0:
413             self.win.addstr(2, left, "None starred")