]> git.armaanb.net Git - lightcards.git/blob - lightcards/display.py
Fix side output in bar and header
[lightcards.git] / lightcards / display.py
1 # Display card output and retreive input
2 # Armaan Bhojwani 2021
3
4 import curses
5 import curses.panel
6 from random import shuffle
7 import sys
8 import textwrap
9 import time
10
11 from . import runner, progress
12
13
14 def panel_create(x, y):
15     """Create popup panels to a certain scale"""
16     win = curses.newwin(x, y)
17     panel = curses.panel.new_panel(win)
18     win.erase()
19     return (win, panel)
20
21
22 class CursesError(BaseException):
23     def __init__(self, message="lightcards: Curses error!"):
24         self.message = message
25         print(self.message)
26         sys.exit(3)
27
28
29 class Help:
30     def __init__(self, outer, mlines=21, mcols=52):
31         """Initialize help screen"""
32         self.outer = outer
33         (self.win, self.panel) = panel_create(mlines, mcols)
34         self.panel.top()
35         self.panel.hide()
36
37         text = [
38             "Welcome to runner. Here are some keybindings",
39             "to get you started:",
40             "",
41             "h, left          previous card",
42             "l, right         next card",
43             "j, k, up, down   flip card",
44             "i, /             star card",
45             "0, ^, home       go to the start of the deck",
46             "$, end           go to the end of the deck",
47             "H, ?             open this screen",
48             "e                open the input file in $EDITOR",
49             "m                open the control menu",
50             "1, 2, 3          switch views",
51             "",
52             "More information can be found in the man page, or",
53             "by running `lightcards --help`.",
54             "",
55             "Press [H], or [?] to go back.",
56         ]
57
58         self.win.addstr(
59             1,
60             int(mcols / 2) - 8,
61             "LIGHTCARDS HELP",
62             curses.color_pair(1) + curses.A_BOLD,
63         )
64         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
65
66         for t in enumerate(text):
67             self.win.addstr(t[0] + 3, 1, t[1])
68
69         self.win.box()
70
71     def disp(self):
72         """Display help screen"""
73         (mlines, mcols) = self.outer.win.getmaxyx()
74         self.win.mvwin(int(mlines / 2) - 10, int(mcols / 2) - 25)
75         self.panel.show()
76
77         while True:
78             key = self.win.getkey()
79             if key == "q":
80                 self.outer.leave()
81             elif key in ["H", "?"]:
82                 self.panel.hide()
83                 self.outer.get_key()
84
85
86 class Menu:
87     def __init__(self, outer, mlines=16, mcols=44):
88         """Initialize the menu with content"""
89         self.outer = outer
90         (self.win, self.panel) = panel_create(mlines, mcols)
91         self.panel.top()
92         self.panel.hide()
93
94         self.win.addstr(
95             1,
96             int(mcols / 2) - 8,
97             "LIGHTCARDS MENU",
98             curses.color_pair(1) + curses.A_BOLD,
99         )
100         self.win.hline(2, 1, curses.ACS_HLINE, mcols)
101         text = [
102             "[y]: reset stack to original state",
103             "[a]: alphabetize stack",
104             "[z]: shuffle stack",
105             "[t]: reverse stack order",
106             "[u]: unstar all",
107             "[d]: star all",
108             "[s]: update stack to include starred only",
109             "",
110             "[r]: restart",
111             "[m]: close menu",
112         ]
113
114         for t in enumerate(text):
115             self.win.addstr(t[0] + 3, 1, t[1])
116
117         self.win.box()
118
119     def menu_print(self, string, err=False):
120         """Print messages on the menu screen"""
121         if err:
122             color = curses.color_pair(2)
123         else:
124             color = curses.color_pair(1)
125
126         self.win.addstr(14, 1, string, color)
127         self.menu_grab()
128
129     def menu_grab(self):
130         """Grab keypresses on the menu screen"""
131         while True:
132             key = self.win.getkey()
133             if key in ["r", "m"]:
134                 self.panel.hide()
135                 self.outer.get_key()
136             elif key == "q":
137                 self.outer.leave()
138             elif key == "y":
139                 self.outer.stack = runner.get_orig()[1]
140                 self.menu_print("Stack reset!")
141             elif key == "a":
142                 self.outer.stack.sort(key=lambda x: x.front)
143                 self.menu_print("Stack alphabetized!")
144             elif key == "u":
145                 [x.unStar() for x in self.outer.stack]
146                 self.menu_print("All unstarred!")
147             elif key == "d":
148                 [x.star() for x in self.outer.stack]
149                 self.menu_print("All starred!")
150             elif key == "t":
151                 self.outer.stack.reverse()
152                 self.menu_print("Stack reversed!")
153             elif key == "z":
154                 shuffle(self.outer.stack)
155                 self.menu_print("Stack shuffled!")
156             elif key == "s":
157                 # Check if there are any starred cards before proceeding, and
158                 # if not, don't allow to proceed and show an error message
159                 cont = False
160                 for x in self.outer.stack:
161                     if x.starred:
162                         cont = True
163                         break
164
165                 if cont:
166                     self.outer.stack = [
167                         x for x in self.outer.stack if x.starred
168                     ]
169                     self.menu_print("Stars only!")
170                 else:
171                     self.menu_print("ERR: None are starred!", err=True)
172             elif key == "r":
173                 self.outer.obj.index = 0
174                 self.outer.get_key()
175
176     def disp(self):
177         """
178         Display a menu offering multiple options on how to manipulate the deck
179         and to continue
180         """
181         for i in range(42):
182             self.win.addch(14, i + 1, " ")
183
184         (mlines, mcols) = self.outer.win.getmaxyx()
185         self.win.mvwin(int(mlines / 2) - 8, int(mcols / 2) - 22)
186         self.panel.show()
187
188         self.menu_grab()
189
190
191 class Display:
192     def __init__(self, stack, headers, obj, view):
193         self.stack = stack
194         self.headers = headers
195         self.obj = obj
196         self.view = view
197
198     def run(self, stdscr):
199         """Set important options that require stdscr before starting"""
200         self.win = stdscr
201         curses.curs_set(0)  # Hide cursor
202         curses.use_default_colors()  # Allow transparency
203         curses.init_pair(1, curses.COLOR_CYAN, -1)
204         curses.init_pair(2, curses.COLOR_RED, -1)
205         curses.init_pair(3, curses.COLOR_YELLOW, -1)
206
207         self.main_panel = curses.panel.new_panel(self.win)
208         self.menu_obj = Menu(self)
209         self.help_obj = Help(self)
210
211         self.get_key()
212
213     def check_size(self):
214         (mlines, mcols) = self.win.getmaxyx()
215
216         while mlines < 24 or mcols < 60:
217             self.win.clear()
218             self.win.addstr(
219                 0,
220                 0,
221                 textwrap.fill(
222                     "Terminal too small! Min size 60x24", width=mcols
223                 ),
224             )
225             self.win.refresh()
226             (mlines, mcols) = self.win.getmaxyx()
227             time.sleep(0.1)
228         else:
229             self.disp_card()
230
231     def leave(self):
232         """Pickle stack before quitting"""
233         if self.obj.index + 1 == len(self.stack):
234             self.obj.index = 0
235
236         progress.dump(self.stack, runner.get_orig()[1])
237         sys.exit(0)
238
239     def nstarred(self):
240         """Get total number of starred cards"""
241         return [card for card in self.stack if card.starred]
242
243     def disp_bar(self):
244         """
245         Display the statusbar at the bottom of the screen with progress, star
246         status, and card side.
247         """
248         (mlines, mcols) = self.win.getmaxyx()
249         self.win.hline(mlines - 2, 0, 0, mcols)
250
251         # Calculate percent done
252         if len(self.stack) <= 1:
253             percent = "100"
254         else:
255             percent = str(
256                 round(self.obj.index / (len(self.stack) - 1) * 100)
257             ).zfill(2)
258
259         # Print yellow if starred
260         if self.current_card().starred:
261             star_color = curses.color_pair(3)
262         else:
263             star_color = curses.color_pair(1)
264
265         # Compose bar text
266         bar_start = "["
267         bar_middle = self.current_card().printStar()
268         bar_end = (
269             f"] [{len(self.nstarred())}/{str(len(self.stack))} starred] "
270             f"[{percent}% ("
271             f"{str(self.obj.index).zfill(len(str(len(self.stack))))}"
272             f"/{str(len(self.stack))})]"
273         )
274         if self.view != 3:
275             bar_end += (
276                 f" [{self.get_side()} ("
277                 f"{str(int(self.current_card().side) + 1)})]"
278             )
279         bar_end += f" [View {str(self.view)}]"
280
281         # Put it all togethor
282         self.win.addstr(mlines - 1, 0, bar_start, curses.color_pair(1))
283         self.win.addstr(mlines - 1, len(bar_start), bar_middle, star_color)
284         self.win.addstr(
285             mlines - 1,
286             len(bar_start + bar_middle),
287             textwrap.shorten(bar_end, width=mcols - 20, placeholder="…"),
288             curses.color_pair(1),
289         )
290
291     def wrap_width(self):
292         """Calculate the width at which the body text should wrap"""
293         (_, mcols) = self.win.getmaxyx()
294         wrap_width = mcols - 20
295         if wrap_width > 80:
296             wrap_width = 80
297         return wrap_width
298
299     def get_side(self):
300         if self.obj.side == 0:
301             return self.headers[self.current_card().side]
302         else:
303             return self.headers[self.current_card().get_reverse()]
304
305     def disp_card(self):
306         (_, mcols) = self.win.getmaxyx()
307         self.main_panel.bottom()
308         self.win.clear()
309         num_done = str(self.obj.index + 1).zfill(len(str(len(self.stack))))
310
311         if self.view in [1, 2]:
312             """
313             Display the contents of the card.
314             Shows a header, a horizontal line, and the contents of the current
315             side.
316             """
317             # If on the back of the card, show the content of the front side in
318             # the header
319             if self.view == 1:
320                 self.obj.side = 0
321             elif self.view == 2:
322                 self.obj.side = 1
323
324             if self.current_card().side == 0:
325                 top = num_done + " | " + self.get_side()
326             else:
327                 top = (
328                     num_done
329                     + " | "
330                     + self.get_side()
331                     + ' | "'
332                     + str(self.current_card().get()[self.obj.get_reverse()])
333                     + '"'
334                 )
335
336             self.win.addstr(
337                 0,
338                 0,
339                 textwrap.shorten(top, width=mcols - 20, placeholder="…"),
340                 curses.A_BOLD,
341             )
342
343             # Show current side
344             self.win.addstr(
345                 2,
346                 0,
347                 textwrap.fill(
348                     self.current_card().get()[self.obj.side],
349                     width=self.wrap_width(),
350                 ),
351             )
352
353         elif self.view == 3:
354             """
355             Display the contents of the card with both the front and back sides.
356             """
357             (_, mcols) = self.win.getmaxyx()
358             self.main_panel.bottom()
359             self.win.clear()
360
361             self.win.addstr(
362                 0,
363                 0,
364                 textwrap.shorten(
365                     num_done,
366                     width=mcols - 20,
367                     placeholder="…",
368                 ),
369                 curses.A_BOLD,
370             )
371
372             # Show card content
373             self.win.addstr(
374                 2,
375                 0,
376                 textwrap.fill(
377                     self.headers[0] + ": " + self.current_card().front,
378                     width=self.wrap_width(),
379                 )
380                 + "\n\n"
381                 + textwrap.fill(
382                     self.headers[1] + ": " + self.current_card().back,
383                     width=self.wrap_width(),
384                 ),
385             )
386
387         self.win.hline(1, 0, curses.ACS_HLINE, mcols)
388         self.disp_bar()
389         self.disp_sidebar()
390
391     def current_card(self):
392         """Get current card object"""
393         return self.stack[self.obj.index]
394
395     def get_key(self):
396         """
397         Display a card and wait for the input.
398         Used as a general way of getting back into the card flow from a menu
399         """
400         while True:
401             self.check_size()
402             key = self.win.getkey()
403             if key == "q":
404                 self.leave()
405             elif key in ["h", "KEY_LEFT"]:
406                 self.obj.back()
407                 self.current_card().side = 0
408                 self.disp_card()
409             elif key in ["l", "KEY_RIGHT"]:
410                 if self.obj.index + 1 == len(self.stack):
411                     self.menu_obj.disp()
412                 else:
413                     self.obj.forward(self.stack)
414                     self.current_card().side = 0
415                     self.disp_card()
416             elif key in ["j", "k", "KEY_UP", "KEY_DOWN"] and self.view != 3:
417                 self.current_card().flip()
418                 self.disp_card()
419             elif key in ["i", "/"]:
420                 self.current_card().toggleStar()
421                 self.disp_card()
422             elif key in ["0", "^", "KEY_HOME"]:
423                 self.obj.index = 0
424                 self.current_card().side = 0
425                 self.disp_card()
426             elif key in ["$", "KEY_END"]:
427                 self.obj.index = len(self.stack) - 1
428                 self.current_card().side = 0
429                 self.disp_card()
430             elif key in ["H", "?"]:
431                 self.help_obj.disp()
432             elif key == "m":
433                 self.menu_obj.disp()
434             elif key == "e":
435                 (self.headers, self.stack) = runner.reparse()
436                 self.get_key()
437             elif key in ["1", "2", "3"]:
438                 self.view = int(key)
439
440     def disp_sidebar(self):
441         """Display a sidebar with the starred terms"""
442         (mlines, mcols) = self.win.getmaxyx()
443         left = mcols - 19
444
445         self.win.addstr(
446             0,
447             mcols - 16,
448             "STARRED CARDS",
449             curses.color_pair(3) + curses.A_BOLD,
450         )
451         self.win.vline(0, mcols - 20, 0, mlines - 2)
452
453         nstarred = self.nstarred()
454         for i, card in enumerate(nstarred):
455             term = card.get()[self.obj.side]
456             if len(term) > 18:
457                 term = term[:18] + "…"
458
459             if i > mlines - 5:
460                 for i in range(19):
461                     self.win.addch(mlines - 3, left + i, " ")
462
463                 self.win.addstr(
464                     mlines - 3,
465                     left,
466                     f"({len(nstarred) - i - 2} more)",
467                 )
468             else:
469                 self.win.addstr(2 + i, left, term)
470
471         if len(self.nstarred()) == 0:
472             self.win.addstr(2, left, "None starred")