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