Commits

Anonymous committed e39e29c

This commit was manufactured by cvs2svn to create tag 'r12beta3'.

Comments (0)

Files changed (97)

Demo/cwilib/cwilib.py

-# Interface to the interactive CWI library catalog.
-
-import sys
-import stdwin
-from stdwinevents import *
-import select
-import telnetlib
-import vt100win
-from form import Form
-
-
-# Main program
-
-def main():
-    vt = vt100win.VT100win()
-    #
-    host = 'biefstuk.cwi.nl'
-    tn = telnetlib.Telnet(host, 0)
-    #
-    try:
-	vt.send(tn.read_until('login: ', 10))
-	tn.write('cwilib\r')
-	#
-	vt.send(tn.read_until('Hit <RETURN> to continue...', 10))
-	tn.write('\r')
-	#
-	vt.send(tn.read_until('QUIT', 20))
-    except EOFError:
-	sys.stderr.write('Connection closed prematurely\n')
-	sys.exit(1)
-    #
-    define_screens(vt)
-    matches = vt.which_screens()
-    if 'menu' not in matches:
-	sys.stderr.write('Main menu does not appear\n')
-	sys.exit(1)
-    #
-    tn.write('\r\r')
-    vt.open('Progress -- CWI Library')
-    vt.set_debuglevel(0)
-    ui = UserInterface()
-    #
-    while 1:
-	try:
-	    data = tn.read_very_eager()
-	except EOFError:
-	    stdwin.message('Connection closed--goodbye')
-	    break
-	if data:
-	    print 'send...'
-	    vt.send(data)
-	    print 'send...done'
-	    continue
-	event = stdwin.pollevent()
-	if event:
-	    type, window, detail = event
-	    if window == None and type == WE_LOST_SEL:
-		window = ui.queryform.window
-		event = type, window, detail
-	    if type == WE_CLOSE:
-		break
-	    if window in ui.windows:
-		ui.dispatch(type, window, detail)
-	    elif window == vt.window:
-		if type == WE_NULL:
-		    pass
-		elif type == WE_COMMAND:
-		    if detail == WC_RETURN:
-			tn.write('\r')
-		    elif detail == WC_BACKSPACE:
-			tn.write('\b')
-		    elif detail == WC_TAB:
-			tn.write('\t')
-		    elif detail == WC_UP:
-			tn.write('\033[A')
-		    elif detail == WC_DOWN:
-			tn.write('\033[B')
-		    elif detail == WC_RIGHT:
-			tn.write('\033[C')
-		    elif detail == WC_LEFT:
-			tn.write('\033[D')
-		    else:
-			print '*** Command:', detail
-		elif type == WE_CHAR:
-		    tn.write(detail)
-		elif type == WE_DRAW:
-		    vt.draw(detail)
-		elif type in (WE_ACTIVATE, WE_DEACTIVATE):
-		    pass
-		else:
-		    print '*** VT100 event:', type, detail
-	    else:
-		print '*** Alien event:', type, window, detail
-	    continue
-	rfd, wfd, xfd = select.select([tn, stdwin], [], [])
-
-
-# Subroutine to define our screen recognition patterns
-
-def define_screens(vt):
-    vt.define_screen('menu', {
-	      'title': ('search', 0, 0, 80,
-			' SEARCH FUNCTIONS  +OTHER FUNCTIONS '),
-	      })
-    vt.define_screen('search', {
-	      'title': ('search', 0, 0, 80, ' Search '),
-	      })
-    vt.define_screen('shortlist', {'title': ('search', 0, 0, 80,
-	      ' Short-list')})
-    vt.define_screen('showrecord', {
-	      'title': ('search', 0, 0, 80, ' Show record '),
-	      })
-    vt.define_screen('timelimit', {
-	      'limit': ('search', 12, 0, 80, ' TIME LIMIT '),
-	      })
-    vt.define_screen('attention', {
-	      'BASE': ('copy', 0, 0, 0, 'search'),
-	      'title': ('search', 10, 0, 80, ' ATTENTION ')})
-    vt.define_screen('syntaxerror', {
-	      'BASE': ('copy', 0, 0, 0, 'attention'),
-	      'message': ('search', 12, 0, 80, ' Syntax error'),
-	      })
-    vt.define_screen('emptyerror', {
-	      'BASE': ('copy', 0, 0, 0, 'attention'),
-	      'message': ('search', 12, 0, 80,
-			  ' Check your input. Search at least one term'),
-	      })
-    vt.define_screen('unsortedwarning', {
-	      'BASE': ('copy', 0, 0, 0, 'attention'),
-	      'message': ('search', 12, 0, 80,
-			  ' Number of records exceeds sort limit'),
-	      })
-    vt.define_screen('thereismore', {
-	      'BASE': ('copy', 0, 0, 0, 'showrecord'),
-	      'message': ('search', 15, 0, 80,
-		 'There is more within this record. Use the arrow keys'),
-	      })
-    vt.define_screen('nofurther', {
-	      'BASE': ('copy', 0, 0, 0, 'showrecord'),
-	      'message': ('search', 17, 0, 80, 'You cannot go further\.'),
-	      })
-    vt.define_screen('nofurtherback', {
-	      'BASE': ('copy', 0, 0, 0, 'showrecord'),
-	      'message': ('search', 17, 0, 80,
-			  'You cannot go further back'),
-	      })
-
-
-# Class to implement our user interface.
-
-class UserInterface:
-
-    def __init__(self):
-	stdwin.setfont('7x14')
-	self.queryform = QueryForm()
-	self.listform = ListForm()
-	self.recordform = RecordForm()
-	self.forms = [self.queryform, self.listform, self.recordform]
-	define_query_fields(self.queryform)
-	self.windows = []
-	for form in self.forms:
-	    if form.formheight > 0:
-		form.open()
-		self.windows.append(form.window)
-
-    def __del__(self):
-	self.close()
-
-    def close(self):
-	for form in self.forms:
-	    form.close()
-
-    def dispatch(self, type, window, detail):
-	for form in self.forms:
-	    if window == form.window:
-		form.dispatch(type, detail)
-
-
-def define_query_fields(f):
-    f.define_field('name', 'Name auth./ed.', 1, 60)
-    f.define_field('title',  'Title', 4, 60)
-    f.define_field('shelfmark', 'Shelf mark', 1, 60)
-    f.define_field('class', 'Prim. classif.', 1, 60)
-    f.define_field('series', 'Series', 1, 60)
-    f.define_field('congress', 'Congr. pl./year', 1, 60)
-    f.define_field('type', 'Type', 1, 60)
-
-
-class QueryForm(Form):
-
-    def __init__(self):
-	Form.__init__(self, 'Query form -- CWI Library')
-
-    def dispatch(self, type, detail):
-	if type == WE_COMMAND and detail == WC_RETURN:
-	    print '*** SUBMIT ***'
-	else:
-	    Form.dispatch(self, type, detail)
-
-
-class ListForm(Form):
-
-    def __init__(self):
-	Form.__init__(self, 'Short list -- CWI Library')
-
-
-class RecordForm(Form):
-
-    def __init__(self):
-	Form.__init__(self, 'Record detail -- CWI Library')
-
-
-main()

Demo/cwilib/form.py

