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