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