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