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