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