-# Fill-out form window
-
-import stdwin
-from stdwinevents import *
-
-
-class Form:
-
-	def __init__(self, title):
-		self.title = title
-		self.window = None
-		self.fields = {}
-		self.fieldnames = []
-		self.formwidth = self.formheight = 0
-		self.focusname = None
-		self.tefocus = None
-
-	def define_field(self, name, label, lines, chars):
-		self.fieldnames.append(name)
-		lh = stdwin.lineheight()
-		cw = stdwin.textwidth('m')
-		left = 20*cw
-		top = self.formheight + 4
-		right = left + chars*cw
-		bottom = top + lines*lh
-		te = None
-		self.fields[name] = (label, left, top, right, bottom, te)
-		self.formheight = bottom + 2
-		self.formwidth = max(self.formwidth, right + 4)
-
-	def open(self):
-		if self.window: return
-		self.formwidth = max(100, self.formwidth)
-		self.formheight = max(50, self.formheight)
-		stdwin.setdefwinsize(self.formwidth, self.formheight)
-		stdwin.setdefscrollbars(0, 0)
-		self.window = stdwin.open(self.title)
-		self.window.setdocsize(self.formwidth, self.formheight)
-		for name in self.fieldnames:
-			label, left, top, right, bottom, te = \
-				  self.fields[name]
-			rect = (left, top), (right, bottom)
-			te = self.window.textcreate(rect)
-			te.setactive(0)
-			te.setview(rect)
-			self.fields[name] = \
-				  label, left, top, right, bottom, te
-		if self.fieldnames:
-			self.setfocus(self.fieldnames[0])
-
-	def setfocus(self, name):
-		if name <> self.focusname and self.tefocus:
-			self.tefocus.setactive(0)
-		self.focusname = name
-		if self.focusname:
-			self.tefocus = self.fields[self.focusname][-1]
-			self.tefocus.setactive(1)
-		else:
-			self.tefocus = None
-
-	def dispatch(self, type, detail):
-		event = type, self.window, detail
-		if type == WE_NULL:
-			pass
-		elif type == WE_DRAW:
-			self.draw(detail)
-		elif type == WE_MOUSE_DOWN:
-			x, y = detail[0]
-			for name in self.fieldnames:
-				label, left, top, right, bottom, te = \
-					  self.fields[name]
-				if left <= x < right and \
-					  top <= y < bottom:
-					self.setfocus(name)
-					break
-			else:
-				stdwin.fleep()
-				return
-			if self.tefocus:
-				(left, top), (right, bottom) = \
-					  self.tefocus.getrect()
-				if x < left: x = left
-				if x >= right: x = right-1
-				if y < top: y = top
-				if y >= bottom:
-					y = bottom-1
-					x = right-1
-				event = type, self.window, ((x,y),)+detail[1:]
-				if not self.tefocus.event(event):
-					stdwin.fleep()
-		elif type in (WE_MOUSE_MOVE, WE_MOUSE_UP, WE_CHAR):
-			if not self.tefocus or not self.tefocus.event(event):
-				stdwin.fleep()
-			elif type == WE_MOUSE_UP:
-				button = detail[2]
-				if button == 2:
-					self.paste_selection()
-				else:
-					self.make_selection()
-		elif type == WE_COMMAND:
-			if detail in (WC_BACKSPACE, WC_UP, WC_DOWN,
-				      WC_LEFT, WC_RIGHT):
-				if not self.tefocus or \
-					  not self.tefocus.event(event):
-					stdwin.fleep()
-			elif detail == WC_RETURN:
-				print '*** Submit query'
-			elif detail == WC_TAB:
-				if not self.fields:
-					stdwin.fleep()
-					return
-				if not self.focusname:
-					i = 0
-				else:
-					i = self.fieldnames.index(
-						  self.focusname)
-					i = (i+1) % len(self.fieldnames)
-				self.setfocus(self.fieldnames[i])
-				self.tefocus.setfocus(0, 0x7fff)
-				self.make_selection()
-		elif type in (WE_ACTIVATE, WE_DEACTIVATE):
-			pass
-		elif type == WE_LOST_SEL:
-			if self.tefocus:
-				a, b = self.tefocus.getfocus()
-				self.tefocus.setfocus(a, a)
-		else:
-			print 'Form.dispatch(%d, %s)' % (type, `detail`)
-
-	def draw(self, detail):
-		d = self.window.begindrawing()
-		d.cliprect(detail)
-		d.erase(detail)
-		self.drawform(d, detail)
-		d.noclip()
-		d.close()
-		# Stupid textedit objects can't draw with open draw object...
-		self.drawtextedit(detail)
-
-	def drawform(self, d, detail):
-		for name in self.fieldnames:
-			label, left, top, right, bottom, te = self.fields[name]
-			d.text((0, top), label)
-			d.box((left-3, top-2), (right+4, bottom+2))
-
-	def drawtextedit(self, detail):
-		for name in self.fieldnames:
-			label, left, top, right, bottom, te = self.fields[name]
-			te.draw(detail)
-
-	def make_selection(self):
-		s = self.tefocus.getfocustext()
-		if not s:
-			return
-		stdwin.rotatecutbuffers(1)
-		stdwin.setcutbuffer(0, s)
-		if not self.window.setselection(WS_PRIMARY, s):
-			stdwin.fleep()
-
-	def paste_selection(self):
-		if not self.tefocus:
-			stdwin.fleep()
-			return
-		s = stdwin.getselection(WS_PRIMARY)
-		if not s:
-			s = stdwin.getcutbuffer(0)
-			if not s:
-				stdwin.fleep()
-				return
-		self.tefocus.replace(s)

Demo/cwilib/telnetlib.py

