]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Change Card() from extending list to independent
[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() + 1 == 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.current_card().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.current_card().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.current_card().getSide()]} ("
87             + f"{str(self.current_card().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() + 1:
123                     self.leave()
124                 elif len(self.stack) < self.obj.getIdx() + 1:
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         self.main_panel.bottom()
235         self.main_win.clear()
236         # If on the back of the card, show the content of the front side in
237         # the header
238         num_done = str(self.obj.getIdx() + 1).zfill(len(str(len(self.stack))))
239         if self.current_card().getSide() == 0:
240             top = (
241                 num_done + " | " + self.headers[self.current_card().getSide()]
242             )
243         else:
244             top = (
245                 num_done
246                 + " | "
247                 + self.headers[self.current_card().getSide()]
248                 + ' | "'
249                 + str(self.current_card().getFront())
250                 + '"'
251             )
252         header_width = mcols
253         if mcols > 80:
254             header_width = 80
255
256         self.main_win.addstr(
257             0,
258             0,
259             textwrap.shorten(top, width=header_width, placeholder="…"),
260             curses.A_BOLD,
261         )
262
263         # Add horizontal line
264         lin_width = header_width
265         if len(top) < header_width:
266             lin_width = len(top)
267         self.main_win.hline(1, 0, curses.ACS_HLINE, lin_width)
268
269         # Show current side
270         self.main_win.addstr(
271             2,
272             0,
273             textwrap.fill(
274                 self.current_card().get(),
275                 width=self.wrap_width(),
276             ),
277         )
278         self.panel_up()
279         self.disp_bar()
280         self.disp_sidebar()
281         self.win.hline(mlines - 2, 0, 0, mcols)
282
283     def help_init(self):
284         """Display help screen"""
285         (self.help_win, self.help_panel) = self.panel_create(20, 52)
286         self.help_panel.top()
287         self.help_panel.hide()
288         self.help_win.clear()
289         self.help_win.addstr(
290             1, 1, "LIGHTCARDS HELP", curses.color_pair(1) + curses.A_BOLD
291         )
292         self.help_win.hline(2, 1, curses.ACS_HLINE, 15)
293         text = [
294             "Welcome to lightcards. Here are some keybindings",
295             "to get you started:",
296             "",
297             "h, left          previous card",
298             "l, right         next card",
299             "j, k, up, down   flip card",
300             "i, /             star card",
301             "0, ^, home       go to the start of the deck",
302             "$, end           go to the end of the deck",
303             "H, ?             open this screen",
304             "e                open the input file in $EDITOR",
305             "m                open the control menu",
306             "",
307             "More information can be found in the man page, or",
308             "by running `lightcards --help`.",
309             "",
310             "Press [q], [H], or [?] to go back.",
311         ]
312
313         for t in enumerate(text):
314             self.help_win.addstr(t[0] + 3, 1, t[1])
315
316         self.help_win.box()
317
318     def disp_help(self):
319         (mlines, mcols) = self.win.getmaxyx()
320         self.help_win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 26)
321         self.panel_up()
322         self.help_panel.show()
323         while True:
324             key = self.help_win.getkey()
325             if key in ["q", "H", "?"]:
326                 self.help_panel.hide()
327                 self.get_key()
328
329     def current_card(self):
330         return self.stack[self.obj.getIdx()]
331
332     def get_key(self):
333         """
334         Display a card and wait for the input.
335         Used as a general way of getting back into the card flow from a menu
336         """
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) = lightcards.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")