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