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