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