Commits

Anonymous committed 1efa7bc

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

Comments (0)

Files changed (419)

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/README

-Demonstrations of Python that use various features of the Silicon
-Graphics IRIS machines.
-
-al		Demonstrations of the audio capabilities of the
-		Indigo. Require the built-in module 'al'.  One program
-		also needs the build-in module 'fl' (the FORMS
-		library by Mark Overmars.)
-
-cd		Demonstrations of the CD-ROM player's audio interface,
-		built-in module 'cd'.
-
-flp		Demonstrations of using the 'flp' standard module,
-		which enables you to quickly create forms using the
-		'fl' built-in module (available if you use the FORMS
-		library by Mark Overmars).
-
-gl		Demonstrations of the Graphics Library (GL).
-		Require the built-in module 'gl'.
-
-sv		Demonstrations of the Indigo Video module.
-		Requires the built-in module 'sv'.  See also the
-		following directory.

Demo/sgi/al/README

-This directory contains programs using the "al" interface, which gives
-access to the most important parts of the SGI Audio Library for the
-Indigo and 4D/35.
-
-alwatch.py		Watch changes in device settings
-broadcast.py		Broadcast audio using UDP packets
-cmpaf.py		Compare different audio compression schemes (uses fl)
-intercom.py		2-way communication with another host (uses fl)
-playaiff.py		Play an AIFF file (as output by recordaiff)
-playback.py		Play raw audio data read from stdin
-playold.py		Play an audio file recorded by the old 4D/25 audio
-radio.py		Listen to UDP packets sent by broadcast.py
-rec_play.py		Repeatedly record and play back a sample
-record.py		Record raw audio data to stdout
-unicast.py		Like broadcast but sends to one host

Demo/sgi/al/alwatch.py

-import time
-import al, AL
-import string
-
-dev = AL.DEFAULT_DEVICE
-
-source_name = ['line', 'microphone', 'digital']
-
-params = al.queryparams(dev)
-for i in range(1, len(params), 2):
-	params[i] = -1
-while 1:
-	time.sleep(0.1)
-	old = params[:]
-	al.getparams(dev, params)
-	if params <> old:
-		for i in range(0, len(params), 2):
-			if params[i+1] <> old[i+1]:
-				name = al.getname(dev, params[i])
-				if params[i] == AL.INPUT_SOURCE:
-					if 0 <= old[i+1] < len(source_name):
-						oldval = source_name[old[i+1]]
-					else:
-						oldval = ''
-					newval = source_name[params[i+1]]
-				else:
-					oldval = `old[i+1]`
-					newval = `params[i+1]`
-				print string.ljust(name, 25),
-				print '(' + string.rjust(oldval, 10) + ')',
-				print '-->',
-				print string.rjust(newval, 10)
-		print

Demo/sgi/al/broadcast.py

-#! /usr/local/bin/python
-
-# broadcast [port]
-#
-# Broadcast audio input on the network as UDP packets;
-# they can be received on any SGI machine with "radio.py".
-# This uses the input sampling rate, input source etc. set by apanel.
-# It uses the default sample width and #channels (16 bit/sample stereo).
-# (This is 192,000 Bytes at a sampling speed of 48 kHz, or ~137
-# packets/second -- use with caution!!!)
-
-import sys, al
-from socket import *
-
-port = 5555
-if sys.argv[1:]: port = eval(sys.argv[1])
-
-s = socket(AF_INET, SOCK_DGRAM)
-s.allowbroadcast(1)
-
-p = al.openport('broadcast', 'r')
-
-address = '<broadcast>', port
-while 1:
-	# 700 samples equals 1400 bytes, or about the max packet size!
-	data = p.readsamps(700)
-	s.sendto(data, address)

Demo/sgi/al/cmpaf.py

