]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Update user interface
[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 from random import shuffle
7 import sys
8 import textwrap
9
10 from . import runner, progress
11
12
13 def panel_create(x, y):
14     """Create popup panels to a certain scale"""
15     win = curses.newwin(x, y)
16     panel = curses.panel.new_panel(win)
17     win.erase()
18     return (win, panel)
19
20
21 class Help:
22     def __init__(self, outer, mlines=20, mcols=52):
23         """Initialize help screen"""
24         self.outer = outer
25         (self.win, self.panel) = panel_create(mlines, mcols)
26         self.panel.top()
27         self.panel.hide()
28         self.win.clear()
29
30         text = [
31             "Welcome to runner. Here are some keybindings",
32             "to get you started:",
33             "",
34             "h, left          previous card",
35             "l, right         next card",
36             "j, k, up, down   flip card",
37             "i, /             star card",
38             "0, ^, home       go to the start of the deck",
39             "$, end           go to the end of the deck",
40             "H, ?             open this screen",
41             "e                open the input file in $EDITOR",
42             "m                open the control menu",
43             "",
44             "More information can be found in the man page, or",
45             "by running `lightcards --help`.",
46             "",
47             "Press [H], or [?] to go back.",
48         ]
49
50         self.win.addstr(
51             1,
52             int(mcols / 2) - 8,
53             "LIGHTCARDS HELP",
54             curses.color_pair(1) + curses.A_BOLD,
55         )
56         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
57
58         for t in enumerate(text):
59             self.win.addstr(t[0] + 3, 1, t[1])
60
61         self.win.box()
62
63     def disp(self):
64         """Display help screen"""
65         (mlines, mcols) = self.outer.win.getmaxyx()
66         self.win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 26)
67         self.outer.update_panels()
68         self.panel.show()
69
70         while True:
71             key = self.win.getkey()
72             if key == "q":
73                 self.outer.leave()
74             elif key in ["H", "?"]:
75                 self.panel.hide()
76                 self.outer.get_key()
77
78
79 class Menu:
80     def __init__(self, outer, mlines=17, mcols=44):
81         """Initialize the menu with content"""
82         self.outer = outer
83         (self.win, self.panel) = panel_create(mlines, mcols)
84         self.panel.top()
85         self.panel.hide()
86
87         self.win.addstr(
88             1,
89             int(mcols / 2) - 8,
90             "LIGHTCARDS MENU",
91             curses.color_pair(1) + curses.A_BOLD,
92         )
93         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
94         text = [
95             "[y]: reset stack to original state",
96             "[a]: alphabetize stack",
97             "[z]: shuffle stack",
98             "[f]: flip all cards in stack",
99             "[t]: reverse stack order",
100             "[u]: unstar all",
101             "[d]: star all",
102             "[s]: update stack to include starred only",
103             "",
104             "[r]: restart",
105             "[m]: close menu",
106         ]
107
108         for t in enumerate(text):
109             self.win.addstr(t[0] + 3, 1, t[1])
110
111         self.win.box()
112         self.outer.update_panels()
113
114     def menu_print(self, string, err=False):
115         """Print messages on the menu screen"""
116         if err:
117             color = curses.color_pair(2)
118         else:
119             color = curses.color_pair(1)
120
121         for i in range(42):
122             self.win.addch(15, i + 1, " ")
123
124         self.win.addstr(15, 1, string, color)
125         self.outer.update_panels()
126         self.menu_grab()
127
128     def menu_grab(self):
129         """Grab keypresses on the menu screen"""
130         while True:
131             key = self.win.getkey()
132             if key in ["r", "m"]:
133                 self.panel.hide()
134                 self.outer.update_panels()
135                 self.outer.get_key()
136             elif key == "q":
137                 self.outer.leave()
138             elif key == "y":
139                 self.outer.stack = runner.get_orig()[1]
140                 self.menu_print("Stack reset!")
141             elif key == "a":
142                 self.outer.stack.sort(key=lambda x: x.front)
143                 self.menu_print("Stack alphabetized!")
144             elif key == "u":
145                 [x.unStar() for x in self.outer.stack]
146                 self.menu_print("All unstarred!")
147             elif key == "d":
148                 [x.star() for x in self.outer.stack]
149                 self.menu_print("All starred!")
150             elif key == "t":
151                 self.outer.stack.reverse()
152                 self.menu_print("Stack reversed!")
153             elif key == "z":
154                 shuffle(self.outer.stack)
155                 self.menu_print("Stack shuffled!")
156             elif key == "f":
157                 for x in self.outer.stack:
158                     x.front, x.back = x.back, x.front
159                 (self.outer.headers[0], self.outer.headers[1]) = (
160                     self.outer.headers[1],
161                     self.outer.headers[0],
162                 )
163                 self.menu_print("Cards flipped!")
164             elif key == "s":
165                 # Check if there are any starred cards before proceeding, and
166                 # if not, don't allow to proceed and show an error message
167                 cont = False
168                 for x in self.outer.stack:
169                     if x.starred:
170                         cont = True
171                         break
172
173                 if cont:
174                     self.outer.stack = [
175                         x for x in self.outer.stack if x.starred
176                     ]
177                     self.menu_print("Stars only!")
178                 else:
179                     self.menu_print("ERR: None are starred!", err=True)
180             elif key in ["h", "KEY_LEFT"]:
181                 self.outer.obj.index = len(self.outer.stack) - 1
182                 self.outer.get_key()
183             elif key == "r":
184                 self.outer.obj.index = 0
185                 self.outer.get_key()
186
187     def disp(self):
188         """
189         Display a menu offering multiple options on how to manipulate the deck
190         and to continue
191         """
192         (mlines, mcols) = self.outer.win.getmaxyx()
193         self.win.mvwin(int(mlines / 2) - 9, int(mcols / 2) - 22)
194         self.panel.show()
195         self.outer.update_panels()
196
197         self.menu_grab()
198
199
200 class Display:
201     def __init__(self, stack, headers, obj):
202         self.stack = stack
203         self.headers = headers
204         self.obj = obj
205
206     def run(self, stdscr):
207         """Set important options that require stdscr before starting"""
208         self.win = stdscr
209         (mlines, mcols) = self.win.getmaxyx()
210         curses.curs_set(0)  # Hide cursor
211         curses.use_default_colors()  # Allow transparency
212         curses.init_pair(1, curses.COLOR_CYAN, -1)
213         curses.init_pair(2, curses.COLOR_RED, -1)
214         curses.init_pair(3, curses.COLOR_YELLOW, -1)
215
216         (self.main_win, self.main_panel) = panel_create(mlines, mcols)
217         self.menu_obj = Menu(self)
218         self.help_obj = Help(self)
219
220         self.get_key()
221
222     def update_panels(self):
223         """Update panel and window contents"""
224         curses.panel.update_panels()
225         self.win.refresh()
226
227     def leave(self):
228         """Pickle stack before quitting"""
229         if self.obj.index + 1 == len(self.stack):
230             self.obj.index = 0
231
232         progress.dump(self.stack, runner.get_orig()[1])
233         sys.exit(0)
234
235     def nstarred(self):
236         """Get total number of starred cards"""
237         return [card for card in self.stack if card.starred]
238
239     def disp_bar(self):
240         """
241         Display the statusbar at the bottom of the screen with progress, star
242         status, and card side.
243         """
244         (mlines, mcols) = self.win.getmaxyx()
245         self.win.hline(mlines - 2, 0, 0, mcols)
246
247         # Calculate percent done
248         if len(self.stack) <= 1:
249             percent = "100"
250         else:
251             percent = str(
252                 round(self.obj.index / (len(self.stack) - 1) * 100)
253             ).zfill(2)
254
255         # Print yellow if starred
256         if self.current_card().starred:
257             star_color = curses.color_pair(3)
258         else:
259             star_color = curses.color_pair(1)
260
261         # Create bar component
262         bar_start = "["
263         bar_middle = self.current_card().printStar()
264         bar_end = (
265             f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
266             f"[{percent}% ("
267             f"{str(self.obj.index).zfill(len(str(len(self.stack))))}"
268             f"/{str(len(self.stack))})] ["
269             f"{self.headers[self.current_card().side]} ("
270             f"{str(int(self.current_card().side) + 1)})]"
271         )
272
273         # Put it all togethor
274         self.win.addstr(mlines - 1, 0, bar_start, curses.color_pair(1))
275         self.win.addstr(mlines - 1, len(bar_start), bar_middle, star_color)
276         self.win.addstr(
277             mlines - 1,
278             len(bar_start + bar_middle),
279             bar_end,
280             curses.color_pair(1),
281         )
282
283     def wrap_width(self):
284         """Calculate the width at which the body text should wrap"""
285         (_, mcols) = self.win.getmaxyx()
286         wrap_width = mcols - 20
287         if wrap_width > 80:
288             wrap_width = 80
289         return wrap_width
290
291     def disp_card(self):
292         """
293         Display the contents of the card.
294         Shows a header, a horizontal line, and the contents of the current
295         side.
296         """
297         (mlines, mcols) = self.win.getmaxyx()
298         self.main_panel.bottom()
299         self.main_win.clear()
300         # If on the back of the card, show the content of the front side in
301         # the header
302         num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
303         if self.current_card().side == 0:
304             top = num_done + " | " + self.headers[self.current_card().side]
305         else:
306             top = (
307                 num_done
308                 + " | "
309                 + self.headers[self.current_card().side]
310                 + ' | "'
311                 + str(self.current_card().front)
312                 + '"'
313             )
314         header_width = mcols
315         if mcols > 80:
316             header_width = 80
317
318         self.main_win.addstr(
319             0,
320             0,
321             textwrap.shorten(top, width=header_width, placeholder="…"),
322             curses.A_BOLD,
323         )
324
325         # Add horizontal line
326         self.main_win.hline(1, 0, curses.ACS_HLINE, mcols)
327
328         # Show current side
329         self.main_win.addstr(
330             2,
331             0,
332             textwrap.fill(
333                 self.current_card().get(),
334                 width=self.wrap_width(),
335             ),
336         )
337         self.update_panels()
338         self.disp_bar()
339         self.disp_sidebar()
340
341     def current_card(self):
342         """Get current card object"""
343         return self.stack[self.obj.index]
344
345     def get_key(self):
346         """
347         Display a card and wait for the input.
348         Used as a general way of getting back into the card flow from a menu
349         """
350         self.disp_card()
351         while True:
352             key = self.win.getkey()
353             if key == "q":
354                 self.leave()
355             elif key in ["h", "KEY_LEFT"]:
356                 self.obj.back()
357                 self.current_card().side = 0
358                 self.disp_card()
359             elif key in ["l", "KEY_RIGHT"]:
360                 if self.obj.index + 1 == len(self.stack):
361                     self.menu_obj.disp()
362                 else:
363                     self.obj.forward(self.stack)
364                     self.current_card().side = 0
365                     self.disp_card()
366             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"]:
367                 self.current_card().flip()
368                 self.disp_card()
369             elif key in ["i", "/"]:
370                 self.current_card().toggleStar()
371                 self.disp_card()
372             elif key in ["0", "^", "KEY_HOME"]:
373                 self.obj.index = 0
374                 self.current_card().side = 0
375                 self.disp_card()
376             elif key in ["$", "KEY_END"]:
377                 self.obj.index = len(self.stack) - 1
378                 self.current_card().side = 0
379                 self.disp_card()
380             elif key in ["H", "?"]:
381                 self.help_obj.disp()
382             elif key == "m":
383                 self.menu_obj.disp()
384             elif key == "e":
385                 (self.headers, self.stack) = runner.reparse()
386                 self.get_key()
387
388     def disp_sidebar(self):
389         """Display a sidebar with the starred terms"""
390         (mlines, mcols) = self.win.getmaxyx()
391         left = mcols - 19
392
393         self.win.addstr(
394             0,
395             mcols - 16,
396             "STARRED CARDS",
397             curses.color_pair(3) + curses.A_BOLD,
398         )
399         self.win.vline(0, mcols - 20, 0, mlines - 2)
400
401         nstarred = self.nstarred()
402         if mlines - 5 < len(self.nstarred()):
403             nstarred = self.nstarred()[: mlines - 4]
404         elif mlines - 5 == len(self.nstarred()):
405             nstarred = self.nstarred()[: mlines - 3]
406
407         for _ in nstarred:
408             for i, card in enumerate(nstarred):
409                 term = card.front
410                 if len(term) > 18:
411                     term = term + "…"
412                 self.win.addstr(2 + i, left, term)
413             if not nstarred == self.nstarred():
414                 self.win.addstr(
415                     mlines - 3,
416                     left,
417                     f"({len(self.nstarred()) - len(nstarred)} more)",
418                 )
419                 break
420
421         if len(self.nstarred()) == 0:
422             self.win.addstr(2, left, "None starred")