-# A TELNET client class.  Based on RFC 854: TELNET Protocol
-# Specification, by J. Postel and J. Reynolds
-
-
-# Example:
-#
-# >>> from telnetlib import Telnet
-# >>> tn = Telnet('voorn.cwi.nl', 79) # connect to finger port
-# >>> tn.write('guido\r\n')
-# >>> print tn.read_all()
-# Login name: guido                       In real life: Guido van Rossum
-# Office: M353,  x4127                    Home phone: 020-6225521
-# Directory: /ufs/guido                   Shell: /usr/local/bin/esh
-# On since Oct 28 11:02:16 on ttyq1   
-# Project: Multimedia Kernel Systems
-# No Plan.
-# >>>
-#
-# Note that read() won't read until eof -- it just reads some data
-# (but it guarantees to read at least one byte unless EOF is hit).
-#
-# It is possible to pass a Telnet object to select.select() in order
-# to wait until more data is available.  Note that in this case,
-# read_eager() may return '' even if there was data on the socket,
-# because the protocol negotiation may have eaten the data.
-# This is why EOFError is needed to distinguish between "no data"
-# and "connection closed" (since the socket also appears ready for
-# reading when it is closed).
-#
-# Bugs:
-# - may hang when connection is slow in the middle of an IAC sequence
-#
-# To do:
-# - option negotiation
-
-
-# Imported modules
-import socket
-import select
-import string
-import regsub
-
-# Tunable parameters
-DEBUGLEVEL = 0
-
-# Telnet protocol defaults
-TELNET_PORT = 23
-
-# Telnet protocol characters (don't change)
-IAC  = chr(255)	# "Interpret As Command"
-DONT = chr(254)
-DO   = chr(253)
-WONT = chr(252)
-WILL = chr(251)
-
-
-# Telnet interface class
-
-class Telnet:
-
-    # Constructor
-    def __init__(self, host, *args):
-	if not args:
-	    port = TELNET_PORT
-	else:
-	    if len(args) > 1: raise TypeError, 'too many args'
-	    port = args[0]
-	    if not port: port = TELNET_PORT
-	self.debuglevel = DEBUGLEVEL
-	self.host = host
-	self.port = port
-	self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-	self.sock.connect((self.host, self.port))
-	self.rawq = ''
-	self.irawq = 0
-	self.cookedq = ''
-	self.eof = 0
-
-    # Destructor
-    def __del__(self):
-	self.close()
-
-    # Debug message
-    def msg(self, msg, *args):
-	if self.debuglevel > 0:
-	    print 'Telnet(%s,%d):' % (self.host, self.port), msg % args
-
-    # Set debug level
-    def set_debuglevel(self, debuglevel):
-	self.debuglevel = debuglevel
-
-    # Explicit close
-    def close(self):
-	if self.sock:
-	    self.sock.close()
-	self.sock = None
-	self.eof = 1
-
-    # Return socket (e.g. for select)
-    def get_socket(self):
-	return self.sock
-
-    # Return socket's fileno (e.g. for select)
-    def fileno(self):
-	return self.sock.fileno()
-
-    # Write a string to the socket, doubling any IAC characters
-    # Might block if the connection is blocked
-    # May raise socket.error if the connection is closed
-    def write(self, buffer):
-	if IAC in buffer:
-	    buffer = regsub.gsub(IAC, IAC+IAC, buffer)
-	self.sock.send(buffer)
-
-    # The following read_* methods exist:
-    # Special case:
-    # - read_until() reads until a string is encountered or a timeout is hit
-    # These may block:
-    # - read_all() reads all data until EOF
-    # - read_some() reads at least one byte until EOF
-    # These may do I/O but won't block doing it:
-    # - read_very_eager() reads all data available on the socket
-    # - read_eager() reads either data already queued or some data
-    #                available on the socket
-    # These don't do I/O:
-    # - read_lazy() reads all data in the raw queue (processing it first)
-    # - read_very_lazy() reads all data in the cooked queue
-
-    # Read until a given string is encountered or until timeout
-    # Raise EOFError if connection closed and no cooked data available
-    # Return '' if no cooked data available otherwise
-    def read_until(self, match, *args):
-	if not args:
-	    timeout = None
-	else:
-	    if len(args) > 1: raise TypeError, 'too many args'
-	    timeout = args[0]
-	n = len(match)
-	self.process_rawq()
-	i = string.find(self.cookedq, match)
-	if i >= 0:
-	    i = i+n
-	    buf = self.cookedq[:i]
-	    self.cookedq = self.cookedq[i:]
-	    return buf
-	s_reply = ([self], [], [])
-	s_args = s_reply
-	if timeout is not None:
-	    s_args = s_args + (timeout,)
-	while not self.eof and apply(select.select, s_args) == s_reply:
-	    i = max(0, len(self.cookedq)-n)
-	    self.fill_rawq()
-	    self.process_rawq()
-	    i = string.find(self.cookedq, match, i)
-	    if i >= 0:
-		i = i+n
-		buf = self.cookedq[:i]
-		self.cookedq = self.cookedq[i:]
-		return buf
-	return self.read_very_lazy()
-
-    # Read all data until EOF
-    # Block until connection closed
-    def read_all(self):
-	self.process_rawq()
-	while not self.eof:
-	    self.fill_rawq()
-	    self.process_rawq()
-	buf = self.cookedq
-	self.cookedq = ''
-	return buf
-
-    # Read at least one byte of cooked data unless EOF is hit
-    # Return '' if EOF is hit
-    # Block if no data is immediately available
-    def read_some(self):
-	self.process_rawq()
-	while not self.cookedq and not self.eof:
-	    self.fill_rawq()
-	    self.process_rawq()
-	buf = self.cookedq
-	self.cookedq = ''
-	return buf
-
-    # Read everything that's possible without blocking in I/O (eager)
-    # Raise EOFError if connection closed and no cooked data available
-    # Return '' if no cooked data available otherwise
-    # Don't block unless in the midst of an IAC sequence
-    def read_very_eager(self):
-	self.process_rawq()
-	while not self.eof and self.sock_avail():
-	    self.fill_rawq()
-	    self.process_rawq()
-	return self.read_very_lazy()
-
-    # Read readily available data
-    # Raise EOFError if connection closed and no cooked data available
-    # Return '' if no cooked data available otherwise
-    # Don't block unless in the midst of an IAC sequence
-    def read_eager(self):
-	self.process_rawq()
-	while not self.cookedq and not self.eof and self.sock_avail():
-	    self.fill_rawq()
-	    self.process_rawq()
-	return self.read_very_lazy()
-
-    # Process and return data that's already in the queues (lazy)
-    # Raise EOFError if connection closed and no data available
-    # Return '' if no cooked data available otherwise
-    # Don't block unless in the midst of an IAC sequence
-    def read_lazy(self):
-	self.process_rawq()
-	return self.read_very_lazy()
-
-    # Return any data available in the cooked queue (very lazy)
-    # Raise EOFError if connection closed and no data available
-    # Return '' if no cooked data available otherwise
-    # Don't block
-    def read_very_lazy(self):
-	buf = self.cookedq
-	self.cookedq = ''
-	if not buf and self.eof and not self.rawq:
-	    raise EOFError, 'telnet connection closed'
-	return buf
-
-    # Transfer from raw queue to cooked queue
-    # Set self.eof when connection is closed
-    # Don't block unless in the midst of an IAC sequence
-    def process_rawq(self):
-	buf = ''
-	try:
-	    while self.rawq:
-		c = self.rawq_getchar()
-		if c != IAC:
-		    buf = buf + c
-		    continue
-		c = self.rawq_getchar()
-		if c == IAC:
-		    buf = buf + c
-		elif c in (DO, DONT):
-		    opt = self.rawq_getchar()
-		    self.msg('IAC %s %d', c == DO and 'DO' or 'DONT', ord(c))
-		    self.sock.send(IAC + WONT + opt)
-		elif c in (WILL, WONT):
-		    opt = self.rawq_getchar()
-		    self.msg('IAC %s %d',
-			  c == WILL and 'WILL' or 'WONT', ord(c))
-		else:
-		    self.msg('IAC %s not recognized' % `c`)
-	except EOFError: # raised by self.rawq_getchar()
-	    pass
-	self.cookedq = self.cookedq + buf
-
-    # Get next char from raw queue
-    # Block if no data is immediately available
-    # Raise EOFError when connection is closed
-    def rawq_getchar(self):
-	if not self.rawq:
-	    self.fill_rawq()
-	    if self.eof:
-		raise EOFError
-	c = self.rawq[self.irawq]
-	self.irawq = self.irawq + 1
-	if self.irawq >= len(self.rawq):
-	    self.rawq = ''
-	    self.irawq = 0
-	return c
-
-    # Fill raw queue from exactly one recv() system call
-    # Block if no data is immediately available
-    # Set self.eof when connection is closed
-    def fill_rawq(self):
-	if self.irawq >= len(self.rawq):
-	    self.rawq = ''
-	    self.irawq = 0
-	# The buffer size should be fairly small so as to avoid quadratic
-	# behavior in process_rawq() above
-	buf = self.sock.recv(50)
-	self.eof = (not buf)
-	self.rawq = self.rawq + buf
-
-    # Test whether data is available on the socket
-    def sock_avail(self):
-	return select.select([self], [], [], 0) == ([self], [], [])
-
-
-# Test program
-# Usage: test [-d] ... [host [port]]
-def test():
-    import sys, string, socket, select
-    debuglevel = 0
-    while sys.argv[1:] and sys.argv[1] == '-d':
-	debuglevel = debuglevel+1
-	del sys.argv[1]
-    host = 'localhost'
-    if sys.argv[1:]:
-	host = sys.argv[1]
-    port = 0
-    if sys.argv[2:]:
-	portstr = sys.argv[2]
-	try:
-	    port = string.atoi(portstr)
-	except string.atoi_error:
-	    port = socket.getservbyname(portstr, 'tcp')
-    tn = Telnet(host, port)
-    tn.set_debuglevel(debuglevel)
-    while 1:
-	rfd, wfd, xfd = select.select([tn, sys.stdin], [], [])
-	if sys.stdin in rfd:
-	    line = sys.stdin.readline()
-	    tn.write(line)
-	if tn in rfd:
-	    try:
-		text = tn.read_eager()
-	    except EOFError:
-		print '*** Connection closed by remote host ***'
-		break
-	    if text:
-		sys.stdout.write(text)
-		sys.stdout.flush()
-    tn.close()

Demo/cwilib/vt100.py

