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["quit_confirmation"]:
55 key = self.win.getkey()
64 def __init__(self, outer, mlines, mcols):
66 (self.win, self.panel) = panel_create(mlines, mcols)
70 def config_get(self, setting, cut=28):
71 return str(list(self.outer.config[setting][:cut])).replace("'", "")
75 def __init__(self, outer, mlines=23, mcols=52):
76 """Initialize help screen"""
77 super().__init__(outer, mlines, mcols)
81 "Welcome to Lightcards. Here are some keybindings",
82 "to get you started:",
84 f"{c('card_prev')}: previous card",
85 f"{c('card_next')}: next card",
86 f"{c('card_flip')}: flip card",
87 f"{c('card_star')}: star card",
88 f"{c('card_first')}: go to first card",
89 f"{c('card_last')}: go to last card",
90 f"{c('help_disp')}: open this help menu",
91 f"{c('menu_disp')}: open the control menu",
92 f"{c('view_one')}: switch to view one",
93 f"{c('view_two')}: switch to view two",
94 f"{c('view_three')}: switch to view three",
95 f"{c('quit_key')}: quit",
97 "More information can be found in the man page, or",
98 "by running `lightcards --help`.",
100 f"Press {c('help_disp')} to go back.",
107 curses.color_pair(1) + curses.A_BOLD,
109 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
111 for i, content in enumerate(text, 3):
112 self.win.addstr(i, 1, content)
117 """Display help screen"""
118 (mlines, mcols) = self.outer.win.getmaxyx()
119 self.win.mvwin(int(mlines / 2) - 12, int(mcols / 2) - 25)
123 key = self.win.getkey()
124 if key in self.outer.config["quit_key"]:
126 elif key in self.outer.config["help_disp"]:
132 def __init__(self, outer, mlines=17, mcols=44):
133 """Initialize the menu with content"""
134 super().__init__(outer, mlines, mcols)
141 curses.color_pair(1) + curses.A_BOLD,
143 self.win.hline(2, 1, curses.ACS_HLINE, mcols)
144 env = os.environ.get("EDITOR", "$EDITOR")[:15]
146 f"{c('menu_reset')}: reset stack to original state",
147 f"{c('menu_alphabetize')}: alphabetize stack",
148 f"{c('menu_shuffle')}: shuffle stack",
149 f"{c('menu_reverse')}: reverse stack order",
150 f"{c('menu_unstar')}: unstar all",
151 f"{c('menu_star')}: star all",
152 f"{c('menu_stars_only')}: update stack to include starred only",
153 f"{c('menu_open_file')}: open the input file in {env}",
155 f"{c('menu_restart')}: restart",
156 f"{c('menu_disp')}: close menu",
159 for i, content in enumerate(text, 3):
160 self.win.addstr(i, 1, content)
166 self.win.addch(15, i + 1, " ")
168 def menu_print(self, string, err=False):
169 """Print messages on the menu screen"""
171 color = curses.color_pair(2)
173 color = curses.color_pair(1)
175 self.win.addstr(15, 1, string, color)
179 """Grab keypresses on the menu screen"""
181 key = self.win.getkey()
184 in self.outer.config["menu_disp"]
185 + self.outer.config["menu_restart"]
189 elif key in self.outer.config["quit_key"]:
191 elif key in self.outer.config["menu_reset"]:
192 self.outer.stack = runner.get_orig()[1]
193 self.menu_print("Stack reset!")
194 elif key in self.outer.config["menu_alphabetize"]:
195 self.outer.stack.sort(key=lambda x: x.front)
196 self.menu_print("Stack alphabetized!")
197 elif key in self.outer.config["menu_unstar"]:
198 [x.unStar() for x in self.outer.stack]
199 self.menu_print("All unstarred!")
200 elif key in self.outer.config["menu_star"]:
201 [x.star() for x in self.outer.stack]
202 self.menu_print("All starred!")
203 elif key in self.outer.config["menu_reverse"]:
204 self.outer.stack.reverse()
205 self.menu_print("Stack reversed!")
206 elif key in self.outer.config["menu_shuffle"]:
207 shuffle(self.outer.stack)
208 self.menu_print("Stack shuffled!")
209 elif key in self.outer.config["menu_open_file"]:
211 os.system(f"$EDITOR {self.outer.input_file}"),
212 (self.outer.headers, self.outer.stack) = parse.parse_html(
213 parse.md2html(self.outer.input_file),
218 elif key in self.outer.config["menu_stars_only"]:
219 # Check if there are any starred cards before proceeding, and
220 # if not, don't allow to proceed and show an error message
222 for x in self.outer.stack:
229 x for x in self.outer.stack if x.starred
231 self.menu_print("Stars only!")
233 self.menu_print("ERR: None are starred!", err=True)
234 elif key in self.outer.config["menu_restart"]:
235 self.outer.obj.index = 0
240 Display a menu offering multiple options on how to manipulate the deck
245 (mlines, mcols) = self.outer.win.getmaxyx()
246 self.win.mvwin(int(mlines / 2) - 8, int(mcols / 2) - 22)
253 def __init__(self, stack, headers, obj, view, args, conf):
255 self.headers = headers
258 self.input_file = args.inp
262 def run(self, stdscr):
263 """Set important options that require stdscr before starting"""
265 curses.curs_set(0) # Hide cursor
266 curses.use_default_colors() # Allow transparency
267 curses.init_pair(1, self.config["highlight_color"], -1)
268 curses.init_pair(2, self.config["error_color"], -1)
269 curses.init_pair(3, self.config["starred_color"], -1)
271 self.main_panel = curses.panel.new_panel(self.win)
272 self.menu_obj = Menu(self)
273 self.help_obj = Help(self)
274 self.quit_obj = Quit(self)
278 def check_size(self):
279 (mlines, mcols) = self.win.getmaxyx()
281 while mlines < 24 or mcols < 60:
287 "Terminal too small! Min size 60x24", width=mcols
291 (mlines, mcols) = self.win.getmaxyx()
297 if self.config["cache"]:
298 progress.dump(self.stack, runner.get_orig()[1])
301 """Pickle stack and confirm before quitting"""
303 if self.obj.index + 1 == len(self.stack):
310 """Get total number of starred cards"""
311 return [card for card in self.stack if card.starred]
314 (mlines, mcols) = self.win.getmaxyx()
316 # Calculate percent done
317 if len(self.stack) <= 1:
321 round(self.obj.index / (len(self.stack) - 1) * 100)
324 # Print yellow if starred
325 if self.current_card().starred:
326 self.star_color = curses.color_pair(3)
328 self.star_color = curses.color_pair(1)
332 self.bar_middle = self.current_card().printStar()
334 f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
338 f" [{self.get_side()} ("
339 f"{str(int(self.current_card().side) + 1)})]"
341 self.bar_end += f" [View {str(self.view)}]"
345 f"{str(self.obj.index + 1).zfill(len(str(len(self.stack))))}"
346 f"/{str(len(self.stack))})] "
351 Display the statusbar at the bottom of the screen with progress, star
352 status, and card side.
354 # Put it all togethor
355 (mlines, mcols) = self.win.getmaxyx()
357 self.win.addstr(height, 0, self.bar_start, curses.color_pair(1))
359 height, len(self.bar_start), self.bar_middle, self.star_color
363 len(self.bar_start + self.bar_middle),
364 textwrap.shorten(self.bar_end, width=mcols - 20, placeholder="…"),
365 curses.color_pair(1),
372 curses.color_pair(1),
378 / (len(self.stack) - 1)
379 * (mcols - len(self.progress))
385 i + len(self.progress),
386 self.config["progress_char"],
387 curses.color_pair(1),
390 self.win.hline(mlines - 3, 0, 0, mcols)
392 def wrap_width(self):
393 """Calculate the width at which the body text should wrap"""
394 (_, mcols) = self.win.getmaxyx()
395 wrap_width = mcols - 20
401 if self.obj.side == 0:
402 return self.headers[self.current_card().side]
404 return self.headers[self.current_card().get_reverse()]
407 (_, mcols) = self.win.getmaxyx()
408 self.main_panel.bottom()
410 num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
412 if self.view in [1, 2, 4]:
414 Display the contents of the card.
415 Shows a header, a horizontal line, and the contents of the current
418 # If on the back of the card, show the content of the front side in
425 if self.current_card().side == 0:
426 top = num_done + " | " + self.get_side()
433 + str(self.current_card().get()[self.obj.get_reverse()])
441 textwrap.shorten(top, width=mcols - 20, placeholder="…"),
450 self.current_card().get()[self.obj.side],
451 width=self.wrap_width(),
457 Display the contents of the card with both the front and back sides.
476 self.headers[0] + ": " + self.current_card().front,
477 width=self.wrap_width(),
481 self.headers[1] + ": " + self.current_card().back,
482 width=self.wrap_width(),
486 self.win.hline(1, 0, curses.ACS_HLINE, mcols)
490 def current_card(self):
491 """Get current card object"""
492 return self.stack[self.obj.index]
496 Display a card and wait for the input.
497 Used as a general way of getting back into the card flow from a menu
501 key = self.win.getkey()
502 if key in self.config["quit_key"]:
504 elif key in self.config["card_prev"]:
506 self.current_card().side = 0
508 elif key in self.config["card_next"]:
509 if self.obj.index + 1 == len(self.stack):
510 if self.config["show_menu_at_end"]:
513 self.obj.forward(self.stack)
514 self.current_card().side = 0
516 elif key in self.config["card_flip"] and self.view != 3:
517 self.current_card().flip()
519 elif key in self.config["card_star"]:
520 self.current_card().toggleStar()
522 elif key in self.config["card_first"]:
524 self.current_card().side = 0
526 elif key in self.config["card_last"]:
527 self.obj.index = len(self.stack) - 1
528 self.current_card().side = 0
530 elif key in self.config["help_disp"]:
532 elif key in self.config["menu_disp"]:
534 elif key in self.config["view_one"]:
536 elif key in self.config["view_two"]:
538 elif key in self.config["view_three"]:
541 def disp_sidebar(self):
542 """Display a sidebar with the starred terms"""
543 (mlines, mcols) = self.win.getmaxyx()
550 curses.color_pair(3) + curses.A_BOLD,
552 self.win.vline(0, mcols - 20, 0, mlines - 3)
554 nstarred = self.nstarred()
555 for i, card in enumerate(nstarred):
556 term = card.get(smart=False)[0]
558 term = term[:18] + "…"
562 self.win.addch(mlines - 4, left + i, " ")
567 f"({len(nstarred) - i - 2} more)",
570 self.win.addstr(2 + i, left, term)
572 if len(self.nstarred()) == 0:
573 self.win.addstr(2, left, "None starred")