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