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