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