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