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