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