-# VT100 terminal emulator.
-# This is incomplete and slow, but will do for now...
-# It shouldn't be difficult to extend it to be a more-or-less complete
-# VT100 emulator.  And little bit of profiling could go a long way...
-
-from array import array
-import regex
-import string
-
-# Tunable parameters
-DEBUGLEVEL = 1
-
-# Symbolic constants
-ESC = '\033'
-
-
-# VT100 emulation class
-
-class VT100:
-
-	def __init__(self):
-		self.debuglevel = DEBUGLEVEL
-		# Unchangeable parameters (for now)
-		self.width = 80
-		self.height = 24
-		self.blankline = array('c', ' '*self.width)
-		self.blankattr = array('b', '\0'*self.width)
-		# Set mutable display state
-		self.reset()
-		# Set parser state
-		self.unfinished = ''
-		# Set screen recognition state
-		self.reset_recognizer()
-
-	def msg(self, msg, *args):
-		if self.debuglevel > 0:
-			print 'VT100:', msg%args
-
-	def set_debuglevel(self, debuglevel):
-		self.debuglevel = debuglevel
-
-	def reset(self):
-		self.lines = []
-		self.attrs = []
-		self.fill_bottom()
-		self.x = 0
-		self.y = 0
-		self.curattrs = []
-
-	def show(self):
-		lineno = 0
-		for line in self.lines:
-			lineno = lineno + 1
-			i = len(line)
-			while i > 0 and line[i-1] == ' ': i = i-1
-			print line[:i]
-			print 'CURSOR:', self.x, self.y
-
-	def fill_bottom(self):
-		while len(self.lines) < self.height:
-			self.lines.append(self.blankline[:])
-			self.attrs.append(self.blankattr[:])
-
-	def fill_top(self):
-		while len(self.lines) < self.height:
-			self.lines.insert(0, self.blankline[:])
-			self.attrs.insert(0, self.blankattr[:])
-
-	def clear_all(self):
-		self.lines = []
-		self.attrs = []
-		self.fill_bottom()
-
-	def clear_below(self):
-		del self.lines[self.y:]
-		del self.attrs[self.y:]
-		self.fill_bottom()
-
-	def clear_above(self):
-		del self.lines[:self.y]
-		del self.attrs[:self.y]
-		self.fill_top()
-
-	def send(self, buffer):
-		self.msg('send: unfinished=%s, buffer=%s',
-			  `self.unfinished`, `buffer`)
-		self.unfinished = self.unfinished + buffer
-		i = 0
-		n = len(self.unfinished)
-		while i < n:
-			c = self.unfinished[i]
-			i = i+1
-			if c != ESC:
-				self.add_char(c)
-				continue
-			if i >= n:
-				i = i-1
-				break
-			c = self.unfinished[i]
-			i = i+1
-			if c == 'c':
-				self.reset()
-				continue
-			if c <> '[':
-				self.msg('unrecognized: ESC %s', `c`)
-				continue
-			argstr = ''
-			while i < n:
-				c = self.unfinished[i]
-				i = i+1
-				if c not in '0123456789;':
-					break
-				argstr = argstr + c
-			else:
-				i = i - len(argstr) - 2
-				break
-##			self.msg('found ESC [ %s %s' % (`argstr`, `c`))
-			args = string.splitfields(argstr, ';')
-			for j in range(len(args)):
-				s = args[j]
-				while s[:1] == '0': s = s[1:]
-				if s: args[j] = eval(s)
-				else: args[j] = 0
-			p1 = p2 = 0
-			if args: p1 = args[0]
-			if args[1:]: p2 = args[1]
-			if c in '@ABCDH':
-				if not p1: p1 = 1
-			if c in 'H':
-				if not p2: p2 = 1
-			if c == '@':
-				for j in range(p1):
-					self.add_char(' ')
-			elif c == 'A':
-				self.move_by(0, -p1)
-			elif c == 'B':
-				self.move_by(0, p1)
-			elif c == 'C':
-				self.move_by(p1, 0)
-			elif c == 'D':
-				self.move_by(-p1, 0)
-			elif c == 'H':
-				self.move_to(p2-1, p1-1)
-			elif c == 'J':
-				if p1 == 0: self.clear_above()
-				elif p1 == 1: self.clear_below()
-				elif p1 == 2: self.clear_all()
-				else: self.msg('weird ESC [ %d J', p1)
-			elif c == 'K':
-				if p1 == 0: self.erase_right()
-				elif p1 == 1: self.erase_left()
-				elif p1 == 2: self.erase_line()
-				else: self.msg('weird ESC [ %d K', p1)
-			elif c == 'm':
-				if p1 == 0:
-					self.curattrs = []
-				else:
-					if p1 not in self.curattrs:
-						self.curattrs.append(p1)
-						self.curattrs.sort()
-			else:
-				self.msg('unrecognized: ESC [ %s', `argstr+c`)
-		self.unfinished = self.unfinished[i:]
-
-	def add_char(self, c):
-		if c == '\r':
-			self.move_to(0, self.y)
-			return
-		if c in '\n\f\v':
-			self.move_to(self.x, self.y + 1)
-			if self.y >= self.height:
-				self.scroll_up(1)
-				self.move_to(self.x, self.height - 1)
-			return
-		if c == '\b':
-			self.move_by(-1, 0)
-			return
-		if c == '\a':
-			self.msg('BELL')
-			return
-		if c == '\t':
-			self.move_to((self.x+8)/8*8, self.y)
-			return
-		if c == '\0':
-			return
-		if c < ' ' or c > '~':
-			self.msg('ignored control char: %s', `c`)
-			return
-		if self.x >= self.width:
-			self.move_to(0, self.y + 1)
-		if self.y >= self.height:
-			self.scroll_up(1)
-			self.move_to(self.x, self.height - 1)
-		self.lines[self.y][self.x] = c
-		if self.curattrs:
-			self.attrs[self.y][self.x] = max(self.curattrs)
-		else:
-			self.attrs[self.y][self.x] = 0
-		self.move_by(1, 0)
-
-	def move_to(self, x, y):
-		self.x = min(max(0, x), self.width)
-		self.y = min(max(0, y), self.height)
-
-	def move_by(self, dx, dy):
-		self.move_to(self.x + dx, self.y + dy)
-
-	def scroll_up(self, nlines):
-		del self.lines[:max(0, nlines)]
-		del self.attrs[:max(0, nlines)]
-		self.fill_bottom()
-
-	def scroll_down(self, nlines):
-		del self.lines[-max(0, nlines):]
-		del self.attrs[-max(0, nlines):]
-		self.fill_top()
-
-	def erase_left(self):
-		x = min(self.width-1, x)
-		y = min(self.height-1, y)
-		self.lines[y][:x] = self.blankline[:x]
-		self.attrs[y][:x] = self.blankattr[:x]
-
-	def erase_right(self):
-		x = min(self.width-1, x)
-		y = min(self.height-1, y)
-		self.lines[y][x:] = self.blankline[x:]
-		self.attrs[y][x:] = self.blankattr[x:]
-
-	def erase_line(self):
-		self.lines[y][:] = self.blankline
-		self.attrs[y][:] = self.blankattr
-
-	# The following routines help automating the recognition of
-	# standard screens.  A standard screen is characterized by
-	# a number of fields.  A field is part of a line,
-	# characterized by a (lineno, begin, end) tuple;
-	# e.g. the first 10 characters of the second line are
-	# specified by the tuple (1, 0, 10).  Fields can be:
-	# - regex: desired contents given by a regular expression,
-	# - extract: can be extracted,
-	# - cursor: screen is only valid if cursor in field,
-	# - copy: identical to another screen (position is ignored).
-	# A screen is defined as a dictionary full of fields.  Screens
-	# also have names and are placed in a dictionary.
-
-	def reset_recognizer(self):
-		self.screens = {}
-
-	def define_screen(self, screenname, fields):
-		fieldscopy = {}
-		# Check if the fields make sense
-		for fieldname in fields.keys():
-			field = fields[fieldname]
-			ftype, lineno, begin, end, extra = field
-			if ftype in ('match', 'search'):
-				extra = regex.compile(extra)
-			elif ftype == 'extract':
-				extra = None
-			elif ftype == 'cursor':
-				extra = None
-			elif ftype == 'copy':
-				if not self.screens.has_key(extra):
-					raise ValueError, 'bad copy ref'
-			else:
-				raise ValueError, 'bad ftype: %s' % `ftype`
-			fieldscopy[fieldname] = (
-				  ftype, lineno, begin, end, extra)
-		self.screens[screenname] = fieldscopy
-
-	def which_screens(self):
-		self.busy = []
-		self.okay = []
-		self.fail = []
-		for name in self.screens.keys():
-			ok = self.match_screen(name)
-		return self.okay[:]
-
-	def match_screen(self, name):
-		if name in self.busy: raise RuntimeError, 'recursive match'
-		if name in self.okay: return 1
-		if name in self.fail: return 0
-		self.busy.append(name)
-		fields = self.screens[name]
-		ok = 0
-		for key in fields.keys():
-			field = fields[key]
-			ftype, lineno, begin, end, extra = field
-			if ftype == 'copy':
-				if not self.match_screen(extra): break
-			elif ftype == 'search':
-				text = self.lines[lineno][begin:end].tostring()
-				if extra.search(text) < 0:
-					break
-			elif ftype == 'match':
-				text = self.lines[lineno][begin:end].tostring()
-				if extra.match(text) < 0:
-					break
-			elif ftype == 'cursor':
-				if self.x != lineno or not \
-					  begin <= self.y < end:
-					break
-		else:
-			ok = 1
-		if ok:
-			self.okay.append(name)
-		else:
-			self.fail.append(name)
-		self.busy.remove(name)
-		return ok
-
-	def extract_field(self, screenname, fieldname):
-		ftype, lineno, begin, end, extra = \
-			  self.screens[screenname][fieldname]
-		return stripright(self.lines[lineno][begin:end].tostring())
-
-	def extract_rect(self, left, top, right, bottom):
-		lines = []
-		for i in range(top, bottom):
-			lines.append(stripright(self.lines[i][left:right])
-				  .tostring())
-		return lines
-
-
-def stripright(line):
-	i = len(line)
-	while i > 0 and line[i-1] in string.whitespace: i = i-1
-	return line[:i]

Demo/cwilib/vt100win.py

-# VT100 terminal emulator in a STDWIN window.
-
-import stdwin
-from stdwinevents import *
-from vt100 import VT100
-
-class VT100win(VT100):
-
-	def __init__(self):
-		VT100.__init__(self)
-		self.window = None
-		self.last_x = -1
-		self.last_y = -1
-
-	def __del__(self):
-		self.close()
-
-	def open(self, title):
-		stdwin.setfont('7x14')
-		self.charwidth = stdwin.textwidth('m')
-		self.lineheight = stdwin.lineheight()
-		self.docwidth = self.width * self.charwidth
-		self.docheight = self.height * self.lineheight
-		stdwin.setdefwinsize(self.docwidth + 2, self.docheight + 2)
-		stdwin.setdefscrollbars(0, 0)
-		self.window = stdwin.open(title)
-		self.window.setdocsize(self.docwidth + 2, self.docheight + 2)
-
-	def close(self):
-		if self.window:
-			self.window.close()
-		self.window = None
-
-	def show(self):
-		if not self.window: return
-		self.window.change(((-10, -10),
-			  (self.docwidth+10, self.docheight+10)))
-
-	def draw(self, detail):
-		d = self.window.begindrawing()
-		fg = stdwin.getfgcolor()
-		red = stdwin.fetchcolor('red')
-		d.cliprect(detail)
-		d.erase(detail)
-		lh = self.lineheight
-		cw = self.charwidth
-		for y in range(self.height):
-			d.text((0, y*lh), self.lines[y].tostring())
-			if self.attrs[y] <> self.blankattr:
-				for x in range(len(self.attrs[y])):
-					if self.attrs[y][x] == 7:
-						p1 = x*cw, y*lh
-						p2 = (x+1)*cw, (y+1)*lh
-						d.invert((p1, p2))
-		x = self.x * cw
-		y = self.y * lh
-		d.setfgcolor(red)
-		d.invert((x, y), (x+cw, y+lh))
-		d.setfgcolor(fg)
-		d.close()
-
-	def move_to(self, x, y):
-		VT100.move_to(self, x, y)
-		if not self.window: return
-		if self.y != self.last_y:
-			self.window.change((0, self.last_y * self.lineheight),
-				  (self.width*self.charwidth,
-				  (self.last_y+1) * self.lineheight))
-		self.last_x = self.x
-		self.last_y = y
-		self.window.change((0, self.y * self.lineheight),
-			  (self.width*self.charwidth,
-			  (self.y+1) * self.lineheight))
-
-	def send(self, str):
-		VT100.send(self, str)
-##		self.show()
-

