]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Modify mvwin() positioning
[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=20, 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             "",
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) - 25)
67         self.panel.show()
68
69         while True:
70             key = self.win.getkey()
71             if key == "q":
72                 self.outer.leave()
73             elif key in ["H", "?"]:
74                 self.panel.hide()
75                 self.outer.get_key()
76
77
78 class Menu:
79     def __init__(self, outer, mlines=17, mcols=44):
80         """Initialize the menu with content"""
81         self.outer = outer
82         (self.win, self.panel) = panel_create(mlines, mcols)
83         self.panel.top()
84         self.panel.hide()
85
86         self.win.addstr(
87             1,
88             int(mcols / 2) - 8,
89             "LIGHTCARDS MENU",
90             curses.color_pair(1) + curses.A_BOLD,
91         )
92         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
93         text = [
94             "[y]: reset stack to original state",
95             "[a]: alphabetize stack",
96             "[z]: shuffle stack",
97             "[f]: flip all cards in 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         for i in range(42):
120             self.win.addch(15, i + 1, " ")
121
122         self.win.addstr(15, 1, string, color)
123         self.menu_grab()
124
125     def menu_grab(self):
126         """Grab keypresses on the menu screen"""
127         while True:
128             key = self.win.getkey()
129             if key in ["r", "m"]:
130                 self.panel.hide()
131                 self.outer.get_key()
132             elif key == "q":
133                 self.outer.leave()
134             elif key == "y":
135                 self.outer.stack = runner.get_orig()[1]
136                 self.menu_print("Stack reset!")
137             elif key == "a":
138                 self.outer.stack.sort(key=lambda x: x.front)
139                 self.menu_print("Stack alphabetized!")
140             elif key == "u":
141                 [x.unStar() for x in self.outer.stack]
142                 self.menu_print("All unstarred!")
143             elif key == "d":
144                 [x.star() for x in self.outer.stack]
145                 self.menu_print("All starred!")
146             elif key == "t":
147                 self.outer.stack.reverse()
148                 self.menu_print("Stack reversed!")
149             elif key == "z":
150                 shuffle(self.outer.stack)
151                 self.menu_print("Stack shuffled!")
152             elif key == "f":
153                 for x in self.outer.stack:
154                     x.front, x.back = x.back, x.front
155                 (self.outer.headers[0], self.outer.headers[1]) = (
156                     self.outer.headers[1],
157                     self.outer.headers[0],
158                 )
159                 self.menu_print("Cards flipped!")
160             elif key == "s":
161                 # Check if there are any starred cards before proceeding, and
162                 # if not, don't allow to proceed and show an error message
163                 cont = False
164                 for x in self.outer.stack:
165                     if x.starred:
166                         cont = True
167                         break
168
169                 if cont:
170                     self.outer.stack = [
171                         x for x in self.outer.stack if x.starred
172                     ]
173                     self.menu_print("Stars only!")
174                 else:
175                     self.menu_print("ERR: None are starred!", err=True)
176             elif key == "r":
177                 self.outer.obj.index = 0
178                 self.outer.get_key()
179
180     def disp(self):
181         """
182         Display a menu offering multiple options on how to manipulate the deck
183         and to continue
184         """
185         (mlines, mcols) = self.outer.win.getmaxyx()
186         self.win.mvwin(int(mlines / 2) - 9, int(mcols / 2) - 21)
187         self.panel.show()
188
189         self.menu_grab()
190
191
192 class Display:
193     def __init__(self, stack, headers, obj):
194         self.stack = stack
195         self.headers = headers
196         self.obj = obj
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         # Create bar component
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             f"{self.headers[self.current_card().side]} ("
274             f"{str(int(self.current_card().side) + 1)})]"
275         )
276
277         # Put it all togethor
278         self.win.addstr(mlines - 1, 0, bar_start, curses.color_pair(1))
279         self.win.addstr(mlines - 1, len(bar_start), bar_middle, star_color)
280         self.win.addstr(
281             mlines - 1,
282             len(bar_start + bar_middle),
283             textwrap.shorten(bar_end, width=mcols - 20, placeholder="…"),
284             curses.color_pair(1),
285         )
286
287     def wrap_width(self):
288         """Calculate the width at which the body text should wrap"""
289         (_, mcols) = self.win.getmaxyx()
290         wrap_width = mcols - 20
291         if wrap_width > 80:
292             wrap_width = 80
293         return wrap_width
294
295     def disp_card(self):
296         """
297         Display the contents of the card.
298         Shows a header, a horizontal line, and the contents of the current
299         side.
300         """
301         (_, mcols) = self.win.getmaxyx()
302         self.main_panel.bottom()
303         self.win.clear()
304
305         # If on the back of the card, show the content of the front side in
306         # the header
307         num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
308         if self.current_card().side == 0:
309             top = num_done + " | " + self.headers[self.current_card().side]
310         else:
311             top = (
312                 num_done
313                 + " | "
314                 + self.headers[self.current_card().side]
315                 + ' | "'
316                 + str(self.current_card().front)
317                 + '"'
318             )
319
320         header_width = mcols
321         if mcols > 80:
322             header_width = 80
323
324         self.win.addstr(
325             0,
326             0,
327             textwrap.shorten(top, width=header_width, placeholder="…"),
328             curses.A_BOLD,
329         )
330
331         # Add horizontal line
332         self.win.hline(1, 0, curses.ACS_HLINE, mcols)
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         self.disp_bar()
345         self.disp_sidebar()
346
347     def current_card(self):
348         """Get current card object"""
349         return self.stack[self.obj.index]
350
351     def get_key(self):
352         """
353         Display a card and wait for the input.
354         Used as a general way of getting back into the card flow from a menu
355         """
356         while True:
357             self.check_size()
358             key = self.win.getkey()
359             if key == "q":
360                 self.leave()
361             elif key in ["h", "KEY_LEFT"]:
362                 self.obj.back()
363                 self.current_card().side = 0
364                 self.disp_card()
365             elif key in ["l", "KEY_RIGHT"]:
366                 if self.obj.index + 1 == len(self.stack):
367                     self.menu_obj.disp()
368                 else:
369                     self.obj.forward(self.stack)
370                     self.current_card().side = 0
371                     self.disp_card()
372             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"]:
373                 self.current_card().flip()
374                 self.disp_card()
375             elif key in ["i", "/"]:
376                 self.current_card().toggleStar()
377                 self.disp_card()
378             elif key in ["0", "^", "KEY_HOME"]:
379                 self.obj.index = 0
380                 self.current_card().side = 0
381                 self.disp_card()
382             elif key in ["$", "KEY_END"]:
383                 self.obj.index = len(self.stack) - 1
384                 self.current_card().side = 0
385                 self.disp_card()
386             elif key in ["H", "?"]:
387                 self.help_obj.disp()
388             elif key == "m":
389                 self.menu_obj.disp()
390             elif key == "e":
391                 (self.headers, self.stack) = runner.reparse()
392                 self.get_key()
393
394     def disp_sidebar(self):
395         """Display a sidebar with the starred terms"""
396         (mlines, mcols) = self.win.getmaxyx()
397         left = mcols - 19
398
399         self.win.addstr(
400             0,
401             mcols - 16,
402             "STARRED CARDS",
403             curses.color_pair(3) + curses.A_BOLD,
404         )
405         self.win.vline(0, mcols - 20, 0, mlines - 2)
406
407         nstarred = self.nstarred()
408         if mlines - 5 < len(self.nstarred()):
409             nstarred = self.nstarred()[: mlines - 4]
410         elif mlines - 5 == len(self.nstarred()):
411             nstarred = self.nstarred()[: mlines - 3]
412
413         for _ in nstarred:
414             for i, card in enumerate(nstarred):
415                 term = card.front
416                 if len(term) > 18:
417                     term = term + "…"
418                 self.win.addstr(2 + i, left, term)
419             if not nstarred == self.nstarred():
420                 self.win.addstr(
421                     mlines - 3,
422                     left,
423                     f"({len(self.nstarred()) - len(nstarred)} more)",
424                 )
425                 break
426
427         if len(self.nstarred()) == 0:
428             self.win.addstr(2, left, "None starred")