]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Add size checker to terminal
[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 in ["h", "KEY_LEFT"]:
182                 self.outer.obj.index = len(self.outer.stack) - 1
183                 self.outer.get_key()
184             elif key == "r":
185                 self.outer.obj.index = 0
186                 self.outer.get_key()
187
188     def disp(self):
189         """
190         Display a menu offering multiple options on how to manipulate the deck
191         and to continue
192         """
193         (mlines, mcols) = self.outer.win.getmaxyx()
194         self.win.mvwin(int(mlines / 2) - 9, int(mcols / 2) - 22)
195         self.panel.show()
196         self.outer.update_panels()
197
198         self.menu_grab()
199
200
201 class Display:
202     def __init__(self, stack, headers, obj):
203         self.stack = stack
204         self.headers = headers
205         self.obj = obj
206
207     def run(self, stdscr):
208         """Set important options that require stdscr before starting"""
209         self.win = stdscr
210         (mlines, mcols) = self.win.getmaxyx()
211         curses.curs_set(0)  # Hide cursor
212         curses.use_default_colors()  # Allow transparency
213         curses.init_pair(1, curses.COLOR_CYAN, -1)
214         curses.init_pair(2, curses.COLOR_RED, -1)
215         curses.init_pair(3, curses.COLOR_YELLOW, -1)
216
217         (self.main_win, self.main_panel) = panel_create(mlines, mcols)
218         self.menu_obj = Menu(self)
219         self.help_obj = Help(self)
220
221         self.get_key()
222
223     def check_size(self):
224         (mlines, mcols) = self.win.getmaxyx()
225
226         while mlines < 24 or mcols < 60:
227             self.main_win.clear()
228             self.main_win.addstr(
229                 0,
230                 0,
231                 textwrap.fill(
232                     "Terminal too small! Min size 60x24", width=mcols
233                 ),
234             )
235             self.main_win.redrawwin()
236             self.main_win.refresh()
237             (mlines, mcols) = self.win.getmaxyx()
238             time.sleep(0.1)
239         else:
240             self.disp_card()
241
242     def update_panels(self):
243         """Update panel and window contents"""
244         curses.panel.update_panels()
245         self.win.refresh()
246
247     def leave(self):
248         """Pickle stack before quitting"""
249         if self.obj.index + 1 == len(self.stack):
250             self.obj.index = 0
251
252         progress.dump(self.stack, runner.get_orig()[1])
253         sys.exit(0)
254
255     def nstarred(self):
256         """Get total number of starred cards"""
257         return [card for card in self.stack if card.starred]
258
259     def disp_bar(self):
260         """
261         Display the statusbar at the bottom of the screen with progress, star
262         status, and card side.
263         """
264         (mlines, mcols) = self.win.getmaxyx()
265         self.win.hline(mlines - 2, 0, 0, mcols)
266
267         # Calculate percent done
268         if len(self.stack) <= 1:
269             percent = "100"
270         else:
271             percent = str(
272                 round(self.obj.index / (len(self.stack) - 1) * 100)
273             ).zfill(2)
274
275         # Print yellow if starred
276         if self.current_card().starred:
277             star_color = curses.color_pair(3)
278         else:
279             star_color = curses.color_pair(1)
280
281         # Create bar component
282         bar_start = "["
283         bar_middle = self.current_card().printStar()
284         bar_end = (
285             f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
286             f"[{percent}% ("
287             f"{str(self.obj.index).zfill(len(str(len(self.stack))))}"
288             f"/{str(len(self.stack))})] ["
289             f"{self.headers[self.current_card().side]} ("
290             f"{str(int(self.current_card().side) + 1)})]"
291         )
292
293         # Put it all togethor
294         self.win.addstr(mlines - 1, 0, bar_start, curses.color_pair(1))
295         self.win.addstr(mlines - 1, len(bar_start), bar_middle, star_color)
296         self.win.addstr(
297             mlines - 1,
298             len(bar_start + bar_middle),
299             textwrap.shorten(bar_end, width=mcols - 20, placeholder="…"),
300             curses.color_pair(1),
301         )
302
303     def wrap_width(self):
304         """Calculate the width at which the body text should wrap"""
305         (_, mcols) = self.win.getmaxyx()
306         wrap_width = mcols - 20
307         if wrap_width > 80:
308             wrap_width = 80
309         return wrap_width
310
311     def disp_card(self):
312         """
313         Display the contents of the card.
314         Shows a header, a horizontal line, and the contents of the current
315         side.
316         """
317         (mlines, mcols) = self.win.getmaxyx()
318         self.main_panel.bottom()
319         self.main_win.clear()
320         # If on the back of the card, show the content of the front side in
321         # the header
322         num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
323         if self.current_card().side == 0:
324             top = num_done + " | " + self.headers[self.current_card().side]
325         else:
326             top = (
327                 num_done
328                 + " | "
329                 + self.headers[self.current_card().side]
330                 + ' | "'
331                 + str(self.current_card().front)
332                 + '"'
333             )
334         header_width = mcols
335         if mcols > 80:
336             header_width = 80
337
338         self.main_win.addstr(
339             0,
340             0,
341             textwrap.shorten(top, width=header_width, placeholder="…"),
342             curses.A_BOLD,
343         )
344
345         # Add horizontal line
346         self.main_win.hline(1, 0, curses.ACS_HLINE, mcols)
347
348         # Show current side
349         self.main_win.addstr(
350             2,
351             0,
352             textwrap.fill(
353                 self.current_card().get(),
354                 width=self.wrap_width(),
355             ),
356         )
357         self.update_panels()
358         self.disp_bar()
359         self.disp_sidebar()
360
361     def current_card(self):
362         """Get current card object"""
363         return self.stack[self.obj.index]
364
365     def get_key(self):
366         """
367         Display a card and wait for the input.
368         Used as a general way of getting back into the card flow from a menu
369         """
370         while True:
371             self.check_size()
372             key = self.win.getkey()
373             if key == "q":
374                 self.leave()
375             elif key in ["h", "KEY_LEFT"]:
376                 self.obj.back()
377                 self.current_card().side = 0
378                 self.disp_card()
379             elif key in ["l", "KEY_RIGHT"]:
380                 if self.obj.index + 1 == len(self.stack):
381                     self.menu_obj.disp()
382                 else:
383                     self.obj.forward(self.stack)
384                     self.current_card().side = 0
385                     self.disp_card()
386             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"]:
387                 self.current_card().flip()
388                 self.disp_card()
389             elif key in ["i", "/"]:
390                 self.current_card().toggleStar()
391                 self.disp_card()
392             elif key in ["0", "^", "KEY_HOME"]:
393                 self.obj.index = 0
394                 self.current_card().side = 0
395                 self.disp_card()
396             elif key in ["$", "KEY_END"]:
397                 self.obj.index = len(self.stack) - 1
398                 self.current_card().side = 0
399                 self.disp_card()
400             elif key in ["H", "?"]:
401                 self.help_obj.disp()
402             elif key == "m":
403                 self.menu_obj.disp()
404             elif key == "e":
405                 (self.headers, self.stack) = runner.reparse()
406                 self.get_key()
407
408     def disp_sidebar(self):
409         """Display a sidebar with the starred terms"""
410         (mlines, mcols) = self.win.getmaxyx()
411         left = mcols - 19
412
413         for i in range(20):
414             self.win.addch(0, mcols - 20 + i, " ")
415
416         self.win.addstr(
417             0,
418             mcols - 16,
419             "STARRED CARDS",
420             curses.color_pair(3) + curses.A_BOLD,
421         )
422         self.win.vline(0, mcols - 20, 0, mlines - 2)
423
424         nstarred = self.nstarred()
425         if mlines - 5 < len(self.nstarred()):
426             nstarred = self.nstarred()[: mlines - 4]
427         elif mlines - 5 == len(self.nstarred()):
428             nstarred = self.nstarred()[: mlines - 3]
429
430         for _ in nstarred:
431             for i, card in enumerate(nstarred):
432                 term = card.front
433                 if len(term) > 18:
434                     term = term + "…"
435                 self.win.addstr(2 + i, left, term)
436             if not nstarred == self.nstarred():
437                 self.win.addstr(
438                     mlines - 3,
439                     left,
440                     f"({len(self.nstarred()) - len(nstarred)} more)",
441                 )
442                 break
443
444         if len(self.nstarred()) == 0:
445             self.win.addstr(2, left, "None starred")