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