]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Add progress bar
[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 import os
7 from random import shuffle
8 import sys
9 import textwrap
10 import time
11
12 from . import runner, progress, parse
13
14
15 def panel_create(x, y):
16     """Create popup panels to a certain scale"""
17     win = curses.newwin(x, y)
18     panel = curses.panel.new_panel(win)
19     win.erase()
20     return (win, panel)
21
22
23 class CursesError(BaseException):
24     def __init__(self, message="lightcards: Curses error!"):
25         self.message = message
26         print(self.message)
27         sys.exit(3)
28
29
30 class Help:
31     def __init__(self, outer, mlines=20, mcols=52):
32         """Initialize help screen"""
33         self.outer = outer
34         (self.win, self.panel) = panel_create(mlines, mcols)
35         self.panel.top()
36         self.panel.hide()
37
38         text = [
39             "Welcome to runner. Here are some keybindings",
40             "to get you started:",
41             "",
42             "h, left          previous card",
43             "l, right         next card",
44             "j, k, up, down   flip card",
45             "i, /             star card",
46             "0, ^, home       go to the start of the deck",
47             "$, end           go to the end of the deck",
48             "H, ?             open this screen",
49             "m                open the control menu",
50             "1, 2, 3          switch views",
51             "",
52             "More information can be found in the man page, or",
53             "by running `lightcards --help`.",
54             "",
55             "Press [H], or [?] to go back.",
56         ]
57
58         self.win.addstr(
59             1,
60             int(mcols / 2) - 8,
61             "LIGHTCARDS HELP",
62             curses.color_pair(1) + curses.A_BOLD,
63         )
64         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
65
66         for t in enumerate(text):
67             self.win.addstr(t[0] + 3, 1, t[1])
68
69         self.win.box()
70
71     def disp(self):
72         """Display help screen"""
73         (mlines, mcols) = self.outer.win.getmaxyx()
74         self.win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 25)
75         self.panel.show()
76
77         while True:
78             key = self.win.getkey()
79             if key == "q":
80                 self.outer.leave()
81             elif key in ["H", "?"]:
82                 self.panel.hide()
83                 self.outer.get_key()
84
85
86 class Menu:
87     def __init__(self, outer, mlines=17, mcols=44):
88         """Initialize the menu with content"""
89         self.outer = outer
90         (self.win, self.panel) = panel_create(mlines, mcols)
91         self.panel.top()
92         self.panel.hide()
93
94         self.win.addstr(
95             1,
96             int(mcols / 2) - 8,
97             "LIGHTCARDS MENU",
98             curses.color_pair(1) + curses.A_BOLD,
99         )
100         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
101         text = [
102             "[y]: reset stack to original state",
103             "[a]: alphabetize stack",
104             "[z]: shuffle stack",
105             "[t]: reverse stack order",
106             "[u]: unstar all",
107             "[d]: star all",
108             "[s]: update stack to include starred only",
109             "[e]: open the input file in $EDITOR",
110             "",
111             "[r]: restart",
112             "[m]: close menu",
113         ]
114
115         for t in enumerate(text):
116             self.win.addstr(t[0] + 3, 1, t[1])
117
118         self.win.box()
119
120     def menu_print(self, string, err=False):
121         """Print messages on the menu screen"""
122         if err:
123             color = curses.color_pair(2)
124         else:
125             color = curses.color_pair(1)
126
127         self.win.addstr(15, 1, string, color)
128         self.menu_grab()
129
130     def menu_grab(self):
131         """Grab keypresses on the menu screen"""
132         while True:
133             key = self.win.getkey()
134             if key in ["r", "m"]:
135                 self.panel.hide()
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 == "e":
158                 curses.endwin()
159                 os.system(f"$EDITOR {self.outer.input_file}"),
160                 (self.outer.headers, self.outer.stack) = parse.parse_html(
161                     parse.md2html(self.outer.input_file)
162                 )
163                 self.outer.get_key()
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         for i in range(42):
190             self.win.addch(14, i + 1, " ")
191
192         (mlines, mcols) = self.outer.win.getmaxyx()
193         self.win.mvwin(int(mlines / 2) - 8, int(mcols / 2) - 22)
194         self.panel.show()
195
196         self.menu_grab()
197
198
199 class Display:
200     def __init__(self, stack, headers, obj, view, input_file):
201         self.stack = stack
202         self.headers = headers
203         self.obj = obj
204         self.view = view
205         self.input_file = input_file
206
207     def run(self, stdscr):
208         """Set important options that require stdscr before starting"""
209         self.win = stdscr
210         curses.curs_set(0)  # Hide cursor
211         curses.use_default_colors()  # Allow transparency
212         curses.init_pair(1, curses.COLOR_CYAN, -1)
213         curses.init_pair(2, curses.COLOR_RED, -1)
214         curses.init_pair(3, curses.COLOR_YELLOW, -1)
215
216         self.main_panel = curses.panel.new_panel(self.win)
217         self.menu_obj = Menu(self)
218         self.help_obj = Help(self)
219
220         self.get_key()
221
222     def check_size(self):
223         (mlines, mcols) = self.win.getmaxyx()
224
225         while mlines < 24 or mcols < 60:
226             self.win.clear()
227             self.win.addstr(
228                 0,
229                 0,
230                 textwrap.fill(
231                     "Terminal too small! Min size 60x24", width=mcols
232                 ),
233             )
234             self.win.refresh()
235             (mlines, mcols) = self.win.getmaxyx()
236             time.sleep(0.1)
237         else:
238             self.disp_card()
239
240     def leave(self):
241         """Pickle stack before quitting"""
242         if self.obj.index + 1 == len(self.stack):
243             self.obj.index = 0
244
245         progress.dump(self.stack, runner.get_orig()[1])
246         sys.exit(0)
247
248     def nstarred(self):
249         """Get total number of starred cards"""
250         return [card for card in self.stack if card.starred]
251
252     def disp_bar(self):
253         """
254         Display the statusbar at the bottom of the screen with progress, star
255         status, and card side.
256         """
257         (mlines, mcols) = self.win.getmaxyx()
258         self.win.hline(mlines - 3, 0, 0, mcols)
259
260         # Calculate percent done
261         if len(self.stack) <= 1:
262             percent = "100"
263         else:
264             percent = str(
265                 round(self.obj.index / (len(self.stack) - 1) * 100)
266             ).zfill(2)
267
268         # Print yellow if starred
269         if self.current_card().starred:
270             star_color = curses.color_pair(3)
271         else:
272             star_color = curses.color_pair(1)
273
274         progress = (
275             f"[{percent}% ("
276             f"{str(self.obj.index).zfill(len(str(len(self.stack))))})]"
277         )
278
279         # Compose bar text
280         bar_start = "["
281         bar_middle = self.current_card().printStar()
282         bar_end = f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
283         if self.view != 3:
284             bar_end += (
285                 f" [{self.get_side()} ("
286                 f"{str(int(self.current_card().side) + 1)})]"
287             )
288         bar_end += f" [View {str(self.view)}]"
289
290         # Put it all togethor
291         height = mlines - 2
292         self.win.addstr(height, 0, bar_start, curses.color_pair(1))
293         self.win.addstr(height, len(bar_start), bar_middle, star_color)
294         self.win.addstr(
295             height,
296             len(bar_start + bar_middle),
297             textwrap.shorten(bar_end, width=mcols - 20, placeholder="…"),
298             curses.color_pair(1),
299         )
300
301         self.win.addstr(
302             height + 1,
303             mcols - len(progress) - 1,
304             progress,
305             curses.color_pair(1),
306         )
307
308         for i in range(
309             int(
310                 self.obj.index
311                 / (len(self.stack) - 1)
312                 * (mcols - len(progress))
313                 - 2
314             )
315         ):
316             # TODO: Use the variying width unicode block characters to make a
317             # super accurate bar
318             self.win.addch(height + 1, i, "»", curses.color_pair(1))
319
320     def wrap_width(self):
321         """Calculate the width at which the body text should wrap"""
322         (_, mcols) = self.win.getmaxyx()
323         wrap_width = mcols - 20
324         if wrap_width > 80:
325             wrap_width = 80
326         return wrap_width
327
328     def get_side(self):
329         if self.obj.side == 0:
330             return self.headers[self.current_card().side]
331         else:
332             return self.headers[self.current_card().get_reverse()]
333
334     def disp_card(self):
335         (_, mcols) = self.win.getmaxyx()
336         self.main_panel.bottom()
337         self.win.clear()
338         num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
339
340         if self.view in [1, 2, 4]:
341             """
342             Display the contents of the card.
343             Shows a header, a horizontal line, and the contents of the current
344             side.
345             """
346             # If on the back of the card, show the content of the front side in
347             # the header
348             if self.view == 1:
349                 self.obj.side = 0
350             elif self.view == 2:
351                 self.obj.side = 1
352
353             if self.current_card().side == 0:
354                 top = num_done + " | " + self.get_side()
355             else:
356                 top = (
357                     num_done
358                     + " | "
359                     + self.get_side()
360                     + ' | "'
361                     + str(self.current_card().get()[self.obj.get_reverse()])
362                     + '"'
363                 )
364
365             self.win.addstr(
366                 0,
367                 0,
368                 textwrap.shorten(top, width=mcols - 20, placeholder="…"),
369                 curses.A_BOLD,
370             )
371
372             # Show current side
373             self.win.addstr(
374                 2,
375                 0,
376                 textwrap.fill(
377                     self.current_card().get()[self.obj.side],
378                     width=self.wrap_width(),
379                 ),
380             )
381
382         elif self.view == 3:
383             """
384             Display the contents of the card with both the front and back sides.
385             """
386             (_, mcols) = self.win.getmaxyx()
387             self.main_panel.bottom()
388             self.win.clear()
389
390             self.win.addstr(
391                 0,
392                 0,
393                 textwrap.shorten(
394                     num_done,
395                     width=mcols - 20,
396                     placeholder="…",
397                 ),
398                 curses.A_BOLD,
399             )
400
401             # Show card content
402             self.win.addstr(
403                 2,
404                 0,
405                 textwrap.fill(
406                     self.headers[0] + ": " + self.current_card().front,
407                     width=self.wrap_width(),
408                 )
409                 + "\n\n"
410                 + textwrap.fill(
411                     self.headers[1] + ": " + self.current_card().back,
412                     width=self.wrap_width(),
413                 ),
414             )
415
416         self.win.hline(1, 0, curses.ACS_HLINE, mcols)
417         self.disp_bar()
418         self.disp_sidebar()
419
420     def current_card(self):
421         """Get current card object"""
422         return self.stack[self.obj.index]
423
424     def get_key(self):
425         """
426         Display a card and wait for the input.
427         Used as a general way of getting back into the card flow from a menu
428         """
429         while True:
430             self.check_size()
431             key = self.win.getkey()
432             if key == "q":
433                 self.leave()
434             elif key in ["h", "KEY_LEFT"]:
435                 self.obj.back()
436                 self.current_card().side = 0
437                 self.disp_card()
438             elif key in ["l", "KEY_RIGHT"]:
439                 if self.obj.index + 1 == len(self.stack):
440                     self.menu_obj.disp()
441                 else:
442                     self.obj.forward(self.stack)
443                     self.current_card().side = 0
444                     self.disp_card()
445             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"] and self.view != 3:
446                 self.current_card().flip()
447                 self.disp_card()
448             elif key in ["i", "/"]:
449                 self.current_card().toggleStar()
450                 self.disp_card()
451             elif key in ["0", "^", "KEY_HOME"]:
452                 self.obj.index = 0
453                 self.current_card().side = 0
454                 self.disp_card()
455             elif key in ["$", "KEY_END"]:
456                 self.obj.index = len(self.stack) - 1
457                 self.current_card().side = 0
458                 self.disp_card()
459             elif key in ["H", "?"]:
460                 self.help_obj.disp()
461             elif key == "m":
462                 self.menu_obj.disp()
463             elif key in ["1", "2", "3", "4"]:
464                 self.view = int(key)
465
466     def disp_sidebar(self):
467         """Display a sidebar with the starred terms"""
468         (mlines, mcols) = self.win.getmaxyx()
469         left = mcols - 19
470
471         self.win.addstr(
472             0,
473             mcols - 16,
474             "STARRED CARDS",
475             curses.color_pair(3) + curses.A_BOLD,
476         )
477         self.win.vline(0, mcols - 20, 0, mlines - 3)
478
479         nstarred = self.nstarred()
480         for i, card in enumerate(nstarred):
481             term = card.get()[self.obj.side]
482             if len(term) > 18:
483                 term = term[:18] + "…"
484
485             if i > mlines - 6:
486                 for i in range(19):
487                     self.win.addch(mlines - 3, left + i, " ")
488
489                 self.win.addstr(
490                     mlines - 4,
491                     left,
492                     f"({len(nstarred) - i - 2} more)",
493                 )
494             else:
495                 self.win.addstr(2 + i, left, term)
496
497         if len(self.nstarred()) == 0:
498             self.win.addstr(2, left, "None starred")