Demo/scripts/freeze.py

-#! /usr/local/bin/python
-
-# Given a Python script, create a binary that runs the script.
-# The binary is 100% independent of Python libraries and binaries.
-# It will not contain any Python source code -- only "compiled" Python
-# (as initialized static variables containing marshalled code objects).
-# It even does the right thing for dynamically loaded modules!
-# The module search path of the binary is set to the current directory.
-#
-# Some problems remain:
-# - It's highly non-portable, since it knows about paths and libraries
-#   (there's a customization section though, and it knows how to
-#   distinguish an SGI from a Sun SPARC system -- adding knowledge
-#   about more systems is left as an exercise for the reader).
-# - You need to have the Python source tree lying around as well as
-#   the "libpython.a" used to generate the Python binary.
-# - For scripts that use many modules it generates absurdly large
-#   files (frozen.c and config.o as well as the final binary),
-#   and is consequently rather slow.
-#
-# Caveats:
-# - The search for modules sometimes finds modules that are never
-#   actually imported since the code importing them is never executed.
-# - If an imported module isn't found, you get a warning but the
-#   process of freezing continues.  The binary will fail if it
-#   actually tries to import one of these modules.
-# - This often happens with the module 'mac', which module 'os' tries
-#   to import (to determine whether it is running on a Macintosh).
-#   You can ignore the warning about this.
-# - If the program dynamically reads or generates Python code and
-#   executes it, this code may reference built-in or library modules
-#   that aren't present in the frozen binary, and this will fail.
-# - Your program may be using external data files, e.g. compiled
-#   forms definitions (*.fd).  These aren't incorporated.  Since
-#   sys.path in the resulting binary only contains '.', if your
-#   program searches its data files along sys.path (as the 'flp'
-#   modules does to find its forms definitions), you may need to
-#   change the program to extend the search path or instruct its users
-#   to set the environment variable PYTHONPATH to point to your data
-#   files.
-#
-# Usage hints:
-# - If you have a bunch of scripts that you want to freeze, instead
-#   of freezing each of them separately, you might consider writing
-#   a tiny main script that looks at sys.argv[0] and then imports
-#   the corresponding module.  You can then make links to the
-#   frozen binary named after the various scripts you support.
-#   Pass the additional scripts as arguments after the main script.
-#   A minimal script to do this is the following.
-#       import sys, posixpath
-#       exec('import ' + posixpath.basename(sys.argv[0]) + '\n')
-
-
-import os
-import sys
-import regex
-import getopt
-import regsub
-import string
-import marshal
-
-# Function to join two pathnames with a slash in between
-j = os.path.join
-
-##################################
-# START OF CONFIGURATION SECTION #
-##################################
-
-# Attempt to guess machine architecture
-if os.path.exists('/usr/lib/libgl_s'): ARCH = 'sgi'
-elif os.path.exists('/etc/issue'): ARCH = 'sequent'
-else: ARCH = 'sun4'
-
-# Site parametrizations (change to match your site)
-CC = 'cc'				# C compiler
-TOP = '/ufs/guido/src'			# Parent of all source trees
-PYTHON = j(TOP, 'python')		# Top of the Python source tree
-SRC = j(PYTHON, 'src')			# Python source directory
-BLD = j(PYTHON, 'build.' + ARCH)	# Python build directory
-#BLD = SRC				# Use this if you build in SRC
-
-LIBINST = '/ufs/guido/src/python/irix4/tmp/lib/python/lib' # installed libraries
-INCLINST = '/ufs/guido/src/python/irix4/tmp/include/Py' # installed include files
-
-# Other packages (change to match your site)
-DL = j(TOP, 'dl')			# Top of the dl source tree
-DL_DLD = j(TOP, 'dl-dld')		# The dl-dld source directory
-DLD = j(TOP, 'dld-3.2.3')		# The dld source directory
-FORMS = j(TOP, 'forms')			# Top of the FORMS source tree
-STDWIN = j(TOP, 'stdwin')		# Top of the STDWIN source tree
-READLINE = j(TOP, 'readline.' + ARCH)	# Top of the GNU Readline source tree
-SUN_X11 = '/usr/local/X11R5/lib/libX11.a'
-
-# File names (usually no need to change)
-LIBP = [				# Main Python libraries
-        j(LIBINST, 'libPython.a'),
-        j(LIBINST, 'libParser.a'),
-        j(LIBINST, 'libObjects.a'),
-        j(LIBINST, 'libModules.a')
-       ]
-CONFIG_IN = j(LIBINST, 'config.c.in')	# Configuration source file
-FMAIN = j(LIBINST, 'frozenmain.c')	# Special main source file
-
-# Libraries needed when linking.  First tuple item is built-in module
-# for which it is needed (or '*' for always), rest are ld arguments.
-# There is a separate list per architecture.
-libdeps_sgi = [ \
-	  ('stdwin',	j(STDWIN, 'Build/' + ARCH + '/x11/lib/lib.a')), \
-	  ('fl',	j(FORMS, 'FORMS/libforms.a'), '-lfm_s'), \
-	  ('*',		j(READLINE, 'libreadline.a'), '-ltermcap'), \
-	  ('al',	'-laudio'), \
-	  ('sv',	'-lsvideo', '-lXext'), \
-	  ('cd',	'-lcdaudio', '-lds'), \
-	  ('cl',	'-lcl'), \
-	  ('imgfile',	'-limage', '-lgutil', '-lm'), \
-	  ('mpz',	'/ufs/guido/src/gmp/libgmp.a'), \
-	  ('*',		'-lsun'), \
-	  ('*',		j(DL, 'libdl.a'), '-lmld'), \
-	  ('*',		'-lmpc'), \
-	  ('fm',	'-lfm_s'), \
-	  ('gl',	'-lgl_s', '-lX11_s'), \
-	  ('stdwin',	'-lX11_s'), \
-	  ('*',		'-lm'), \
-	  ('*',		'-lc_s'), \
-	  ]
-libdeps_sun4 = [ \
-	  ('*',		'-Bstatic'), \
-	  ('stdwin',	j(STDWIN, 'Build/' + ARCH + '/x11/lib/lib.a')), \
-	  ('*',		j(READLINE, 'libreadline.a')), \
-	  ('*',		'-lm'), \
-	  ('*',		j(DL_DLD,'libdl.a'), j(DLD,'libdld.a')), \
-	  ('*',		SUN_X11), \
-	  ('*',		'-ltermcap'), \
-	  ('*',		'-lc'), \
-	  ]
-libdeps_sequent = [ \
-	  ('*',		j(LIBINST, 'libreadline.a'), '-ltermcap'), \
-	  ('*',		'-lsocket'), \
-	  ('*',		'-linet'), \
-	  ('*',		'-lnsl'), \
-	  ('*',		'-lm'), \
-	  ('*',		'-lc'), \
-	  ]
-libdeps = eval('libdeps_' + ARCH)
-
-################################
-# END OF CONFIGURATION SECTION #
-################################
-
-# Exception used when scanfile fails
-NoSuchFile = 'NoSuchFile'
-
-# Global options
-quiet = 0				# -q
-verbose = 0				# -v
-noexec = 0				# -n
-nowrite = 0				# -N
-ofile = 'a.out'				# -o file
-
-# Main program -- argument parsing etc.
-def main():
-	global quiet, verbose, noexec, nowrite, ofile
-	try:
-		opts, args = getopt.getopt(sys.argv[1:], 'nNo:qv')
-	except getopt.error, msg:
-		usage(str(msg))
-		sys.exit(2)
-	for o, a in opts:
-		if o == '-n': noexec = 1
-		if o == '-N': nowrite = 1
-		if o == '-o': ofile = a
-		if o == '-q': verbose = 0; quiet = 1
-		if o == '-v': verbose = verbose + 1; quiet = 0
-	if len(args) < 1:
-		usage('please pass at least one file argument')
-		sys.exit(2)
-	process(args[0], args[1:])
-
-# Print usage message to stderr
-def usage(*msgs):
-	sys.stdout = sys.stderr
-	for msg in msgs: print msg
-	print 'Usage: freeze [options] scriptfile [modulefile ...]'
-	print '-n      : generate the files but don\'t compile and link'
-	print '-N      : don\'t write frozen.c (do compile unless -n given)'
-	print '-o file : binary output file (default a.out)'
-	print '-q      : quiet (no messages at all except errors)'
-	print '-v      : verbose (lots of extra messages)'
-
-# Process the script file
-def process(filename, addmodules):
-	global noexec
-	#
-	if not quiet: print 'Computing needed modules ...'
-	todo = {}
-	todo['__main__'] = filename
-	for name in addmodules:
-		mod = os.path.basename(name)
-		if mod[-3:] == '.py': mod = mod[:-3]
-		todo[mod] = name
-	try:
-		dict = closure(todo)
-	except NoSuchFile, filename:
-		sys.stderr.write('Can\'t open file %s\n' % filename)
-		sys.exit(1)
-	#
-	mods = dict.keys()
-	mods.sort()
-	#
-	if verbose:
-		print '%-15s %s' % ('Module', 'Filename')
-		for mod in mods:
-			print '%-15s %s' % (`mod`, dict[mod])
-	#
-	if not quiet: print 'Looking for dynamically linked modules ...'
-	dlmodules = []
-	objs = []
-	libs = []
-	for mod in mods:
-		if dict[mod][-2:] == '.o':
-			if verbose: print 'Found', mod, dict[mod]
-			dlmodules.append(mod)
-			objs.append(dict[mod])
-			libsname = dict[mod][:-2] + '.libs'
-			try:
-				f = open(libsname, 'r')
-			except IOError:
-				f = None
-			if f:
-				libtext = f.read()
-				f.close()
-				for lib in string.split(libtext):
-					if lib in libs: libs.remove(lib)
-					libs.append(lib)
-	#
-	if not nowrite:
-		if not quiet: print 'Writing frozen.c ...'
-		writefrozen('frozen.c', dict)
-	else:
-		if not quiet: print 'NOT writing frozen.c ...'
-	#
-##	if not dlmodules:
-	if 0:
-		config = CONFIG
-		if not quiet: print 'Using existing', config, '...'
-	else:
-		config = 'tmpconfig.c'
-		if nowrite:
-			if not quiet: print 'NOT writing config.c ...'
-		else:
-			if not quiet:
-				print 'Writing config.c with dl modules ...'
-			f = open(CONFIG_IN, 'r')
-			g = open(config, 'w')
-			m1 = regex.compile('-- ADDMODULE MARKER 1 --')
-			m2 = regex.compile('-- ADDMODULE MARKER 2 --')
-			builtinmodules = []
-			stdmodules = ('sys', '__main__', '__builtin__',
-				      'marshal')
-			todomodules = builtinmodules + dlmodules
-			for mod in dict.keys():
-				if dict[mod] == '<builtin>' and \
-					  mod not in stdmodules:
-					builtinmodules.append(mod)
-			while 1:
-				line = f.readline()
-				if not line: break
-				g.write(line)
-				if m1.search(line) >= 0:
-					if verbose: print 'Marker 1 ...'
-					for mod in todomodules:
-						g.write('extern void init' + \
-						  mod + '();\n')
-				if m2.search(line) >= 0:
-					if verbose: print 'Marker 2 ...'
-					for mod in todomodules:
-						g.write('{"' + mod + \
-						  '", init' + mod + '},\n')
-			g.close()
-	#
-	if not quiet:
-		if noexec: print 'Generating compilation commands ...'
-		else: print 'Starting compilation ...'
-	defs = ['-DNO_MAIN', '-DUSE_FROZEN', '-DPYTHONPATH=\'"."\'']
-	#
-	incs = ['-I.', '-I' + INCLINST]
-	if dict.has_key('stdwin'):
-		incs.append('-I' + j(STDWIN, 'H'))
-	#
-	srcs = [config, FMAIN]
-	#
-	if type(LIBP) == type(''):
-		libs.append(LIBP)
-	else:
-		for lib in LIBP:
-			libs.append(lib)
-	for item in libdeps:
-		m = item[0]
-		if m == '*' or dict.has_key(m):
-			for l in item[1:]:
-				if l in libs: libs.remove(l)
-				libs.append(l)
-	#
-	sts = 0
-	#
-	cmd = CC + ' -c'
-	cmd = cmd + ' ' + string.join(defs)
-	cmd = cmd + ' ' + string.join(incs)
-	cmd = cmd + ' ' + string.join(srcs)
-	print cmd
-	#
-	if not noexec:
-		sts = os.system(cmd)
-		if sts:
-			print 'Exit status', sts, '-- turning on -n'
-			noexec = 1
-	#
-	for s in srcs:
-		s = os.path.basename(s)
-		if s[-2:] == '.c': s = s[:-2]
-		o = s + '.o'
-		objs.insert(0, o)
-	#
-	cmd = CC
-	cmd = cmd + ' ' + string.join(objs)
-	cmd = cmd + ' ' + string.join(libs)
-	cmd = cmd + ' -o ' + ofile
-	print cmd
-	#
-	if not noexec:
-		sts = os.system(cmd)
-		if sts:
-			print 'Exit status', sts
-		else:
-			print 'Done.'
-	#
-	if not quiet and not noexec and sts == 0:
-		print 'Note: consider this:'; print '\tstrip', ofile
-	#
-	sys.exit(sts)
-
-
-# Generate code for a given module
-def makecode(filename):
-	if filename[-2:] == '.o':
-		return None
-	try:
-		f = open(filename, 'r')
-	except IOError:
-		return None
-	if verbose: print 'Making code from', filename, '...'
-	text = f.read()
-	code = compile(text, filename, 'exec')
-	f.close()
-	return marshal.dumps(code)
-
-
-# Write the C source file containing the frozen Python code
-def writefrozen(filename, dict):
-	f = open(filename, 'w')
-	codelist = []
-	for mod in dict.keys():
-		codestring = makecode(dict[mod])
-		if codestring is not None:
-			codelist.append((mod, codestring))
-	write = sys.stdout.write
-	save_stdout = sys.stdout
-	try:
-		sys.stdout = f
-		for mod, codestring in codelist:
-			if verbose:
-				write('Writing initializer for %s\n'%mod)
-			print 'static unsigned char M_' + mod + '[' + \
-				  str(len(codestring)) + '+1] = {'
-			for i in range(0, len(codestring), 16):
-				for c in codestring[i:i+16]:
-					print str(ord(c)) + ',',
-				print
-			print '};'
-		print 'struct frozen {'
-		print '  char *name;'
-		print '  unsigned char *code;'
-		print '  int size;'
-		print '} frozen_modules[] = {'
-		for mod, codestring in codelist:
-			print '  {"' + mod + '",',
-			print 'M_' + mod + ',',
-			print str(len(codestring)) + '},'
-		print '  {0, 0, 0} /* sentinel */'
-		print '};'
-	finally:
-		sys.stdout = save_stdout
-	f.close()
-
-
-# Determine the names and filenames of the modules imported by the
-# script, recursively.  This is done by scanning for lines containing
-# import statements.  (The scanning has only superficial knowledge of
-# Python syntax and no knowledge of semantics, so in theory the result
-# may be incorrect -- however this is quite unlikely if you don't
-# intentionally obscure your Python code.)
-
-# Compute the closure of scanfile() -- special first file because of script
-def closure(todo):
-	done = {}
-	while todo:
-		newtodo = {}
-		for modname in todo.keys():
-			if not done.has_key(modname):
-				filename = todo[modname]
-				if filename is None:
-					filename = findmodule(modname)
-				done[modname] = filename
-				if filename in ('<builtin>', '<unknown>'):
-					continue
-				modules = scanfile(filename)
-				for m in modules:
-					if not done.has_key(m):
-						newtodo[m] = None
-		todo = newtodo
-	return done
-
-# Scan a file looking for import statements
-importstr = '\(^\|:\)[ \t]*import[ \t]+\([a-zA-Z0-9_, \t]+\)'
-fromstr   = '\(^\|:\)[ \t]*from[ \t]+\([a-zA-Z0-9_]+\)[ \t]+import[ \t]+'
-isimport = regex.compile(importstr)
-isfrom = regex.compile(fromstr)
-def scanfile(filename):
-	allmodules = {}
-	try:
-		f = open(filename, 'r')
-	except IOError, msg:
-		raise NoSuchFile, filename
-	while 1:
-		line = f.readline()
-		if not line: break # EOF
-		while line[-2:] == '\\\n': # Continuation line
-			line = line[:-2] + ' '
-			line = line + f.readline()
-		if isimport.search(line) >= 0:
-			rawmodules = isimport.group(2)
-			modules = string.splitfields(rawmodules, ',')
-			for i in range(len(modules)):
-				modules[i] = string.strip(modules[i])
-		elif isfrom.search(line) >= 0:
-			modules = [isfrom.group(2)]
-		else:
-			continue
-		for mod in modules:
-			allmodules[mod] = None
-	f.close()
-	return allmodules.keys()
-
-# Find the file containing a module, given its name; None if not found
-builtins = sys.builtin_module_names + ['sys']
-def findmodule(modname):
-	if modname in builtins: return '<builtin>'
-	for dirname in sys.path:
-		dlfullname = os.path.join(dirname, modname + 'module.o')
-		try:
-			f = open(dlfullname, 'r')
-		except IOError:
-			f = None
-		if f:
-			f.close()
-			return dlfullname
-		fullname = os.path.join(dirname, modname + '.py')
-		try:
-			f = open(fullname, 'r')
-		except IOError:
-			continue
-		f.close()
-		return fullname
-	if not quiet:
-		sys.stderr.write('Warning: module %s not found\n' % modname)
-	return '<unknown>'
-
-
-# Call the main program
-main()

