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