]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Reformat using Black
[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.obj.getSide()]} ("
87             + f"{str(self.obj.getSide() + 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.obj.getSide() == 0:
245                 top = num_done + " | " + self.headers[self.obj.getSide()]
246             else:
247                 top = (
248                     num_done
249                     + " | "
250                     + self.headers[self.obj.getSide()]
251                     + ' | "'
252                     + str(self.stack[self.obj.getIdx()][0])
253                     + '"'
254                 )
255             header_width = mcols
256             if mcols > 80:
257                 header_width = 80
258
259             self.main_win.addstr(
260                 0,
261                 0,
262                 textwrap.shorten(top, width=header_width, placeholder="…"),
263                 curses.A_BOLD,
264             )
265
266             # Add horizontal line
267             lin_width = header_width
268             if len(top) < header_width:
269                 lin_width = len(top)
270             self.main_win.hline(1, 0, curses.ACS_HLINE, lin_width)
271
272             # Show current side
273             self.main_win.addstr(
274                 2,
275                 0,
276                 textwrap.fill(
277                     self.stack[self.obj.getIdx()][self.obj.getSide()],
278                     width=self.wrap_width(),
279                 ),
280             )
281         self.panel_up()
282         self.disp_bar()
283         self.disp_sidebar()
284         self.win.hline(mlines - 2, 0, 0, mcols)
285
286     def help_init(self):
287         """Display help screen"""
288         (self.help_win, self.help_panel) = self.panel_create(20, 52)
289         self.help_panel.top()
290         self.help_panel.hide()
291         self.help_win.clear()
292         self.help_win.addstr(
293             1, 1, "LIGHTCARDS HELP", curses.color_pair(1) + curses.A_BOLD
294         )
295         self.help_win.hline(2, 1, curses.ACS_HLINE, 15)
296         text = [
297             "Welcome to lightcards. Here are some keybindings",
298             "to get you started:",
299             "",
300             "h, left          previous card",
301             "l, right         next card",
302             "j, k, up, down   flip card",
303             "i, /             star card",
304             "0, ^, home       go to the start of the deck",
305             "$, end           go to the end of the deck",
306             "H, ?             open this screen",
307             "e                open the input file in $EDITOR",
308             "m                open the control menu",
309             "",
310             "More information can be found in the man page, or",
311             "by running `lightcards --help`.",
312             "",
313             "Press [q], [H], or [?] to go back.",
314         ]
315
316         for t in enumerate(text):
317             self.help_win.addstr(t[0] + 3, 1, t[1])
318
319         self.help_win.box()
320
321     def disp_help(self):
322         (mlines, mcols) = self.win.getmaxyx()
323         self.help_win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 26)
324         self.panel_up()
325         self.help_panel.show()
326         while True:
327             key = self.help_win.getkey()
328             if key in ["q", "H", "?"]:
329                 self.help_panel.hide()
330                 self.get_key()
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.obj.setSide(0)
346                 self.disp_card()
347             elif key in ["l", "KEY_RIGHT"]:
348                 self.obj.forward(self.stack)
349                 self.obj.setSide(0)
350                 self.disp_card()
351             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"]:
352                 self.obj.flip()
353                 self.disp_card()
354             elif key in ["i", "/"]:
355                 self.stack[self.obj.getIdx()].toggleStar()
356                 self.disp_card()
357             elif key in ["0", "^", "KEY_HOME"]:
358                 self.obj.setIdx(0)
359                 self.obj.setSide(0)
360                 self.disp_card()
361             elif key in ["$", "KEY_END"]:
362                 self.obj.setIdx(len(self.stack) - 1)
363                 self.obj.setSide(0)
364                 self.disp_card()
365             elif key in ["H", "?"]:
366                 self.disp_help()
367             elif key == "m":
368                 self.disp_menu()
369             elif key == "e":
370                 (self.headers, self.stack) = lightcards.reparse()
371                 self.get_key()
372
373     def disp_sidebar(self):
374         """Display a sidebar with the starred terms"""
375         (mlines, mcols) = self.win.getmaxyx()
376         left = mcols - 19
377
378         self.win.addstr(
379             0,
380             mcols - 16,
381             "STARRED CARDS",
382             curses.color_pair(3) + curses.A_BOLD,
383         )
384         self.win.vline(0, mcols - 20, 0, mlines - 2)
385         self.win.hline(1, left, 0, mlines)
386
387         i = 0
388         # TODO: Fix this, some off by one error
389         newntotal = self.ntotal()
390         if mlines - 5 < len(self.ntotal()):
391             newntotal = self.ntotal()[: mlines - 4]
392         elif mlines - 5 == len(self.ntotal()):
393             newntotal = self.ntotal()[: mlines - 3]
394
395         for card in newntotal:
396             for i in enumerate(newntotal):
397                 term = i[1][0]
398                 if len(i[1][0]) > 18:
399                     term = i[1][0][:18] + "…"
400                 self.win.addstr(2 + i[0], left, term)
401             if not newntotal == self.ntotal():
402                 self.win.addstr(
403                     mlines - 3,
404                     left,
405                     f"({len(self.ntotal()) - len(newntotal)} more)",
406                 )
407                 break
408
409         if len(self.ntotal()) == 0:
410             self.win.addstr(2, left, "None starred")