def setup():
"""
sets environment up and creates main window
:returns: the main window object
"""
# setup the console
mmask = curses.ALL_MOUSE_EVENTS # for now accept all mouse events
main = curses.initscr() # get a window object
y,x = main.getmaxyx() # get size
if y < 24 or x < 80: # verify minimum size rqmts
raise RuntimeError("Terminal must be at least 80 x 24")
curses.noecho() # turn off key echoing
curses.cbreak() # turn off key buffering
curses.mousemask(mmask) # accept mouse events
initcolors() # turn on and set color pallet
main.keypad(1) # let curses handle multibyte special keys
main.clear() # erase everything
banner(main) # write the banner
mainmenu(main) # then the min and menu
main.attron(CPS[RED]) # make the border red
main.border(0) # place the border
main.attroff(CPS[RED]) # turn off the red
curses.curs_set(0) # hide the cursor
main.refresh() # and show everything
return main
python类curs_set()的实例源码
def refresh(self):
prior, (cursr_y, cursr_x) = curses.curs_set(0), curses.getsyx()
for idx, item in enumerate(self.items):
fmt = '{{: <{}}}'.format(self.width-1)
s = fmt.format(str(item))[:self.width-1]
# s = str(item)[:self.width-1] if len(str(item)) > self.width-1 else str(item)
color = colors.get_colorpair(self.default_color)
if self.current == idx:
if self.is_selected:
color = colors.get_colorpair('black-white')
else:
color = colors.get_colorpair(self.highlight_color)
self.textinpt.addstr(idx, 0, s, color)
if self.is_selected:
self.borderbox.bkgd(' ', curses.A_BOLD)
else:
self.borderbox.bkgd(' ', curses.A_DIM)
self.borderbox.border()
self.borderbox.refresh()
self.textinpt.refresh()
curses.curs_set(prior)
curses.setsyx(cursr_y, cursr_x)
curses.doupdate()
def __init__(self, stdscreen):
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_WHITE)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
global screen
screen = stdscreen
self.screen = stdscreen
curses.curs_set(0)
main_menu_items = get_records()
main_menu_items += [{'field': 'Insert new station information record', 'function': selection_main_menu}]
main_menu = Menu(cnn, main_menu_items, self.screen, 'Station information new/edit/delete - %s.%s' % (stn['NetworkCode'], stn['StationCode']))
main_menu.display()
def __init__(self, ui):
self.ui = ui
self.scr = ui.stdscr
self.player = ui.player
self.colors = ui.colors
self.height, self.width = self.scr.getmaxyx()
self.header_height = 2
self.footer_height = 2
self.viewheight = self.height - self.header_height - self.footer_height
self.current = None
self.previous = []
self.item = 0
self.current_item = None
self._search_mode = False
curses.curs_set(0)
self.scr.timeout(17)
def edit(self, validate=None):
"""Edit in the widget window and collect the results."""
# Make the cursor visible and update the screen
curses.curs_set(1)
self.win.refresh()
while 1:
ch = self.win.getch()
if validate:
ch = validate(ch)
if not ch:
continue
if not self.do_command(ch):
break
self.win.refresh()
# Hide the cursor
curses.curs_set(0)
return self.gather()
def enter(self):
self.history_point = 0
curses.curs_set(1)
curses.setsyx(2, 2)
curses.doupdate()
self.inp.erase()
self.canceled = False
res = self.text.edit(self._handle_key).strip()
curses.curs_set(0)
if self.canceled:
self.inp.erase()
self.inp.refresh()
return ''
elif (not(self.search_history) or self.search_history[-1] != res):
self.search_history.append(res)
return res
def _start_ui(self, stdscr):
"""TODO docs"""
rogue_height = 26
rogue_width = 84
# using a pad instead of the default win, it's safer
self.stdscr = curses.newpad(rogue_height, rogue_width)
self.stdscr.nodelay(True)
curses.curs_set(False)
self.draw_from_rogue()
minlogsize = 4
if curses.LINES - 1 >= rogue_height + minlogsize:
# there's enough space to show the logs
self.logpad = curses.newpad(curses.LINES - 1, curses.COLS - 1)
while True:
if self.timer_callback:
self.timer_callback()
time.sleep(self.sleep_time)
if self.keypress_callback:
try:
key = self.stdscr.getkey()
event = Event()
event.char = key
self.keypress_callback(event)
except curses.error:
pass
def display(self, title, content):
curses.curs_set(0)
self.infowin.clear()
y, x = self.infowin.getmaxyx()
self.infowin.bkgd(" ", curses.color_pair(6))
self.infowin.box()
self.infowin.addstr(0, 0, title + " - 'q' to close", curses.A_UNDERLINE | curses.A_BOLD)
for count, line in enumerate(content.split('\n'), start=1):
try:
self.infowin.addstr(count, 1, line)
except:
pass
self.infopanel.show()
curses.panel.update_panels()
curses.doupdate()
while self.infowin.getch() != ord('q'):
pass
curses.curs_set(1)
def focus(self):
modeline.update_activeWindow("Map")
curses.curs_set(0)
while True:
event = self.mapwin.getch()
# if event == -1:
# continue
logging.info(event)
try_handle_global_event(event)
if event == curses.KEY_UP:
self.pan("up")
if event == curses.KEY_DOWN:
self.pan("down")
if event == curses.KEY_LEFT:
self.pan("left")
if event == curses.KEY_RIGHT:
self.pan("right")
if event == curses.KEY_NPAGE:
self.zoom_out(5)
if event == curses.KEY_PPAGE:
self.zoom_in(5)
def getinstr(self,prompt):
self.scr.nodelay(0)
self.scr.addstr(self.y+2,self.x+1,' '*(self.w-2),curses.color_pair(TOPSTATUS))
self.scr.addstr(self.y+2,self.x+1,prompt,curses.color_pair(TOPSTATUS))
self.scr.refresh()
curses.curs_set(1)
curses.echo()
self.scr.attron(curses.color_pair(TOPSTATUS))
retval = self.scr.getstr(self.y+2,self.x+len(prompt)+1,8)
self.scr.addstr(self.y+2,self.x+len(prompt)+1,str(retval),curses.color_pair(TOPSTATUS))
self.scr.attroff(curses.color_pair(TOPSTATUS))
self.scr.refresh()
curses.noecho()
curses.curs_set(0)
self.scr.nodelay(1)
return retval
def __init__(self, curses, curses_window):
curses.start_color()
curses.curs_set(0)
curses_window.nodelay(1)
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(6, curses.COLOR_BLUE, curses.COLOR_BLACK)
self._curses = curses
self._curses_window = curses_window
self._stack = list()
def countdown(stdscr, end_time, font, fg_color, bg_color, msg=None):
stdscr.clear()
curses.curs_set(False)
curses.init_pair(1, fg_color, bg_color)
now = datetime.datetime.now()
timefmt = '%I:%M %p' if now.day == end_time.day else '%I:%M %p, %d %b'
stdscr.addstr(0, 0, 'Alarm set for: ' + end_time.strftime(timefmt))
stdscr.refresh()
win = None
while now < end_time:
time_left = str(end_time - now).split('.')[0]
win = center(stdscr, time_left, font, curses.color_pair(1), win)
sleep(1)
now = datetime.datetime.now()
alert(stdscr, args, win)
def __init__(self):
self.stdscr = curses.initscr()
# don't display keys
curses.noecho()
# don't need key + enter
curses.cbreak()
# remove cursor
curses.curs_set(0)
self.stdscr.keypad(1)
#stdscr.border(0)
self.height, self.width = self.stdscr.getmaxyx()
self.header = self.stdscr.subwin(3, self.width, 0, 0)
self.header.box()
self.main_win = self.stdscr.subwin(20, self.width-2, 3, 1)
self.main_win.scrollok(True)
self.setup_colours()
# self.main()
def init():
height_term, width_term = get_terminal_size()
height_min = COL_HEIGHT * HEIGHT + 2 + 9
width_min = COL_WIDTH * WIDTH + 2 + 5
if height_term < height_min or width_term < width_min:
# resize the terminal to fit the minimum size to display the connect4 before exit
stdout.write("\x1b[8;{h};{w}t".format(h=max(height_min, height_term), w=max(width_min, width_term)))
exit('\033[91m' + 'The terminal was too small, you can now restart ' + '\033[1m' + 'Connect4' + '\033[0m')
stdscr = curses.initscr()
height,width = stdscr.getmaxyx()
if height < height_min or width < width_min:
# abort the program if the terminal can't be resized
curses.endwin()
exit('Please resize your terminal [%d%s%d] (minimum required %d%s%d)' %(width, 'x', height, width_min, 'x', height_min))
curses.noecho()
curses.cbreak()
curses.curs_set(0)
stdscr.keypad(1)
#define the different colors
if curses.can_change_color():
defineColors()
#return stdscr, width
stdscr.clear()
stdscr.border(0)
return stdscr, width, height
def refresh(self, drawList, cursor):
"""Repaint stacked windows, furthest to nearest in the main thread."""
# Ask curses to hold the back buffer until curses refresh().
cursesWindow = app.window.mainCursesWindow
cursesWindow.noutrefresh()
curses.curs_set(0)
#drawList, cursor = app.render.frame.grabFrame()
for i in drawList:
try:
cursesWindow.addstr(*i)
except:
#app.log.error('failed to draw', repr(i))
pass
if cursor is not None:
curses.curs_set(1)
try:
cursesWindow.leaveok(0) # Do update cursor position.
cursesWindow.move(cursor[0], cursor[1])
# Calling refresh will draw the cursor.
cursesWindow.refresh()
cursesWindow.leaveok(1) # Don't update cursor position.
except:
pass
def processmenu(screen, menu, parent=None, status_bottom = 'Uninitialized...'):
curses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.curs_set(0)
status_mid = ''
optioncount = len(menu['options'])
exitmenu = False
# response = None
while not exitmenu: #Loop until the user exits the menu
getin = runmenu(screen, menu, parent, status_mid, status_bottom)
if getin == optioncount:
exitmenu = True
elif menu['options'][getin]['type'] == COMMAND:
screen.clear() #clears previous screen
status_mid, status_bottom = processrequest(menu['options'][getin], screen) # Add additional space
## Show the updated status
screen.clear() #clears previous screen on key press and updates display based on pos
elif menu['options'][getin]['type'] == MENU:
screen.clear() #clears previous screen on key press and updates display based on pos
processmenu(screen, menu['options'][getin], menu, status_bottom) # display the submenu, and make sure the status is persistent
screen.clear() #clears previous screen on key press and updates display based on pos
elif menu['options'][getin]['type'] == EXITMENU:
exitmenu = True
def goodbye(self, msg=''):
"""
Exit gpymusic.
Arguements:
msg='': Message to display prior to exiting.
"""
if not self.curses:
if not self.test:
print(msg)
sys.exit()
self.addstr(self.outbar, msg)
common.mc.logout()
try:
common.client.mm.logout()
except:
pass
sleep(2)
crs.curs_set(1)
crs.endwin()
sys.exit()
def get_input(self):
"""
Get user input in the bottom bar.
Returns: The user-inputted string.
"""
if not self.curses:
return input('Enter some input: ')
self.addstr(self.inbar, '> ')
crs.curs_set(2) # Show the cursor.
try:
string = self.inbar.getstr()
except KeyboardInterrupt:
common.np.close()
self.goodbye('Goodbye, thanks for using Google Py Music!')
self.inbar.deleteln()
crs.curs_set(0) # Hide the cursor.
return string.decode('utf-8')
def login(user):
"""
Log into Google Play Music. Succeeds or exits.
Arguments:
user: Dict containing auth information.
"""
crs.curs_set(0)
common.w.outbar_msg('Logging in...')
try:
if not common.mc.login(user['email'], user['password'], user['deviceid']):
common.w.goodbye('Login failed: Exiting.')
common.w.outbar_msg(
'Logging in... Logged in as %s (%s).' %
(user['email'], 'Full' if common.mc.is_subscribed else 'Free')
)
except KeyboardInterrupt:
common.w.goodbye()
def _create_desktop(self):
global _s_screen
_s_screen = curses.initscr()
curses.noecho()
curses.curs_set(0)
curses.start_color()
self._desktop = Form(None, 0, 0)
self._stats = Form(self._desktop, 0, 0, 70, 20)
self._stats.set_centering(True, True)
self._title = Label(self._stats, 0, 0, 'S2E')
self._title.set_centering(True, False)
self._exitmsg = Label(self._stats, 0, 17, 'Press q to exit')
self._exitmsg.set_centering(True, False)
self._table = Table(self._stats, 2, 2, self._data, self._legend,
self._layout)
self._table.set_centering(True, True)
def processmenu(menu, parent = None):
optioncount = len(menu['options'])
exitmenu = False
while not exitmenu:
getin = runmenu(menu, parent)
if getin == optioncount:
exitmenu = True
elif menu['options'][getin]['type'] == COMMAND:
curses.def_prog_mode()
os.system('reset')
screen.clear()
os.system(menu['options'][getin]['command'])
screen.clear()
curses.reset_prog_mode()
curses.curs_set(1)
curses.curs_set(0)
elif menu['options'][getin]['type'] == MENU:
screen.clear()
processmenu(menu['options'][getin], menu)
screen.clear()
elif menu['options'][getin]['type'] == EXITMENU:
exitmenu = True
def getstr(window, empty_ok=False):
curses.curs_set(1)
curses.echo()
window.clear()
window.move(0, 0)
if empty_ok:
response = window.getstr()
else:
response = b''
while response == b'':
response = window.getstr()
window.clear()
window.refresh()
window.move(0, 0)
curses.curs_set(0)
return response
def select(self):
'''
Not only selects this textbox, but turns on the cursor and moves it to
the correct possition within this textbox.
'''
self.borderbox.bkgd(' ', curses.A_BOLD)
self.textinpt.bkgd(' ', colors.get_colorpair(self.default_color))
curses.curs_set(1)
self.textinpt.move(0, self.keypos)
self.refresh()
def deselect(self):
'''
Deselects this Textbox and turns off cursor visiblity.
'''
self.borderbox.bkgd(' ', curses.A_NORMAL)
self.textinpt.bkgd(' ', colors.get_colorpair(self.default_color))
curses.curs_set(0)
self.refresh()
def redraw_bomb(stdscr, refresh_lock):
global UPDATE_BOMBSPRITE
idx = 0
while True:
time.sleep(0.25)
if UPDATE_BOMBSPRITE:
refresh_lock.acquire()
curses.curs_set(0)
idx = drawbomb(stdscr, idx)
refresh_lock.release()
else:
break
def leave(self):
'''Leave curses mode.'''
curses.nocbreak()
curses.echo()
self.window.keypad(False)
try:
curses.curs_set(self.old_cursor)
except:
pass
curses.endwin()
def __init__(self, scr, title="", inittext="", win_location=(0, 0),
win_size=(20, 80), box=True, max_paragraphs=0, pw_mode=False,
edit=True):
# Fix for python curses resize bug:
# http://bugs.python.org/issue2675
os.unsetenv('LINES')
os.unsetenv('COLUMNS')
self.scr = scr
self.title_orig = title
if sys.version_info.major < 3:
enc = locale.getpreferredencoding() or 'utf-8'
self.title_orig = str(self.title_orig, encoding=enc)
inittext = str(inittext, encoding=enc)
self.box = box
self.max_paragraphs = max_paragraphs
self.pw_mode = pw_mode
self.edit = edit
self.win_location_orig_y, self.win_location_orig_x = win_location
self.win_size_orig_y, self.win_size_orig_x = win_size
self.win_size_y = self.win_size_orig_y
self.win_size_x = self.win_size_orig_x
self.win_location_y = self.win_location_orig_y
self.win_location_x = self.win_location_orig_x
self.win_init()
self.box_init()
self.text_init(inittext)
if self.edit is False:
self.keys_init_noedit()
try:
curses.curs_set(0)
except _curses.error:
pass
else:
self.keys_init()
curses.curs_set(1)
self.display()
def __init__(self, this_plant, this_data):
'''Initialization'''
self.initialized = False
self.screen = curses.initscr()
curses.noecho()
curses.raw()
curses.start_color()
try:
curses.curs_set(0)
except curses.error:
# Not all terminals support this functionality.
# When the error is ignored the screen will look a little uglier, but that's not terrible
# So in order to keep botany as accesible as possible to everyone, it should be safe to ignore the error.
pass
self.screen.keypad(1)
self.plant = this_plant
self.user_data = this_data
self.plant_string = self.plant.parse_plant()
self.plant_ticks = str(self.plant.ticks)
self.exit = False
self.infotoggle = 0
self.maxy, self.maxx = self.screen.getmaxyx()
# Highlighted and Normal line definitions
self.define_colors()
self.highlighted = curses.color_pair(1)
self.normal = curses.A_NORMAL
# Threaded screen update for live changes
screen_thread = threading.Thread(target=self.update_plant_live, args=())
screen_thread.daemon = True
screen_thread.start()
self.screen.clear()
self.show(["water","look","garden","instructions"], title=' botany ', subtitle='options')
def __exit__(self):
self.exit = True
curses.curs_set(2)
curses.endwin()
os.system('clear')
def enter_edit_mode(self, value=None):
if self.items[self.position]['field'] == 'Comments':
editwin = curses.newwin(10, 60, self.position+2, 27)
rectangle(self.window, self.position + 1, 26, self.position + 12, 26 + 61)
else:
editwin = curses.newwin(1, 30, self.position+2, 27)
editwin.attron(curses.color_pair(2))
curses.curs_set(1)
if value:
box = _Textbox(editwin, True, text=value)
else:
box = _Textbox(editwin, True, text=self.items[self.position]['value'])
_Textbox.stripspaces = True
self.window.refresh()
while True:
edit_field = box.edit()
if not edit_field is None:
result = self.validate(edit_field.strip())
if result:
self.navigate(1)
break
else:
break
curses.curs_set(0)
self.window.clear()