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