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