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