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