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