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)
53 if self.outer.config["confirm_quit"]:
55 key = self.win.getkey()
64 def __init__(self, outer, mlines=23, mcols=52):
65 """Initialize help screen"""
67 (self.win, self.panel) = panel_create(mlines, mcols)
72 return str(list(self.outer.config[setting][:28])).replace("'", "")
75 "Welcome to Lightcards. Here are some keybindings",
76 "to get you started:",
78 f"{c('card_prev')}: previous card",
79 f"{c('card_next')}: next card",
80 f"{c('card_flip')}: flip card",
81 f"{c('card_star')}: star card",
82 f"{c('card_first')}: go to first card",
83 f"{c('card_last')}: go to last card",
84 f"{c('help_disp')}: open this help menu",
85 f"{c('menu_disp')}: open the control menu",
86 f"{c('view_one')}: switch to view one",
87 f"{c('view_two')}: switch to view two",
88 f"{c('view_three')}: switch to view three",
89 f"{c('quit_key')}: quit",
91 "More information can be found in the man page, or",
92 "by running `lightcards --help`.",
94 f"Press {c('help_disp')} to go back.",
101 curses.color_pair(1) + curses.A_BOLD,
103 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
105 for t in enumerate(text):
106 self.win.addstr(t[0] + 3, 1, t[1])
111 """Display help screen"""
112 (mlines, mcols) = self.outer.win.getmaxyx()
113 self.win.mvwin(int(mlines / 2) - 12, int(mcols / 2) - 25)
117 key = self.win.getkey()
120 elif key in ["H", "?"]:
126 def __init__(self, outer, mlines=17, mcols=44):
127 """Initialize the menu with content"""
129 (self.win, self.panel) = panel_create(mlines, mcols)
137 curses.color_pair(1) + curses.A_BOLD,
139 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
140 env = os.environ.get("EDITOR", "$EDITOR")[:15]
142 "[y]: reset stack to original state",
143 "[a]: alphabetize stack",
144 "[z]: shuffle stack",
145 "[t]: reverse stack order",
148 "[s]: update stack to include starred only",
149 f"[e]: open the input file in {env}" "",
154 for t in enumerate(text):
155 self.win.addstr(t[0] + 3, 1, t[1])
161 self.win.addch(15, i + 1, " ")
163 def menu_print(self, string, err=False):
164 """Print messages on the menu screen"""
166 color = curses.color_pair(2)
168 color = curses.color_pair(1)
170 self.win.addstr(15, 1, string, color)
174 """Grab keypresses on the menu screen"""
176 key = self.win.getkey()
177 if key in ["r", "m"]:
183 self.outer.stack = runner.get_orig()[1]
184 self.menu_print("Stack reset!")
186 self.outer.stack.sort(key=lambda x: x.front)
187 self.menu_print("Stack alphabetized!")
189 [x.unStar() for x in self.outer.stack]
190 self.menu_print("All unstarred!")
192 [x.star() for x in self.outer.stack]
193 self.menu_print("All starred!")
195 self.outer.stack.reverse()
196 self.menu_print("Stack reversed!")
198 shuffle(self.outer.stack)
199 self.menu_print("Stack shuffled!")
201 progress.dump(self.outer.stack, runner.get_orig()[1])
203 os.system(f"$EDITOR {self.outer.input_file}"),
204 (self.outer.headers, self.outer.stack) = parse.parse_html(
205 parse.md2html(self.outer.input_file)
209 # Check if there are any starred cards before proceeding, and
210 # if not, don't allow to proceed and show an error message
212 for x in self.outer.stack:
219 x for x in self.outer.stack if x.starred
221 self.menu_print("Stars only!")
223 self.menu_print("ERR: None are starred!", err=True)
225 self.outer.obj.index = 0
230 Display a menu offering multiple options on how to manipulate the deck
235 (mlines, mcols) = self.outer.win.getmaxyx()
236 self.win.mvwin(int(mlines / 2) - 8, int(mcols / 2) - 22)
243 def __init__(self, stack, headers, obj, view, args, conf):
245 self.headers = headers
248 self.input_file = args.inp[0]
251 def run(self, stdscr):
252 """Set important options that require stdscr before starting"""
254 curses.curs_set(0) # Hide cursor
255 curses.use_default_colors() # Allow transparency
256 curses.init_pair(1, self.config["highlight_color"], -1)
257 curses.init_pair(2, self.config["error_color"], -1)
258 curses.init_pair(3, self.config["starred_color"], -1)
260 self.main_panel = curses.panel.new_panel(self.win)
261 self.menu_obj = Menu(self)
262 self.help_obj = Help(self)
263 self.quit_obj = Quit(self)
267 def check_size(self):
268 (mlines, mcols) = self.win.getmaxyx()
270 while mlines < 24 or mcols < 60:
276 "Terminal too small! Min size 60x24", width=mcols
280 (mlines, mcols) = self.win.getmaxyx()
286 """Pickle stack and confirm before quitting"""
288 if self.obj.index + 1 == len(self.stack):
291 progress.dump(self.stack, runner.get_orig()[1])
295 """Get total number of starred cards"""
296 return [card for card in self.stack if card.starred]
300 Display the statusbar at the bottom of the screen with progress, star
301 status, and card side.
303 (mlines, mcols) = self.win.getmaxyx()
304 self.win.hline(mlines - 3, 0, 0, mcols)
306 # Calculate percent done
307 if len(self.stack) <= 1:
311 round(self.obj.index / (len(self.stack) - 1) * 100)
314 # Print yellow if starred
315 if self.current_card().starred:
316 star_color = curses.color_pair(3)
318 star_color = curses.color_pair(1)
322 bar_middle = self.current_card().printStar()
323 bar_end = f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
326 f" [{self.get_side()} ("
327 f"{str(int(self.current_card().side) + 1)})]"
329 bar_end += f" [View {str(self.view)}]"
331 # Put it all togethor
333 self.win.addstr(height, 0, bar_start, curses.color_pair(1))
334 self.win.addstr(height, len(bar_start), bar_middle, star_color)
337 len(bar_start + bar_middle),
338 textwrap.shorten(bar_end, width=mcols - 20, placeholder="…"),
339 curses.color_pair(1),
344 f"{str(self.obj.index + 1).zfill(len(str(len(self.stack))))}"
345 f"/{str(len(self.stack))})] "
352 curses.color_pair(1),
358 / (len(self.stack) - 1)
359 * (mcols - len(progress))
366 self.config["progress_char"],
367 curses.color_pair(1),
370 def wrap_width(self):
371 """Calculate the width at which the body text should wrap"""
372 (_, mcols) = self.win.getmaxyx()
373 wrap_width = mcols - 20
379 if self.obj.side == 0:
380 return self.headers[self.current_card().side]
382 return self.headers[self.current_card().get_reverse()]
385 (_, mcols) = self.win.getmaxyx()
386 self.main_panel.bottom()
388 num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
390 if self.view in [1, 2, 4]:
392 Display the contents of the card.
393 Shows a header, a horizontal line, and the contents of the current
396 # If on the back of the card, show the content of the front side in
403 if self.current_card().side == 0:
404 top = num_done + " | " + self.get_side()
411 + str(self.current_card().get()[self.obj.get_reverse()])
418 textwrap.shorten(top, width=mcols - 20, placeholder="…"),
427 self.current_card().get()[self.obj.side],
428 width=self.wrap_width(),
434 Display the contents of the card with both the front and back sides.
436 (_, mcols) = self.win.getmaxyx()
437 self.main_panel.bottom()
456 self.headers[0] + ": " + self.current_card().front,
457 width=self.wrap_width(),
461 self.headers[1] + ": " + self.current_card().back,
462 width=self.wrap_width(),
466 self.win.hline(1, 0, curses.ACS_HLINE, mcols)
470 def current_card(self):
471 """Get current card object"""
472 return self.stack[self.obj.index]
476 Display a card and wait for the input.
477 Used as a general way of getting back into the card flow from a menu
481 key = self.win.getkey()
482 if key == self.config["quit_key"]:
484 elif key in self.config["card_prev"]:
486 self.current_card().side = 0
488 elif key in self.config["card_next"]:
489 if self.obj.index + 1 == len(self.stack):
490 if self.config["show_menu_at_end"]:
493 self.obj.forward(self.stack)
494 self.current_card().side = 0
496 elif key in self.config["card_flip"] and self.view != 3:
497 self.current_card().flip()
499 elif key in self.config["card_star"]:
500 self.current_card().toggleStar()
502 elif key in self.config["card_first"]:
504 self.current_card().side = 0
506 elif key in self.config["card_last"]:
507 self.obj.index = len(self.stack) - 1
508 self.current_card().side = 0
510 elif key in self.config["help_disp"]:
512 elif key in self.config["menu_disp"]:
514 elif key in self.config["view_one"]:
516 elif key in self.config["view_two"]:
518 elif key in self.config["view_three"]:
521 def disp_sidebar(self):
522 """Display a sidebar with the starred terms"""
523 (mlines, mcols) = self.win.getmaxyx()
530 curses.color_pair(3) + curses.A_BOLD,
532 self.win.vline(0, mcols - 20, 0, mlines - 3)
534 nstarred = self.nstarred()
535 for i, card in enumerate(nstarred):
536 term = card.get()[self.obj.side]
538 term = term[:18] + "…"
542 self.win.addch(mlines - 3, left + i, " ")
547 f"({len(nstarred) - i - 2} more)",
550 self.win.addstr(2 + i, left, term)
552 if len(self.nstarred()) == 0:
553 self.win.addstr(2, left, "None starred")