Demo/sgi/video/IN.py

-IPPROTO_IP = 0
-IPPROTO_ICMP = 1
-IPPROTO_IGMP = 2
-IPPROTO_GGP = 3
-IPPROTO_TCP = 6
-IPPROTO_EGP = 8
-IPPROTO_PUP = 12
-IPPROTO_UDP = 17
-IPPROTO_IDP = 22
-IPPROTO_TP = 29
-IPPROTO_XTP = 36
-IPPROTO_EON = 80
-IPPROTO_RAW = 255
-IPPROTO_MAX = 256
-IPPORT_RESERVED = 1024
-IPPORT_USERRESERVED = 5000
-IN_CLASSA_NET = 0xff000000
-IN_CLASSA_NSHIFT = 24
-IN_CLASSA_HOST = 0x00ffffff
-IN_CLASSA_MAX = 128
-IN_CLASSB_NET = 0xffff0000
-IN_CLASSB_NSHIFT = 16
-IN_CLASSB_HOST = 0x0000ffff
-IN_CLASSB_MAX = 65536
-IN_CLASSC_NET = 0xffffff00
-IN_CLASSC_NSHIFT = 8
-IN_CLASSC_HOST = 0x000000ff
-IN_CLASSD_NET = 0xf0000000
-IN_CLASSD_NSHIFT = 28
-IN_CLASSD_HOST = 0x0fffffff
-INADDR_ANY = 0x00000000
-INADDR_BROADCAST = 0xffffffff
-INADDR_LOOPBACK = 0x7F000001
-INADDR_UNSPEC_GROUP = 0xe0000000
-INADDR_ALLHOSTS_GROUP = 0xe0000001
-INADDR_MAX_LOCAL_GROUP = 0xe00000ff
-INADDR_NONE = 0xffffffff
-IN_LOOPBACKNET = 127
-IP_OPTIONS = 1
-IP_HDRINCL = 7
-IP_TOS = 8
-IP_TTL = 9
-IP_RECVOPTS = 10
-IP_RECVRETOPTS = 11
-IP_RECVDSTADDR = 12
-IP_RETOPTS = 13
-IP_MULTICAST_IF = 2
-IP_MULTICAST_TTL = 3
-IP_MULTICAST_LOOP = 4
-IP_ADD_MEMBERSHIP = 5
-IP_DROP_MEMBERSHIP = 6
-IP_DEFAULT_MULTICAST_TTL = 1
-IP_DEFAULT_MULTICAST_LOOP = 1
-IP_MAX_MEMBERSHIPS = 20

