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