]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Set index to 0 before saving if at end of set
[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 disp_bar(self):
34         """
35         Display the statusbar at the bottom of the screen with progress, star
36         status, and card side.
37         """
38         (mlines, _) = self.win.getmaxyx()
39
40         # Calculate percent done
41         if len(self.stack) <= 1:
42             percent = "100"
43         else:
44             percent = str(round(self.obj.getIdx() /
45                                 len(self.stack) * 100)).zfill(2)
46
47         # Print yellow if starred
48         if self.stack[self.obj.getIdx()].getStar():
49             star_color = curses.color_pair(3)
50         else:
51             star_color = curses.color_pair(1)
52
53         # Create bar component
54         bar_start = "["
55         bar_middle = self.stack[self.obj.getIdx()].printStar()
56         bar_end = "] [" + percent + "% (" + \
57             str(self.obj.getIdx() + 1).zfill(len(str(len(self.stack)))) + \
58             "/" + str(len(self.stack)) + ")] [" + \
59             self.headers[self.obj.getSide()] + " (" + \
60             str(self.obj.getSide() + 1) + ")]"
61
62         # Put it all togethor
63         self.win.addstr(mlines - 1, 0, bar_start, curses.color_pair(1))
64         self.win.addstr(bar_middle, star_color)
65         self.win.insstr(bar_end, curses.color_pair(1))
66
67     def menu_print(self, string, err=False):
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, quit=False):
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         quit_text = "[q]: back"
136         if quit:
137             quit_text = "[q]: quit"
138
139         self.win.addstr("LIGHTCARDS MENU", curses.color_pair(1) +
140                         curses.A_BOLD)
141         self.win.hline(1, 0, curses.ACS_HLINE, 15)
142         self.win.addstr(2, 0, "[y]: reset stack to original state\n" +
143                         "[z]: shuffle stack\n" +
144                         "[f]: flip all cards in stack\n" +
145                         "[t]: reverse stack order\n" +
146                         "[u]: unstar all\n" +
147                         "[d]: star all\n" +
148                         "[s]: update stack to include starred only\n\n" +
149                         "[r]: restart\n" +
150                         quit_text)
151
152         if keygrab:
153             self.menu_grab()
154
155     def wrap_width(self):
156         (_, mcols) = self.win.getmaxyx()
157         wrap_width = mcols
158         if mcols > 80:
159             wrap_width = 80
160         return wrap_width
161
162     def disp_card(self):
163         """
164         Display the contents of the card
165         Shows a header, a horizontal line, and the contents of the current
166         side.
167         """
168         self.win.clear()
169         (_, mcols) = self.win.getmaxyx()
170         if self.obj.getIdx() == len(self.stack):
171             self.disp_menu(quit=True)
172         else:
173             # If on the back of the card, show the content of the front side in
174             # the header
175             num_done = str(self.obj.getIdx() +
176                            1).zfill(len(str(len(self.stack))))
177             if self.obj.getSide() == 0:
178                 top = num_done + " | " + self.headers[self.obj.getSide()]
179             else:
180                 top = num_done + " | " + self.headers[self.obj.getSide()] + \
181                     " | \"" + str(self.stack[self.obj.getIdx()][0]) + "\""
182             header_width = mcols
183             if mcols > 80:
184                 header_width = 80
185
186             self.win.addstr(textwrap.shorten(top, width=header_width,
187                                              placeholder="…"), curses.A_BOLD)
188
189             # Add horizontal line
190             lin_width = header_width
191             if len(top) < header_width:
192                 lin_width = len(top)
193             self.win.hline(1, 0, curses.ACS_HLINE, lin_width)
194
195             # Show current side
196             self.win.addstr(2, 0, textwrap.fill(
197                 self.stack[self.obj.getIdx()][self.obj.getSide()],
198                 width=self.wrap_width()))
199         self.disp_bar()
200
201     def disp_help(self):
202         """Display help screen"""
203         self.win.clear()
204         self.win.addstr("LIGHTCARDS HELP", curses.color_pair(1) +
205                         curses.A_BOLD)
206         self.win.hline(1, 0, curses.ACS_HLINE, 15)
207         self.win.addstr(2, 0, textwrap.fill(
208             "Welcome to lightcards. Here are some keybindings to get you " +
209             "started:", width=self.wrap_width()) +
210                         "\n\nh, left          previous card\n" +
211                         "l, right         next card\n" +
212                         "j, k, up, down   flip card\n" +
213                         "i, /             star card\n" +
214                         "0, ^, home       go to the start of the deck\n" +
215                         "$, end           go to the end of the deck\n" +
216                         "H, ?             open this screen\n" +
217                         "e                open the input file in $EDITOR\n" +
218                         "m                open the control menu\n\n" +
219                         textwrap.fill(
220                             "More information can be found in the man page, " +
221                             "or by running `lightcards --help`.",
222                             width=self.wrap_width()) +
223                         "\n\nPress [q], [H], or [?] to go back.")
224         while True:
225             key = self.win.getkey()
226             if key in ["q", "H", "?"]:
227                 self.get_key()
228
229     def get_key(self):
230         """
231         Display a card and wait for the input.
232         Used as a general way of getting back into the card flow from a menu
233         """
234
235         self.disp_card()
236         while True:
237             key = self.win.getkey()
238             if key == "q":
239                 self.leave()
240             elif key in ["l", "KEY_RIGHT"]:
241                 self.obj.forward(self.stack)
242                 self.obj.setSide(0)
243                 self.disp_card()
244             elif key in ["h", "KEY_LEFT"]:
245                 self.obj.back()
246                 self.obj.setSide(0)
247                 self.disp_card()
248             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"]:
249                 self.obj.flip()
250                 self.disp_card()
251             elif key in ["i", "/"]:
252                 self.stack[self.obj.getIdx()].toggleStar()
253                 self.disp_card()
254             elif key in ["0", "^", "KEY_HOME"]:
255                 self.obj.setIdx(0)
256                 self.obj.setSide(0)
257                 self.disp_card()
258             elif key in ["$", "KEY_END"]:
259                 self.obj.setIdx(len(self.stack) - 1)
260                 self.obj.setSide(0)
261                 self.disp_card()
262             elif key in ["H", "?"]:
263                 self.disp_help()
264             elif key == "m":
265                 self.win.clear()
266                 self.disp_menu()
267             elif key == "e":
268                 (self.headers, self.stack) = lightcards.reparse()
269                 self.get_key()