-# Compare different audio compression schemes.
-#
-# This copies mono audio data from the input port to the output port,
-# and puts up a window with 4 toggle buttons:
-#
-# uLAW       : convert the data to uLAW and back
-# ADPCM      : convert the data to ADPCM and back
-# Difference : make only the difference between the converted and the
-#              original data audible
-# Exit       : quit from the program
-
-import fl
-import FL
-import flp
-import al
-import AL
-import audioop
-import sys
-
-class Cmpaf:
-	def __init__(self):
-		parsetree = flp.parse_form('cmpaf_form','form')
-		flp.create_full_form(self, parsetree)
-		c = al.newconfig()
-		c.setchannels(AL.MONO)
-		c.setqueuesize(1800)
-		self.iport = al.openport('cmpaf','r', c)
-		self.oport = al.openport('cmpaf','w', c)
-		self.do_adpcm = self.do_ulaw = self.do_diff = 0
-		self.acstate = None
-		self.form.show_form(FL.PLACE_SIZE, 1, 'compare audio formats')
-
-	def run(self):
-		while 1:
-			olddata = data = self.iport.readsamps(600)
-			if self.do_ulaw:
-				data = audioop.lin2ulaw(data, 2)
-				data = audioop.ulaw2lin(data, 2)
-			if self.do_adpcm:
-				data, nacstate = audioop.lin2adpcm(data, 2, \
-					  self.acstate)
-				data, dummy = audioop.adpcm2lin(data, 2, \
-					  self.acstate)
-				self.acstate = nacstate
-			if self.do_diff:
-				olddata = audioop.mul(olddata, 2, -1)
-				data = audioop.add(olddata, data, 2)
-			self.oport.writesamps(data)
-			fl.check_forms()
-
-	def cb_exit(self, *args):
-		sys.exit(0)
-
-	def cb_adpcm(self, obj, val):
-		self.do_adpcm = obj.get_button()
-
-	def cb_ulaw(self, obj, val):
-		self.do_ulaw = obj.get_button()
-
-	def cb_diff(self, obj, val):
-		self.do_diff = obj.get_button()
-
-cmpaf = Cmpaf()
-cmpaf.run()

Demo/sgi/al/cmpaf_form.fd

-Magic: 12321
-
-Internal Form Definition File
-    (do not change)
-
-Number of forms: 1
-
-=============== FORM ===============
-Name: form
-Width: 230.000000
-Height: 80.000000
-Number of Objects: 5
-
---------------------
-class: 1
-type: 1
-box: 0.000000 0.000000 230.000000 80.000000
-boxtype: 1
-colors: 47 47
-alignment: 4
-style: 0
-size: 11.000000
-lcol: 0
-label: 
-name: 
-callback: 
-argument: 
-
---------------------
-class: 12
-type: 1
-box: 10.000000 40.000000 100.000000 30.000000
-boxtype: 1
-colors: 39 3
-alignment: 4
-style: 0
-size: 11.000000
-lcol: 0
-label: uLAW
-name: ulawbutton
-callback: cb_ulaw
-argument: 0
-
---------------------
-class: 12
-type: 1
-box: 10.000000 10.000000 100.000000 30.000000
-boxtype: 1
-colors: 39 3
-alignment: 4
-style: 0
-size: 11.000000
-lcol: 0
-label: ADPCM
-name: adpcm_button
-callback: cb_adpcm
-argument: 0
-
---------------------
-class: 11
-type: 0
-box: 170.000000 10.000000 50.000000 20.000000
-boxtype: 1
-colors: 47 47
-alignment: 4
-style: 0
-size: 11.000000
-lcol: 0
-label: EXIT
-name: exit_button
-callback: cb_exit
-argument: 0
-
---------------------
-class: 12
-type: 1
-box: 120.000000 40.000000 100.000000 30.000000
-boxtype: 1
-colors: 39 3
-alignment: 4
-style: 0
-size: 11.000000
-lcol: 0
-label: Difference
-name: diffbutton
-callback: cb_diff
-argument: 0
-
-==============================
-create_the_forms

Demo/sgi/al/intercom.py

-# intercom -- use mike and headset to *talk* to a person on another host.
-# For SGI 4D/35 or Indigo running IRIX 4.0.
-# Uses 16 bit sampling at 16000 samples/sec, or 32000 bytes/sec,
-# tranmitted in 32 1000-byte UDP packets.  (In each direction!)
-#
-# usage:
-#	intercom hostname	- start talking to person on other host
-#	intercom -r hostname	- called remotely to do the setup
-
-from names import *
-import sys, time, posix, gl, fl, FL, al, AL, getopt, rand
-from socket import *
-
-# UDP port numbers used (one for each direction!)
-PORT1 = 51042
-PORT2 = PORT1+1
-
-# Figure out the user name
-try:
-	user = posix.environ['LOGNAME']
-except:
-	user = posix.environ['USER']
-
-# Debug flags (Implemented as a list; non-empty means debugging is on)
-debug = []
-
-def main():
-	remote = 0
-	opts, args = getopt.getopt(sys.argv[1:], 'rd')
-	for opt, arg in opts:
-		if opt == '-r': remote = 1
-		elif opt == '-d': debug.append(opt)
-	if len(args) <> 1:
-		msg = 'usage: intercom [-d] [-r] hostname'
-		msg = msg + ' (-r is for internal use only!)\n'
-		sys.stderr.write(msg)
-		sys.exit(2)
-	if remote:
-		server(args[0])
-	else:
-		client(args[0])
-
-def client(hostname):
-	print 'client starting'
-	cmd = 'rsh ' + hostname + ' "cd ' + AUDIODIR
-	cmd = cmd + '; DISPLAY=:0; export DISPLAY'
-	cmd = cmd + '; ' + PYTHON + ' intercom.py -r '
-	for flag in debug: cmd = cmd + flag + ' '
-	cmd = cmd + gethostname()
-	cmd = cmd + '"'
-	if debug: print cmd
-	pipe = posix.popen(cmd, 'r')
-	ack = 0
-	nak = 0
-	while 1:
-		line = pipe.readline()
-		if not line: break
-		sys.stdout.write('remote: ' + line)
-		if line == 'NAK\n':
-			nak = 1
-			break
-		elif line == 'ACK\n':
-			ack = 1
-			break
-	if nak:
-		print 'Remote user doesn\'t want to talk to you.'
-		return
-	if not ack:
-		print 'No acknowledgement (remote side crashed?).'
-		return
-	#
-	print 'Ready...'
-	#
-	s = socket(AF_INET, SOCK_DGRAM)
-	s.bind('', PORT2)
-	#
-	otheraddr = gethostbyname(hostname), PORT1
-	try:
-		try:
-			ioloop(s, otheraddr)
-		except KeyboardInterrupt:
-			log('client got intr')
-		except error:
-			log('client got error')
-	finally:
-		s.sendto('', otheraddr)
-		log('client finished sending empty packet to server')
-	#
-	log('client exit')
-	print 'Done.'
-
-def server(hostname):
-	print 'server starting'
-	sys.stdout.flush()
-	# 
-	if not remotedialog():
-		print 'NAK'
-		return
-	#
-	print 'ACK'
-	#
-	s = socket(AF_INET, SOCK_DGRAM)
-	s.bind('', PORT1)
-	#
-	# Close std{in,out,err} so rsh will exit; reopen them as dummies
-	#
-	sys.stdin.close()
-	sys.stdin = open('/dev/null', 'r')
-	sys.stdout.close()
-	sys.stdout = open('/dev/null', 'w')
-	sys.stderr.close()
-	if debug:
-		sys.stderr = open('/tmp/intercom.err', 'a')
-	else:
-		sys.stderr = open('/dev/null', 'w')
-	#
-	ioloop(s, (gethostbyname(hostname), PORT2))
-	log('server exit')
-	sys.exit(0)
-
-def remotedialog():
-	gl.foreground()
-	gl.ringbell()
-	m1 = user + ' wants to talk to you over the audio channel.'
-	m2 = 'If it\'s OK, put on your headset and click Yes.'
-	m3 = 'If you\'re too busy, click No.'
-	return fl.show_question(m1, m2, m3)
-
-def ioloop(s, otheraddr):
-	#
-	dev = AL.DEFAULT_DEVICE
-	params = al.queryparams(dev)
-	al.getparams(dev, params)
-	time.sleep(1)
-	saveparams = params[:]
-	for i in range(0, len(params), 2):
-		if params[i] in (AL.INPUT_RATE, AL.OUTPUT_RATE):
-			params[i+1] = AL.RATE_16000
-		elif params[i] == AL.INPUT_SOURCE:
-			params[i+1] = AL.INPUT_MIC
-	try:
-		al.setparams(dev, params)
-		ioloop1(s, otheraddr)
-	finally:
-		al.setparams(dev, saveparams)
-
-def ioloop1(s, otheraddr):
-	#
-	# Watch out! data is in bytes, but the port counts in samples,
-	# which are two bytes each (for 16-bit samples).
-	# Luckily, we use mono, else it would be worse (2 samples/frame...)
-	#
-	SAMPSPERBUF = 500
-	BYTESPERSAMP = 2 # AL.SAMPLE_16
-	BUFSIZE = BYTESPERSAMP*SAMPSPERBUF
-	QSIZE = 4*SAMPSPERBUF
-	#
-	config = al.newconfig()
-	config.setqueuesize(QSIZE)
-	config.setwidth(AL.SAMPLE_16)
-	config.setchannels(AL.MONO)
-	#
-	pid = posix.fork()
-	if pid:
-		# Parent -- speaker/headphones handler
-		log('parent started')
-		spkr = al.openport('spkr', 'w', config)
-		while 1:
-			data = s.recv(BUFSIZE)
-			if len(data) == 0:
-				# EOF packet
-				log('parent got empty packet; killing child')
-				posix.kill(pid, 15)
-				return
-			# Discard whole packet if we are too much behind
-			if spkr.getfillable() > len(data) / BYTESPERSAMP:
-				if len(debug) >= 2:
-					log('parent Q full; dropping packet')
-				spkr.writesamps(data)
-	else:
-		# Child -- microphone handler
-		log('child started')
-		try:
-		    try:
-			    mike = al.openport('mike', 'r', config)
-			    # Sleep a while to let the other side get started
-			    time.sleep(1)
-			    # Drain the queue before starting to read
-			    data = mike.readsamps(mike.getfilled())
-			    # Loop, sending packets from the mike to the net
-			    while 1:
-				    data = mike.readsamps(SAMPSPERBUF)
-				    s.sendto(data, otheraddr)
-		    except KeyboardInterrupt:
-			    log('child got interrupt; exiting')
-			    posix._exit(0)
-		    except error:
-			    log('child got error; exiting')
-			    posix._exit(1)
-		finally:
-			log('child got unexpected error; leaving w/ traceback')
-
-def log(msg):
-	if not debug: return
-	if type(msg) <> type(''):
-		msg = `msg`
-	
-	f = open('/tmp/intercom.log', 'a')
-	f.write(`sys.argv` + ' ' + `posix.getpid()` + ': ' + msg + '\n')
-	f.close()
-
-main()

Demo/sgi/al/listen.py

-# Listen to the input on host argv[1].
-
-import sys, al, AL, posix
-
-BUFSIZE = 2000
-QSIZE = 4000
-
-def main():
-	if len(sys.argv) <> 2:
-		sys.stderr.write('usage: ' + sys.argv[0] + ' hostname\n')
-		sys.exit(2)
-	hostname = sys.argv[1]
-	cmd = 'exec rsh </dev/null ' + hostname + \
-		' "cd /ufs/guido/mm/demo/audio; ' + \
-		'exec /ufs/guido/bin/sgi/python record.py"'
-	pipe = posix.popen(cmd, 'r')
-	config = al.newconfig()
-	config.setchannels(AL.MONO)
-	config.setqueuesize(QSIZE)
-	port = al.openport('', 'w', config)
-	while 1:
-		data = pipe.read(BUFSIZE)
-		if not data:
-			sts = pipe.close()
-			sys.stderr.write(sys.argv[0] + ': end of data\n')
-			if sts: sys.stderr.write('rsh exit status '+`sts`+'\n')
-			sys.exit(1)
-		port.writesamps(data)
-		del data
-
-try:
-	main()
-except KeyboardInterrupt:
-	sys.exit(1)

Demo/sgi/al/names.py

-import sys
-
-# My home directory/
-GUIDO = '/ufs/guido/'
-
-# Hack sys.path so AL can be found
-LIB = GUIDO + 'lib/python'
-if LIB not in sys.path: sys.path.insert(0, LIB)
-
-# Python binary to be used on remote machine
-PYTHON = GUIDO + 'bin/sgi/python'
-
-# Directory where the programs live
-AUDIODIR = GUIDO + 'src/python/demo/sgi/al'

Demo/sgi/al/playaiff.py

-import aiff
-import al
-import sys
-import time
-
-def main():
-	v = 1
-	c = al.newconfig()
-	nchannels = c.getchannels()
-	nsampframes = 0 # ???
-	sampwidth = c.getwidth()
-	samprate = 0.0 # unknown
-	filename = sys.argv[1]
-	f = open(filename, 'r')
-	type, totalsize = aiff.read_chunk_header(f)
-	if type <> 'FORM':
-		raise aiff.Error, 'FORM chunk expected at start of file'
-	aiff.read_form_chunk(f)
-	while 1:
-		try:
-			type, size = aiff.read_chunk_header(f)
-		except EOFError:
-			break
-		if v: print 'header:', `type`, size
-		if type == 'COMM':
-			nchannels, nsampframes, sampwidth, samprate = \
-				aiff.read_comm_chunk(f)
-			if v: print nchannels, nsampframes, sampwidth, samprate
-		elif type == 'SSND':
-			offset, blocksize = aiff.read_ssnd_chunk(f)
-			if v: print offset, blocksize
-			data = f.read(size-8)
-			if size%2: void = f.read(1)
-			p = makeport(nchannels, sampwidth, samprate)
-			play(p, data, offset, blocksize)
-		elif type in aiff.skiplist:
-			aiff.skip_chunk(f, size)
-		else:
-			raise aiff.Error, 'bad chunk type ' + type
-
-def makeport(nchannels, sampwidth, samprate):
-	c = al.newconfig()
-	c.setchannels(nchannels)
-	c.setwidth(sampwidth/8)
-	# can't set the rate...
-	p = al.openport('', 'w', c)
-	return p
-
-def play(p, data, offset, blocksize):
-	data = data[offset:]
-	p.writesamps(data)
-	while p.getfilled() > 0: time.sleep(0.01)
-
-main()

Demo/sgi/al/playback.py

-# Read mono 16bit samples from stdin and write them to the audio device.
-# Assume the sampling rate is compatible.
-# Use a small queue size to minimize delays.
-
-import al, sys
-import AL
-
-BUFSIZE = 2000
-QSIZE = 4000
-
-def main():
-	c = al.newconfig()
-	c.setchannels(AL.MONO)
-	c.setqueuesize(QSIZE)
-	p = al.openport('', 'w', c)
-	while 1:
-		data = sys.stdin.read(BUFSIZE)
-		p.writesamps(data)
-
-try:
-	main()
-except KeyboardInterrupt:
-	sys.exit(1)

Demo/sgi/al/playold.py

-# Play old style sound files (Guido's private format)
-
-import al, sys, time
-import AL
-
-BUFSIZE = 8000
-
-def main():
-	if len(sys.argv) < 2:
-		f = sys.stdin
-		filename = sys.argv[0]
-	else:
-		if len(sys.argv) <> 2:
-			sys.stderr.write('usage: ' + \
-					 sys.argv[0] + ' filename\n')
-			sys.exit(2)
-		filename = sys.argv[1]
-		f = open(filename, 'r')
-	#
-	magic = f.read(4)
-	extra = ''
-	if magic == '0008':
-		rate = 8000
-	elif magic == '0016':
-		rate = 16000
-	elif magic == '0032':
-		rate = 32000
-	else:
-		sys.stderr.write('no magic header; assuming 8k samples/sec.\n')
-		rate = 8000
-		extra = magic
-	#
-	pv = [AL.OUTPUT_RATE, rate]
-	al.setparams(AL.DEFAULT_DEVICE, pv)
-	c = al.newconfig()
-	c.setchannels(AL.MONO)
-	c.setwidth(AL.SAMPLE_8)
-	port = al.openport(filename, 'w', c)
-	if extra:
-		port.writesamps(extra)
-	while 1:
-		buf = f.read(BUFSIZE)
-		if not buf: break
-		port.writesamps(buf)
-	while port.getfilled() > 0:
-		time.sleep(0.1)
-
-try:
-	main()
-except KeyboardInterrupt:
-	sys.exit(1)

Demo/sgi/al/radio.py

-#! /usr/local/bin/python
-
-# radio [port]
-#
-# Receive audio packets broadcast by "broadcast.py" on another SGI machine.
-# Use apanel to set the output sampling rate to match that of the broadcast.
-
-import sys, al
-from socket import *
-
-port = 5555
-if sys.argv[1:]: port = eval(sys.argv[1])
-
-s = socket(AF_INET, SOCK_DGRAM)
-s.bind('', port)
-
-p = al.openport('radio', 'w')
-
-while 1:
-	data = s.recv(1400)
-	p.writesamps(data)

Demo/sgi/al/rec_play.py

-#
-# records an AIFF sample and plays it
-# infinity number of times.
-#
-
-import time
-import al
-
-def recordit () :
-	p = al.openport('hello', 'r')
-	print 'recording...'
-	buf = p.readsamps(500000)
-	print 'done.'
-	p.closeport()
-	
-	return buf
-
-def playit (buf) :
-	p = al.openport('hello', 'w')
-	print 'playing...'
-	p.writesamps(buf)
-	while p.getfilled() > 0:
-		time.sleep(0.01)
-	print 'done.'
-	p.closeport()
-
-while 1 :
-	playit (recordit ())

Demo/sgi/al/record.py

-# Record mono 16bits samples from the audio device and send them to stdout.
-# Assume the sampling rate is compatible.
-# Use a small queue size to minimize delays.
-
-import al, sys
-import AL
-
-BUFSIZE = 2000
-QSIZE = 4000
-
-def main():
-	c = al.newconfig()
-	c.setchannels(AL.MONO)
-	c.setqueuesize(QSIZE)
-	p = al.openport('', 'r', c)
-	while 1:
-		data = p.readsamps(BUFSIZE)
-		sys.stdout.write(data)
-
-try:
-	main()
-except KeyboardInterrupt:
-	sys.exit(1)

Demo/sgi/al/unicast.py

-#! /usr/local/bin/python
-
-# unicast host [port]
-#
-# Similar to "broadcast.py" but sends to a specific host only;
-# use "radio.py" on the designated host to receive.
-# This is less stressful on other hosts on the same ethernet segment
-# if you need to send to one host only.
-
-import sys, al
-from socket import *
-
-host = sys.argv[1]
-
-port = 5555
-if sys.argv[2:]: port = eval(sys.argv[1])
-
-s = socket(AF_INET, SOCK_DGRAM)
-
-p = al.openport('unicast', 'r')
-
-address = host, port
-while 1:
-	# 700 samples equals 1400 bytes, or about the max packet size!
-	data = p.readsamps(700)
-	s.sendto(data, address)

Demo/sgi/al/x.py

-# Demonstrate that rsh exits when the remote end closes std{in,out,err}.
-# rsh voorn exec /ufs/guido/bin/sgi/python /ufs/guido/mm/demo/audio/x.py
-
-print 'hoi!'
-import sys
-sys.stdin.close()
-sys.stdout.close()
-sys.stderr.close()
-import time
-time.sleep(5)
-sys.stdout = open('@', 'w')
-sys.stdout.write('Hello\n')

Demo/sgi/audio/README

-Programs that demonstrate the use of the audio device on the SGI 4D/25.
-These require the built-in module 'audio'.
-
-XXX This hardware is already obsolete; see ../al for examples of audio
-XXX on the Indigo and 4D/35.
-
-play		Read a sound sample from a file and play it through the
-		speaker.  Options to set volume, sampling rate etc.

Demo/sgi/audio/play.py

-#! /usr/local/python
-
-import sys
-import audio
-
-import string
-import getopt
-import auds
-
-debug = []
-
-DEF_RATE = 3
-
-def main():
-	#
-	gain = 100
-	rate = 0
-	starter = audio.write
-	stopper = 0
-	#
-	optlist, args = getopt.getopt(sys.argv[1:], 'adg:r:')
-	#
-	for optname, optarg in optlist:
-		if 0:
-			pass
-		elif optname == '-d':
-			debug.append(1)
-		elif optname == '-g':
-			gain = string.atoi(optarg)
-			if not (0 < gain < 256):
-				raise optarg.error, '-g gain out of range'
-		elif optname == '-r':
-			rate = string.atoi(optarg)
-			if not (1 <= rate <= 3):
-				raise optarg.error, '-r rate out of range'
-		elif optname == '-a':
-			starter = audio.start_playing
-			stopper = audio.wait_playing
-	#
-	audio.setoutgain(gain)
-	audio.setrate(rate)
-	#
-	if not args:
-		play(starter, rate, auds.loadfp(sys.stdin))
-	else:
-		real_stopper = 0
-		for file in args:
-			if real_stopper:
-				real_stopper()
-			play(starter, rate, auds.load(file))
-			real_stopper = stopper
-
-def play(starter, rate, data):
-	magic = data[:4]
-	if magic == '0008':
-		mrate = 3
-	elif magic == '0016':
-		mrate = 2
-	elif magic == '0032':
-		mrate = 1
-	else:
-		mrate = 0
-	if mrate:
-		data = data[4:]
-	else:
-		mrate = DEF_RATE
-	if not rate: rate = mrate
-	audio.setrate(rate)
-	starter(data)
-
-try:
-	main()
-finally:
-	audio.setoutgain(0)
-	audio.done()

Demo/sgi/audio_stdwin/README

-Three programs that provide a user interface based upon STDWIN to the
-audio device of the SGI 4D/25.  These scripts also demonstrate the power
-of a set of window interface classes implemented in Python that simplify
-the construction of all sorts of buttons, etc.
-
-XXX This hardware is already obsolete; see ../al for examples of audio
-XXX on the Indigo and 4D/35.
-
-jukebox		Browses a directory full of sound samples and lets you
-		play selected ones.  (Probably not fully functional, it
-		requires a conversion program.)
-
-rec		A tape recorder that lets you record a sound sample,
-		play it back, and save it to a file.  Various options to
-		set sampling rate, volume etc.  When idle it doubles
-		as a VU meter.
-
-vumeter		A VU meter that displays a history of the volume of
-		sound recently sampled from the microphone.

Demo/sgi/audio_stdwin/jukebox.py

-#! /usr/local/python
-
-# JUKEBOX: browse directories full of sampled sound files.
-#
-# One or more "list windows" display the files and subdirectories of
-# the arguments.  Double-clicking on a subdirectory opens a new window
-# displaying its contents (and so on recursively).  Double clicking
-# on a file plays it as a sound file (assuming it is one).
-#
-# Playing is asynchronous: the application keeps listening to events
-# while the sample is playing, so you can change the volume (gain)
-# during playing, cancel playing or start a new sample right away.
-#
-# The control window displays the current output gain and a primitive
-# "stop button" to cancel the current play request.
-#
-# Sound files must currently be in Dik Winter's compressed Mac format.
-# Since decompression is costly, decompressed samples are saved in
-# /usr/tmp/@j* until the application is left.  The files are read
-# afresh each time, though.
-
-import audio
-import sunaudio
-import commands
-import getopt
-import path
-import posix
-import rand
-import stdwin
-from stdwinevents import *
-import string
-import sys
-
-from WindowParent import WindowParent
-from HVSplit import VSplit
-from Buttons import PushButton
-from Sliders import ComplexSlider
-
-# Pathnames
-
-HOME_BIN_SGI = '/ufs/guido/bin/sgi/'	# Directory where macsound2sgi lives
-DEF_DB = '/ufs/dik/sounds/Mac/HCOM'	# Default directory of sounds
-
-
-# Global variables
-
-class struct: pass		# Class to define featureless structures
-
-G = struct()			# Holds writable global variables
-
-
-# Main program
-
-def main():
-	G.synchronous = 0	# If set, use synchronous audio.write()
-	G.debug = 0		# If set, print debug messages
-	G.gain = 75		# Output gain
-	G.rate = 3		# Sampling rate
-	G.busy = 0		# Set while asynchronous playing is active
-	G.windows = []		# List of open windows (except control)
-	G.mode = 'mac'		# Macintosh mode
-	G.tempprefix = '/usr/tmp/@j' + `rand.rand()` + '-'
-	#
-	optlist, args = getopt.getopt(sys.argv[1:], 'dg:r:sSa')
-	for optname, optarg in optlist:
-		if   optname == '-d':
-			G.debug = 1
-		elif optname == '-g':
-			G.gain = string.atoi(optarg)
-			if not (0 < G.gain < 256):
-				raise optarg.error, '-g gain out of range'
-		elif optname == '-r':
-			G.rate = string.atoi(optarg)
-			if not (1 <= G.rate <= 3):
-				raise optarg.error, '-r rate out of range'
-		elif optname == '-s':
-			G.synchronous = 1
-		elif optname == '-S':
-			G.mode = 'sgi'
-		elif optname == '-a':
-			G.mode = 'sun'
-	#
-	if not args:
-		args = [DEF_DB]
-	#
-	G.cw = opencontrolwindow()
-	for dirname in args:
-		G.windows.append(openlistwindow(dirname))
-	#
-	#
-	savegain = audio.getoutgain()
-	try:
-		# Initialize stdaudio
-		audio.setoutgain(0)
-		audio.start_playing('')
-		dummy = audio.wait_playing()
-		audio.setoutgain(0)
-		maineventloop()
-	finally:
-		audio.setoutgain(savegain)
-		audio.done()
-		clearcache()
-
-def maineventloop():
-	mouse_events = WE_MOUSE_DOWN, WE_MOUSE_MOVE, WE_MOUSE_UP
-	while G.windows:
-		type, w, detail = event = stdwin.getevent()
-		if w == G.cw.win:
-			if type == WE_CLOSE:
-				return
-			G.cw.dispatch(event)
-		else:
-			if type == WE_DRAW:
-				w.drawproc(w, detail)
-			elif type in mouse_events:
-				w.mouse(w, type, detail)
-			elif type == WE_CLOSE:
-				w.close(w)
-				del w, event
-			else:
-				if G.debug: print type, w, detail
-
-# Control window -- to set gain and cancel play operations in progress
-
-def opencontrolwindow():
-	cw = WindowParent().create('Jukebox', (0, 0))
-	v = VSplit().create(cw)
-	#
-	gain = ComplexSlider().define(v)
-	gain.setminvalmax(0, G.gain, 255)
-	gain.settexts('  ', '  ')
-	gain.sethook(gain_setval_hook)
-	#
-	stop = PushButton().definetext(v, 'Stop')
-	stop.hook = stop_hook
-	#
-	cw.realize()
-	return cw
-
-def gain_setval_hook(self):
-	G.gain = self.val
-	if G.busy: audio.setoutgain(G.gain)
-
-def stop_hook(self):
-	if G.busy:
-		audio.setoutgain(0)
-		dummy = audio.stop_playing()
-		G.busy = 0
-
-
-# List windows -- to display list of files and subdirectories
-
-def openlistwindow(dirname):
-	list = posix.listdir(dirname)
-	list.sort()
-	i = 0
-	while i < len(list):
-		if list[i] == '.' or list[i] == '..':
-			del list[i]
-		else:
-			i = i+1
-	for i in range(len(list)):
-		name = list[i]
-		if path.isdir(path.join(dirname, name)):
-			list[i] = list[i] + '/'
-	width = maxwidth(list)
-	width = width + stdwin.textwidth(' ')	# XXX X11 stdwin bug workaround
-	height = len(list) * stdwin.lineheight()
-	stdwin.setdefwinsize(width, min(height, 500))
-	w = stdwin.open(dirname)
-	stdwin.setdefwinsize(0, 0)
-	w.setdocsize(width, height)
-	w.drawproc = drawlistwindow
-	w.mouse = mouselistwindow
-	w.close = closelistwindow
-	w.dirname = dirname
-	w.list = list
-	w.selected = -1
-	return w
-
-def maxwidth(list):
-	width = 1
-	for name in list:
-		w = stdwin.textwidth(name)
-		if w > width: width = w
-	return width
-
-def drawlistwindow(w, area):
-	d = w.begindrawing()
-	d.erase((0, 0), (1000, 10000))
-	lh = d.lineheight()
-	h, v = 0, 0
-	for name in w.list:
-		d.text((h, v), name)
-		v = v + lh
-	showselection(w, d)
-
-def hideselection(w, d):
-	if w.selected >= 0:
-		invertselection(w, d)
-
-def showselection(w, d):
-	if w.selected >= 0:
-		invertselection(w, d)
-
-def invertselection(w, d):
-	lh = d.lineheight()
-	h1, v1 = p1 = 0, w.selected*lh
-	h2, v2 = p2 = 1000, v1 + lh
-	d.invert(p1, p2)
-
-def mouselistwindow(w, type, detail):
-	(h, v), clicks, button = detail[:3]
-	d = w.begindrawing()
-	lh = d.lineheight()
-	if 0 <= v < lh*len(w.list):
-		i = v / lh
-	else:
-		i = -1
-	if w.selected <> i:
-		hideselection(w, d)
-		w.selected = i
-		showselection(w, d)
-	if type == WE_MOUSE_DOWN and clicks >= 2 and i >= 0:
-		name = path.join(w.dirname, w.list[i])
-		if name[-1:] == '/':
-			if clicks == 2:
-				G.windows.append(openlistwindow(name[:-1]))
-		else:
-			playfile(name)
-
-def closelistwindow(w):
-	remove(G.windows, w)
-
-def remove(list, item):
-	for i in range(len(list)):
-		if list[i] == item:
-			del list[i]
-			break
-
-
-# Playing tools
-
-cache = {}
-
-def clearcache():
-	for x in cache.keys():
-		try:
-			sts = posix.system('rm -f ' + cache[x])
-			if sts:
-				print cmd
-				print 'Exit status', sts
-		except:
-			print cmd
-			print 'Exception?!'
-		del cache[x]
-
-def playfile(name):
-	if G.mode <> 'mac':
-		tempname = name
-	elif cache.has_key(name):
-		tempname = cache[name]
-	else:
-		tempname = G.tempprefix + `rand.rand()`
-		cmd = HOME_BIN_SGI + 'macsound2sgi'
-		cmd = cmd + ' ' + commands.mkarg(name)
-		cmd = cmd + ' >' + tempname
-		if G.debug: print cmd
-		sts = posix.system(cmd)
-		if sts:
-			print cmd
-			print 'Exit status', sts
-			stdwin.fleep()
-			return
-		cache[name] = tempname
-	fp = open(tempname, 'r')
-	try:
-		hdr = sunaudio.gethdr(fp)
-	except sunaudio.error, msg:
-		hdr = ()
-	if hdr:
-		data_size = hdr[0]
-		data = fp.read(data_size)
-		# XXX this doesn't work yet, need to convert from uLAW!!!
-		del fp