]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Make percent complete end at 100%
[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             + str(self.obj.getIdx() + 1).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", "q", "m"]:
121                 self.menu_panel.hide()
122                 self.panel_up()
123             if key in ["q", "m"]:
124                 if len(self.stack) == self.obj.getIdx() + 1:
125                     self.leave()
126                 elif len(self.stack) < self.obj.getIdx() + 1:
127                     self.obj.setIdx(0)
128                 self.get_key()
129             elif key == "y":
130                 self.stack = runner.get_orig()[1]
131                 self.menu_print("Stack reset!")
132             elif key == "a":
133                 self.stack.sort()
134                 self.menu_print("Stack alphabetized!")
135             elif key == "u":
136                 [x.unStar() for x in self.stack]
137                 self.menu_print("All unstarred!")
138             elif key == "d":
139                 [x.star() for x in self.stack]
140                 self.menu_print("All starred!")
141             elif key == "t":
142                 self.stack.reverse()
143                 self.menu_print("Stack reversed!")
144             elif key == "z":
145                 shuffle(self.stack)
146                 self.menu_print("Stack shuffled!")
147             elif key == "f":
148                 for x in self.stack:
149                     x[0], x[1] = x[1], x[0]
150                 (self.headers[0], self.headers[1]) = (
151                     self.headers[1],
152                     self.headers[0],
153                 )
154                 self.menu_print("Cards flipped!")
155             elif key == "s":
156                 # Check if there are any starred cards before proceeding, and
157                 # if not, don't allow to proceed and show an error message
158                 cont = False
159                 for x in self.stack:
160                     if x.getStar():
161                         cont = True
162                         break
163
164                 if cont:
165                     self.stack = [x for x in self.stack if x.getStar()]
166                     self.menu_print("Stars only!")
167                 else:
168                     self.menu_print("ERR: None are starred!", err=True)
169             elif key in ["h", "KEY_LEFT"]:
170                 self.obj.setIdx(len(self.stack) - 1)
171                 self.get_key()
172             elif key == "r":
173                 self.obj.setIdx(0)
174                 self.get_key()
175
176     def menu_init(self, quit=True):
177         """Initialize the menu with content"""
178         (self.menu_win, self.menu_panel) = self.panel_create(17, 44)
179         self.menu_panel.top()
180         self.menu_panel.hide()
181         # TODO: fix this
182         quit_text = "[q]: back"
183         if quit:
184             quit_text = "[q]: quit"
185
186         self.menu_win.addstr(
187             1, 1, "LIGHTCARDS MENU", curses.color_pair(1) + curses.A_BOLD
188         )
189         self.menu_win.hline(2, 1, curses.ACS_HLINE, 15)
190         text = [
191             "[y]: reset stack to original state",
192             "[a]: alphabetize stack",
193             "[z]: shuffle stack",
194             "[f]: flip all cards in stack",
195             "[t]: reverse stack order",
196             "[u]: unstar all",
197             "[d]: star all",
198             "[s]: update stack to include starred only",
199         ]
200
201         for t in enumerate(text):
202             self.menu_win.addstr(t[0] + 3, 1, t[1])
203         self.menu_win.addstr(len(text) + 4, 1, "[r]: restart")
204         self.menu_win.addstr(len(text) + 5, 1, quit_text)
205
206         self.menu_win.box()
207         self.panel_up()
208
209     def disp_menu(self, keygrab=True):
210         """
211         Display a menu offering multiple options on how to manipulate the deck
212         and to continue
213         """
214         (mlines, mcols) = self.win.getmaxyx()
215         self.menu_win.mvwin(int(mlines / 2) - 9, int(mcols / 2) - 22)
216         self.menu_panel.show()
217         self.panel_up()
218
219         if keygrab:
220             self.menu_grab()
221
222     def wrap_width(self):
223         """Calculate the width at which the body text should wrap"""
224         (_, mcols) = self.win.getmaxyx()
225         wrap_width = mcols - 20
226         if wrap_width > 80:
227             wrap_width = 80
228         return wrap_width
229
230     def disp_card(self):
231         """
232         Display the contents of the card.
233         Shows a header, a horizontal line, and the contents of the current
234         side.
235         """
236         (mlines, mcols) = self.win.getmaxyx()
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(len(str(len(self.stack))))
242         if self.current_card().getSide() == 0:
243             top = (
244                 num_done + " | " + self.headers[self.current_card().getSide()]
245             )
246         else:
247             top = (
248                 num_done
249                 + " | "
250                 + self.headers[self.current_card().getSide()]
251                 + ' | "'
252                 + str(self.current_card().getFront())
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.current_card().get(),
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         """Initialize 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 runner. 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         """Display help screen"""
323         (mlines, mcols) = self.win.getmaxyx()
324         self.help_win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 26)
325         self.panel_up()
326         self.help_panel.show()
327         while True:
328             key = self.help_win.getkey()
329             if key in ["q", "H", "?"]:
330                 self.help_panel.hide()
331                 self.get_key()
332
333     def current_card(self):
334         """Get current card object"""
335         return self.stack[self.obj.getIdx()]
336
337     def get_key(self):
338         """
339         Display a card and wait for the input.
340         Used as a general way of getting back into the card flow from a menu
341         """
342         self.disp_card()
343         while True:
344             key = self.win.getkey()
345             if key == "q":
346                 self.leave()
347             elif key in ["h", "KEY_LEFT"]:
348                 self.obj.back()
349                 self.current_card().setSide(0)
350                 self.disp_card()
351             elif key in ["l", "KEY_RIGHT"]:
352                 if self.obj.getIdx() + 1 == len(self.stack):
353                     self.disp_menu()
354                 else:
355                     self.obj.forward(self.stack)
356                     self.current_card().setSide(0)
357                     self.disp_card()
358             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"]:
359                 self.current_card().flip()
360                 self.disp_card()
361             elif key in ["i", "/"]:
362                 self.current_card().toggleStar()
363                 self.disp_card()
364             elif key in ["0", "^", "KEY_HOME"]:
365                 self.obj.setIdx(0)
366                 self.current_card().setSide(0)
367                 self.disp_card()
368             elif key in ["$", "KEY_END"]:
369                 self.obj.setIdx(len(self.stack) - 1)
370                 self.current_card().setSide(0)
371                 self.disp_card()
372             elif key in ["H", "?"]:
373                 self.disp_help()
374             elif key == "m":
375                 self.disp_menu()
376             elif key == "e":
377                 (self.headers, self.stack) = runner.reparse()
378                 self.get_key()
379
380     def disp_sidebar(self):
381         """Display a sidebar with the starred terms"""
382         (mlines, mcols) = self.win.getmaxyx()
383         left = mcols - 19
384
385         self.win.addstr(
386             0,
387             mcols - 16,
388             "STARRED CARDS",
389             curses.color_pair(3) + curses.A_BOLD,
390         )
391         self.win.vline(0, mcols - 20, 0, mlines - 2)
392         self.win.hline(1, left, 0, mlines)
393
394         i = 0
395         # TODO: Fix this, some off by one error
396         newntotal = self.ntotal()
397         if mlines - 5 < len(self.ntotal()):
398             newntotal = self.ntotal()[: mlines - 4]
399         elif mlines - 5 == len(self.ntotal()):
400             newntotal = self.ntotal()[: mlines - 3]
401
402         for _ in newntotal:
403             for i, card in enumerate(newntotal):
404                 term = card.getFront()
405                 if len(term) > 18:
406                     term = term + "…"
407                 self.win.addstr(2 + i, left, term)
408             if not newntotal == self.ntotal():
409                 self.win.addstr(
410                     mlines - 3,
411                     left,
412                     f"({len(self.ntotal()) - len(newntotal)} more)",
413                 )
414                 break
415
416         if len(self.ntotal()) == 0:
417             self.win.addstr(2, left, "None starred")