⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 curses_display.py

📁 Urwid is a Python library for making text console applications. It has many features including fluid
💻 PY
📖 第 1 页 / 共 2 页
字号:
#!/usr/bin/python## Urwid curses output wrapper.. the horror..#    Copyright (C) 2004-2007  Ian Ward##    This library is free software; you can redistribute it and/or#    modify it under the terms of the GNU Lesser General Public#    License as published by the Free Software Foundation; either#    version 2.1 of the License, or (at your option) any later version.##    This library is distributed in the hope that it will be useful,#    but WITHOUT ANY WARRANTY; without even the implied warranty of#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU#    Lesser General Public License for more details.##    You should have received a copy of the GNU Lesser General Public#    License along with this library; if not, write to the Free Software#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA## Urwid web site: http://excess.org/urwid/"""Curses-based UI implementation"""from __future__ import nested_scopesimport cursesimport _cursesimport sysimport utilimport escapeKEY_RESIZE = 410 # curses.KEY_RESIZE (sometimes not defined)KEY_MOUSE = 409 # curses.KEY_MOUSE_curses_colours = {	'default':		(-1,			0),	'black':		(curses.COLOR_BLACK,	0),	'dark red':		(curses.COLOR_RED,	0),	'dark green':		(curses.COLOR_GREEN,	0),	'brown':		(curses.COLOR_YELLOW,	0),	'dark blue':		(curses.COLOR_BLUE,	0),	'dark magenta':		(curses.COLOR_MAGENTA,	0),	'dark cyan':		(curses.COLOR_CYAN,	0),	'light gray':		(curses.COLOR_WHITE,	0),	'dark gray':		(curses.COLOR_BLACK,    1),	'light red':		(curses.COLOR_RED,      1),	'light green':		(curses.COLOR_GREEN,    1),	'yellow':		(curses.COLOR_YELLOW,   1),	'light blue':		(curses.COLOR_BLUE,     1),	'light magenta':	(curses.COLOR_MAGENTA,  1),	'light cyan':		(curses.COLOR_CYAN,     1),	'white':		(curses.COLOR_WHITE,	1),}# replace control characters with ?'s_trans_table = "?"*32+"".join([chr(x) for x in range(32,256)])class Screen(object):	def __init__(self):		self.curses_pairs = [			(None,None), # Can't be sure what pair 0 will default to		]		self.palette = {}		self.has_color = False		self.s = None		self.cursor_state = None		self._keyqueue = []		self.prev_input_resize = 0		self.set_input_timeouts()		self.last_bstate = 0		self._started = False	def register_palette( self, l ):		"""Register a list of palette entries.		l -- list of (name, foreground, background, mono),		     (name, foreground, background) or		     (name, same_as_other_name) palette entries.		calls self.register_palette_entry for each item in l		"""				for item in l:			if len(item) in (3,4):				self.register_palette_entry( *item )				continue			assert len(item) == 2, "Invalid register_palette usage"			name, like_name = item			if not self.palette.has_key(like_name):				raise Exception("palette entry '%s' doesn't exist"%like_name)			self.palette[name] = self.palette[like_name]	def register_palette_entry( self, name, foreground, background,		mono=None):		"""Register a single palette entry.		name -- new entry/attribute name		foreground -- foreground colour, one of: 'black', 'dark red',			'dark green', 'brown', 'dark blue', 'dark magenta',			'dark cyan', 'light gray', 'dark gray', 'light red',			'light green', 'yellow', 'light blue', 'light magenta',			'light cyan', 'white', 'default' (black if unable to			use terminal's default)		background -- background colour, one of: 'black', 'dark red',			'dark green', 'brown', 'dark blue', 'dark magenta',			'dark cyan', 'light gray', 'default' (light gray if			unable to use terminal's default)		mono -- monochrome terminal attribute, one of: None (default),			'bold',	'underline', 'standout', or a tuple containing			a combination eg. ('bold','underline')					"""		assert not self._started		fg_a, fg_b = _curses_colours[foreground]		bg_a, bg_b = _curses_colours[background]		if bg_b: # can't do bold backgrounds			raise Exception("%s is not a supported background colour"%background )		assert (mono is None or 			mono in (None, 'bold', 'underline', 'standout') or			type(mono)==type(()))			for i in range(len(self.curses_pairs)):			pair = self.curses_pairs[i]			if pair == (fg_a, bg_a): break		else:			i = len(self.curses_pairs)			self.curses_pairs.append( (fg_a, bg_a) )				self.palette[name] = (i, fg_b, mono)				def set_mouse_tracking(self):		"""		Enable mouse tracking.  				After calling this function get_input will include mouse		click events along with keystrokes.		"""		rval = curses.mousemask( 0 			| curses.BUTTON1_PRESSED | curses.BUTTON1_RELEASED			| curses.BUTTON2_PRESSED | curses.BUTTON2_RELEASED			| curses.BUTTON3_PRESSED | curses.BUTTON3_RELEASED			| curses.BUTTON4_PRESSED | curses.BUTTON4_RELEASED			| curses.BUTTON_SHIFT | curses.BUTTON_ALT			| curses.BUTTON_CTRL )	def start(self):		"""		Initialize the screen and input mode.		"""		assert self._started == False		self.s = curses.initscr()		self._started = True		self.has_color = curses.has_colors()		if self.has_color:			curses.start_color()			if curses.COLORS < 8:				# not colourful enough				self.has_color = False		if self.has_color:			try:				curses.use_default_colors()				self.has_default_colors=True			except _curses.error:				self.has_default_colors=False		self._setup_colour_pairs()		curses.noecho()		curses.meta(1)		curses.halfdelay(10) # use set_input_timeouts to adjust		self.s.keypad(0)				def stop(self):		"""		Restore the screen.		"""		if self._started == False:			return		curses.echo()		self._curs_set(1)		try:			curses.endwin()		except _curses.error:			pass # don't block original error with curses error		self._started = False		def run_wrapper(self,fn):		"""Call fn in fullscreen mode.  Return to normal on exit.				This function should be called to wrap your main program loop.		Exception tracebacks will be displayed in normal mode.		"""			try:			self.start()			return fn()		finally:			self.stop()	def _setup_colour_pairs(self):			k = 1		if self.has_color:			if len(self.curses_pairs) > curses.COLOR_PAIRS:				raise Exception("Too many colour pairs!  Use fewer combinations.")					for fg,bg in self.curses_pairs[1:]:				if not self.has_default_colors and fg == -1:					fg = _curses_colours["black"][0]				if not self.has_default_colors and bg == -1:					bg = _curses_colours["light gray"][0]				curses.init_pair(k,fg,bg)				k+=1		else:			wh, bl = curses.COLOR_WHITE, curses.COLOR_BLACK				self.attrconv = {}		for name, (cp, a, mono) in self.palette.items():			if self.has_color:				self.attrconv[name] = curses.color_pair(cp)				if a: self.attrconv[name] |= curses.A_BOLD			elif type(mono)==type(()):				attr = 0				for m in mono:					attr |= self._curses_attr(m)				self.attrconv[name] = attr			else:				attr = self._curses_attr(mono)				self.attrconv[name] = attr		def _curses_attr(self, a):		if a == 'bold':			return curses.A_BOLD		elif a == 'standout':			return curses.A_STANDOUT		elif a == 'underline':			return curses.A_UNDERLINE		else:			return 0									def _curs_set(self,x):		if self.cursor_state== "fixed" or x == self.cursor_state: 			return		try:			curses.curs_set(x)			self.cursor_state = x		except _curses.error:			self.cursor_state = "fixed"		def _clear(self):		self.s.clear()		self.s.refresh()			def _getch(self, wait_tenths):		if wait_tenths==0:			return self._getch_nodelay()		curses.halfdelay(wait_tenths)		self.s.nodelay(0)		return self.s.getch()		def _getch_nodelay(self):		self.s.nodelay(1)		while 1:			# this call fails sometimes, but seems to work when I try again			try:				curses.cbreak()				break			except _curses.error:				pass					return self.s.getch()	def set_input_timeouts(self, max_wait=0.5, complete_wait=0.1, 		resize_wait=0.1):		"""		Set the get_input timeout values.  All values have a granularity		of 0.1s, ie. any value between 0.15 and 0.05 will be treated as		0.1 and any value less than 0.05 will be treated as 0. 			max_wait -- amount of time in seconds to wait for input when			there is no input pending		complete_wait -- amount of time in seconds to wait when			get_input detects an incomplete escape sequence at the			end of the available input		resize_wait -- amount of time in seconds to wait for more input			after receiving two screen resize requests in a row to			stop urwid from consuming 100% cpu during a gradual			window resize operation		"""		def convert_to_tenths( s ):			return int( (s+0.05)*10 )		self.max_tenths = convert_to_tenths(max_wait)		self.complete_tenths = convert_to_tenths(complete_wait)		self.resize_tenths = convert_to_tenths(resize_wait)		def get_input(self, raw_keys=False):		"""Return pending input as a list.		raw_keys -- return raw keycodes as well as translated versions		This function will immediately return all the input since the		last time it was called.  If there is no input pending it will		wait before returning an empty list.  The wait time may be		configured with the set_input_timeouts function.		If raw_keys is False (default) this function will return a list

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -