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=20, 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",
85 "More information can be found in the man page, or",
86 "by running `lightcards --help`.",
88 "Press [H], or [?] to go back.",
95 curses.color_pair(1) + curses.A_BOLD,
97 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
99 for t in enumerate(text):
100 self.win.addstr(t[0] + 3, 1, t[1])
105 """Display help screen"""
106 (mlines, mcols) = self.outer.win.getmaxyx()
107 self.win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 25)
111 key = self.win.getkey()
114 elif key in ["H", "?"]:
120 def __init__(self, outer, mlines=17, mcols=44):
121 """Initialize the menu with content"""
123 (self.win, self.panel) = panel_create(mlines, mcols)
131 curses.color_pair(1) + curses.A_BOLD,
133 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
135 "[y]: reset stack to original state",
136 "[a]: alphabetize stack",
137 "[z]: shuffle stack",
138 "[t]: reverse stack order",
141 "[s]: update stack to include starred only",
142 "[e]: open the input file in $EDITOR",
148 for t in enumerate(text):
149 self.win.addstr(t[0] + 3, 1, t[1])
153 def menu_print(self, string, err=False):
154 """Print messages on the menu screen"""
156 color = curses.color_pair(2)
158 color = curses.color_pair(1)
160 self.win.addstr(15, 1, string, color)
164 """Grab keypresses on the menu screen"""
166 key = self.win.getkey()
167 if key in ["r", "m"]:
173 self.outer.stack = runner.get_orig()[1]
174 self.menu_print("Stack reset!")
176 self.outer.stack.sort(key=lambda x: x.front)
177 self.menu_print("Stack alphabetized!")
179 [x.unStar() for x in self.outer.stack]
180 self.menu_print("All unstarred!")
182 [x.star() for x in self.outer.stack]
183 self.menu_print("All starred!")
185 self.outer.stack.reverse()
186 self.menu_print("Stack reversed!")
188 shuffle(self.outer.stack)
189 self.menu_print("Stack shuffled!")
192 os.system(f"$EDITOR {self.outer.input_file}"),
193 (self.outer.headers, self.outer.stack) = parse.parse_html(
194 parse.md2html(self.outer.input_file)
198 # Check if there are any starred cards before proceeding, and
199 # if not, don't allow to proceed and show an error message
201 for x in self.outer.stack:
208 x for x in self.outer.stack if x.starred
210 self.menu_print("Stars only!")
212 self.menu_print("ERR: None are starred!", err=True)
214 self.outer.obj.index = 0
219 Display a menu offering multiple options on how to manipulate the deck
223 self.win.addch(14, i + 1, " ")
225 (mlines, mcols) = self.outer.win.getmaxyx()
226 self.win.mvwin(int(mlines / 2) - 8, int(mcols / 2) - 22)
233 def __init__(self, stack, headers, obj, view, input_file):
235 self.headers = headers
238 self.input_file = input_file
240 def run(self, stdscr):
241 """Set important options that require stdscr before starting"""
243 curses.curs_set(0) # Hide cursor
244 curses.use_default_colors() # Allow transparency
245 curses.init_pair(1, curses.COLOR_CYAN, -1)
246 curses.init_pair(2, curses.COLOR_RED, -1)
247 curses.init_pair(3, curses.COLOR_YELLOW, -1)
249 self.main_panel = curses.panel.new_panel(self.win)
250 self.menu_obj = Menu(self)
251 self.help_obj = Help(self)
252 self.quit_obj = Quit(self)
256 def check_size(self):
257 (mlines, mcols) = self.win.getmaxyx()
259 while mlines < 24 or mcols < 60:
265 "Terminal too small! Min size 60x24", width=mcols
269 (mlines, mcols) = self.win.getmaxyx()
275 """Pickle stack and confirm before quitting"""
277 if self.obj.index + 1 == len(self.stack):
280 progress.dump(self.stack, runner.get_orig()[1])
284 """Get total number of starred cards"""
285 return [card for card in self.stack if card.starred]
289 Display the statusbar at the bottom of the screen with progress, star
290 status, and card side.
292 (mlines, mcols) = self.win.getmaxyx()
293 self.win.hline(mlines - 3, 0, 0, mcols)
295 # Calculate percent done
296 if len(self.stack) <= 1:
300 round(self.obj.index / (len(self.stack) - 1) * 100)
303 # Print yellow if starred
304 if self.current_card().starred:
305 star_color = curses.color_pair(3)
307 star_color = curses.color_pair(1)
311 f"{str(self.obj.index).zfill(len(str(len(self.stack))))})]"
316 bar_middle = self.current_card().printStar()
317 bar_end = f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
320 f" [{self.get_side()} ("
321 f"{str(int(self.current_card().side) + 1)})]"
323 bar_end += f" [View {str(self.view)}]"
325 # Put it all togethor
327 self.win.addstr(height, 0, bar_start, curses.color_pair(1))
328 self.win.addstr(height, len(bar_start), bar_middle, star_color)
331 len(bar_start + bar_middle),
332 textwrap.shorten(bar_end, width=mcols - 20, placeholder="…"),
333 curses.color_pair(1),
338 mcols - len(progress) - 1,
340 curses.color_pair(1),
346 / (len(self.stack) - 1)
347 * (mcols - len(progress))
351 # TODO: Use the variying width unicode block characters to make a
353 self.win.addch(height + 1, i, "»", curses.color_pair(1))
355 def wrap_width(self):
356 """Calculate the width at which the body text should wrap"""
357 (_, mcols) = self.win.getmaxyx()
358 wrap_width = mcols - 20
364 if self.obj.side == 0:
365 return self.headers[self.current_card().side]
367 return self.headers[self.current_card().get_reverse()]
370 (_, mcols) = self.win.getmaxyx()
371 self.main_panel.bottom()
373 num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
375 if self.view in [1, 2, 4]:
377 Display the contents of the card.
378 Shows a header, a horizontal line, and the contents of the current
381 # If on the back of the card, show the content of the front side in
388 if self.current_card().side == 0:
389 top = num_done + " | " + self.get_side()
396 + str(self.current_card().get()[self.obj.get_reverse()])
403 textwrap.shorten(top, width=mcols - 20, placeholder="…"),
412 self.current_card().get()[self.obj.side],
413 width=self.wrap_width(),
419 Display the contents of the card with both the front and back sides.
421 (_, mcols) = self.win.getmaxyx()
422 self.main_panel.bottom()
441 self.headers[0] + ": " + self.current_card().front,
442 width=self.wrap_width(),
446 self.headers[1] + ": " + self.current_card().back,
447 width=self.wrap_width(),
451 self.win.hline(1, 0, curses.ACS_HLINE, mcols)
455 def current_card(self):
456 """Get current card object"""
457 return self.stack[self.obj.index]
461 Display a card and wait for the input.
462 Used as a general way of getting back into the card flow from a menu
466 key = self.win.getkey()
469 elif key in ["h", "KEY_LEFT"]:
471 self.current_card().side = 0
473 elif key in ["l", "KEY_RIGHT"]:
474 if self.obj.index + 1 == len(self.stack):
477 self.obj.forward(self.stack)
478 self.current_card().side = 0
480 elif key in ["j", "k", "KEY_UP", "KEY_DOWN"] and self.view != 3:
481 self.current_card().flip()
483 elif key in ["i", "/"]:
484 self.current_card().toggleStar()
486 elif key in ["0", "^", "KEY_HOME"]:
488 self.current_card().side = 0
490 elif key in ["$", "KEY_END"]:
491 self.obj.index = len(self.stack) - 1
492 self.current_card().side = 0
494 elif key in ["H", "?"]:
498 elif key in ["1", "2", "3", "4"]:
501 def disp_sidebar(self):
502 """Display a sidebar with the starred terms"""
503 (mlines, mcols) = self.win.getmaxyx()
510 curses.color_pair(3) + curses.A_BOLD,
512 self.win.vline(0, mcols - 20, 0, mlines - 3)
514 nstarred = self.nstarred()
515 for i, card in enumerate(nstarred):
516 term = card.get()[self.obj.side]
518 term = term[:18] + "…"
522 self.win.addch(mlines - 3, left + i, " ")
527 f"({len(nstarred) - i - 2} more)",
530 self.win.addstr(2 + i, left, term)
532 if len(self.nstarred()) == 0:
533 self.win.addstr(2, left, "None starred")