1 # Display card output and retreive input
7 from random import shuffle
12 from . import runner, progress, parse
15 def panel_create(x, y):
16 """Create popup panels to a certain scale"""
17 win = curses.newwin(x, y)
18 panel = curses.panel.new_panel(win)
23 class CursesError(BaseException):
24 def __init__(self, message="lightcards: Curses error!"):
25 self.message = message
31 def __init__(self, outer, mlines=5, mcols=20):
33 (self.win, self.panel) = panel_create(mlines, mcols)
41 curses.color_pair(1) + curses.A_BOLD,
43 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
44 self.win.addstr(3, 1, "Quit? [y/n]")
49 """Display quit confirmation screen"""
50 (mlines, mcols) = self.outer.win.getmaxyx()
51 self.win.mvwin(int(mlines / 2) - 3, int(mcols / 2) - 10)
55 key = self.win.getkey()
64 def __init__(self, outer, mlines=21, mcols=52):
65 """Initialize help screen"""
67 (self.win, self.panel) = panel_create(mlines, mcols)
72 "Welcome to runner. Here are some keybindings",
73 "to get you started:",
75 "h, left previous card",
77 "j, k, up, down flip card",
79 "0, ^, home go to the start of the deck",
80 "$, end go to the end of the deck",
81 "H, ? open this screen",
82 "m open the control menu",
83 "1, 2, 3 switch views",
86 "More information can be found in the man page, or",
87 "by running `lightcards --help`.",
89 "Press [H], or [?] to go back.",
96 curses.color_pair(1) + curses.A_BOLD,
98 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
100 for t in enumerate(text):
101 self.win.addstr(t[0] + 3, 1, t[1])
106 """Display help screen"""
107 (mlines, mcols) = self.outer.win.getmaxyx()
108 self.win.mvwin(int(mlines / 2) - 11, int(mcols / 2) - 25)
112 key = self.win.getkey()
115 elif key in ["H", "?"]:
121 def __init__(self, outer, mlines=17, mcols=44):
122 """Initialize the menu with content"""
124 (self.win, self.panel) = panel_create(mlines, mcols)
132 curses.color_pair(1) + curses.A_BOLD,
134 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
136 "[y]: reset stack to original state",
137 "[a]: alphabetize stack",
138 "[z]: shuffle stack",
139 "[t]: reverse stack order",
142 "[s]: update stack to include starred only",
143 "[e]: open the input file in $EDITOR",
149 for t in enumerate(text):
150 self.win.addstr(t[0] + 3, 1, t[1])
154 def menu_print(self, string, err=False):
155 """Print messages on the menu screen"""
157 color = curses.color_pair(2)
159 color = curses.color_pair(1)
161 self.win.addstr(15, 1, string, color)
165 """Grab keypresses on the menu screen"""
167 key = self.win.getkey()
168 if key in ["r", "m"]:
174 self.outer.stack = runner.get_orig()[1]
175 self.menu_print("Stack reset!")
177 self.outer.stack.sort(key=lambda x: x.front)
178 self.menu_print("Stack alphabetized!")
180 [x.unStar() for x in self.outer.stack]
181 self.menu_print("All unstarred!")
183 [x.star() for x in self.outer.stack]
184 self.menu_print("All starred!")
186 self.outer.stack.reverse()
187 self.menu_print("Stack reversed!")
189 shuffle(self.outer.stack)
190 self.menu_print("Stack shuffled!")
193 os.system(f"$EDITOR {self.outer.input_file}"),
194 (self.outer.headers, self.outer.stack) = parse.parse_html(
195 parse.md2html(self.outer.input_file)
199 # Check if there are any starred cards before proceeding, and
200 # if not, don't allow to proceed and show an error message
202 for x in self.outer.stack:
209 x for x in self.outer.stack if x.starred
211 self.menu_print("Stars only!")
213 self.menu_print("ERR: None are starred!", err=True)
215 self.outer.obj.index = 0
220 Display a menu offering multiple options on how to manipulate the deck
224 self.win.addch(14, i + 1, " ")
226 (mlines, mcols) = self.outer.win.getmaxyx()
227 self.win.mvwin(int(mlines / 2) - 8, int(mcols / 2) - 22)
234 def __init__(self, stack, headers, obj, view, input_file):
236 self.headers = headers
239 self.input_file = input_file
241 def run(self, stdscr):
242 """Set important options that require stdscr before starting"""
244 curses.curs_set(0) # Hide cursor
245 curses.use_default_colors() # Allow transparency
246 curses.init_pair(1, curses.COLOR_CYAN, -1)
247 curses.init_pair(2, curses.COLOR_RED, -1)
248 curses.init_pair(3, curses.COLOR_YELLOW, -1)
250 self.main_panel = curses.panel.new_panel(self.win)
251 self.menu_obj = Menu(self)
252 self.help_obj = Help(self)
253 self.quit_obj = Quit(self)
257 def check_size(self):
258 (mlines, mcols) = self.win.getmaxyx()
260 while mlines < 24 or mcols < 60:
266 "Terminal too small! Min size 60x24", width=mcols
270 (mlines, mcols) = self.win.getmaxyx()
276 """Pickle stack and confirm before quitting"""
278 if self.obj.index + 1 == len(self.stack):
281 progress.dump(self.stack, runner.get_orig()[1])
285 """Get total number of starred cards"""
286 return [card for card in self.stack if card.starred]
290 Display the statusbar at the bottom of the screen with progress, star
291 status, and card side.
293 (mlines, mcols) = self.win.getmaxyx()
294 self.win.hline(mlines - 3, 0, 0, mcols)
296 # Calculate percent done
297 if len(self.stack) <= 1:
301 round(self.obj.index / (len(self.stack) - 1) * 100)
304 # Print yellow if starred
305 if self.current_card().starred:
306 star_color = curses.color_pair(3)
308 star_color = curses.color_pair(1)
312 bar_middle = self.current_card().printStar()
313 bar_end = f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
316 f" [{self.get_side()} ("
317 f"{str(int(self.current_card().side) + 1)})]"
319 bar_end += f" [View {str(self.view)}]"
321 # Put it all togethor
323 self.win.addstr(height, 0, bar_start, curses.color_pair(1))
324 self.win.addstr(height, len(bar_start), bar_middle, star_color)
327 len(bar_start + bar_middle),
328 textwrap.shorten(bar_end, width=mcols - 20, placeholder="…"),
329 curses.color_pair(1),
334 f"{str(self.obj.index + 1).zfill(len(str(len(self.stack))))}"
335 f"/{str(len(self.stack))})] "
342 curses.color_pair(1),
348 / (len(self.stack) - 1)
349 * (mcols - len(progress))
353 # TODO: Use the variying width unicode block characters to make a
356 height + 1, i + len(progress), "»", curses.color_pair(1)
359 def wrap_width(self):
360 """Calculate the width at which the body text should wrap"""
361 (_, mcols) = self.win.getmaxyx()
362 wrap_width = mcols - 20
368 if self.obj.side == 0:
369 return self.headers[self.current_card().side]
371 return self.headers[self.current_card().get_reverse()]
374 (_, mcols) = self.win.getmaxyx()
375 self.main_panel.bottom()
377 num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
379 if self.view in [1, 2, 4]:
381 Display the contents of the card.
382 Shows a header, a horizontal line, and the contents of the current
385 # If on the back of the card, show the content of the front side in
392 if self.current_card().side == 0:
393 top = num_done + " | " + self.get_side()
400 + str(self.current_card().get()[self.obj.get_reverse()])
407 textwrap.shorten(top, width=mcols - 20, placeholder="…"),
416 self.current_card().get()[self.obj.side],
417 width=self.wrap_width(),
423 Display the contents of the card with both the front and back sides.
425 (_, mcols) = self.win.getmaxyx()
426 self.main_panel.bottom()
445 self.headers[0] + ": " + self.current_card().front,
446 width=self.wrap_width(),
450 self.headers[1] + ": " + self.current_card().back,
451 width=self.wrap_width(),
455 self.win.hline(1, 0, curses.ACS_HLINE, mcols)
459 def current_card(self):
460 """Get current card object"""
461 return self.stack[self.obj.index]
465 Display a card and wait for the input.
466 Used as a general way of getting back into the card flow from a menu
470 key = self.win.getkey()
473 elif key in ["h", "KEY_LEFT"]:
475 self.current_card().side = 0
477 elif key in ["l", "KEY_RIGHT"]:
478 if self.obj.index + 1 == len(self.stack):
481 self.obj.forward(self.stack)
482 self.current_card().side = 0
484 elif key in ["j", "k", "KEY_UP", "KEY_DOWN"] and self.view != 3:
485 self.current_card().flip()
487 elif key in ["i", "/"]:
488 self.current_card().toggleStar()
490 elif key in ["0", "^", "KEY_HOME"]:
492 self.current_card().side = 0
494 elif key in ["$", "KEY_END"]:
495 self.obj.index = len(self.stack) - 1
496 self.current_card().side = 0
498 elif key in ["H", "?"]:
502 elif key in ["1", "2", "3", "4"]:
505 def disp_sidebar(self):
506 """Display a sidebar with the starred terms"""
507 (mlines, mcols) = self.win.getmaxyx()
514 curses.color_pair(3) + curses.A_BOLD,
516 self.win.vline(0, mcols - 20, 0, mlines - 3)
518 nstarred = self.nstarred()
519 for i, card in enumerate(nstarred):
520 term = card.get()[self.obj.side]
522 term = term[:18] + "…"
526 self.win.addch(mlines - 3, left + i, " ")
531 f"({len(nstarred) - i - 2} more)",
534 self.win.addstr(2 + i, left, term)
536 if len(self.nstarred()) == 0:
537 self.win.addstr(2, left, "None starred")