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

📄 canvas.py

📁 Urwid is a Python library for making text console applications. It has many features including fluid
💻 PY
📖 第 1 页 / 共 3 页
字号:
#!/usr/bin/python## Urwid canvas class and functions#    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/from __future__ import generatorsimport weakreffrom util import *from escape import * class CanvasCache(object):	"""	Cache for rendered canvases.  Automatically populated and	accessed by Widget render() MetaClass magic, cleared by 	Widget._invalidate().	Stores weakrefs to the canvas objects, so an external class	must maintain a reference for this cache to be effective.	At present the Screen classes store the last topmost canvas 	after redrawing the screen, keeping the canvases from being 	garbage collected.	_widgets[widget] = {(wcls, size, focus): weakref.ref(canvas), ...}	_refs[weakref.ref(canvas)] = (widget, wcls, size, focus)	_deps[widget} = [dependent_widget, ...]	"""	_widgets = {}	_refs = {}	_deps = {}	hits = 0	fetches = 0	cleanups = 0	def store(cls, wcls, canvas):		"""		Store a weakref to canvas in the cache.		wcls -- widget class that contains render() function		canvas -- rendered canvas with widget_info (widget, size, focus)		"""		assert canvas.widget_info, "Can't store canvas without widget_info"		widget, size, focus = canvas.widget_info		def walk_depends(canv):			"""			Collect all child widgets for determining who we			depend on.			"""			# FIXME: is this recursion necessary?  The cache 			# invalidating might work with only one level.			depends = []			for x, y, c, pos in canv.children:				if c.widget_info:					depends.append(c.widget_info[0])				elif hasattr(c, 'children'):					depends.extend(walk_depends(c))			return depends		# use explicit depends_on if available from the canvas		depends_on = getattr(canvas, 'depends_on', None)		if depends_on is None and hasattr(canvas, 'children'):			depends_on = walk_depends(canvas)		if depends_on:			for w in depends_on:				if w not in cls._widgets:					return			for w in depends_on:				cls._deps.setdefault(w,[]).append(widget)		ref = weakref.ref(canvas, cls.cleanup)		cls._refs[ref] = (widget, wcls, size, focus)		cls._widgets.setdefault(widget, {})[(wcls, size, focus)] = ref	store = classmethod(store)	def fetch(cls, widget, wcls, size, focus):		"""		Return the cached canvas or None.		widget -- widget object requested		wcls -- widget class that contains render() function		size, focus -- render() parameters		"""		cls.fetches += 1 # collect stats		sizes = cls._widgets.get(widget, None)		if not sizes:			return None		ref = sizes.get((wcls, size, focus), None)		if not ref:			return None		canv = ref()		if canv:			cls.hits += 1 # more stats		return canv	fetch = classmethod(fetch)		def invalidate(cls, widget):		"""		Remove all canvases cached for widget.		"""		try:			for ref in cls._widgets[widget].values():				try:					del cls._refs[ref]				except KeyError:					pass			del cls._widgets[widget]		except KeyError:			pass		if widget not in cls._deps:			return		dependants = cls._deps.get(widget, [])		try:			del cls._deps[widget]		except KeyError:			pass		for w in dependants:			cls.invalidate(w)	invalidate = classmethod(invalidate)	def cleanup(cls, ref):		cls.cleanups += 1 # collect stats		w = cls._refs.get(ref, None)		del cls._refs[ref]		if not w:			return		widget, wcls, size, focus = w		sizes = cls._widgets.get(widget, None)		if not sizes:			return		try:			del sizes[(wcls, size, focus)]		except KeyError:			pass		if not sizes:			try:				del cls._widgets[widget]				del cls._deps[widget]			except KeyError:				pass	cleanup = classmethod(cleanup)	def clear(cls):		"""		Empty the cache.		"""		cls._widgets = {}		cls._refs = {}		cls._deps = {}	clear = classmethod(clear)		class CanvasError(Exception):	passclass Canvas(object):	"""	base class for canvases	"""	_finalized_error = CanvasError("This canvas has been finalized. "		"Use CompositeCanvas to wrap this canvas if "		"you need to make changes.")	_renamed_error = CanvasError("The old Canvas class is now called "		"TextCanvas. Canvas is now the base class for all canvas "		"classes.")	_old_repr_error = CanvasError("The internal representation of "		"canvases is no longer stored as .text, .attr, and .cs "		"lists, please see the TextCanvas class for the new "		"representation of canvas content.")	def __init__(self, value1=None, value2=None, value3=None):		"""		value1, value2, value3 -- if not None, raise a helpful error:			the old Canvas class is now called TextCanvas.		"""		if value1 is not None: 			raise _renamed_error		self._widget_info = None		self.coords = {}		self.shortcuts = {}		def finalize(self, widget, size, focus):		"""		Mark this canvas as finalized (should not be any future		changes to its content). This is required before caching		the canvas.  This happens automatically after a widget's		render call returns the canvas thanks to some metaclass		magic.		widget -- widget that rendered this canvas		size -- size parameter passed to widget's render method		focus -- focus parameter passed to widget's render method		"""		if self.widget_info:			raise self._finalized_error		self._widget_info = widget, size, focus	def _get_widget_info(self):		return self._widget_info	widget_info = property(_get_widget_info)	def _raise_old_repr_error(self, val=None):		raise self._old_repr_error	text = property(_raise_old_repr_error, _raise_old_repr_error)	attr = property(_raise_old_repr_error, _raise_old_repr_error)	cs = property(_raise_old_repr_error, _raise_old_repr_error)		def content(self, trim_left=0, trim_top=0, cols=None, rows=None, 			attr=None):		raise NotImplementedError()	def cols(self):		raise NotImplementedError()	def rows(self):		raise NotImplementedError()		def content_delta(self):		raise NotImplementedError()	def get_cursor(self):		c = self.coords.get("cursor", None)		if not c:			return		return c[:2] # trim off data part	def set_cursor(self, c):		if self.widget_info:			raise self._finalized_error		if c is None:			try:				del self.coords["cursor"]			except KeyError:				pass			return		self.coords["cursor"] = c + (None,) # data part	cursor = property(get_cursor, set_cursor)	def translate_coords(self, dx, dy):		"""		Return coords shifted by (dx, dy).		"""		d = {}		for name, (x, y, data) in self.coords.items():			d[name] = (x+dx, y+dy, data)		return dclass TextCanvas(Canvas):	"""	class for storing rendered text and attributes	"""	def __init__(self, text=None, attr=None, cs=None, 		cursor=None, maxcol=None, check_width=True):		"""		text -- list of strings, one for each line		attr -- list of run length encoded attributes for text		cs -- list of run length encoded character set for text		cursor -- (x,y) of cursor or None		maxcol -- screen columns taken by this canvas		check_width -- check and fix width of all lines in text		"""		Canvas.__init__(self)		if text == None: 			text = []		if check_width:			widths = []			for t in text:				if type(t) != type(""):					raise CanvasError("Canvas text must be plain strings encoded in the screen's encoding", `text`)				widths.append( calc_width( t, 0, len(t)) )		else:			assert type(maxcol) == type(0)			widths = [maxcol] * len(text)		if maxcol is None:			if widths:				# find maxcol ourselves				maxcol = max(widths)			else:				maxcol = 0		if attr == None: 			attr = [[] for x in range(len(text))]		if cs == None:			cs = [[] for x in range(len(text))]				# pad text and attr to maxcol		for i in range(len(text)):			w = widths[i]			if w > maxcol: 				raise CanvasError("Canvas text is wider than the maxcol specified \n%s\n%s\n%s"%(`maxcol`,`widths`,`text`))			if w < maxcol:				text[i] = text[i] + " "*(maxcol-w)			a_gap = len(text[i]) - rle_len( attr[i] )			if a_gap < 0:				raise CanvasError("Attribute extends beyond text \n%s\n%s" % (`text[i]`,`attr[i]`) )			if a_gap:				rle_append_modify( attr[i], (None, a_gap))						cs_gap = len(text[i]) - rle_len( cs[i] )			if cs_gap < 0:				raise CanvasError("Character Set extends beyond text \n%s\n%s" % (`text[i]`,`cs[i]`) )			if cs_gap:				rle_append_modify( cs[i], (None, cs_gap))					self._attr = attr		self._cs = cs		self.cursor = cursor		self._text = text		self._maxcol = maxcol	def rows(self):		"""Return the number of rows in this canvas."""		return len(self._text)	def cols(self):		"""Return the screen column width of this canvas."""		return self._maxcol		def translated_coords(self,dx,dy):		"""		Return cursor coords shifted by (dx, dy), or None if there		is no cursor.		"""		if self.cursor:			x, y = self.cursor			return x+dx, y+dy		return None	def content(self, trim_left=0, trim_top=0, cols=None, rows=None,			def_attr=None):		"""		Return the canvas content as a list of rows where each row		is a list of (attr, cs, text) tuples.		trim_left, trim_top, cols, rows may be set by 		CompositeCanvas when rendering a partially obscured		canvas.		"""		maxcol, maxrow = self.cols(), self.rows()		if not cols: 			cols = maxcol - trim_left		if not rows:			rows = maxrow - trim_top					assert trim_left >= 0 and trim_left < maxcol		assert cols > 0 and trim_left + cols <= maxcol		assert trim_top >=0 and trim_top < maxrow		assert rows > 0 and trim_top + rows <= maxrow				if trim_top or rows < maxrow:			text_attr_cs = zip(				self._text[trim_top:trim_top+rows],				self._attr[trim_top:trim_top+rows], 				self._cs[trim_top:trim_top+rows])		else:			text_attr_cs = zip(self._text, self._attr, self._cs)				for text, a_row, cs_row in text_attr_cs:			if trim_left or cols < self._maxcol:				text, a_row, cs_row = trim_text_attr_cs(					text, a_row, cs_row, trim_left, 					trim_left + cols)			attr_cs = util.rle_product(a_row, cs_row)			i = 0			row = []			for (a, cs), run in attr_cs:				if a is None:					a = def_attr				row.append((a, cs, text[i:i+run]))				i += run			yield row				def content_delta(self, other):		"""		Return the differences between other and this canvas.		If other is the same object as self this will return no 		differences, otherwise this is the same as calling 		content().		"""		if other is self:			return [self.cols()]*self.rows()		return self.content()	class BlankCanvas(Canvas):	"""	a canvas with nothing on it, only works as part of a composite canvas	since it doesn't know its own size

⌨️ 快捷键说明

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