Demo/sgi/video/Makefile

-all:	v2i i2v
-
-v2i:	v2i.o
-	$(CC) v2i.o -limage -o v2i
-
-i2v:	i2v.o
-	$(CC) i2v.o -limage -o i2v

Demo/sgi/video/Vrecc.py

-#! /ufs/guido/bin/sgi/python-405
-#! /ufs/guido/bin/sgi/python
-
-# Capture a continuous CMIF movie using the Indigo video library and board
-
-
-# Usage:
-#
-# makemovie [-r rate] [-w width] [moviefile]
-
-
-# Options:
-#
-# -r rate       : capture 1 out of every 'rate' frames (default 1)
-# -w width      : initial window width (default interactive placement)
-# -d		: drop fields if needed
-# -g bits	: greyscale (2, 4 or 8 bits)
-# -G            : 2-bit greyscale dithered
-# -m		: monochrome dithered
-# -M value	: monochrome tresholded with value
-# -f		: Capture fields (in stead of frames)
-# -n number     : Capture 'number' fields (default 60)
-# 
-# moviefile     : here goes the movie data (default film.video);
-#                 the format is documented in cmif-film.ms
-
-
-# User interface:
-#
-# Start the application.  Resize the window to the desired movie size.
-# Press the left mouse button to start recording, release it to end
-# recording.  You can record as many times as you wish, but each time
-# you overwrite the output file(s), so only the last recording is
-# kept.
-#
-# Press ESC or select the window manager Quit or Close window option
-# to quit.  If you quit before recording anything, the output file(s)
-# are not touched.
-
-
-import sys
-sys.path.append('/ufs/guido/src/video')
-import sv, SV
-import VFile
-import gl, GL, DEVICE
-import al, AL
-import time
-import posix
-import getopt
-import string
-import imageop
-import sgi
-
-# Main program
-
-def main():
-	format = SV.RGB8_FRAMES
-	rate = 1
-	width = 0
-	drop = 0
-	mono = 0
-	grey = 0
-	greybits = 0
-	monotreshold = -1
-	fields = 0
-	number = 60
-
-	opts, args = getopt.getopt(sys.argv[1:], 'r:w:dg:mM:Gfn:')
-	for opt, arg in opts:
-		if opt == '-r':
-			rate = string.atoi(arg)
-			if rate < 2:
-				sys.stderr.write('-r rate must be >= 2\n')
-				sys.exit(2)
-		elif opt == '-w':
-			width = string.atoi(arg)
-		elif opt == '-d':
-			drop = 1
-		elif opt == '-g':
-			grey = 1
-			greybits = string.atoi(arg)
-			if not greybits in (2,4,8):
-				print 'Only 2, 4 or 8 bit greyscale supported'
-		elif opt == '-G':
-			grey = 1
-			greybits = -2
-		elif opt == '-m':
-			mono = 1
-		elif opt == '-M':
-			mono = 1
-			monotreshold = string.atoi(arg)
-		elif opt == '-f':
-			fields = 1
-		elif opt == '-n':
-			number = string.atoi(arg)
-
-	if args[2:]:
-		sys.stderr.write('usage: Vrec [options] [file]\n')
-		sys.exit(2)
-
-	if args:
-		filename = args[0]
-	else:
-		filename = 'film.video'
-
-	v = sv.OpenVideo()
-	# Determine maximum window size based on signal standard
-	param = [SV.BROADCAST, 0]
-	v.GetParam(param)
-	if param[1] == SV.PAL:
-		x = SV.PAL_XMAX
-		y = SV.PAL_YMAX
-	elif param[1] == SV.NTSC:
-		x = SV.NTSC_XMAX
-		y = SV.NTSC_YMAX
-	else:
-		print 'Unknown video standard', param[1]
-		sys.exit(1)
-
-	gl.foreground()
-	gl.maxsize(x, y)
-	gl.keepaspect(x, y)
-	gl.stepunit(8, 6)
-	if width:
-		gl.prefsize(width, width*3/4)
-	win = gl.winopen(filename)
-	if width:
-		gl.maxsize(x, y)
-		gl.keepaspect(x, y)
-		gl.stepunit(8, 6)
-		gl.winconstraints()
-	x, y = gl.getsize()
-	print x, 'x', y
-
-	v.SetSize(x, y)
-
-	if drop:
-		param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF]
-	else:
-		param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON]
-	if mono or grey:
-		param = param+[SV.COLOR, SV.MONO, SV.INPUT_BYPASS, 1]
-	else:
-		param = param+[SV.COLOR, SV.DEFAULT_COLOR, SV.INPUT_BYPASS, 0]
-	v.SetParam(param)
-
-	v.BindGLWindow(win, SV.IN_REPLACE)
-
-	gl.qdevice(DEVICE.LEFTMOUSE)
-	gl.qdevice(DEVICE.WINQUIT)
-	gl.qdevice(DEVICE.WINSHUT)
-	gl.qdevice(DEVICE.ESCKEY)
-
-	print 'Press left mouse to start recording'
-
-	while 1:
-		dev, val = gl.qread()
-		if dev == DEVICE.LEFTMOUSE:
-			if val == 1:
-				info = format, x, y, number, rate
-				record(v, info, filename, mono, grey, \
-					  greybits, monotreshold, fields)
-		elif dev == DEVICE.REDRAW:
-			# Window resize (or move)
-			x, y = gl.getsize()
-			print x, 'x', y
-			v.SetSize(x, y)
-			v.BindGLWindow(win, SV.IN_REPLACE)
-		elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT):
-			# Quit
-			v.CloseVideo()
-			gl.winclose(win)
-			break
-
-
-# Record until the mouse is released (or any other GL event)
-# XXX audio not yet supported
-
-def record(v, info, filename, mono, grey, greybits, monotreshold, fields):
-	import thread
-	format, x, y, number, rate = info
-	fps = 59.64 # Fields per second
-	# XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!)
-	tpf = 1000.0 / fps # Time per field in msec
-	#
-	# Go grab
-	#
-	gl.wintitle('(rec) ' + filename)
-	try:
-		ninfo, data, bitvec = v.CaptureBurst(info)
-	except sv.error, arg:
-		print 'CaptureBurst failed:', arg
-		print 'info:', info
-		gl.wintitle(filename)
-		return
-	gl.wintitle('(save) '+ filename)
-	#
-	# Check results
-	#
-	if info <> ninfo:
-		print 'Sorry, format changed.'
-		print 'Wanted:',info
-		print 'Got   :',ninfo
-		gl.wintitle(filename)
-		return
-	# print bitvec
-	if x*y*number <> len(data):
-		print 'Funny data length: wanted',x,'*',y,'*', number,'=',\
-			  x*y*number,'got',len(data)
-		gl.wintitle(filename)
-		return
-	#
-	# Save
-	#
-	if filename:
-		#
-		# Construct header and write it
-		#
-		vout = VFile.VoutFile().init(filename)
-		if mono:
-			vout.format = 'mono'
-		elif grey and greybits == 8:
-			vout.format = 'grey'
-		elif grey:
-			vout.format = 'grey'+`abs(greybits)`
-		else:
-			vout.format = 'rgb8'
-		vout.width = x
-		vout.height = y
-		if fields:
-			vout.packfactor = (1,-2)
-		else:
-			print 'Sorry, can only save fields at the moment'
-			gl.wintitle(filename)
-			return
-		vout.writeheader()
-		#
-		# Compute convertor, if needed
-		#
-		convertor = None
-		if grey:
-			if greybits == 2:
-				convertor = imageop.grey2grey2
-			elif greybits == 4:
-				convertor = imageop.grey2grey4
-			elif greybits == -2:
-				convertor = imageop.dither2grey2
-		fieldsize = x*y/2
-		nskipped = 0
-		realframeno = 0
-		tpf = 1000 / 50.0     #XXXX
-		for frameno in range(0, number*2):
-			if frameno <> 0 and \
-				  bitvec[frameno] == bitvec[frameno-1]:
-				nskipped = nskipped + 1
-				continue
-			#
-			# Save field.
-			# XXXX Works only for fields and top-to-bottom
-			#
-			start = frameno*fieldsize
-			field = data[start:start+fieldsize]
-			if convertor:
-				field = convertor(field, x, y)
-			elif mono and monotreshold >= 0:
-				field = imageop.grey2mono(field, x, y, \
-					  1, monotreshold)
-			elif mono:
-				field = imageop.dither2mono(field, x, y)
-			vout.writeframe(int(realframeno*tpf), field, None)
-		print 'Skipped',nskipped,'duplicate frames'
-		vout.close()
-			
-	gl.wintitle('(done) ' + filename)
-
-# Don't forget to call the main program
-
-try:
-	main()
-except KeyboardInterrupt:
-	print '[Interrupt]'

