]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
49840583eb27c1987a68bd0df13db85dfc07f3c6
[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.obj, self.stack, self.headers), self.stack)
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 == "u":
96                 [x.unStar() for x in self.stack]
97                 self.menu_print("All unstarred!")
98             elif key == "d":
99                 [x.star() for x in self.stack]
100                 self.menu_print("All starred!")
101             elif key == "t":
102                 self.stack.reverse()
103                 self.menu_print(
104                     "self.stack reversed!")
105             elif key == "z":
106                 shuffle(self.stack)
107                 self.menu_print("Stack shuffled!")
108             elif key == "f":
109                 for x in self.stack:
110                     x[0], x[1] = x[1], x[0]
111                 (self.headers[0], self.headers[1]) = (self.headers[1],
112                                                       self.headers[0])
113                 self.menu_print("Cards flipped!")
114             elif key == "s":
115                 # Check if there are any starred cards before proceeding, and
116                 # if not, don't allow to proceed and show an error message
117                 cont = False
118                 for x in self.stack:
119                     if x.getStar():
120                         cont = True
121                         break
122
123                 if cont:
124                     self.stack = [x for x in self.stack if x.getStar()]
125                     self.menu_print("Stars only!")
126                 else:
127                     self.menu_print("ERR: None are starred!", err=True)
128             elif key in ["h", "KEY_LEFT"]:
129                 self.obj.setIdx(len(self.stack) - 1)
130                 self.get_key()
131             elif key == "r":
132                 self.obj.setIdx(0)
133                 self.get_key()
134
135     def disp_menu(self, keygrab=True, quit=False):
136         """
137         Display a menu once the end of the deck has been reached, offering
138         multiple options on how to continue.
139         """
140
141         quit_text = "[q]: back"
142         if quit:
143             quit_text = "[q]: quit"
144
145         self.win.addstr("LIGHTCARDS MENU", curses.color_pair(1) +
146                         curses.A_BOLD)
147         self.win.hline(1, 0, curses.ACS_HLINE, 15)
148         self.win.addstr(2, 0, "[y]: reset stack to original state\n" +
149                         "[z]: shuffle stack\n" +
150                         "[f]: flip all cards in stack\n" +
151                         "[t]: reverse stack order\n" +
152                         "[u]: unstar all\n" +
153                         "[d]: star all\n" +
154                         "[s]: update stack to include starred only\n\n" +
155                         "[r]: restart\n" +
156                         quit_text)
157
158         if keygrab:
159             self.menu_grab()
160
161     def wrap_width(self):
162         (_, mcols) = self.win.getmaxyx()
163         wrap_width = mcols - 20
164         if wrap_width > 80:
165             wrap_width = 80
166         return wrap_width
167
168     def disp_card(self):
169         """
170         Display the contents of the card
171         Shows a header, a horizontal line, and the contents of the current
172         side.
173         """
174         self.win.clear()
175         (_, mcols) = self.win.getmaxyx()
176         if self.obj.getIdx() == len(self.stack):
177             self.disp_menu(quit=True)
178         else:
179             # If on the back of the card, show the content of the front side in
180             # the header
181             num_done = str(self.obj.getIdx() +
182                            1).zfill(len(str(len(self.stack))))
183             if self.obj.getSide() == 0:
184                 top = num_done + " | " + self.headers[self.obj.getSide()]
185             else:
186                 top = num_done + " | " + self.headers[self.obj.getSide()] + \
187                     " | \"" + str(self.stack[self.obj.getIdx()][0]) + "\""
188             header_width = mcols
189             if mcols > 80:
190                 header_width = 80
191
192             self.win.addstr(textwrap.shorten(top, width=header_width,
193                                              placeholder="…"), curses.A_BOLD)
194
195             # Add horizontal line
196             lin_width = header_width
197             if len(top) < header_width:
198                 lin_width = len(top)
199             self.win.hline(1, 0, curses.ACS_HLINE, lin_width)
200
201             # Show current side
202             self.win.addstr(2, 0, textwrap.fill(
203                 self.stack[self.obj.getIdx()][self.obj.getSide()],
204                 width=self.wrap_width()))
205         self.disp_bar()
206         self.disp_sidebar()
207
208     def disp_help(self):
209         """Display help screen"""
210         self.win.clear()
211         self.win.addstr("LIGHTCARDS HELP", curses.color_pair(1) +
212                         curses.A_BOLD)
213         self.win.hline(1, 0, curses.ACS_HLINE, 15)
214         self.win.addstr(2, 0, textwrap.fill(
215             "Welcome to lightcards. Here are some keybindings to get you " +
216             "started:", width=self.wrap_width()) +
217                         "\n\nh, left          previous card\n" +
218                         "l, right         next card\n" +
219                         "j, k, up, down   flip card\n" +
220                         "i, /             star card\n" +
221                         "0, ^, home       go to the start of the deck\n" +
222                         "$, end           go to the end of the deck\n" +
223                         "H, ?             open this screen\n" +
224                         "e                open the input file in $EDITOR\n" +
225                         "m                open the control menu\n\n" +
226                         textwrap.fill(
227                             "More information can be found in the man page, " +
228                             "or by running `lightcards --help`.",
229                             width=self.wrap_width()) +
230                         "\n\nPress [q], [H], or [?] to go back.")
231         while True:
232             key = self.win.getkey()
233             if key in ["q", "H", "?"]:
234                 self.get_key()
235
236     def get_key(self):
237         """
238         Display a card and wait for the input.
239         Used as a general way of getting back into the card flow from a menu
240         """
241
242         self.disp_card()
243         while True:
244             key = self.win.getkey()
245             if key == "q":
246                 self.leave()
247             elif key in ["l", "KEY_RIGHT"]:
248                 self.obj.forward(self.stack)
249                 self.obj.setSide(0)
250                 self.disp_card()
251             elif key in ["h", "KEY_LEFT"]:
252                 self.obj.back()
253                 self.obj.setSide(0)
254                 self.disp_card()
255             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"]:
256                 self.obj.flip()
257                 self.disp_card()
258             elif key in ["i", "/"]:
259                 self.stack[self.obj.getIdx()].toggleStar()
260                 self.disp_card()
261             elif key in ["0", "^", "KEY_HOME"]:
262                 self.obj.setIdx(0)
263                 self.obj.setSide(0)
264                 self.disp_card()
265             elif key in ["$", "KEY_END"]:
266                 self.obj.setIdx(len(self.stack) - 1)
267                 self.obj.setSide(0)
268                 self.disp_card()
269             elif key in ["H", "?"]:
270                 self.disp_help()
271             elif key == "m":
272                 self.win.clear()
273                 self.disp_menu()
274             elif key == "e":
275                 (self.headers, self.stack) = lightcards.reparse()
276                 self.get_key()
277
278     def disp_sidebar(self):
279         (mlines, mcols) = self.win.getmaxyx()
280         left = mcols - 19
281
282         self.win.addstr(0, mcols - 16, "STARRED CARDS",
283                         curses.color_pair(3) + curses.A_BOLD)
284         self.win.vline(0, mcols - 20, 0, mlines - 2)
285         self.win.hline(1, left, 0, mlines)
286
287         i = 0
288         for card in self.stack:
289             if i > mlines - 6:
290                 self.win.addstr(2 + i, left, f"... ({self.ntotal() - i} more)")
291                 break
292             elif card.getStar():
293                 term = card[0]
294                 if len(card[0]) > 18:
295                     term = card[0][:18] + "…"
296                 self.win.addstr(2 + i, left, term)
297
298                 i += 1
299
300         if i == 0:
301             self.win.addstr(2, left, "None starred")
302