]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
0b7fbd59af5db2fd02835f8b9f89de4f72ed4ed0
[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
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=20, 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 runner. Here are some keybindings",
73             "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             "",
85             "More information can be found in the man page, or",
86             "by running `lightcards --help`.",
87             "",
88             "Press [H], or [?] to go back.",
89         ]
90
91         self.win.addstr(
92             1,
93             int(mcols / 2) - 8,
94             "LIGHTCARDS HELP",
95             curses.color_pair(1) + curses.A_BOLD,
96         )
97         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
98
99         for t in enumerate(text):
100             self.win.addstr(t[0] + 3, 1, t[1])
101
102         self.win.box()
103
104     def disp(self):
105         """Display help screen"""
106         (mlines, mcols) = self.outer.win.getmaxyx()
107         self.win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 25)
108         self.panel.show()
109
110         while True:
111             key = self.win.getkey()
112             if key == "q":
113                 self.outer.leave()
114             elif key in ["H", "?"]:
115                 self.panel.hide()
116                 self.outer.get_key()
117
118
119 class Menu:
120     def __init__(self, outer, mlines=17, mcols=44):
121         """Initialize the menu with content"""
122         self.outer = outer
123         (self.win, self.panel) = panel_create(mlines, mcols)
124         self.panel.top()
125         self.panel.hide()
126
127         self.win.addstr(
128             1,
129             int(mcols / 2) - 8,
130             "LIGHTCARDS MENU",
131             curses.color_pair(1) + curses.A_BOLD,
132         )
133         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
134         text = [
135             "[y]: reset stack to original state",
136             "[a]: alphabetize stack",
137             "[z]: shuffle stack",
138             "[t]: reverse stack order",
139             "[u]: unstar all",
140             "[d]: star all",
141             "[s]: update stack to include starred only",
142             "[e]: open the input file in $EDITOR",
143             "",
144             "[r]: restart",
145             "[m]: close menu",
146         ]
147
148         for t in enumerate(text):
149             self.win.addstr(t[0] + 3, 1, t[1])
150
151         self.win.box()
152
153     def menu_print(self, string, err=False):
154         """Print messages on the menu screen"""
155         if err:
156             color = curses.color_pair(2)
157         else:
158             color = curses.color_pair(1)
159
160         self.win.addstr(15, 1, string, color)
161         self.menu_grab()
162
163     def menu_grab(self):
164         """Grab keypresses on the menu screen"""
165         while True:
166             key = self.win.getkey()
167             if key in ["r", "m"]:
168                 self.panel.hide()
169                 self.outer.get_key()
170             elif key == "q":
171                 self.outer.leave()
172             elif key == "y":
173                 self.outer.stack = runner.get_orig()[1]
174                 self.menu_print("Stack reset!")
175             elif key == "a":
176                 self.outer.stack.sort(key=lambda x: x.front)
177                 self.menu_print("Stack alphabetized!")
178             elif key == "u":
179                 [x.unStar() for x in self.outer.stack]
180                 self.menu_print("All unstarred!")
181             elif key == "d":
182                 [x.star() for x in self.outer.stack]
183                 self.menu_print("All starred!")
184             elif key == "t":
185                 self.outer.stack.reverse()
186                 self.menu_print("Stack reversed!")
187             elif key == "z":
188                 shuffle(self.outer.stack)
189                 self.menu_print("Stack shuffled!")
190             elif key == "e":
191                 curses.endwin()
192                 os.system(f"$EDITOR {self.outer.input_file}"),
193                 (self.outer.headers, self.outer.stack) = parse.parse_html(
194                     parse.md2html(self.outer.input_file)
195                 )
196                 self.outer.get_key()
197             elif key == "s":
198                 # Check if there are any starred cards before proceeding, and
199                 # if not, don't allow to proceed and show an error message
200                 cont = False
201                 for x in self.outer.stack:
202                     if x.starred:
203                         cont = True
204                         break
205
206                 if cont:
207                     self.outer.stack = [
208                         x for x in self.outer.stack if x.starred
209                     ]
210                     self.menu_print("Stars only!")
211                 else:
212                     self.menu_print("ERR: None are starred!", err=True)
213             elif key == "r":
214                 self.outer.obj.index = 0
215                 self.outer.get_key()
216
217     def disp(self):
218         """
219         Display a menu offering multiple options on how to manipulate the deck
220         and to continue
221         """
222         for i in range(42):
223             self.win.addch(14, i + 1, " ")
224
225         (mlines, mcols) = self.outer.win.getmaxyx()
226         self.win.mvwin(int(mlines / 2) - 8, int(mcols / 2) - 22)
227         self.panel.show()
228
229         self.menu_grab()
230
231
232 class Display:
233     def __init__(self, stack, headers, obj, view, input_file):
234         self.stack = stack
235         self.headers = headers
236         self.obj = obj
237         self.view = view
238         self.input_file = input_file
239
240     def run(self, stdscr):
241         """Set important options that require stdscr before starting"""
242         self.win = stdscr
243         curses.curs_set(0)  # Hide cursor
244         curses.use_default_colors()  # Allow transparency
245         curses.init_pair(1, curses.COLOR_CYAN, -1)
246         curses.init_pair(2, curses.COLOR_RED, -1)
247         curses.init_pair(3, curses.COLOR_YELLOW, -1)
248
249         self.main_panel = curses.panel.new_panel(self.win)
250         self.menu_obj = Menu(self)
251         self.help_obj = Help(self)
252         self.quit_obj = Quit(self)
253
254         self.get_key()
255
256     def check_size(self):
257         (mlines, mcols) = self.win.getmaxyx()
258
259         while mlines < 24 or mcols < 60:
260             self.win.clear()
261             self.win.addstr(
262                 0,
263                 0,
264                 textwrap.fill(
265                     "Terminal too small! Min size 60x24", width=mcols
266                 ),
267             )
268             self.win.refresh()
269             (mlines, mcols) = self.win.getmaxyx()
270             time.sleep(0.1)
271         else:
272             self.disp_card()
273
274     def leave(self):
275         """Pickle stack and confirm before quitting"""
276         self.quit_obj.disp()
277         if self.obj.index + 1 == len(self.stack):
278             self.obj.index = 0
279
280         progress.dump(self.stack, runner.get_orig()[1])
281         sys.exit(0)
282
283     def nstarred(self):
284         """Get total number of starred cards"""
285         return [card for card in self.stack if card.starred]
286
287     def disp_bar(self):
288         """
289         Display the statusbar at the bottom of the screen with progress, star
290         status, and card side.
291         """
292         (mlines, mcols) = self.win.getmaxyx()
293         self.win.hline(mlines - 3, 0, 0, mcols)
294
295         # Calculate percent done
296         if len(self.stack) <= 1:
297             percent = "100"
298         else:
299             percent = str(
300                 round(self.obj.index / (len(self.stack) - 1) * 100)
301             ).zfill(2)
302
303         # Print yellow if starred
304         if self.current_card().starred:
305             star_color = curses.color_pair(3)
306         else:
307             star_color = curses.color_pair(1)
308
309         progress = (
310             f"[{percent}% ("
311             f"{str(self.obj.index).zfill(len(str(len(self.stack))))})]"
312         )
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         self.win.addstr(
337             height + 1,
338             mcols - len(progress) - 1,
339             progress,
340             curses.color_pair(1),
341         )
342
343         for i in range(
344             int(
345                 self.obj.index
346                 / (len(self.stack) - 1)
347                 * (mcols - len(progress))
348                 - 2
349             )
350         ):
351             # TODO: Use the variying width unicode block characters to make a
352             # super accurate bar
353             self.win.addch(height + 1, i, "»", curses.color_pair(1))
354
355     def wrap_width(self):
356         """Calculate the width at which the body text should wrap"""
357         (_, mcols) = self.win.getmaxyx()
358         wrap_width = mcols - 20
359         if wrap_width > 80:
360             wrap_width = 80
361         return wrap_width
362
363     def get_side(self):
364         if self.obj.side == 0:
365             return self.headers[self.current_card().side]
366         else:
367             return self.headers[self.current_card().get_reverse()]
368
369     def disp_card(self):
370         (_, mcols) = self.win.getmaxyx()
371         self.main_panel.bottom()
372         self.win.clear()
373         num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
374
375         if self.view in [1, 2, 4]:
376             """
377             Display the contents of the card.
378             Shows a header, a horizontal line, and the contents of the current
379             side.
380             """
381             # If on the back of the card, show the content of the front side in
382             # the header
383             if self.view == 1:
384                 self.obj.side = 0
385             elif self.view == 2:
386                 self.obj.side = 1
387
388             if self.current_card().side == 0:
389                 top = num_done + " | " + self.get_side()
390             else:
391                 top = (
392                     num_done
393                     + " | "
394                     + self.get_side()
395                     + ' | "'
396                     + str(self.current_card().get()[self.obj.get_reverse()])
397                     + '"'
398                 )
399
400             self.win.addstr(
401                 0,
402                 0,
403                 textwrap.shorten(top, width=mcols - 20, placeholder="…"),
404                 curses.A_BOLD,
405             )
406
407             # Show current side
408             self.win.addstr(
409                 2,
410                 0,
411                 textwrap.fill(
412                     self.current_card().get()[self.obj.side],
413                     width=self.wrap_width(),
414                 ),
415             )
416
417         elif self.view == 3:
418             """
419             Display the contents of the card with both the front and back sides.
420             """
421             (_, mcols) = self.win.getmaxyx()
422             self.main_panel.bottom()
423             self.win.clear()
424
425             self.win.addstr(
426                 0,
427                 0,
428                 textwrap.shorten(
429                     num_done,
430                     width=mcols - 20,
431                     placeholder="…",
432                 ),
433                 curses.A_BOLD,
434             )
435
436             # Show card content
437             self.win.addstr(
438                 2,
439                 0,
440                 textwrap.fill(
441                     self.headers[0] + ": " + self.current_card().front,
442                     width=self.wrap_width(),
443                 )
444                 + "\n\n"
445                 + textwrap.fill(
446                     self.headers[1] + ": " + self.current_card().back,
447                     width=self.wrap_width(),
448                 ),
449             )
450
451         self.win.hline(1, 0, curses.ACS_HLINE, mcols)
452         self.disp_bar()
453         self.disp_sidebar()
454
455     def current_card(self):
456         """Get current card object"""
457         return self.stack[self.obj.index]
458
459     def get_key(self):
460         """
461         Display a card and wait for the input.
462         Used as a general way of getting back into the card flow from a menu
463         """
464         while True:
465             self.check_size()
466             key = self.win.getkey()
467             if key == "q":
468                 self.leave()
469             elif key in ["h", "KEY_LEFT"]:
470                 self.obj.back()
471                 self.current_card().side = 0
472                 self.disp_card()
473             elif key in ["l", "KEY_RIGHT"]:
474                 if self.obj.index + 1 == len(self.stack):
475                     self.menu_obj.disp()
476                 else:
477                     self.obj.forward(self.stack)
478                     self.current_card().side = 0
479                     self.disp_card()
480             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"] and self.view != 3:
481                 self.current_card().flip()
482                 self.disp_card()
483             elif key in ["i", "/"]:
484                 self.current_card().toggleStar()
485                 self.disp_card()
486             elif key in ["0", "^", "KEY_HOME"]:
487                 self.obj.index = 0
488                 self.current_card().side = 0
489                 self.disp_card()
490             elif key in ["$", "KEY_END"]:
491                 self.obj.index = len(self.stack) - 1
492                 self.current_card().side = 0
493                 self.disp_card()
494             elif key in ["H", "?"]:
495                 self.help_obj.disp()
496             elif key == "m":
497                 self.menu_obj.disp()
498             elif key in ["1", "2", "3", "4"]:
499                 self.view = int(key)
500
501     def disp_sidebar(self):
502         """Display a sidebar with the starred terms"""
503         (mlines, mcols) = self.win.getmaxyx()
504         left = mcols - 19
505
506         self.win.addstr(
507             0,
508             mcols - 16,
509             "STARRED CARDS",
510             curses.color_pair(3) + curses.A_BOLD,
511         )
512         self.win.vline(0, mcols - 20, 0, mlines - 3)
513
514         nstarred = self.nstarred()
515         for i, card in enumerate(nstarred):
516             term = card.get()[self.obj.side]
517             if len(term) > 18:
518                 term = term[:18] + "…"
519
520             if i > mlines - 6:
521                 for i in range(19):
522                     self.win.addch(mlines - 3, left + i, " ")
523
524                 self.win.addstr(
525                     mlines - 4,
526                     left,
527                     f"({len(nstarred) - i - 2} more)",
528                 )
529             else:
530                 self.win.addstr(2 + i, left, term)
531
532         if len(self.nstarred()) == 0:
533             self.win.addstr(2, left, "None starred")