Demo/sgi/video/cam.py

-import sys
-from socket import *
-from gl import *
-from GL import *
-from DEVICE import *
-from time import millitimer
-
-HS = 40 # Header size (must be same as in tv.py)
-
-# Rely on UDP packet (de)fragmentation for smoother images
-# (Changed for broadcast)
-MAX = 16000
-
-PF = 2 # Default packfactor
-
-# Default receiver station is voorn.
-# Kwik has no yellow pages, so...
-HOST = '192.16.201.121'
-PORT = 5555
-
-if sys.argv[1:]:
-	PF = eval(sys.argv[1])
-
-if sys.argv[2:]:
-	HOST = sys.argv[2]
-	if HOST == 'all':
-		HOST = '<broadcast>'
-		MAX = 1400
-
-PF2 = PF*PF
-
-def main():
-	centerx, centery = 400, 300
-
-	foreground()
-	wid = winopen('cam')
-	RGBmode()
-	doublebuffer()
-	gconfig()
-	qdevice(ESCKEY)
-
-	w, h = getsize()
-	ortho2(0, w, 0, h)
-	w = w/PF*PF
-	h = h/PF*PF
-
-	readsource(SRC_FRAMEGRABBER)
-
-	s = socket(AF_INET, SOCK_DGRAM)
-	if HOST == '<broadcast>':
-		s.allowbroadcast(1)
-	addr = HOST, PORT
-
-	bytesperline = w/PF2
-	linesperchunk = MAX/bytesperline
-	linesperchunk = linesperchunk/PF*PF
-	nchunks = (h+linesperchunk-1)/linesperchunk
-
-	print 'MAX=', MAX,
-	print 'linesperchunk=', linesperchunk,
-	print 'nchunks=', nchunks,
-	print 'w=', w, 'h=', h
-
-	x1, x2 = 0, w-1
-
-	t1 = millitimer()
-	nframes = 0
-	fps = 0
-
-	msg = ''
-
-	while 1:
-		while qtest():
-			dev, val = qread()
-			if dev == REDRAW:
-				reshapeviewport()
-				w, h = getsize()
-				ortho2(0, w, 0, h)
-				w = w/PF*PF
-				h = h/PF*PF
-
-				bytesperline = w/PF2
-				linesperchunk = MAX/bytesperline
-				linesperchunk = linesperchunk/PF*PF
-				nchunks = (h+linesperchunk-1)/linesperchunk
-
-				print 'MAX=', MAX,
-				print 'linesperchunk=', linesperchunk,
-				print 'nchunks=', nchunks,
-				print 'w=', w, 'h=', h
-
-				x1, x2 = 0, w-1
-
-				fps = 0
-
-			elif dev == ESCKEY:
-				winclose(wid)
-				return
-
-		readsource(SRC_FRAMEGRABBER)
-
-		nframes = nframes+1
-		if nframes >= fps:
-			t2 = millitimer()
-			if t2 <> t1:
-				fps = int(10000.0*nframes/(t2-t1)) * 0.1
-				msg = `fps` +  ' frames/sec'
-				t1 = t2
-				nframes = 0
-
-		RGBcolor(255,255,255)
-		cmov2i(9,9)
-		charstr(msg)
-
-		swapbuffers()
-		rectcopy(centerx-w/2, centery-w/2, centerx+w/2, centery+w/2, 0, 0)
-
-		for i in range(nchunks):
-			y1 = i*linesperchunk
-			y2 = y1 + linesperchunk-1
-			if y2 >= h: y2 = h-1
-			data = lrectread(x1, y1, x2, y2)
-			data2 = packrect(x2-x1+1, y2-y1+1, PF, data)
-			prefix = `w, h, PF, x1, y1, x2, y2`
-			prefix = prefix + ' ' * (HS-len(prefix))
-			data3 = prefix + data2
-			s.sendto(data3, addr)
-
-main()

Demo/sgi/video/camcorder.py

-from gl import *
-from GL import *
-from DEVICE import *
-import time
-import sys
-import getopt
-import socket
-import posix
-import vtime
-
-# Preallocation parameter
-PREALLOC = 4 # Megabyte
-
-# Sync audio parameters
-SYNCPORT = 10000
-CTLPORT = 10001
-
-from vpregs import *
-
-class Struct(): pass
-epoch = Struct()
-
-def getvideosize():
-    w = getvideo(VP_WIDTH)
-    h = getvideo(VP_HEIGHT)
-    print 'WIDTH,HEIGHT:', w, h
-    print 'GB{X,Y}ORG:', getvideo(VP_GBXORG), getvideo(VP_GBYORG)
-    print 'FB{X,Y}ORG:',  getvideo(VP_FBXORG), getvideo(VP_FBYORG)
-    x = 0
-    y = 0
-    return x,y,w,h
-
-framelist = []
-
-def prealloc(w, h):
-	nbytes = w*h*4
-	limit = PREALLOC*1024*1024
-	total = 0
-	list = []
-	print 'Prealloc to', PREALLOC, 'Megabytes...'
-	while total+nbytes <=  limit:
-		list.append('x'*nbytes)
-		total = total + nbytes
-	print 'Done.'
-
-def grabframe(f,x,y,w,h,pf):
-    readsource(SRC_FRONT)
-    if pf:
-    	w = w/pf*pf
-    	h = h/pf*pf
-    data = lrectread(x,y,x+w-1,y+h-1)
-    t = time.millitimer()-epoch.epoch
-    framelist.append(data, t)
-    readsource(SRC_FRAMEGRABBER)
-
-def saveframes(f, w, h, pf):
-	for data, t in framelist:
-		if pf:
-		    	w = w/pf*pf
-		    	h = h/pf*pf
-			data = packrect(w,h,pf,data)
-		f.write(`t` + ',' + `len(data)` + '\n')
-		f.write(data)
-	framelist[:] = []
-
-def saveframe(f,x,y,w,h,pf, notime):
-    readsource(SRC_FRONT)
-    if pf: