]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Move percent done from right to left
[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         # Compose bar text
310         bar_start = "["
311         bar_middle = self.current_card().printStar()
312         bar_end = f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
313         if self.view != 3:
314             bar_end += (
315                 f" [{self.get_side()} ("
316                 f"{str(int(self.current_card().side) + 1)})]"
317             )
318         bar_end += f" [View {str(self.view)}]"
319
320         # Put it all togethor
321         height = mlines - 2
322         self.win.addstr(height, 0, bar_start, curses.color_pair(1))
323         self.win.addstr(height, len(bar_start), bar_middle, star_color)
324         self.win.addstr(
325             height,
326             len(bar_start + bar_middle),
327             textwrap.shorten(bar_end, width=mcols - 20, placeholder="…"),
328             curses.color_pair(1),
329         )
330
331         progress = (
332             f"[{percent}% ("
333             f"{str(self.obj.index + 1).zfill(len(str(len(self.stack))))}"
334             f"/{str(len(self.stack))})] "
335         )
336
337         self.win.addstr(
338             height + 1,
339             0,
340             progress,
341             curses.color_pair(1),
342         )
343
344         for i in range(
345             int(
346                 self.obj.index
347                 / (len(self.stack) - 1)
348                 * (mcols - len(progress))
349                 - 1
350             )
351         ):
352             # TODO: Use the variying width unicode block characters to make a
353             # super accurate bar
354             self.win.addch(
355                 height + 1, i + len(progress), "»", curses.color_pair(1)
356             )
357
358     def wrap_width(self):
359         """Calculate the width at which the body text should wrap"""
360         (_, mcols) = self.win.getmaxyx()
361         wrap_width = mcols - 20
362         if wrap_width > 80:
363             wrap_width = 80
364         return wrap_width
365
366     def get_side(self):
367         if self.obj.side == 0:
368             return self.headers[self.current_card().side]
369         else:
370             return self.headers[self.current_card().get_reverse()]
371
372     def disp_card(self):
373         (_, mcols) = self.win.getmaxyx()
374         self.main_panel.bottom()
375         self.win.clear()
376         num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
377
378         if self.view in [1, 2, 4]:
379             """
380             Display the contents of the card.
381             Shows a header, a horizontal line, and the contents of the current
382             side.
383             """
384             # If on the back of the card, show the content of the front side in
385             # the header
386             if self.view == 1:
387                 self.obj.side = 0
388             elif self.view == 2:
389                 self.obj.side = 1
390
391             if self.current_card().side == 0:
392                 top = num_done + " | " + self.get_side()
393             else:
394                 top = (
395                     num_done
396                     + " | "
397                     + self.get_side()
398                     + ' | "'
399                     + str(self.current_card().get()[self.obj.get_reverse()])
400                     + '"'
401                 )
402
403             self.win.addstr(
404                 0,
405                 0,
406                 textwrap.shorten(top, width=mcols - 20, placeholder="…"),
407                 curses.A_BOLD,
408             )
409
410             # Show current side
411             self.win.addstr(
412                 2,
413                 0,
414                 textwrap.fill(
415                     self.current_card().get()[self.obj.side],
416                     width=self.wrap_width(),
417                 ),
418             )
419
420         elif self.view == 3:
421             """
422             Display the contents of the card with both the front and back sides.
423             """
424             (_, mcols) = self.win.getmaxyx()
425             self.main_panel.bottom()
426             self.win.clear()
427
428             self.win.addstr(
429                 0,
430                 0,
431                 textwrap.shorten(
432                     num_done,
433                     width=mcols - 20,
434                     placeholder="…",
435                 ),
436                 curses.A_BOLD,
437             )
438
439             # Show card content
440             self.win.addstr(
441                 2,
442                 0,
443                 textwrap.fill(
444                     self.headers[0] + ": " + self.current_card().front,
445                     width=self.wrap_width(),
446                 )
447                 + "\n\n"
448                 + textwrap.fill(
449                     self.headers[1] + ": " + self.current_card().back,
450                     width=self.wrap_width(),
451                 ),
452             )
453
454         self.win.hline(1, 0, curses.ACS_HLINE, mcols)
455         self.disp_bar()
456         self.disp_sidebar()
457
458     def current_card(self):
459         """Get current card object"""
460         return self.stack[self.obj.index]
461
462     def get_key(self):
463         """
464         Display a card and wait for the input.
465         Used as a general way of getting back into the card flow from a menu
466         """
467         while True:
468             self.check_size()
469             key = self.win.getkey()
470             if key == "q":
471                 self.leave()
472             elif key in ["h", "KEY_LEFT"]:
473                 self.obj.back()
474                 self.current_card().side = 0
475                 self.disp_card()
476             elif key in ["l", "KEY_RIGHT"]:
477                 if self.obj.index + 1 == len(self.stack):
478                     self.menu_obj.disp()
479                 else:
480                     self.obj.forward(self.stack)
481                     self.current_card().side = 0
482                     self.disp_card()
483             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"] and self.view != 3:
484                 self.current_card().flip()
485                 self.disp_card()
486             elif key in ["i", "/"]:
487                 self.current_card().toggleStar()
488                 self.disp_card()
489             elif key in ["0", "^", "KEY_HOME"]:
490                 self.obj.index = 0
491                 self.current_card().side = 0
492                 self.disp_card()
493             elif key in ["$", "KEY_END"]:
494                 self.obj.index = len(self.stack) - 1
495                 self.current_card().side = 0
496                 self.disp_card()
497             elif key in ["H", "?"]:
498                 self.help_obj.disp()
499             elif key == "m":
500                 self.menu_obj.disp()
501             elif key in ["1", "2", "3", "4"]:
502                 self.view = int(key)
503
504     def disp_sidebar(self):
505         """Display a sidebar with the starred terms"""
506         (mlines, mcols) = self.win.getmaxyx()
507         left = mcols - 19
508
509         self.win.addstr(
510             0,
511             mcols - 16,
512             "STARRED CARDS",
513             curses.color_pair(3) + curses.A_BOLD,
514         )
515         self.win.vline(0, mcols - 20, 0, mlines - 3)
516
517         nstarred = self.nstarred()
518         for i, card in enumerate(nstarred):
519             term = card.get()[self.obj.side]
520             if len(term) > 18:
521                 term = term[:18] + "…"
522
523             if i > mlines - 6:
524                 for i in range(19):
525                     self.win.addch(mlines - 3, left + i, " ")
526
527                 self.win.addstr(
528                     mlines - 4,
529                     left,
530                     f"({len(nstarred) - i - 2} more)",
531                 )
532             else:
533                 self.win.addstr(2 + i, left, term)
534
535         if len(self.nstarred()) == 0:
536             self.win.addstr(2, left, "None starred")