Skip to content

Instantly share code, notes, and snippets.

@alangarf
Created September 15, 2014 00:23
Show Gist options
  • Save alangarf/3aa7bb470af6bf20547c to your computer and use it in GitHub Desktop.
Save alangarf/3aa7bb470af6bf20547c to your computer and use it in GitHub Desktop.
Curses Widgits
import curses
class WidgitWrapper(object):
"""
A widgit wrapper class to handle the framing of the widgit
"""
def __init__(self, win, y, x, height, width):
self.parent_win = win
self.y_pos = y
self.x_pos = x
self.height = height+2
self.width = width
if self.height > self.parent_win.getmaxyx()[0]:
raise Exception("Cannot fit screen into terminal")
if (self.height+self.y_pos) > self.parent_win.getmaxyx()[0]:
self.parent_win.clear()
self.y_pos = 1
self.win = self.parent_win.subwin(
self.height, self.width, self.y_pos, self.x_pos)
(self.max_y, self.max_x) = self.win.getmaxyx()
self.win.box()
self.parent_win.refresh()
def getx(self):
return self.max_x+self.x_pos
def gety(self):
return self.max_y+self.y_pos
def error_overlay(self, win, text):
pass
class Textbox(object):
"""
Editing widget using the interior of a window object.
Supports the following Emacs-like key bindings:
Ctrl-A Go to left edge of window.
Ctrl-B Cursor left, wrapping to previous line if appropriate.
Ctrl-D Delete character under cursor.
Ctrl-E Got to end of line (stripspaces on).
Ctrl-F Cursor right, wrapping to next line when appropriate.
Ctrl-G Terminate, returning the window contents.
Ctrl-H Delete character backward.
Ctrl-J Terminate if the window is 1 line, otherwise insert newline.
Ctrl-K If line is blank, delete it, otherwise clear to end of line.
Ctrl-L Refresh screen.
Ctrl-N Cursor down; move down one line.
Ctrl-O Insert a blank line at cursor location.
Ctrl-P Cursor up; move up one line.
Move operations do nothing if the cursor is at an edge where the movement
is not possible. The following synonyms are supported where possible:
KEY_LEFT = Ctrl-B, KEY_RIGHT = Ctrl-F, KEY_UP = Ctrl-P, KEY_DOWN = Ctrl-N
KEY_BACKSPACE = Ctrl-h
"""
def __init__(self, win):
self.win = win
(self.maxy, self.maxx) = win.getmaxyx()
self.maxy = self.maxy - 1
self.maxx = self.maxx - 1
self.stripspaces = 1
self.lastcmd = None
win.keypad(1)
def _end_of_line(self, y):
last = self.maxx
while True:
if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP:
last = min(self.maxx, last+1)
break
elif last == 0:
break
last = last - 1
return last
def _insert_printable_char(self, ch):
(y, x) = self.win.getyx()
if y < self.maxy or x < self.maxx:
# The try-catch ignores the error we trigger from some curses
# versions by trying to write into the lowest-rightmost spot
# in the window.
try:
self.win.addch(ch)
except curses.error:
pass
def do_command(self, ch):
(y, x) = self.win.getyx()
self.lastcmd = ch
if curses.ascii.isprint(ch):
if y < self.maxy or x < self.maxx:
self._insert_printable_char(ch)
elif ch == curses.ascii.SOH: # ^a
self.win.move(y, 0)
elif ch in (curses.ascii.STX, curses.KEY_LEFT,
curses.ascii.BS, curses.ascii.DEL):
if x > 0:
self.win.move(y, x-1)
elif y == 0:
pass
elif self.stripspaces:
self.win.move(y-1, self._end_of_line(y-1))
else:
self.win.move(y-1, self.maxx)
if ch in (curses.ascii.BS, curses.ascii.DEL):
self.win.delch()
elif ch == curses.ascii.EOT: # ^d
self.win.delch()
elif ch == curses.ascii.ENQ: # ^e
if self.stripspaces:
self.win.move(y, self._end_of_line(y))
else:
self.win.move(y, self.maxx)
elif ch in (curses.ascii.ACK, curses.KEY_RIGHT): # ^f
if x < self.maxx:
self.win.move(y, x+1)
elif y == self.maxy:
pass
else:
self.win.move(y+1, 0)
elif ch == curses.ascii.BEL: # ^g
return False
elif ch == curses.ascii.NL: # ^j
if self.maxy == 0:
return False
elif y < self.maxy:
self.win.move(y+1, 0)
elif ch == curses.ascii.VT: # ^k
if x == 0 and self._end_of_line(y) == 0:
self.win.deleteln()
else:
# first undo the effect of self._end_of_line
self.win.move(y, x)
self.win.clrtoeol()
elif ch == curses.ascii.FF: # ^l
self.win.refresh()
elif ch in (curses.ascii.SO, curses.KEY_DOWN): # ^n
if y < self.maxy:
self.win.move(y+1, x)
if x > self._end_of_line(y+1):
self.win.move(y+1, self._end_of_line(y+1))
elif ch == curses.ascii.SI: # ^o
self.win.insertln()
elif ch in (curses.ascii.DLE, curses.KEY_UP): # ^p
if y > 0:
self.win.move(y-1, x)
if x > self._end_of_line(y-1):
self.win.move(y-1, self._end_of_line(y-1))
return True
def gather(self):
"Collect and return the contents of the window."
result = ""
for y in range(self.maxy+1):
self.win.move(y, 0)
stop = self._end_of_line(y)
if stop == 0 and self.stripspaces:
continue
for x in range(self.maxx+1):
if self.stripspaces and x > stop:
break
result = result + chr(curses.ascii.ascii(self.win.inch(y, x)))
if self.maxy > 0:
result = result + "\n"
return result
def edit(self, validate=None):
while True:
ch = self.win.getch()
if validate:
ch = validate(ch)
if not ch:
continue
if not self.do_command(ch):
break
self.win.refresh()
return self.gather()
def clear(self):
self.win.clear()
class Promptbox(WidgitWrapper):
"""
A curses Prompt widget
"""
def __init__(self, win, y, x, width=78, height=1, prompt=""):
super(Promptbox, self).__init__(win, y, x, height, width)
self.prompt = prompt
self.win.addstr(1, self.x_pos+1, self.prompt, curses.color_pair(1))
tw = self.win.subwin(1,
self.width-len(self.prompt)-5,
self.y_pos+1,
self.x_pos+len(self.prompt)+3)
self.txtbox = Textbox(tw)
self.win.refresh()
def edit(self, empty_ok=False, validate=None):
def validate_func(ch):
# pass through control characters
if not curses.ascii.isprint(ch):
return ch
# validate using named function
return ch if validate(ch) else None
v = validate_func if validate else None
while True:
result = self.txtbox.edit(v).strip()
if not empty_ok:
if not result:
self.error_overlay(
self.txtbox.win, "You must enter something!")
continue
return result
def error_overlay(self, win, text):
import math
# setup error window
err_win = win.derwin(0, 0)
err_win.bkgd(' ', curses.color_pair(3))
(maxy, maxx) = err_win.getmaxyx()
x_offset = int(math.floor(float(maxx / 2) - float(len(text) / 2)))
err_win.addstr(0, x_offset, text)
# Show error message for a second or till keypress
err_win.overlay(self.win)
err_win.timeout(1500)
err_win.getch()
err_win.bkgd(' ', curses.A_NORMAL)
err_win.clear()
del err_win
win.touchwin()
win.refresh()
class Selectbox(WidgitWrapper):
"""
A curses Select Box widgit
"""
def __init__(self, win, y, x, field_width, items, width=78,
top_prompt="", bottom_prompt=""):
super(Selectbox, self).__init__(win, y, x, len(items)+4, width)
self.field_width = field_width
self.items = items
self.top_prompt = top_prompt
self.bottom_prompt = bottom_prompt
self.win.addstr(1, 2, self.top_prompt, curses.color_pair(2))
for key, item in enumerate(self.items):
self.win.addstr(key+3, 3, "[{}] - {}".format(key+1, item))
self.win.addstr(self.max_y-2, self.x_pos+1,
self.bottom_prompt, curses.color_pair(1))
tw = self.win.subwin(1,
self.field_width,
self.y_pos+self.max_y-2,
self.x_pos+len(self.bottom_prompt)+3)
self.txtbox = Textbox(tw)
self.win.refresh()
def edit(self):
def validate_func(ch):
if not curses.ascii.isprint(ch):
return ch # pass ctrl chars
return ch if curses.ascii.isdigit(ch) else None
while True:
result = self.txtbox.edit(validate_func).strip()
if not result:
self.error_overlay(self.win, "You must enter something!")
continue
try:
result = int(result)-1
if result < 1:
raise ValueError()
return self.items[result]
except (ValueError, IndexError):
self.txtbox.clear()
self.error_overlay(
self.win,
"You must enter a number between 1 and {}".format(
len(self.items)))
continue
def error_overlay(self, win, text):
import math
len_prompt = len(self.bottom_prompt)
# setup error window
err_win = win.derwin(
1, self.max_x-len_prompt-5,
self.max_y-2, len_prompt+3)
err_win.bkgd(' ', curses.color_pair(3))
(maxy, maxx) = err_win.getmaxyx()
x_offset = int(math.floor(float(maxx / 2) - float(len(text) / 2)))
err_win.addstr(0, x_offset, text)
# Show error message for a second or till keypress
err_win.overlay(self.win)
err_win.timeout(1500)
err_win.getch()
err_win.bkgd(' ', curses.A_NORMAL)
err_win.clear()
self.win.touchwin()
self.win.refresh()
del err_win
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment