code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
# Generated from 'OSA.h'
def FOUR_CHAR_CODE(x): return x
from Carbon.AppleEvents import *
kAEUseStandardDispatch = -1
kOSAComponentType = FOUR_CHAR_CODE('osa ')
kOSAGenericScriptingComponentSubtype = FOUR_CHAR_CODE('scpt')
kOSAFileType = FOUR_CHAR_CODE('osas')
kOSASuite = FOUR_CHAR_CODE('ascr')
kOSARecordedText = FOUR_CHAR_CODE('recd')
kOSAScriptIsModified = FOUR_CHAR_CODE('modi')
kOSAScriptIsTypeCompiledScript = FOUR_CHAR_CODE('cscr')
kOSAScriptIsTypeScriptValue = FOUR_CHAR_CODE('valu')
kOSAScriptIsTypeScriptContext = FOUR_CHAR_CODE('cntx')
kOSAScriptBestType = FOUR_CHAR_CODE('best')
kOSACanGetSource = FOUR_CHAR_CODE('gsrc')
typeOSADialectInfo = FOUR_CHAR_CODE('difo')
keyOSADialectName = FOUR_CHAR_CODE('dnam')
keyOSADialectCode = FOUR_CHAR_CODE('dcod')
keyOSADialectLangCode = FOUR_CHAR_CODE('dlcd')
keyOSADialectScriptCode = FOUR_CHAR_CODE('dscd')
kOSANullScript = 0L
kOSANullMode = 0
kOSAModeNull = 0
kOSASupportsCompiling = 0x0002
kOSASupportsGetSource = 0x0004
kOSASupportsAECoercion = 0x0008
kOSASupportsAESending = 0x0010
kOSASupportsRecording = 0x0020
kOSASupportsConvenience = 0x0040
kOSASupportsDialects = 0x0080
kOSASupportsEventHandling = 0x0100
kOSASelectLoad = 0x0001
kOSASelectStore = 0x0002
kOSASelectExecute = 0x0003
kOSASelectDisplay = 0x0004
kOSASelectScriptError = 0x0005
kOSASelectDispose = 0x0006
kOSASelectSetScriptInfo = 0x0007
kOSASelectGetScriptInfo = 0x0008
kOSASelectSetActiveProc = 0x0009
kOSASelectGetActiveProc = 0x000A
kOSASelectScriptingComponentName = 0x0102
kOSASelectCompile = 0x0103
kOSASelectCopyID = 0x0104
kOSASelectCopyScript = 0x0105
kOSASelectGetSource = 0x0201
kOSASelectCoerceFromDesc = 0x0301
kOSASelectCoerceToDesc = 0x0302
kOSASelectSetSendProc = 0x0401
kOSASelectGetSendProc = 0x0402
kOSASelectSetCreateProc = 0x0403
kOSASelectGetCreateProc = 0x0404
kOSASelectSetDefaultTarget = 0x0405
kOSASelectStartRecording = 0x0501
kOSASelectStopRecording = 0x0502
kOSASelectLoadExecute = 0x0601
kOSASelectCompileExecute = 0x0602
kOSASelectDoScript = 0x0603
kOSASelectSetCurrentDialect = 0x0701
kOSASelectGetCurrentDialect = 0x0702
kOSASelectAvailableDialects = 0x0703
kOSASelectGetDialectInfo = 0x0704
kOSASelectAvailableDialectCodeList = 0x0705
kOSASelectSetResumeDispatchProc = 0x0801
kOSASelectGetResumeDispatchProc = 0x0802
kOSASelectExecuteEvent = 0x0803
kOSASelectDoEvent = 0x0804
kOSASelectMakeContext = 0x0805
kOSADebuggerCreateSession = 0x0901
kOSADebuggerGetSessionState = 0x0902
kOSADebuggerSessionStep = 0x0903
kOSADebuggerDisposeSession = 0x0904
kOSADebuggerGetStatementRanges = 0x0905
kOSADebuggerGetBreakpoint = 0x0910
kOSADebuggerSetBreakpoint = 0x0911
kOSADebuggerGetDefaultBreakpoint = 0x0912
kOSADebuggerGetCurrentCallFrame = 0x0906
kOSADebuggerGetCallFrameState = 0x0907
kOSADebuggerGetVariable = 0x0908
kOSADebuggerSetVariable = 0x0909
kOSADebuggerGetPreviousCallFrame = 0x090A
kOSADebuggerDisposeCallFrame = 0x090B
kOSADebuggerCountVariables = 0x090C
kOSASelectComponentSpecificStart = 0x1001
kOSAModePreventGetSource = 0x00000001
kOSAModeNeverInteract = kAENeverInteract
kOSAModeCanInteract = kAECanInteract
kOSAModeAlwaysInteract = kAEAlwaysInteract
kOSAModeDontReconnect = kAEDontReconnect
kOSAModeCantSwitchLayer = 0x00000040
kOSAModeDoRecord = 0x00001000
kOSAModeCompileIntoContext = 0x00000002
kOSAModeAugmentContext = 0x00000004
kOSAModeDisplayForHumans = 0x00000008
kOSAModeDontStoreParent = 0x00010000
kOSAModeDispatchToDirectObject = 0x00020000
kOSAModeDontGetDataForArguments = 0x00040000
kOSAScriptResourceType = kOSAGenericScriptingComponentSubtype
typeOSAGenericStorage = kOSAScriptResourceType
kOSAErrorNumber = keyErrorNumber
kOSAErrorMessage = keyErrorString
kOSAErrorBriefMessage = FOUR_CHAR_CODE('errb')
kOSAErrorApp = FOUR_CHAR_CODE('erap')
kOSAErrorPartialResult = FOUR_CHAR_CODE('ptlr')
kOSAErrorOffendingObject = FOUR_CHAR_CODE('erob')
kOSAErrorExpectedType = FOUR_CHAR_CODE('errt')
kOSAErrorRange = FOUR_CHAR_CODE('erng')
typeOSAErrorRange = FOUR_CHAR_CODE('erng')
keyOSASourceStart = FOUR_CHAR_CODE('srcs')
keyOSASourceEnd = FOUR_CHAR_CODE('srce')
kOSAUseStandardDispatch = kAEUseStandardDispatch
kOSANoDispatch = kAENoDispatch
kOSADontUsePhac = 0x0001
eNotStarted = 0
eRunnable = 1
eRunning = 2
eStopped = 3
eTerminated = 4
eStepOver = 0
eStepIn = 1
eStepOut = 2
eRun = 3
eLocal = 0
eGlobal = 1
eProperties = 2
keyProgramState = FOUR_CHAR_CODE('dsps')
typeStatementRange = FOUR_CHAR_CODE('srng')
keyProcedureName = FOUR_CHAR_CODE('dfnm')
keyStatementRange = FOUR_CHAR_CODE('dfsr')
keyLocalsNames = FOUR_CHAR_CODE('dfln')
keyGlobalsNames = FOUR_CHAR_CODE('dfgn')
keyParamsNames = FOUR_CHAR_CODE('dfpn')
| Python |
from _Help import *
| Python |
from _Mlte import *
| Python |
try:
from OverrideFrom23._Res import *
except ImportError:
from _Res import *
| Python |
# Generated from 'IBCarbonRuntime.h'
kIBCarbonRuntimeCantFindNibFile = -10960
kIBCarbonRuntimeObjectNotOfRequestedType = -10961
kIBCarbonRuntimeCantFindObject = -10962
| Python |
from _Menu import *
| Python |
"""terminalcommand.py -- A minimal interface to Terminal.app.
To run a shell command in a new Terminal.app window:
import terminalcommand
terminalcommand.run("ls -l")
No result is returned; it is purely meant as a quick way to run a script
with a decent input/output window.
"""
#
# This module is a fairly straightforward translation of Jack Jansen's
# Mac/OSX/PythonLauncher/doscript.m.
#
import time
import os
from Carbon import AE
from Carbon.AppleEvents import *
TERMINAL_SIG = "trmx"
START_TERMINAL = "/usr/bin/open /Applications/Utilities/Terminal.app"
SEND_MODE = kAENoReply # kAEWaitReply hangs when run from Terminal.app itself
def run(command):
"""Run a shell command in a new Terminal.app window."""
termAddress = AE.AECreateDesc(typeApplSignature, TERMINAL_SIG)
theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress,
kAutoGenerateReturnID, kAnyTransactionID)
commandDesc = AE.AECreateDesc(typeChar, command)
theEvent.AEPutParamDesc(kAECommandClass, commandDesc)
try:
theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
except AE.Error, why:
if why[0] != -600: # Terminal.app not yet running
raise
os.system(START_TERMINAL)
time.sleep(1)
theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
if __name__ == "__main__":
run("ls -l")
| Python |
"""codefragments.py -- wrapper to modify code fragments."""
# (c) 1998, Just van Rossum, Letterror
__version__ = "0.8b3"
__author__ = "jvr"
import Carbon.File
import struct
from Carbon import Res
import os
import sys
DEBUG = 0
error = "cfm.error"
BUFSIZE = 0x80000
def mergecfmfiles(srclist, dst, architecture = 'fat'):
"""Merge all files in srclist into a new file dst.
If architecture is given, only code fragments of that type will be used:
"pwpc" for PPC, "m68k" for cfm68k. This does not work for "classic"
68k code, since it does not use code fragments to begin with.
If architecture is None, all fragments will be used, enabling FAT binaries.
"""
srclist = list(srclist)
for i in range(len(srclist)):
srclist[i] = Carbon.File.pathname(srclist[i])
dst = Carbon.File.pathname(dst)
dstfile = open(dst, "wb")
rf = Res.FSpOpenResFile(dst, 3)
try:
dstcfrg = CfrgResource()
for src in srclist:
srccfrg = CfrgResource(src)
for frag in srccfrg.fragments:
if frag.architecture == 'pwpc' and architecture == 'm68k':
continue
if frag.architecture == 'm68k' and architecture == 'pwpc':
continue
dstcfrg.append(frag)
frag.copydata(dstfile)
cfrgres = Res.Resource(dstcfrg.build())
Res.UseResFile(rf)
cfrgres.AddResource('cfrg', 0, "")
finally:
dstfile.close()
rf = Res.CloseResFile(rf)
class CfrgResource:
def __init__(self, path = None):
self.version = 1
self.fragments = []
self.path = path
if path is not None and os.path.exists(path):
currentresref = Res.CurResFile()
resref = Res.FSpOpenResFile(path, 1)
Res.UseResFile(resref)
try:
try:
data = Res.Get1Resource('cfrg', 0).data
except Res.Error:
raise Res.Error, "no 'cfrg' resource found", sys.exc_traceback
finally:
Res.CloseResFile(resref)
Res.UseResFile(currentresref)
self.parse(data)
if self.version <> 1:
raise error, "unknown 'cfrg' resource format"
def parse(self, data):
(res1, res2, self.version,
res3, res4, res5, res6,
self.memberCount) = struct.unpack("8l", data[:32])
data = data[32:]
while data:
frag = FragmentDescriptor(self.path, data)
data = data[frag.memberSize:]
self.fragments.append(frag)
def build(self):
self.memberCount = len(self.fragments)
data = struct.pack("8l", 0, 0, self.version, 0, 0, 0, 0, self.memberCount)
for frag in self.fragments:
data = data + frag.build()
return data
def append(self, frag):
self.fragments.append(frag)
class FragmentDescriptor:
def __init__(self, path, data = None):
self.path = path
if data is not None:
self.parse(data)
def parse(self, data):
self.architecture = data[:4]
( self.updatelevel,
self.currentVersion,
self.oldDefVersion,
self.stacksize,
self.applibdir,
self.fragtype,
self.where,
self.offset,
self.length,
self.res1, self.res2,
self.memberSize,) = struct.unpack("4lhBB4lh", data[4:42])
pname = data[42:self.memberSize]
self.name = pname[1:1+ord(pname[0])]
def build(self):
data = self.architecture
data = data + struct.pack("4lhBB4l",
self.updatelevel,
self.currentVersion,
self.oldDefVersion,
self.stacksize,
self.applibdir,
self.fragtype,
self.where,
self.offset,
self.length,
self.res1, self.res2)
self.memberSize = len(data) + 2 + 1 + len(self.name)
# pad to 4 byte boundaries
if self.memberSize % 4:
self.memberSize = self.memberSize + 4 - (self.memberSize % 4)
data = data + struct.pack("hb", self.memberSize, len(self.name))
data = data + self.name
data = data + '\000' * (self.memberSize - len(data))
return data
def getfragment(self):
if self.where <> 1:
raise error, "can't read fragment, unsupported location"
f = open(self.path, "rb")
f.seek(self.offset)
if self.length:
frag = f.read(self.length)
else:
frag = f.read()
f.close()
return frag
def copydata(self, outfile):
if self.where <> 1:
raise error, "can't read fragment, unsupported location"
infile = open(self.path, "rb")
if self.length == 0:
infile.seek(0, 2)
self.length = infile.tell()
# Position input file and record new offset from output file
infile.seek(self.offset)
# pad to 16 byte boundaries
offset = outfile.tell()
if offset % 16:
offset = offset + 16 - (offset % 16)
outfile.seek(offset)
self.offset = offset
l = self.length
while l:
if l > BUFSIZE:
outfile.write(infile.read(BUFSIZE))
l = l - BUFSIZE
else:
outfile.write(infile.read(l))
l = 0
infile.close()
| Python |
"""icopen patch
OVERVIEW
icopen patches MacOS Python to use the Internet Config file mappings to select
the type and creator for a file.
Version 1 released to the public domain 3 November 1999
by Oliver Steele (steele@cs.brandeis.edu).
DETAILS
This patch causes files created by Python's open(filename, 'w') command (and
by functions and scripts that call it) to set the type and creator of the file
to the type and creator associated with filename's extension (the
portion of the filename after the last period), according to Internet Config.
Thus, a script that creates a file foo.html will create one that opens in whatever
browser you've set to handle *.html files, and so on.
Python IDE uses its own algorithm to select the type and creator for saved
editor windows, so this patch won't effect their types.
As of System 8.6 at least, Internet Config is built into the system, and the
file mappings are accessed from the Advanced pane of the Internet control
panel. User Mode (in the Edit menu) needs to be set to Advanced in order to
access this pane.
INSTALLATION
Put this file in your Python path, and create a file named {Python}:sitecustomize.py
that contains:
import icopen
(If {Python}:sitecustomizer.py already exists, just add the 'import' line to it.)
The next time you launch PythonInterpreter or Python IDE, the patch will take
effect.
"""
import __builtin__
_builtin_open = globals().get('_builtin_open', __builtin__.open)
def _open_with_typer(*args):
file = _builtin_open(*args)
filename = args[0]
mode = 'r'
if args[1:]:
mode = args[1]
if mode[0] == 'w':
from ic import error, settypecreator
try:
settypecreator(filename)
except error:
pass
return file
__builtin__.open = _open_with_typer
"""
open('test.py')
_open_with_typer('test.py', 'w')
_open_with_typer('test.txt', 'w')
_open_with_typer('test.html', 'w')
_open_with_typer('test.foo', 'w')
"""
| Python |
"""Easy to use dialogs.
Message(msg) -- display a message and an OK button.
AskString(prompt, default) -- ask for a string, display OK and Cancel buttons.
AskPassword(prompt, default) -- like AskString(), but shows text as bullets.
AskYesNoCancel(question, default) -- display a question and Yes, No and Cancel buttons.
GetArgv(optionlist, commandlist) -- fill a sys.argv-like list using a dialog
AskFileForOpen(...) -- Ask the user for an existing file
AskFileForSave(...) -- Ask the user for an output file
AskFolder(...) -- Ask the user to select a folder
bar = Progress(label, maxvalue) -- Display a progress bar
bar.set(value) -- Set value
bar.inc( *amount ) -- increment value by amount (default=1)
bar.label( *newlabel ) -- get or set text label.
More documentation in each function.
This module uses DLOG resources 260 and on.
Based upon STDWIN dialogs with the same names and functions.
"""
from Carbon.Dlg import GetNewDialog, SetDialogItemText, GetDialogItemText, ModalDialog
from Carbon import Qd
from Carbon import QuickDraw
from Carbon import Dialogs
from Carbon import Windows
from Carbon import Dlg,Win,Evt,Events # sdm7g
from Carbon import Ctl
from Carbon import Controls
from Carbon import Menu
from Carbon import AE
import Nav
import MacOS
import string
from Carbon.ControlAccessor import * # Also import Controls constants
import Carbon.File
import macresource
import os
import sys
__all__ = ['Message', 'AskString', 'AskPassword', 'AskYesNoCancel',
'GetArgv', 'AskFileForOpen', 'AskFileForSave', 'AskFolder',
'ProgressBar']
_initialized = 0
def _initialize():
global _initialized
if _initialized: return
macresource.need("DLOG", 260, "dialogs.rsrc", __name__)
def _interact():
"""Make sure the application is in the foreground"""
AE.AEInteractWithUser(50000000)
def cr2lf(text):
if '\r' in text:
text = string.join(string.split(text, '\r'), '\n')
return text
def lf2cr(text):
if '\n' in text:
text = string.join(string.split(text, '\n'), '\r')
if len(text) > 253:
text = text[:253] + '\311'
return text
def Message(msg, id=260, ok=None):
"""Display a MESSAGE string.
Return when the user clicks the OK button or presses Return.
The MESSAGE string can be at most 255 characters long.
"""
_initialize()
_interact()
d = GetNewDialog(id, -1)
if not d:
print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
return
h = d.GetDialogItemAsControl(2)
SetDialogItemText(h, lf2cr(msg))
if ok != None:
h = d.GetDialogItemAsControl(1)
h.SetControlTitle(ok)
d.SetDialogDefaultItem(1)
d.AutoSizeDialog()
d.GetDialogWindow().ShowWindow()
while 1:
n = ModalDialog(None)
if n == 1:
return
def AskString(prompt, default = "", id=261, ok=None, cancel=None):
"""Display a PROMPT string and a text entry field with a DEFAULT string.
Return the contents of the text entry field when the user clicks the
OK button or presses Return.
Return None when the user clicks the Cancel button.
If omitted, DEFAULT is empty.
The PROMPT and DEFAULT strings, as well as the return value,
can be at most 255 characters long.
"""
_initialize()
_interact()
d = GetNewDialog(id, -1)
if not d:
print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
return
h = d.GetDialogItemAsControl(3)
SetDialogItemText(h, lf2cr(prompt))
h = d.GetDialogItemAsControl(4)
SetDialogItemText(h, lf2cr(default))
d.SelectDialogItemText(4, 0, 999)
# d.SetDialogItem(4, 0, 255)
if ok != None:
h = d.GetDialogItemAsControl(1)
h.SetControlTitle(ok)
if cancel != None:
h = d.GetDialogItemAsControl(2)
h.SetControlTitle(cancel)
d.SetDialogDefaultItem(1)
d.SetDialogCancelItem(2)
d.AutoSizeDialog()
d.GetDialogWindow().ShowWindow()
while 1:
n = ModalDialog(None)
if n == 1:
h = d.GetDialogItemAsControl(4)
return cr2lf(GetDialogItemText(h))
if n == 2: return None
def AskPassword(prompt, default='', id=264, ok=None, cancel=None):
"""Display a PROMPT string and a text entry field with a DEFAULT string.
The string is displayed as bullets only.
Return the contents of the text entry field when the user clicks the
OK button or presses Return.
Return None when the user clicks the Cancel button.
If omitted, DEFAULT is empty.
The PROMPT and DEFAULT strings, as well as the return value,
can be at most 255 characters long.
"""
_initialize()
_interact()
d = GetNewDialog(id, -1)
if not d:
print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
return
h = d.GetDialogItemAsControl(3)
SetDialogItemText(h, lf2cr(prompt))
pwd = d.GetDialogItemAsControl(4)
bullets = '\245'*len(default)
## SetControlData(pwd, kControlEditTextPart, kControlEditTextTextTag, bullets)
SetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag, default)
d.SelectDialogItemText(4, 0, 999)
Ctl.SetKeyboardFocus(d.GetDialogWindow(), pwd, kControlEditTextPart)
if ok != None:
h = d.GetDialogItemAsControl(1)
h.SetControlTitle(ok)
if cancel != None:
h = d.GetDialogItemAsControl(2)
h.SetControlTitle(cancel)
d.SetDialogDefaultItem(Dialogs.ok)
d.SetDialogCancelItem(Dialogs.cancel)
d.AutoSizeDialog()
d.GetDialogWindow().ShowWindow()
while 1:
n = ModalDialog(None)
if n == 1:
h = d.GetDialogItemAsControl(4)
return cr2lf(GetControlData(pwd, kControlEditTextPart, kControlEditTextPasswordTag))
if n == 2: return None
def AskYesNoCancel(question, default = 0, yes=None, no=None, cancel=None, id=262):
"""Display a QUESTION string which can be answered with Yes or No.
Return 1 when the user clicks the Yes button.
Return 0 when the user clicks the No button.
Return -1 when the user clicks the Cancel button.
When the user presses Return, the DEFAULT value is returned.
If omitted, this is 0 (No).
The QUESTION string can be at most 255 characters.
"""
_initialize()
_interact()
d = GetNewDialog(id, -1)
if not d:
print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
return
# Button assignments:
# 1 = default (invisible)
# 2 = Yes
# 3 = No
# 4 = Cancel
# The question string is item 5
h = d.GetDialogItemAsControl(5)
SetDialogItemText(h, lf2cr(question))
if yes != None:
if yes == '':
d.HideDialogItem(2)
else:
h = d.GetDialogItemAsControl(2)
h.SetControlTitle(yes)
if no != None:
if no == '':
d.HideDialogItem(3)
else:
h = d.GetDialogItemAsControl(3)
h.SetControlTitle(no)
if cancel != None:
if cancel == '':
d.HideDialogItem(4)
else:
h = d.GetDialogItemAsControl(4)
h.SetControlTitle(cancel)
d.SetDialogCancelItem(4)
if default == 1:
d.SetDialogDefaultItem(2)
elif default == 0:
d.SetDialogDefaultItem(3)
elif default == -1:
d.SetDialogDefaultItem(4)
d.AutoSizeDialog()
d.GetDialogWindow().ShowWindow()
while 1:
n = ModalDialog(None)
if n == 1: return default
if n == 2: return 1
if n == 3: return 0
if n == 4: return -1
screenbounds = Qd.GetQDGlobalsScreenBits().bounds
screenbounds = screenbounds[0]+4, screenbounds[1]+4, \
screenbounds[2]-4, screenbounds[3]-4
kControlProgressBarIndeterminateTag = 'inde' # from Controls.py
class ProgressBar:
def __init__(self, title="Working...", maxval=0, label="", id=263):
self.w = None
self.d = None
_initialize()
self.d = GetNewDialog(id, -1)
self.w = self.d.GetDialogWindow()
self.label(label)
self.title(title)
self.set(0, maxval)
self.d.AutoSizeDialog()
self.w.ShowWindow()
self.d.DrawDialog()
def __del__( self ):
if self.w:
self.w.BringToFront()
self.w.HideWindow()
del self.w
del self.d
def title(self, newstr=""):
"""title(text) - Set title of progress window"""
self.w.BringToFront()
self.w.SetWTitle(newstr)
def label( self, *newstr ):
"""label(text) - Set text in progress box"""
self.w.BringToFront()
if newstr:
self._label = lf2cr(newstr[0])
text_h = self.d.GetDialogItemAsControl(2)
SetDialogItemText(text_h, self._label)
def _update(self, value):
maxval = self.maxval
if maxval == 0: # an indeterminate bar
Ctl.IdleControls(self.w) # spin the barber pole
else: # a determinate bar
if maxval > 32767:
value = int(value/(maxval/32767.0))
maxval = 32767
maxval = int(maxval)
value = int(value)
progbar = self.d.GetDialogItemAsControl(3)
progbar.SetControlMaximum(maxval)
progbar.SetControlValue(value) # set the bar length
# Test for cancel button
ready, ev = Evt.WaitNextEvent( Events.mDownMask, 1 )
if ready :
what,msg,when,where,mod = ev
part = Win.FindWindow(where)[0]
if Dlg.IsDialogEvent(ev):
ds = Dlg.DialogSelect(ev)
if ds[0] and ds[1] == self.d and ds[-1] == 1:
self.w.HideWindow()
self.w = None
self.d = None
raise KeyboardInterrupt, ev
else:
if part == 4: # inDrag
self.w.DragWindow(where, screenbounds)
else:
MacOS.HandleEvent(ev)
def set(self, value, max=None):
"""set(value) - Set progress bar position"""
if max != None:
self.maxval = max
bar = self.d.GetDialogItemAsControl(3)
if max <= 0: # indeterminate bar
bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x01')
else: # determinate bar
bar.SetControlData(0,kControlProgressBarIndeterminateTag,'\x00')
if value < 0:
value = 0
elif value > self.maxval:
value = self.maxval
self.curval = value
self._update(value)
def inc(self, n=1):
"""inc(amt) - Increment progress bar position"""
self.set(self.curval + n)
ARGV_ID=265
ARGV_ITEM_OK=1
ARGV_ITEM_CANCEL=2
ARGV_OPTION_GROUP=3
ARGV_OPTION_EXPLAIN=4
ARGV_OPTION_VALUE=5
ARGV_OPTION_ADD=6
ARGV_COMMAND_GROUP=7
ARGV_COMMAND_EXPLAIN=8
ARGV_COMMAND_ADD=9
ARGV_ADD_OLDFILE=10
ARGV_ADD_NEWFILE=11
ARGV_ADD_FOLDER=12
ARGV_CMDLINE_GROUP=13
ARGV_CMDLINE_DATA=14
##def _myModalDialog(d):
## while 1:
## ready, ev = Evt.WaitNextEvent(0xffff, -1)
## print 'DBG: WNE', ready, ev
## if ready :
## what,msg,when,where,mod = ev
## part, window = Win.FindWindow(where)
## if Dlg.IsDialogEvent(ev):
## didit, dlgdone, itemdone = Dlg.DialogSelect(ev)
## print 'DBG: DialogSelect', didit, dlgdone, itemdone, d
## if didit and dlgdone == d:
## return itemdone
## elif window == d.GetDialogWindow():
## d.GetDialogWindow().SelectWindow()
## if part == 4: # inDrag
## d.DragWindow(where, screenbounds)
## else:
## MacOS.HandleEvent(ev)
## else:
## MacOS.HandleEvent(ev)
##
def _setmenu(control, items):
mhandle = control.GetControlData_Handle(Controls.kControlMenuPart,
Controls.kControlPopupButtonMenuHandleTag)
menu = Menu.as_Menu(mhandle)
for item in items:
if type(item) == type(()):
label = item[0]
else:
label = item
if label[-1] == '=' or label[-1] == ':':
label = label[:-1]
menu.AppendMenu(label)
## mhandle, mid = menu.getpopupinfo()
## control.SetControlData_Handle(Controls.kControlMenuPart,
## Controls.kControlPopupButtonMenuHandleTag, mhandle)
control.SetControlMinimum(1)
control.SetControlMaximum(len(items)+1)
def _selectoption(d, optionlist, idx):
if idx < 0 or idx >= len(optionlist):
MacOS.SysBeep()
return
option = optionlist[idx]
if type(option) == type(()):
if len(option) == 4:
help = option[2]
elif len(option) > 1:
help = option[-1]
else:
help = ''
else:
help = ''
h = d.GetDialogItemAsControl(ARGV_OPTION_EXPLAIN)
if help and len(help) > 250:
help = help[:250] + '...'
Dlg.SetDialogItemText(h, help)
hasvalue = 0
if type(option) == type(()):
label = option[0]
else:
label = option
if label[-1] == '=' or label[-1] == ':':
hasvalue = 1
h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE)
Dlg.SetDialogItemText(h, '')
if hasvalue:
d.ShowDialogItem(ARGV_OPTION_VALUE)
d.SelectDialogItemText(ARGV_OPTION_VALUE, 0, 0)
else:
d.HideDialogItem(ARGV_OPTION_VALUE)
def GetArgv(optionlist=None, commandlist=None, addoldfile=1, addnewfile=1, addfolder=1, id=ARGV_ID):
_initialize()
_interact()
d = GetNewDialog(id, -1)
if not d:
print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
return
# h = d.GetDialogItemAsControl(3)
# SetDialogItemText(h, lf2cr(prompt))
# h = d.GetDialogItemAsControl(4)
# SetDialogItemText(h, lf2cr(default))
# d.SelectDialogItemText(4, 0, 999)
# d.SetDialogItem(4, 0, 255)
if optionlist:
_setmenu(d.GetDialogItemAsControl(ARGV_OPTION_GROUP), optionlist)
_selectoption(d, optionlist, 0)
else:
d.GetDialogItemAsControl(ARGV_OPTION_GROUP).DeactivateControl()
if commandlist:
_setmenu(d.GetDialogItemAsControl(ARGV_COMMAND_GROUP), commandlist)
if type(commandlist[0]) == type(()) and len(commandlist[0]) > 1:
help = commandlist[0][-1]
h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN)
Dlg.SetDialogItemText(h, help)
else:
d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).DeactivateControl()
if not addoldfile:
d.GetDialogItemAsControl(ARGV_ADD_OLDFILE).DeactivateControl()
if not addnewfile:
d.GetDialogItemAsControl(ARGV_ADD_NEWFILE).DeactivateControl()
if not addfolder:
d.GetDialogItemAsControl(ARGV_ADD_FOLDER).DeactivateControl()
d.SetDialogDefaultItem(ARGV_ITEM_OK)
d.SetDialogCancelItem(ARGV_ITEM_CANCEL)
d.GetDialogWindow().ShowWindow()
d.DrawDialog()
if hasattr(MacOS, 'SchedParams'):
appsw = MacOS.SchedParams(1, 0)
try:
while 1:
stringstoadd = []
n = ModalDialog(None)
if n == ARGV_ITEM_OK:
break
elif n == ARGV_ITEM_CANCEL:
raise SystemExit
elif n == ARGV_OPTION_GROUP:
idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1
_selectoption(d, optionlist, idx)
elif n == ARGV_OPTION_VALUE:
pass
elif n == ARGV_OPTION_ADD:
idx = d.GetDialogItemAsControl(ARGV_OPTION_GROUP).GetControlValue()-1
if 0 <= idx < len(optionlist):
option = optionlist[idx]
if type(option) == type(()):
option = option[0]
if option[-1] == '=' or option[-1] == ':':
option = option[:-1]
h = d.GetDialogItemAsControl(ARGV_OPTION_VALUE)
value = Dlg.GetDialogItemText(h)
else:
value = ''
if len(option) == 1:
stringtoadd = '-' + option
else:
stringtoadd = '--' + option
stringstoadd = [stringtoadd]
if value:
stringstoadd.append(value)
else:
MacOS.SysBeep()
elif n == ARGV_COMMAND_GROUP:
idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1
if 0 <= idx < len(commandlist) and type(commandlist[idx]) == type(()) and \
len(commandlist[idx]) > 1:
help = commandlist[idx][-1]
h = d.GetDialogItemAsControl(ARGV_COMMAND_EXPLAIN)
Dlg.SetDialogItemText(h, help)
elif n == ARGV_COMMAND_ADD:
idx = d.GetDialogItemAsControl(ARGV_COMMAND_GROUP).GetControlValue()-1
if 0 <= idx < len(commandlist):
command = commandlist[idx]
if type(command) == type(()):
command = command[0]
stringstoadd = [command]
else:
MacOS.SysBeep()
elif n == ARGV_ADD_OLDFILE:
pathname = AskFileForOpen()
if pathname:
stringstoadd = [pathname]
elif n == ARGV_ADD_NEWFILE:
pathname = AskFileForSave()
if pathname:
stringstoadd = [pathname]
elif n == ARGV_ADD_FOLDER:
pathname = AskFolder()
if pathname:
stringstoadd = [pathname]
elif n == ARGV_CMDLINE_DATA:
pass # Nothing to do
else:
raise RuntimeError, "Unknown dialog item %d"%n
for stringtoadd in stringstoadd:
if '"' in stringtoadd or "'" in stringtoadd or " " in stringtoadd:
stringtoadd = repr(stringtoadd)
h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
oldstr = GetDialogItemText(h)
if oldstr and oldstr[-1] != ' ':
oldstr = oldstr + ' '
oldstr = oldstr + stringtoadd
if oldstr[-1] != ' ':
oldstr = oldstr + ' '
SetDialogItemText(h, oldstr)
d.SelectDialogItemText(ARGV_CMDLINE_DATA, 0x7fff, 0x7fff)
h = d.GetDialogItemAsControl(ARGV_CMDLINE_DATA)
oldstr = GetDialogItemText(h)
tmplist = string.split(oldstr)
newlist = []
while tmplist:
item = tmplist[0]
del tmplist[0]
if item[0] == '"':
while item[-1] != '"':
if not tmplist:
raise RuntimeError, "Unterminated quoted argument"
item = item + ' ' + tmplist[0]
del tmplist[0]
item = item[1:-1]
if item[0] == "'":
while item[-1] != "'":
if not tmplist:
raise RuntimeError, "Unterminated quoted argument"
item = item + ' ' + tmplist[0]
del tmplist[0]
item = item[1:-1]
newlist.append(item)
return newlist
finally:
if hasattr(MacOS, 'SchedParams'):
MacOS.SchedParams(*appsw)
del d
def _process_Nav_args(dftflags, **args):
import aepack
import Carbon.AE
import Carbon.File
for k in args.keys():
if args[k] is None:
del args[k]
# Set some defaults, and modify some arguments
if not args.has_key('dialogOptionFlags'):
args['dialogOptionFlags'] = dftflags
if args.has_key('defaultLocation') and \
not isinstance(args['defaultLocation'], Carbon.AE.AEDesc):
defaultLocation = args['defaultLocation']
if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)):
args['defaultLocation'] = aepack.pack(defaultLocation)
else:
defaultLocation = Carbon.File.FSRef(defaultLocation)
args['defaultLocation'] = aepack.pack(defaultLocation)
if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType):
typeList = args['typeList'][:]
# Workaround for OSX typeless files:
if 'TEXT' in typeList and not '\0\0\0\0' in typeList:
typeList = typeList + ('\0\0\0\0',)
data = 'Pyth' + struct.pack("hh", 0, len(typeList))
for type in typeList:
data = data+type
args['typeList'] = Carbon.Res.Handle(data)
tpwanted = str
if args.has_key('wanted'):
tpwanted = args['wanted']
del args['wanted']
return args, tpwanted
def _dummy_Nav_eventproc(msg, data):
pass
_default_Nav_eventproc = _dummy_Nav_eventproc
def SetDefaultEventProc(proc):
global _default_Nav_eventproc
rv = _default_Nav_eventproc
if proc is None:
proc = _dummy_Nav_eventproc
_default_Nav_eventproc = proc
return rv
def AskFileForOpen(
message=None,
typeList=None,
# From here on the order is not documented
version=None,
defaultLocation=None,
dialogOptionFlags=None,
location=None,
clientName=None,
windowTitle=None,
actionButtonLabel=None,
cancelButtonLabel=None,
preferenceKey=None,
popupExtension=None,
eventProc=_dummy_Nav_eventproc,
previewProc=None,
filterProc=None,
wanted=None,
multiple=None):
"""Display a dialog asking the user for a file to open.
wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
the other arguments can be looked up in Apple's Navigation Services documentation"""
default_flags = 0x56 # Or 0xe4?
args, tpwanted = _process_Nav_args(default_flags, version=version,
defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags,
location=location,clientName=clientName,windowTitle=windowTitle,
actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel,
message=message,preferenceKey=preferenceKey,
popupExtension=popupExtension,eventProc=eventProc,previewProc=previewProc,
filterProc=filterProc,typeList=typeList,wanted=wanted,multiple=multiple)
_interact()
try:
rr = Nav.NavChooseFile(args)
good = 1
except Nav.error, arg:
if arg[0] != -128: # userCancelledErr
raise Nav.error, arg
return None
if not rr.validRecord or not rr.selection:
return None
if issubclass(tpwanted, Carbon.File.FSRef):
return tpwanted(rr.selection_fsr[0])
if issubclass(tpwanted, Carbon.File.FSSpec):
return tpwanted(rr.selection[0])
if issubclass(tpwanted, str):
return tpwanted(rr.selection_fsr[0].as_pathname())
if issubclass(tpwanted, unicode):
return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8')
raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
def AskFileForSave(
message=None,
savedFileName=None,
# From here on the order is not documented
version=None,
defaultLocation=None,
dialogOptionFlags=None,
location=None,
clientName=None,
windowTitle=None,
actionButtonLabel=None,
cancelButtonLabel=None,
preferenceKey=None,
popupExtension=None,
eventProc=_dummy_Nav_eventproc,
fileType=None,
fileCreator=None,
wanted=None,
multiple=None):
"""Display a dialog asking the user for a filename to save to.
wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
the other arguments can be looked up in Apple's Navigation Services documentation"""
default_flags = 0x07
args, tpwanted = _process_Nav_args(default_flags, version=version,
defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags,
location=location,clientName=clientName,windowTitle=windowTitle,
actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel,
savedFileName=savedFileName,message=message,preferenceKey=preferenceKey,
popupExtension=popupExtension,eventProc=eventProc,fileType=fileType,
fileCreator=fileCreator,wanted=wanted,multiple=multiple)
_interact()
try:
rr = Nav.NavPutFile(args)
good = 1
except Nav.error, arg:
if arg[0] != -128: # userCancelledErr
raise Nav.error, arg
return None
if not rr.validRecord or not rr.selection:
return None
if issubclass(tpwanted, Carbon.File.FSRef):
raise TypeError, "Cannot pass wanted=FSRef to AskFileForSave"
if issubclass(tpwanted, Carbon.File.FSSpec):
return tpwanted(rr.selection[0])
if issubclass(tpwanted, (str, unicode)):
if sys.platform == 'mac':
fullpath = rr.selection[0].as_pathname()
else:
# This is gross, and probably incorrect too
vrefnum, dirid, name = rr.selection[0].as_tuple()
pardir_fss = Carbon.File.FSSpec((vrefnum, dirid, ''))
pardir_fsr = Carbon.File.FSRef(pardir_fss)
pardir_path = pardir_fsr.FSRefMakePath() # This is utf-8
name_utf8 = unicode(name, 'macroman').encode('utf8')
fullpath = os.path.join(pardir_path, name_utf8)
if issubclass(tpwanted, unicode):
return unicode(fullpath, 'utf8')
return tpwanted(fullpath)
raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
def AskFolder(
message=None,
# From here on the order is not documented
version=None,
defaultLocation=None,
dialogOptionFlags=None,
location=None,
clientName=None,
windowTitle=None,
actionButtonLabel=None,
cancelButtonLabel=None,
preferenceKey=None,
popupExtension=None,
eventProc=_dummy_Nav_eventproc,
filterProc=None,
wanted=None,
multiple=None):
"""Display a dialog asking the user for select a folder.
wanted is the return type wanted: FSSpec, FSRef, unicode or string (default)
the other arguments can be looked up in Apple's Navigation Services documentation"""
default_flags = 0x17
args, tpwanted = _process_Nav_args(default_flags, version=version,
defaultLocation=defaultLocation, dialogOptionFlags=dialogOptionFlags,
location=location,clientName=clientName,windowTitle=windowTitle,
actionButtonLabel=actionButtonLabel,cancelButtonLabel=cancelButtonLabel,
message=message,preferenceKey=preferenceKey,
popupExtension=popupExtension,eventProc=eventProc,filterProc=filterProc,
wanted=wanted,multiple=multiple)
_interact()
try:
rr = Nav.NavChooseFolder(args)
good = 1
except Nav.error, arg:
if arg[0] != -128: # userCancelledErr
raise Nav.error, arg
return None
if not rr.validRecord or not rr.selection:
return None
if issubclass(tpwanted, Carbon.File.FSRef):
return tpwanted(rr.selection_fsr[0])
if issubclass(tpwanted, Carbon.File.FSSpec):
return tpwanted(rr.selection[0])
if issubclass(tpwanted, str):
return tpwanted(rr.selection_fsr[0].as_pathname())
if issubclass(tpwanted, unicode):
return tpwanted(rr.selection_fsr[0].as_pathname(), 'utf8')
raise TypeError, "Unknown value for argument 'wanted': %s" % repr(tpwanted)
def test():
import time
Message("Testing EasyDialogs.")
optionlist = (('v', 'Verbose'), ('verbose', 'Verbose as long option'),
('flags=', 'Valued option'), ('f:', 'Short valued option'))
commandlist = (('start', 'Start something'), ('stop', 'Stop something'))
argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0)
Message("Command line: %s"%' '.join(argv))
for i in range(len(argv)):
print 'arg[%d] = %r' % (i, argv[i])
ok = AskYesNoCancel("Do you want to proceed?")
ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No")
if ok > 0:
s = AskString("Enter your first name", "Joe")
s2 = AskPassword("Okay %s, tell us your nickname"%s, s, cancel="None")
if not s2:
Message("%s has no secret nickname"%s)
else:
Message("Hello everybody!!\nThe secret nickname of %s is %s!!!"%(s, s2))
else:
s = 'Anonymous'
rv = AskFileForOpen(message="Gimme a file, %s"%s, wanted=Carbon.File.FSSpec)
Message("rv: %s"%rv)
rv = AskFileForSave(wanted=Carbon.File.FSRef, savedFileName="%s.txt"%s)
Message("rv.as_pathname: %s"%rv.as_pathname())
rv = AskFolder()
Message("Folder name: %s"%rv)
text = ( "Working Hard...", "Hardly Working..." ,
"So far, so good!", "Keep on truckin'" )
bar = ProgressBar("Progress, progress...", 0, label="Ramping up...")
try:
if hasattr(MacOS, 'SchedParams'):
appsw = MacOS.SchedParams(1, 0)
for i in xrange(20):
bar.inc()
time.sleep(0.05)
bar.set(0,100)
for i in xrange(100):
bar.set(i)
time.sleep(0.05)
if i % 10 == 0:
bar.label(text[(i/10) % 4])
bar.label("Done.")
time.sleep(1.0) # give'em a chance to see "Done."
finally:
del bar
if hasattr(MacOS, 'SchedParams'):
MacOS.SchedParams(*appsw)
if __name__ == '__main__':
try:
test()
except KeyboardInterrupt:
Message("Operation Canceled.")
| Python |
"""Tools for use in AppleEvent clients and servers:
conversion between AE types and python types
pack(x) converts a Python object to an AEDesc object
unpack(desc) does the reverse
coerce(x, wanted_sample) coerces a python object to another python object
"""
#
# This code was originally written by Guido, and modified/extended by Jack
# to include the various types that were missing. The reference used is
# Apple Event Registry, chapter 9.
#
import struct
import string
import types
from string import strip
from types import *
from Carbon import AE
from Carbon.AppleEvents import *
import MacOS
import Carbon.File
import StringIO
import aetypes
from aetypes import mkenum, ObjectSpecifier
import os
# These ones seem to be missing from AppleEvents
# (they're in AERegistry.h)
#typeColorTable = 'clrt'
#typeDrawingArea = 'cdrw'
#typePixelMap = 'cpix'
#typePixelMapMinus = 'tpmm'
#typeRotation = 'trot'
#typeTextStyles = 'tsty'
#typeStyledText = 'STXT'
#typeAEText = 'tTXT'
#typeEnumeration = 'enum'
#
# Some AE types are immedeately coerced into something
# we like better (and which is equivalent)
#
unpacker_coercions = {
typeComp : typeFloat,
typeColorTable : typeAEList,
typeDrawingArea : typeAERecord,
typeFixed : typeFloat,
typeExtended : typeFloat,
typePixelMap : typeAERecord,
typeRotation : typeAERecord,
typeStyledText : typeAERecord,
typeTextStyles : typeAERecord,
};
#
# Some python types we need in the packer:
#
AEDescType = AE.AEDescType
FSSType = Carbon.File.FSSpecType
FSRefType = Carbon.File.FSRefType
AliasType = Carbon.File.AliasType
def packkey(ae, key, value):
if hasattr(key, 'which'):
keystr = key.which
elif hasattr(key, 'want'):
keystr = key.want
else:
keystr = key
ae.AEPutParamDesc(keystr, pack(value))
def pack(x, forcetype = None):
"""Pack a python object into an AE descriptor"""
if forcetype:
if type(x) is StringType:
return AE.AECreateDesc(forcetype, x)
else:
return pack(x).AECoerceDesc(forcetype)
if x == None:
return AE.AECreateDesc('null', '')
if isinstance(x, AEDescType):
return x
if isinstance(x, FSSType):
return AE.AECreateDesc('fss ', x.data)
if isinstance(x, FSRefType):
return AE.AECreateDesc('fsrf', x.data)
if isinstance(x, AliasType):
return AE.AECreateDesc('alis', x.data)
if isinstance(x, IntType):
return AE.AECreateDesc('long', struct.pack('l', x))
if isinstance(x, FloatType):
return AE.AECreateDesc('doub', struct.pack('d', x))
if isinstance(x, StringType):
return AE.AECreateDesc('TEXT', x)
if isinstance(x, UnicodeType):
data = x.encode('utf16')
if data[:2] == '\xfe\xff':
data = data[2:]
return AE.AECreateDesc('utxt', data)
if isinstance(x, ListType):
list = AE.AECreateList('', 0)
for item in x:
list.AEPutDesc(0, pack(item))
return list
if isinstance(x, DictionaryType):
record = AE.AECreateList('', 1)
for key, value in x.items():
packkey(record, key, value)
#record.AEPutParamDesc(key, pack(value))
return record
if type(x) == types.ClassType and issubclass(x, ObjectSpecifier):
# Note: we are getting a class object here, not an instance
return AE.AECreateDesc('type', x.want)
if hasattr(x, '__aepack__'):
return x.__aepack__()
if hasattr(x, 'which'):
return AE.AECreateDesc('TEXT', x.which)
if hasattr(x, 'want'):
return AE.AECreateDesc('TEXT', x.want)
return AE.AECreateDesc('TEXT', repr(x)) # Copout
def unpack(desc, formodulename=""):
"""Unpack an AE descriptor to a python object"""
t = desc.type
if unpacker_coercions.has_key(t):
desc = desc.AECoerceDesc(unpacker_coercions[t])
t = desc.type # This is a guess by Jack....
if t == typeAEList:
l = []
for i in range(desc.AECountItems()):
keyword, item = desc.AEGetNthDesc(i+1, '****')
l.append(unpack(item, formodulename))
return l
if t == typeAERecord:
d = {}
for i in range(desc.AECountItems()):
keyword, item = desc.AEGetNthDesc(i+1, '****')
d[keyword] = unpack(item, formodulename)
return d
if t == typeAEText:
record = desc.AECoerceDesc('reco')
return mkaetext(unpack(record, formodulename))
if t == typeAlias:
return Carbon.File.Alias(rawdata=desc.data)
# typeAppleEvent returned as unknown
if t == typeBoolean:
return struct.unpack('b', desc.data)[0]
if t == typeChar:
return desc.data
if t == typeUnicodeText:
return unicode(desc.data, 'utf16')
# typeColorTable coerced to typeAEList
# typeComp coerced to extended
# typeData returned as unknown
# typeDrawingArea coerced to typeAERecord
if t == typeEnumeration:
return mkenum(desc.data)
# typeEPS returned as unknown
if t == typeFalse:
return 0
if t == typeFloat:
data = desc.data
return struct.unpack('d', data)[0]
if t == typeFSS:
return Carbon.File.FSSpec(rawdata=desc.data)
if t == typeFSRef:
return Carbon.File.FSRef(rawdata=desc.data)
if t == typeInsertionLoc:
record = desc.AECoerceDesc('reco')
return mkinsertionloc(unpack(record, formodulename))
# typeInteger equal to typeLongInteger
if t == typeIntlText:
script, language = struct.unpack('hh', desc.data[:4])
return aetypes.IntlText(script, language, desc.data[4:])
if t == typeIntlWritingCode:
script, language = struct.unpack('hh', desc.data)
return aetypes.IntlWritingCode(script, language)
if t == typeKeyword:
return mkkeyword(desc.data)
if t == typeLongInteger:
return struct.unpack('l', desc.data)[0]
if t == typeLongDateTime:
a, b = struct.unpack('lL', desc.data)
return (long(a) << 32) + b
if t == typeNull:
return None
if t == typeMagnitude:
v = struct.unpack('l', desc.data)
if v < 0:
v = 0x100000000L + v
return v
if t == typeObjectSpecifier:
record = desc.AECoerceDesc('reco')
# If we have been told the name of the module we are unpacking aedescs for,
# we can attempt to create the right type of python object from that module.
if formodulename:
return mkobjectfrommodule(unpack(record, formodulename), formodulename)
return mkobject(unpack(record, formodulename))
# typePict returned as unknown
# typePixelMap coerced to typeAERecord
# typePixelMapMinus returned as unknown
# typeProcessSerialNumber returned as unknown
if t == typeQDPoint:
v, h = struct.unpack('hh', desc.data)
return aetypes.QDPoint(v, h)
if t == typeQDRectangle:
v0, h0, v1, h1 = struct.unpack('hhhh', desc.data)
return aetypes.QDRectangle(v0, h0, v1, h1)
if t == typeRGBColor:
r, g, b = struct.unpack('hhh', desc.data)
return aetypes.RGBColor(r, g, b)
# typeRotation coerced to typeAERecord
# typeScrapStyles returned as unknown
# typeSessionID returned as unknown
if t == typeShortFloat:
return struct.unpack('f', desc.data)[0]
if t == typeShortInteger:
return struct.unpack('h', desc.data)[0]
# typeSMFloat identical to typeShortFloat
# typeSMInt indetical to typeShortInt
# typeStyledText coerced to typeAERecord
if t == typeTargetID:
return mktargetid(desc.data)
# typeTextStyles coerced to typeAERecord
# typeTIFF returned as unknown
if t == typeTrue:
return 1
if t == typeType:
return mktype(desc.data, formodulename)
#
# The following are special
#
if t == 'rang':
record = desc.AECoerceDesc('reco')
return mkrange(unpack(record, formodulename))
if t == 'cmpd':
record = desc.AECoerceDesc('reco')
return mkcomparison(unpack(record, formodulename))
if t == 'logi':
record = desc.AECoerceDesc('reco')
return mklogical(unpack(record, formodulename))
return mkunknown(desc.type, desc.data)
def coerce(data, egdata):
"""Coerce a python object to another type using the AE coercers"""
pdata = pack(data)
pegdata = pack(egdata)
pdata = pdata.AECoerceDesc(pegdata.type)
return unpack(pdata)
#
# Helper routines for unpack
#
def mktargetid(data):
sessionID = getlong(data[:4])
name = mkppcportrec(data[4:4+72])
location = mklocationnamerec(data[76:76+36])
rcvrName = mkppcportrec(data[112:112+72])
return sessionID, name, location, rcvrName
def mkppcportrec(rec):
namescript = getword(rec[:2])
name = getpstr(rec[2:2+33])
portkind = getword(rec[36:38])
if portkind == 1:
ctor = rec[38:42]
type = rec[42:46]
identity = (ctor, type)
else:
identity = getpstr(rec[38:38+33])
return namescript, name, portkind, identity
def mklocationnamerec(rec):
kind = getword(rec[:2])
stuff = rec[2:]
if kind == 0: stuff = None
if kind == 2: stuff = getpstr(stuff)
return kind, stuff
def mkunknown(type, data):
return aetypes.Unknown(type, data)
def getpstr(s):
return s[1:1+ord(s[0])]
def getlong(s):
return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
def getword(s):
return (ord(s[0])<<8) | (ord(s[1])<<0)
def mkkeyword(keyword):
return aetypes.Keyword(keyword)
def mkrange(dict):
return aetypes.Range(dict['star'], dict['stop'])
def mkcomparison(dict):
return aetypes.Comparison(dict['obj1'], dict['relo'].enum, dict['obj2'])
def mklogical(dict):
return aetypes.Logical(dict['logc'], dict['term'])
def mkstyledtext(dict):
return aetypes.StyledText(dict['ksty'], dict['ktxt'])
def mkaetext(dict):
return aetypes.AEText(dict[keyAEScriptTag], dict[keyAEStyles], dict[keyAEText])
def mkinsertionloc(dict):
return aetypes.InsertionLoc(dict[keyAEObject], dict[keyAEPosition])
def mkobject(dict):
want = dict['want'].type
form = dict['form'].enum
seld = dict['seld']
fr = dict['from']
if form in ('name', 'indx', 'rang', 'test'):
if want == 'text': return aetypes.Text(seld, fr)
if want == 'cha ': return aetypes.Character(seld, fr)
if want == 'cwor': return aetypes.Word(seld, fr)
if want == 'clin': return aetypes.Line(seld, fr)
if want == 'cpar': return aetypes.Paragraph(seld, fr)
if want == 'cwin': return aetypes.Window(seld, fr)
if want == 'docu': return aetypes.Document(seld, fr)
if want == 'file': return aetypes.File(seld, fr)
if want == 'cins': return aetypes.InsertionPoint(seld, fr)
if want == 'prop' and form == 'prop' and aetypes.IsType(seld):
return aetypes.Property(seld.type, fr)
return aetypes.ObjectSpecifier(want, form, seld, fr)
# Note by Jack: I'm not 100% sure of the following code. This was
# provided by Donovan Preston, but I wonder whether the assignment
# to __class__ is safe. Moreover, shouldn't there be a better
# initializer for the classes in the suites?
def mkobjectfrommodule(dict, modulename):
if type(dict['want']) == types.ClassType and issubclass(dict['want'], ObjectSpecifier):
# The type has already been converted to Python. Convert back:-(
classtype = dict['want']
dict['want'] = aetypes.mktype(classtype.want)
want = dict['want'].type
module = __import__(modulename)
codenamemapper = module._classdeclarations
classtype = codenamemapper.get(want, None)
newobj = mkobject(dict)
if classtype:
assert issubclass(classtype, ObjectSpecifier)
newobj.__class__ = classtype
return newobj
def mktype(typecode, modulename=None):
if modulename:
module = __import__(modulename)
codenamemapper = module._classdeclarations
classtype = codenamemapper.get(typecode, None)
if classtype:
return classtype
return aetypes.mktype(typecode)
| Python |
"""MiniAEFrame - A minimal AppleEvent Application framework.
There are two classes:
AEServer -- a mixin class offering nice AE handling.
MiniApplication -- a very minimal alternative to FrameWork.py,
only suitable for the simplest of AppleEvent servers.
"""
import sys
import traceback
import MacOS
from Carbon import AE
from Carbon.AppleEvents import *
from Carbon import Evt
from Carbon.Events import *
from Carbon import Menu
from Carbon import Win
from Carbon.Windows import *
from Carbon import Qd
import aetools
import EasyDialogs
kHighLevelEvent = 23 # Not defined anywhere for Python yet?
class MiniApplication:
"""A minimal FrameWork.Application-like class"""
def __init__(self):
self.quitting = 0
# Initialize menu
self.appleid = 1
self.quitid = 2
Menu.ClearMenuBar()
self.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024")
applemenu.AppendMenu("%s;(-" % self.getaboutmenutext())
if MacOS.runtimemodel == 'ppc':
applemenu.AppendResMenu('DRVR')
applemenu.InsertMenu(0)
self.quitmenu = Menu.NewMenu(self.quitid, "File")
self.quitmenu.AppendMenu("Quit")
self.quitmenu.SetItemCmd(1, ord("Q"))
self.quitmenu.InsertMenu(0)
Menu.DrawMenuBar()
def __del__(self):
self.close()
def close(self):
pass
def mainloop(self, mask = everyEvent, timeout = 60*60):
while not self.quitting:
self.dooneevent(mask, timeout)
def _quit(self):
self.quitting = 1
def dooneevent(self, mask = everyEvent, timeout = 60*60):
got, event = Evt.WaitNextEvent(mask, timeout)
if got:
self.lowlevelhandler(event)
def lowlevelhandler(self, event):
what, message, when, where, modifiers = event
h, v = where
if what == kHighLevelEvent:
msg = "High Level Event: %r %r" % (code(message), code(h | (v<<16)))
try:
AE.AEProcessAppleEvent(event)
except AE.Error, err:
print 'AE error: ', err
print 'in', msg
traceback.print_exc()
return
elif what == keyDown:
c = chr(message & charCodeMask)
if modifiers & cmdKey:
if c == '.':
raise KeyboardInterrupt, "Command-period"
if c == 'q':
if hasattr(MacOS, 'OutputSeen'):
MacOS.OutputSeen()
self.quitting = 1
return
elif what == mouseDown:
partcode, window = Win.FindWindow(where)
if partcode == inMenuBar:
result = Menu.MenuSelect(where)
id = (result>>16) & 0xffff # Hi word
item = result & 0xffff # Lo word
if id == self.appleid:
if item == 1:
EasyDialogs.Message(self.getabouttext())
elif item > 1 and hasattr(Menu, 'OpenDeskAcc'):
name = self.applemenu.GetMenuItemText(item)
Menu.OpenDeskAcc(name)
elif id == self.quitid and item == 1:
if hasattr(MacOS, 'OutputSeen'):
MacOS.OutputSeen()
self.quitting = 1
Menu.HiliteMenu(0)
return
# Anything not handled is passed to Python/SIOUX
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
else:
print "Unhandled event:", event
def getabouttext(self):
return self.__class__.__name__
def getaboutmenutext(self):
return "About %s\311" % self.__class__.__name__
class AEServer:
def __init__(self):
self.ae_handlers = {}
def installaehandler(self, classe, type, callback):
AE.AEInstallEventHandler(classe, type, self.callback_wrapper)
self.ae_handlers[(classe, type)] = callback
def close(self):
for classe, type in self.ae_handlers.keys():
AE.AERemoveEventHandler(classe, type)
def callback_wrapper(self, _request, _reply):
_parameters, _attributes = aetools.unpackevent(_request)
_class = _attributes['evcl'].type
_type = _attributes['evid'].type
if self.ae_handlers.has_key((_class, _type)):
_function = self.ae_handlers[(_class, _type)]
elif self.ae_handlers.has_key((_class, '****')):
_function = self.ae_handlers[(_class, '****')]
elif self.ae_handlers.has_key(('****', '****')):
_function = self.ae_handlers[('****', '****')]
else:
raise 'Cannot happen: AE callback without handler', (_class, _type)
# XXXX Do key-to-name mapping here
_parameters['_attributes'] = _attributes
_parameters['_class'] = _class
_parameters['_type'] = _type
if _parameters.has_key('----'):
_object = _parameters['----']
del _parameters['----']
# The try/except that used to be here can mask programmer errors.
# Let the program crash, the programmer can always add a **args
# to the formal parameter list.
rv = _function(_object, **_parameters)
else:
#Same try/except comment as above
rv = _function(**_parameters)
if rv == None:
aetools.packevent(_reply, {})
else:
aetools.packevent(_reply, {'----':rv})
def code(x):
"Convert a long int to the 4-character code it really is"
s = ''
for i in range(4):
x, c = divmod(x, 256)
s = chr(c) + s
return s
class _Test(AEServer, MiniApplication):
"""Mini test application, handles required events"""
def __init__(self):
MiniApplication.__init__(self)
AEServer.__init__(self)
self.installaehandler('aevt', 'oapp', self.open_app)
self.installaehandler('aevt', 'quit', self.quit)
self.installaehandler('****', '****', self.other)
self.mainloop()
def quit(self, **args):
self._quit()
def open_app(self, **args):
pass
def other(self, _object=None, _class=None, _type=None, **args):
print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args
if __name__ == '__main__':
_Test()
| Python |
#
# Local customizations for generating the Carbon interface modules.
# Edit this file to reflect where things should be on your system.
# Note that pathnames are unix-style for OSX MachoPython/unix-Python,
# but mac-style for MacPython, whether running on OS9 or OSX.
#
import sys, os
Error = "bgenlocations.Error"
#
# Where bgen is. For unix-Python bgen isn't installed, so you have to refer to
# the source tree here.
BGENDIR="/Users/jack/src/python/Tools/bgen/bgen"
#
# Where to find the Universal Header include files. If you have CodeWarrior
# installed you can use the Universal Headers from there, otherwise you can
# download them from the Apple website. Bgen can handle both unix- and mac-style
# end of lines, so don't worry about that.
#
INCLUDEDIR="/Users/jack/src/Universal/Interfaces/CIncludes"
#
# Where to put the python definitions files. Note that, on unix-Python,
# if you want to commit your changes to the CVS repository this should refer to
# your source directory, not your installed directory.
#
TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon"
# Creator for C files:
CREATOR="CWIE"
# The previous definitions can be overriden by creating a module
# bgenlocationscustomize.py and putting it in site-packages (or anywere else
# on sys.path, actually)
try:
from bgenlocationscustomize import *
except ImportError:
pass
if not os.path.exists(BGENDIR):
raise Error, "Please fix bgenlocations.py, BGENDIR does not exist: %s" % BGENDIR
if not os.path.exists(INCLUDEDIR):
raise Error, "Please fix bgenlocations.py, INCLUDEDIR does not exist: %s" % INCLUDEDIR
if not os.path.exists(TOOLBOXDIR):
raise Error, "Please fix bgenlocations.py, TOOLBOXDIR does not exist: %s" % TOOLBOXDIR
# Sigh, due to the way these are used make sure they end with : or /.
if BGENDIR[-1] != os.sep:
BGENDIR = BGENDIR + os.sep
if INCLUDEDIR[-1] != os.sep:
INCLUDEDIR = INCLUDEDIR + os.sep
if TOOLBOXDIR[-1] != os.sep:
TOOLBOXDIR = TOOLBOXDIR + os.sep
| Python |
#! /usr/bin/env python
"""\
bundlebuilder.py -- Tools to assemble MacOS X (application) bundles.
This module contains two classes to build so called "bundles" for
MacOS X. BundleBuilder is a general tool, AppBuilder is a subclass
specialized in building application bundles.
[Bundle|App]Builder objects are instantiated with a bunch of keyword
arguments, and have a build() method that will do all the work. See
the class doc strings for a description of the constructor arguments.
The module contains a main program that can be used in two ways:
% python bundlebuilder.py [options] build
% python buildapp.py [options] build
Where "buildapp.py" is a user-supplied setup.py-like script following
this model:
from bundlebuilder import buildapp
buildapp(<lots-of-keyword-args>)
"""
__all__ = ["BundleBuilder", "BundleBuilderError", "AppBuilder", "buildapp"]
import sys
import os, errno, shutil
import imp, marshal
import re
from copy import deepcopy
import getopt
from plistlib import Plist
from types import FunctionType as function
class BundleBuilderError(Exception): pass
class Defaults:
"""Class attributes that don't start with an underscore and are
not functions or classmethods are (deep)copied to self.__dict__.
This allows for mutable default values.
"""
def __init__(self, **kwargs):
defaults = self._getDefaults()
defaults.update(kwargs)
self.__dict__.update(defaults)
def _getDefaults(cls):
defaults = {}
for base in cls.__bases__:
if hasattr(base, "_getDefaults"):
defaults.update(base._getDefaults())
for name, value in cls.__dict__.items():
if name[0] != "_" and not isinstance(value,
(function, classmethod)):
defaults[name] = deepcopy(value)
return defaults
_getDefaults = classmethod(_getDefaults)
class BundleBuilder(Defaults):
"""BundleBuilder is a barebones class for assembling bundles. It
knows nothing about executables or icons, it only copies files
and creates the PkgInfo and Info.plist files.
"""
# (Note that Defaults.__init__ (deep)copies these values to
# instance variables. Mutable defaults are therefore safe.)
# Name of the bundle, with or without extension.
name = None
# The property list ("plist")
plist = Plist(CFBundleDevelopmentRegion = "English",
CFBundleInfoDictionaryVersion = "6.0")
# The type of the bundle.
type = "BNDL"
# The creator code of the bundle.
creator = None
# the CFBundleIdentifier (this is used for the preferences file name)
bundle_id = None
# List of files that have to be copied to <bundle>/Contents/Resources.
resources = []
# List of (src, dest) tuples; dest should be a path relative to the bundle
# (eg. "Contents/Resources/MyStuff/SomeFile.ext).
files = []
# List of shared libraries (dylibs, Frameworks) to bundle with the app
# will be placed in Contents/Frameworks
libs = []
# Directory where the bundle will be assembled.
builddir = "build"
# Make symlinks instead copying files. This is handy during debugging, but
# makes the bundle non-distributable.
symlink = 0
# Verbosity level.
verbosity = 1
# Destination root directory
destroot = ""
def setup(self):
# XXX rethink self.name munging, this is brittle.
self.name, ext = os.path.splitext(self.name)
if not ext:
ext = ".bundle"
bundleextension = ext
# misc (derived) attributes
self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
plist = self.plist
plist.CFBundleName = self.name
plist.CFBundlePackageType = self.type
if self.creator is None:
if hasattr(plist, "CFBundleSignature"):
self.creator = plist.CFBundleSignature
else:
self.creator = "????"
plist.CFBundleSignature = self.creator
if self.bundle_id:
plist.CFBundleIdentifier = self.bundle_id
elif not hasattr(plist, "CFBundleIdentifier"):
plist.CFBundleIdentifier = self.name
def build(self):
"""Build the bundle."""
builddir = self.builddir
if builddir and not os.path.exists(builddir):
os.mkdir(builddir)
self.message("Building %s" % repr(self.bundlepath), 1)
if os.path.exists(self.bundlepath):
shutil.rmtree(self.bundlepath)
os.mkdir(self.bundlepath)
self.preProcess()
self._copyFiles()
self._addMetaFiles()
self.postProcess()
self.message("Done.", 1)
def preProcess(self):
"""Hook for subclasses."""
pass
def postProcess(self):
"""Hook for subclasses."""
pass
def _addMetaFiles(self):
contents = pathjoin(self.bundlepath, "Contents")
makedirs(contents)
#
# Write Contents/PkgInfo
assert len(self.type) == len(self.creator) == 4, \
"type and creator must be 4-byte strings."
pkginfo = pathjoin(contents, "PkgInfo")
f = open(pkginfo, "wb")
f.write(self.type + self.creator)
f.close()
#
# Write Contents/Info.plist
infoplist = pathjoin(contents, "Info.plist")
self.plist.write(infoplist)
def _copyFiles(self):
files = self.files[:]
for path in self.resources:
files.append((path, pathjoin("Contents", "Resources",
os.path.basename(path))))
for path in self.libs:
files.append((path, pathjoin("Contents", "Frameworks",
os.path.basename(path))))
if self.symlink:
self.message("Making symbolic links", 1)
msg = "Making symlink from"
else:
self.message("Copying files", 1)
msg = "Copying"
files.sort()
for src, dst in files:
if os.path.isdir(src):
self.message("%s %s/ to %s/" % (msg, src, dst), 2)
else:
self.message("%s %s to %s" % (msg, src, dst), 2)
dst = pathjoin(self.bundlepath, dst)
if self.symlink:
symlink(src, dst, mkdirs=1)
else:
copy(src, dst, mkdirs=1)
def message(self, msg, level=0):
if level <= self.verbosity:
indent = ""
if level > 1:
indent = (level - 1) * " "
sys.stderr.write(indent + msg + "\n")
def report(self):
# XXX something decent
pass
if __debug__:
PYC_EXT = ".pyc"
else:
PYC_EXT = ".pyo"
MAGIC = imp.get_magic()
USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
# For standalone apps, we have our own minimal site.py. We don't need
# all the cruft of the real site.py.
SITE_PY = """\
import sys
if not %(semi_standalone)s:
del sys.path[1:] # sys.path[0] is Contents/Resources/
"""
if USE_ZIPIMPORT:
ZIP_ARCHIVE = "Modules.zip"
SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
def getPycData(fullname, code, ispkg):
if ispkg:
fullname += ".__init__"
path = fullname.replace(".", os.sep) + PYC_EXT
return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
#
# Extension modules can't be in the modules zip archive, so a placeholder
# is added instead, that loads the extension from a specified location.
#
EXT_LOADER = """\
def __load():
import imp, sys, os
for p in sys.path:
path = os.path.join(p, "%(filename)s")
if os.path.exists(path):
break
else:
assert 0, "file not found: %(filename)s"
mod = imp.load_dynamic("%(name)s", path)
__load()
del __load
"""
MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
]
STRIP_EXEC = "/usr/bin/strip"
#
# We're using a stock interpreter to run the app, yet we need
# a way to pass the Python main program to the interpreter. The
# bootstrapping script fires up the interpreter with the right
# arguments. os.execve() is used as OSX doesn't like us to
# start a real new process. Also, the executable name must match
# the CFBundleExecutable value in the Info.plist, so we lie
# deliberately with argv[0]. The actual Python executable is
# passed in an environment variable so we can "repair"
# sys.executable later.
#
BOOTSTRAP_SCRIPT = """\
#!%(hashbang)s
import sys, os
execdir = os.path.dirname(sys.argv[0])
executable = os.path.join(execdir, "%(executable)s")
resdir = os.path.join(os.path.dirname(execdir), "Resources")
libdir = os.path.join(os.path.dirname(execdir), "Frameworks")
mainprogram = os.path.join(resdir, "%(mainprogram)s")
sys.argv.insert(1, mainprogram)
if %(standalone)s or %(semi_standalone)s:
os.environ["PYTHONPATH"] = resdir
if %(standalone)s:
os.environ["PYTHONHOME"] = resdir
else:
pypath = os.getenv("PYTHONPATH", "")
if pypath:
pypath = ":" + pypath
os.environ["PYTHONPATH"] = resdir + pypath
os.environ["PYTHONEXECUTABLE"] = executable
os.environ["DYLD_LIBRARY_PATH"] = libdir
os.environ["DYLD_FRAMEWORK_PATH"] = libdir
os.execve(executable, sys.argv, os.environ)
"""
#
# Optional wrapper that converts "dropped files" into sys.argv values.
#
ARGV_EMULATOR = """\
import argvemulator, os
argvemulator.ArgvCollector().mainloop()
execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
"""
#
# When building a standalone app with Python.framework, we need to copy
# a subset from Python.framework to the bundle. The following list
# specifies exactly what items we'll copy.
#
PYTHONFRAMEWORKGOODIES = [
"Python", # the Python core library
"Resources/English.lproj",
"Resources/Info.plist",
"Resources/version.plist",
]
def isFramework():
return sys.exec_prefix.find("Python.framework") > 0
LIB = os.path.join(sys.prefix, "lib", "python" + sys.version[:3])
SITE_PACKAGES = os.path.join(LIB, "site-packages")
class AppBuilder(BundleBuilder):
# Override type of the bundle.
type = "APPL"
# platform, name of the subfolder of Contents that contains the executable.
platform = "MacOS"
# A Python main program. If this argument is given, the main
# executable in the bundle will be a small wrapper that invokes
# the main program. (XXX Discuss why.)
mainprogram = None
# The main executable. If a Python main program is specified
# the executable will be copied to Resources and be invoked
# by the wrapper program mentioned above. Otherwise it will
# simply be used as the main executable.
executable = None
# The name of the main nib, for Cocoa apps. *Must* be specified
# when building a Cocoa app.
nibname = None
# The name of the icon file to be copied to Resources and used for
# the Finder icon.
iconfile = None
# Symlink the executable instead of copying it.
symlink_exec = 0
# If True, build standalone app.
standalone = 0
# If True, build semi-standalone app (only includes third-party modules).
semi_standalone = 0
# If set, use this for #! lines in stead of sys.executable
python = None
# If True, add a real main program that emulates sys.argv before calling
# mainprogram
argv_emulation = 0
# The following attributes are only used when building a standalone app.
# Exclude these modules.
excludeModules = []
# Include these modules.
includeModules = []
# Include these packages.
includePackages = []
# Strip binaries from debug info.
strip = 0
# Found Python modules: [(name, codeobject, ispkg), ...]
pymodules = []
# Modules that modulefinder couldn't find:
missingModules = []
maybeMissingModules = []
def setup(self):
if ((self.standalone or self.semi_standalone)
and self.mainprogram is None):
raise BundleBuilderError, ("must specify 'mainprogram' when "
"building a standalone application.")
if self.mainprogram is None and self.executable is None:
raise BundleBuilderError, ("must specify either or both of "
"'executable' and 'mainprogram'")
self.execdir = pathjoin("Contents", self.platform)
if self.name is not None:
pass
elif self.mainprogram is not None:
self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
elif executable is not None:
self.name = os.path.splitext(os.path.basename(self.executable))[0]
if self.name[-4:] != ".app":
self.name += ".app"
if self.executable is None:
if not self.standalone and not isFramework():
self.symlink_exec = 1
if self.python:
self.executable = self.python
else:
self.executable = sys.executable
if self.nibname:
self.plist.NSMainNibFile = self.nibname
if not hasattr(self.plist, "NSPrincipalClass"):
self.plist.NSPrincipalClass = "NSApplication"
if self.standalone and isFramework():
self.addPythonFramework()
BundleBuilder.setup(self)
self.plist.CFBundleExecutable = self.name
if self.standalone or self.semi_standalone:
self.findDependencies()
def preProcess(self):
resdir = "Contents/Resources"
if self.executable is not None:
if self.mainprogram is None:
execname = self.name
else:
execname = os.path.basename(self.executable)
execpath = pathjoin(self.execdir, execname)
if not self.symlink_exec:
self.files.append((self.destroot + self.executable, execpath))
self.execpath = execpath
if self.mainprogram is not None:
mainprogram = os.path.basename(self.mainprogram)
self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
if self.argv_emulation:
# Change the main program, and create the helper main program (which
# does argv collection and then calls the real main).
# Also update the included modules (if we're creating a standalone
# program) and the plist
realmainprogram = mainprogram
mainprogram = '__argvemulator_' + mainprogram
resdirpath = pathjoin(self.bundlepath, resdir)
mainprogrampath = pathjoin(resdirpath, mainprogram)
makedirs(resdirpath)
open(mainprogrampath, "w").write(ARGV_EMULATOR % locals())
if self.standalone or self.semi_standalone:
self.includeModules.append("argvemulator")
self.includeModules.append("os")
if not self.plist.has_key("CFBundleDocumentTypes"):
self.plist["CFBundleDocumentTypes"] = [
{ "CFBundleTypeOSTypes" : [
"****",
"fold",
"disk"],
"CFBundleTypeRole": "Viewer"}]
# Write bootstrap script
executable = os.path.basename(self.executable)
execdir = pathjoin(self.bundlepath, self.execdir)
bootstrappath = pathjoin(execdir, self.name)
makedirs(execdir)
if self.standalone or self.semi_standalone:
# XXX we're screwed when the end user has deleted
# /usr/bin/python
hashbang = "/usr/bin/python"
elif self.python:
hashbang = self.python
else:
hashbang = os.path.realpath(sys.executable)
standalone = self.standalone
semi_standalone = self.semi_standalone
open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
os.chmod(bootstrappath, 0775)
if self.iconfile is not None:
iconbase = os.path.basename(self.iconfile)
self.plist.CFBundleIconFile = iconbase
self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
def postProcess(self):
if self.standalone or self.semi_standalone:
self.addPythonModules()
if self.strip and not self.symlink:
self.stripBinaries()
if self.symlink_exec and self.executable:
self.message("Symlinking executable %s to %s" % (self.executable,
self.execpath), 2)
dst = pathjoin(self.bundlepath, self.execpath)
makedirs(os.path.dirname(dst))
os.symlink(os.path.abspath(self.executable), dst)
if self.missingModules or self.maybeMissingModules:
self.reportMissing()
def addPythonFramework(self):
# If we're building a standalone app with Python.framework,
# include a minimal subset of Python.framework, *unless*
# Python.framework was specified manually in self.libs.
for lib in self.libs:
if os.path.basename(lib) == "Python.framework":
# a Python.framework was specified as a library
return
frameworkpath = sys.exec_prefix[:sys.exec_prefix.find(
"Python.framework") + len("Python.framework")]
version = sys.version[:3]
frameworkpath = pathjoin(frameworkpath, "Versions", version)
destbase = pathjoin("Contents", "Frameworks", "Python.framework",
"Versions", version)
for item in PYTHONFRAMEWORKGOODIES:
src = pathjoin(frameworkpath, item)
dst = pathjoin(destbase, item)
self.files.append((src, dst))
def _getSiteCode(self):
return compile(SITE_PY % {"semi_standalone": self.semi_standalone},
"<-bundlebuilder.py->", "exec")
def addPythonModules(self):
self.message("Adding Python modules", 1)
if USE_ZIPIMPORT:
# Create a zip file containing all modules as pyc.
import zipfile
relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
abspath = pathjoin(self.bundlepath, relpath)
zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
for name, code, ispkg in self.pymodules:
self.message("Adding Python module %s" % name, 2)
path, pyc = getPycData(name, code, ispkg)
zf.writestr(path, pyc)
zf.close()
# add site.pyc
sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
"site" + PYC_EXT)
writePyc(self._getSiteCode(), sitepath)
else:
# Create individual .pyc files.
for name, code, ispkg in self.pymodules:
if ispkg:
name += ".__init__"
path = name.split(".")
path = pathjoin("Contents", "Resources", *path) + PYC_EXT
if ispkg:
self.message("Adding Python package %s" % path, 2)
else:
self.message("Adding Python module %s" % path, 2)
abspath = pathjoin(self.bundlepath, path)
makedirs(os.path.dirname(abspath))
writePyc(code, abspath)
def stripBinaries(self):
if not os.path.exists(STRIP_EXEC):
self.message("Error: can't strip binaries: no strip program at "
"%s" % STRIP_EXEC, 0)
else:
import stat
self.message("Stripping binaries", 1)
def walk(top):
for name in os.listdir(top):
path = pathjoin(top, name)
if os.path.islink(path):
continue
if os.path.isdir(path):
walk(path)
else:
mod = os.stat(path)[stat.ST_MODE]
if not (mod & 0100):
continue
relpath = path[len(self.bundlepath):]
self.message("Stripping %s" % relpath, 2)
inf, outf = os.popen4("%s -S \"%s\"" %
(STRIP_EXEC, path))
output = outf.read().strip()
if output:
# usually not a real problem, like when we're
# trying to strip a script
self.message("Problem stripping %s:" % relpath, 3)
self.message(output, 3)
walk(self.bundlepath)
def findDependencies(self):
self.message("Finding module dependencies", 1)
import modulefinder
mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
if USE_ZIPIMPORT:
# zipimport imports zlib, must add it manually
mf.import_hook("zlib")
# manually add our own site.py
site = mf.add_module("site")
site.__code__ = self._getSiteCode()
mf.scan_code(site.__code__, site)
# warnings.py gets imported implicitly from C
mf.import_hook("warnings")
includeModules = self.includeModules[:]
for name in self.includePackages:
includeModules.extend(findPackageContents(name).keys())
for name in includeModules:
try:
mf.import_hook(name)
except ImportError:
self.missingModules.append(name)
mf.run_script(self.mainprogram)
modules = mf.modules.items()
modules.sort()
for name, mod in modules:
path = mod.__file__
if path and self.semi_standalone:
# skip the standard library
if path.startswith(LIB) and not path.startswith(SITE_PACKAGES):
continue
if path and mod.__code__ is None:
# C extension
filename = os.path.basename(path)
pathitems = name.split(".")[:-1] + [filename]
dstpath = pathjoin(*pathitems)
if USE_ZIPIMPORT:
if name != "zlib":
# neatly pack all extension modules in a subdirectory,
# except zlib, since it's neccesary for bootstrapping.
dstpath = pathjoin("ExtensionModules", dstpath)
# Python modules are stored in a Zip archive, but put
# extensions in Contents/Resources/. Add a tiny "loader"
# program in the Zip archive. Due to Thomas Heller.
source = EXT_LOADER % {"name": name, "filename": dstpath}
code = compile(source, "<dynloader for %s>" % name, "exec")
mod.__code__ = code
self.files.append((path, pathjoin("Contents", "Resources", dstpath)))
if mod.__code__ is not None:
ispkg = mod.__path__ is not None
if not USE_ZIPIMPORT or name != "site":
# Our site.py is doing the bootstrapping, so we must
# include a real .pyc file if USE_ZIPIMPORT is True.
self.pymodules.append((name, mod.__code__, ispkg))
if hasattr(mf, "any_missing_maybe"):
missing, maybe = mf.any_missing_maybe()
else:
missing = mf.any_missing()
maybe = []
self.missingModules.extend(missing)
self.maybeMissingModules.extend(maybe)
def reportMissing(self):
missing = [name for name in self.missingModules
if name not in MAYMISS_MODULES]
if self.maybeMissingModules:
maybe = self.maybeMissingModules
else:
maybe = [name for name in missing if "." in name]
missing = [name for name in missing if "." not in name]
missing.sort()
maybe.sort()
if maybe:
self.message("Warning: couldn't find the following submodules:", 1)
self.message(" (Note that these could be false alarms -- "
"it's not always", 1)
self.message(" possible to distinguish between \"from package "
"import submodule\" ", 1)
self.message(" and \"from package import name\")", 1)
for name in maybe:
self.message(" ? " + name, 1)
if missing:
self.message("Warning: couldn't find the following modules:", 1)
for name in missing:
self.message(" ? " + name, 1)
def report(self):
# XXX something decent
import pprint
pprint.pprint(self.__dict__)
if self.standalone or self.semi_standalone:
self.reportMissing()
#
# Utilities.
#
SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
def findPackageContents(name, searchpath=None):
head = name.split(".")[-1]
if identifierRE.match(head) is None:
return {}
try:
fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
except ImportError:
return {}
modules = {name: None}
if tp == imp.PKG_DIRECTORY and path:
files = os.listdir(path)
for sub in files:
sub, ext = os.path.splitext(sub)
fullname = name + "." + sub
if sub != "__init__" and fullname not in modules:
modules.update(findPackageContents(fullname, [path]))
return modules
def writePyc(code, path):
f = open(path, "wb")
f.write(MAGIC)
f.write("\0" * 4) # don't bother about a time stamp
marshal.dump(code, f)
f.close()
def copy(src, dst, mkdirs=0):
"""Copy a file or a directory."""
if mkdirs:
makedirs(os.path.dirname(dst))
if os.path.isdir(src):
shutil.copytree(src, dst, symlinks=1)
else:
shutil.copy2(src, dst)
def copytodir(src, dstdir):
"""Copy a file or a directory to an existing directory."""
dst = pathjoin(dstdir, os.path.basename(src))
copy(src, dst)
def makedirs(dir):
"""Make all directories leading up to 'dir' including the leaf
directory. Don't moan if any path element already exists."""
try:
os.makedirs(dir)
except OSError, why:
if why.errno != errno.EEXIST:
raise
def symlink(src, dst, mkdirs=0):
"""Copy a file or a directory."""
if not os.path.exists(src):
raise IOError, "No such file or directory: '%s'" % src
if mkdirs:
makedirs(os.path.dirname(dst))
os.symlink(os.path.abspath(src), dst)
def pathjoin(*args):
"""Safe wrapper for os.path.join: asserts that all but the first
argument are relative paths."""
for seg in args[1:]:
assert seg[0] != "/"
return os.path.join(*args)
cmdline_doc = """\
Usage:
python bundlebuilder.py [options] command
python mybuildscript.py [options] command
Commands:
build build the application
report print a report
Options:
-b, --builddir=DIR the build directory; defaults to "build"
-n, --name=NAME application name
-r, --resource=FILE extra file or folder to be copied to Resources
-f, --file=SRC:DST extra file or folder to be copied into the bundle;
DST must be a path relative to the bundle root
-e, --executable=FILE the executable to be used
-m, --mainprogram=FILE the Python main program
-a, --argv add a wrapper main program to create sys.argv
-p, --plist=FILE .plist file (default: generate one)
--nib=NAME main nib name
-c, --creator=CCCC 4-char creator code (default: '????')
--iconfile=FILE filename of the icon (an .icns file) to be used
as the Finder icon
--bundle-id=ID the CFBundleIdentifier, in reverse-dns format
(eg. org.python.BuildApplet; this is used for
the preferences file name)
-l, --link symlink files/folder instead of copying them
--link-exec symlink the executable instead of copying it
--standalone build a standalone application, which is fully
independent of a Python installation
--semi-standalone build a standalone application, which depends on
an installed Python, yet includes all third-party
modules.
--python=FILE Python to use in #! line in stead of current Python
--lib=FILE shared library or framework to be copied into
the bundle
-x, --exclude=MODULE exclude module (with --(semi-)standalone)
-i, --include=MODULE include module (with --(semi-)standalone)
--package=PACKAGE include a whole package (with --(semi-)standalone)
--strip strip binaries (remove debug info)
-v, --verbose increase verbosity level
-q, --quiet decrease verbosity level
-h, --help print this message
"""
def usage(msg=None):
if msg:
print msg
print cmdline_doc
sys.exit(1)
def main(builder=None):
if builder is None:
builder = AppBuilder(verbosity=1)
shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
"mainprogram=", "creator=", "nib=", "plist=", "link",
"link-exec", "help", "verbose", "quiet", "argv", "standalone",
"exclude=", "include=", "package=", "strip", "iconfile=",
"lib=", "python=", "semi-standalone", "bundle-id=", "destroot=")
try:
options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
except getopt.error:
usage()
for opt, arg in options:
if opt in ('-b', '--builddir'):
builder.builddir = arg
elif opt in ('-n', '--name'):
builder.name = arg
elif opt in ('-r', '--resource'):
builder.resources.append(os.path.normpath(arg))
elif opt in ('-f', '--file'):
srcdst = arg.split(':')
if len(srcdst) != 2:
usage("-f or --file argument must be two paths, "
"separated by a colon")
builder.files.append(srcdst)
elif opt in ('-e', '--executable'):
builder.executable = arg
elif opt in ('-m', '--mainprogram'):
builder.mainprogram = arg
elif opt in ('-a', '--argv'):
builder.argv_emulation = 1
elif opt in ('-c', '--creator'):
builder.creator = arg
elif opt == '--bundle-id':
builder.bundle_id = arg
elif opt == '--iconfile':
builder.iconfile = arg
elif opt == "--lib":
builder.libs.append(os.path.normpath(arg))
elif opt == "--nib":
builder.nibname = arg
elif opt in ('-p', '--plist'):
builder.plist = Plist.fromFile(arg)
elif opt in ('-l', '--link'):
builder.symlink = 1
elif opt == '--link-exec':
builder.symlink_exec = 1
elif opt in ('-h', '--help'):
usage()
elif opt in ('-v', '--verbose'):
builder.verbosity += 1
elif opt in ('-q', '--quiet'):
builder.verbosity -= 1
elif opt == '--standalone':
builder.standalone = 1
elif opt == '--semi-standalone':
builder.semi_standalone = 1
elif opt == '--python':
builder.python = arg
elif opt in ('-x', '--exclude'):
builder.excludeModules.append(arg)
elif opt in ('-i', '--include'):
builder.includeModules.append(arg)
elif opt == '--package':
builder.includePackages.append(arg)
elif opt == '--strip':
builder.strip = 1
elif opt == '--destroot':
builder.destroot = arg
if len(args) != 1:
usage("Must specify one command ('build', 'report' or 'help')")
command = args[0]
if command == "build":
builder.setup()
builder.build()
elif command == "report":
builder.setup()
builder.report()
elif command == "help":
usage()
else:
usage("Unknown command '%s'" % command)
def buildapp(**kwargs):
builder = AppBuilder(**kwargs)
main(builder)
if __name__ == "__main__":
main()
| Python |
"A sort of application framework for the Mac"
DEBUG=0
import MacOS
import traceback
from Carbon.AE import *
from Carbon.AppleEvents import *
from Carbon.Ctl import *
from Carbon.Controls import *
from Carbon.Dlg import *
from Carbon.Dialogs import *
from Carbon.Evt import *
from Carbon.Events import *
from Carbon.Help import *
from Carbon.Menu import *
from Carbon.Menus import *
from Carbon.Qd import *
from Carbon.QuickDraw import *
#from Carbon.Res import *
#from Carbon.Resources import *
#from Carbon.Snd import *
#from Carbon.Sound import *
from Carbon.Win import *
from Carbon.Windows import *
import types
import EasyDialogs
try:
MyFrontWindow = FrontNonFloatingWindow
except NameError:
MyFrontWindow = FrontWindow
kHighLevelEvent = 23 # Don't know what header file this should come from
SCROLLBARWIDTH = 16 # Again, not a clue...
# Trick to forestall a set of SIOUX menus being added to our menubar
SIOUX_APPLEMENU_ID=32000
# Map event 'what' field to strings
eventname = {}
eventname[1] = 'mouseDown'
eventname[2] = 'mouseUp'
eventname[3] = 'keyDown'
eventname[4] = 'keyUp'
eventname[5] = 'autoKey'
eventname[6] = 'updateEvt'
eventname[7] = 'diskEvt'
eventname[8] = 'activateEvt'
eventname[15] = 'osEvt'
eventname[23] = 'kHighLevelEvent'
# Map part codes returned by WhichWindow() to strings
partname = {}
partname[0] = 'inDesk'
partname[1] = 'inMenuBar'
partname[2] = 'inSysWindow'
partname[3] = 'inContent'
partname[4] = 'inDrag'
partname[5] = 'inGrow'
partname[6] = 'inGoAway'
partname[7] = 'inZoomIn'
partname[8] = 'inZoomOut'
#
# The useable portion of the screen
# ## but what happens with multiple screens? jvr
screenbounds = GetQDGlobalsScreenBits().bounds
screenbounds = screenbounds[0]+4, screenbounds[1]+4, \
screenbounds[2]-4, screenbounds[3]-4
next_window_x = 16 # jvr
next_window_y = 44 # jvr
def windowbounds(width, height):
"Return sensible window bounds"
global next_window_x, next_window_y
r, b = next_window_x+width, next_window_y+height
if r > screenbounds[2]:
next_window_x = 16
if b > screenbounds[3]:
next_window_y = 44
l, t = next_window_x, next_window_y
r, b = next_window_x+width, next_window_y+height
next_window_x, next_window_y = next_window_x + 8, next_window_y + 20 # jvr
return l, t, r, b
_watch = None
def setwatchcursor():
global _watch
if _watch == None:
_watch = GetCursor(4).data
SetCursor(_watch)
def setarrowcursor():
SetCursor(GetQDGlobalsArrow())
class Application:
"Application framework -- your application should be a derived class"
def __init__(self, nomenubar=0):
self._doing_asyncevents = 0
self.quitting = 0
self.needmenubarredraw = 0
self._windows = {}
self._helpmenu = None
if nomenubar:
self.menubar = None
else:
self.makemenubar()
def __del__(self):
if self._doing_asyncevents:
self._doing_asyncevents = 0
MacOS.SetEventHandler()
def makemenubar(self):
self.menubar = MenuBar(self)
AppleMenu(self.menubar, self.getabouttext(), self.do_about)
self.makeusermenus()
def makeusermenus(self):
self.filemenu = m = Menu(self.menubar, "File")
self._quititem = MenuItem(m, "Quit", "Q", self._quit)
def gethelpmenu(self):
if self._helpmenu == None:
self._helpmenu = HelpMenu(self.menubar)
return self._helpmenu
def _quit(self, *args):
self.quitting = 1
def cleanup(self):
for w in self._windows.values():
w.do_close()
return self._windows == {}
def appendwindow(self, wid, window):
self._windows[wid] = window
def removewindow(self, wid):
del self._windows[wid]
def getabouttext(self):
return "About %s..." % self.__class__.__name__
def do_about(self, id, item, window, event):
EasyDialogs.Message("Hello, world!" + "\015(%s)" % self.__class__.__name__)
# The main event loop is broken up in several simple steps.
# This is done so you can override each individual part,
# if you have a need to do extra processing independent of the
# event type.
# Normally, however, you'd just define handlers for individual
# events.
schedparams = (0, 0) # By default disable Python's event handling
default_wait = None # By default we wait GetCaretTime in WaitNextEvent
def mainloop(self, mask = everyEvent, wait = None):
self.quitting = 0
if hasattr(MacOS, 'SchedParams'):
saveparams = MacOS.SchedParams(*self.schedparams)
try:
while not self.quitting:
try:
self.do1event(mask, wait)
except (Application, SystemExit):
# Note: the raising of "self" is old-fashioned idiom to
# exit the mainloop. Calling _quit() is better for new
# applications.
break
finally:
if hasattr(MacOS, 'SchedParams'):
MacOS.SchedParams(*saveparams)
def dopendingevents(self, mask = everyEvent):
"""dopendingevents - Handle all pending events"""
while self.do1event(mask, wait=0):
pass
def do1event(self, mask = everyEvent, wait = None):
ok, event = self.getevent(mask, wait)
if IsDialogEvent(event):
if self.do_dialogevent(event):
return
if ok:
self.dispatch(event)
else:
self.idle(event)
def idle(self, event):
pass
def getevent(self, mask = everyEvent, wait = None):
if self.needmenubarredraw:
DrawMenuBar()
self.needmenubarredraw = 0
if wait is None:
wait = self.default_wait
if wait is None:
wait = GetCaretTime()
ok, event = WaitNextEvent(mask, wait)
return ok, event
def dispatch(self, event):
# The following appears to be double work (already done in do1event)
# but we need it for asynchronous event handling
if IsDialogEvent(event):
if self.do_dialogevent(event):
return
(what, message, when, where, modifiers) = event
if eventname.has_key(what):
name = "do_" + eventname[what]
else:
name = "do_%d" % what
try:
handler = getattr(self, name)
except AttributeError:
handler = self.do_unknownevent
handler(event)
def asyncevents(self, onoff):
"""asyncevents - Set asynchronous event handling on or off"""
if MacOS.runtimemodel == 'macho':
raise 'Unsupported in MachoPython'
old = self._doing_asyncevents
if old:
MacOS.SetEventHandler()
MacOS.SchedParams(*self.schedparams)
if onoff:
MacOS.SetEventHandler(self.dispatch)
doint, dummymask, benice, howoften, bgyield = \
self.schedparams
MacOS.SchedParams(doint, everyEvent, benice,
howoften, bgyield)
self._doing_asyncevents = onoff
return old
def do_dialogevent(self, event):
gotone, dlg, item = DialogSelect(event)
if gotone:
window = dlg.GetDialogWindow()
if self._windows.has_key(window):
self._windows[window].do_itemhit(item, event)
else:
print 'Dialog event for unknown dialog'
return 1
return 0
def do_mouseDown(self, event):
(what, message, when, where, modifiers) = event
partcode, wid = FindWindow(where)
#
# Find the correct name.
#
if partname.has_key(partcode):
name = "do_" + partname[partcode]
else:
name = "do_%d" % partcode
if wid == None:
# No window, or a non-python window
try:
handler = getattr(self, name)
except AttributeError:
# Not menubar or something, so assume someone
# else's window
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
return
elif self._windows.has_key(wid):
# It is a window. Hand off to correct window.
window = self._windows[wid]
try:
handler = getattr(window, name)
except AttributeError:
handler = self.do_unknownpartcode
else:
# It is a python-toolbox window, but not ours.
handler = self.do_unknownwindow
handler(partcode, wid, event)
def do_inSysWindow(self, partcode, window, event):
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
def do_inDesk(self, partcode, window, event):
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
def do_inMenuBar(self, partcode, window, event):
if not self.menubar:
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
return
(what, message, when, where, modifiers) = event
result = MenuSelect(where)
id = (result>>16) & 0xffff # Hi word
if id >= 0x8000:
id = -65536 + id
item = result & 0xffff # Lo word
self.do_rawmenu(id, item, window, event)
def do_rawmenu(self, id, item, window, event):
try:
self.do_menu(id, item, window, event)
finally:
HiliteMenu(0)
def do_menu(self, id, item, window, event):
if hasattr(MacOS, 'OutputSeen'):
MacOS.OutputSeen()
self.menubar.dispatch(id, item, window, event)
def do_unknownpartcode(self, partcode, window, event):
(what, message, when, where, modifiers) = event
if DEBUG: print "Mouse down at global:", where
if DEBUG: print "\tUnknown part code:", partcode
if DEBUG: print "\tEvent:", self.printevent(event)
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
def do_unknownwindow(self, partcode, window, event):
if DEBUG: print 'Unknown window:', window
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
def do_keyDown(self, event):
self.do_key(event)
def do_autoKey(self, event):
if not event[-1] & cmdKey:
self.do_key(event)
def do_key(self, event):
(what, message, when, where, modifiers) = event
c = chr(message & charCodeMask)
if self.menubar:
result = MenuEvent(event)
id = (result>>16) & 0xffff # Hi word
item = result & 0xffff # Lo word
if id:
self.do_rawmenu(id, item, None, event)
return
# Otherwise we fall-through
if modifiers & cmdKey:
if c == '.':
raise self
else:
if not self.menubar:
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
return
else:
# See whether the front window wants it
w = MyFrontWindow()
if w and self._windows.has_key(w):
window = self._windows[w]
try:
do_char = window.do_char
except AttributeError:
do_char = self.do_char
do_char(c, event)
# else it wasn't for us, sigh...
def do_char(self, c, event):
if DEBUG: print "Character", repr(c)
def do_updateEvt(self, event):
(what, message, when, where, modifiers) = event
wid = WhichWindow(message)
if wid and self._windows.has_key(wid):
window = self._windows[wid]
window.do_rawupdate(wid, event)
else:
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
def do_activateEvt(self, event):
(what, message, when, where, modifiers) = event
wid = WhichWindow(message)
if wid and self._windows.has_key(wid):
window = self._windows[wid]
window.do_activate(modifiers & 1, event)
else:
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
def do_osEvt(self, event):
(what, message, when, where, modifiers) = event
which = (message >> 24) & 0xff
if which == 1: # suspend/resume
self.do_suspendresume(event)
else:
if DEBUG:
print 'unknown osEvt:',
self.printevent(event)
def do_suspendresume(self, event):
(what, message, when, where, modifiers) = event
wid = MyFrontWindow()
if wid and self._windows.has_key(wid):
window = self._windows[wid]
window.do_activate(message & 1, event)
def do_kHighLevelEvent(self, event):
(what, message, when, where, modifiers) = event
if DEBUG:
print "High Level Event:",
self.printevent(event)
try:
AEProcessAppleEvent(event)
except:
pass
#print "AEProcessAppleEvent error:"
#traceback.print_exc()
def do_unknownevent(self, event):
if DEBUG:
print "Unhandled event:",
self.printevent(event)
def printevent(self, event):
(what, message, when, where, modifiers) = event
nicewhat = repr(what)
if eventname.has_key(what):
nicewhat = eventname[what]
print nicewhat,
if what == kHighLevelEvent:
h, v = where
print repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))),
else:
print hex(message), hex(when), where,
print hex(modifiers)
class MenuBar:
"""Represent a set of menus in a menu bar.
Interface:
- (constructor)
- (destructor)
- addmenu
- addpopup (normally used internally)
- dispatch (called from Application)
"""
nextid = 1 # Necessarily a class variable
def getnextid(self):
id = MenuBar.nextid
MenuBar.nextid = id+1
return id
def __init__(self, parent=None):
self.parent = parent
ClearMenuBar()
self.bar = GetMenuBar()
self.menus = {}
# XXX necessary?
def close(self):
self.parent = None
self.bar = None
self.menus = None
def addmenu(self, title, after = 0, id=None):
if id == None:
id = self.getnextid()
if DEBUG: print 'Newmenu', title, id # XXXX
m = NewMenu(id, title)
m.InsertMenu(after)
if after >= 0:
if self.parent:
self.parent.needmenubarredraw = 1
else:
DrawMenuBar()
return id, m
def delmenu(self, id):
if DEBUG: print 'Delmenu', id # XXXX
DeleteMenu(id)
def addpopup(self, title = ''):
return self.addmenu(title, -1)
# Useless:
# def install(self):
# if not self.bar: return
# SetMenuBar(self.bar)
# if self.parent:
# self.parent.needmenubarredraw = 1
# else:
# DrawMenuBar()
def fixmenudimstate(self):
for m in self.menus.keys():
menu = self.menus[m]
if menu.__class__ == FrameWork.AppleMenu:
continue
for i in range(len(menu.items)):
label, shortcut, callback, kind = menu.items[i]
if type(callback) == types.StringType:
wid = MyFrontWindow()
if wid and self.parent._windows.has_key(wid):
window = self.parent._windows[wid]
if hasattr(window, "domenu_" + callback):
menu.menu.EnableMenuItem(i + 1)
elif hasattr(self.parent, "domenu_" + callback):
menu.menu.EnableMenuItem(i + 1)
else:
menu.menu.DisableMenuItem(i + 1)
elif hasattr(self.parent, "domenu_" + callback):
menu.menu.EnableMenuItem(i + 1)
else:
menu.menu.DisableMenuItem(i + 1)
elif callback:
pass
def dispatch(self, id, item, window, event):
if self.menus.has_key(id):
self.menus[id].dispatch(id, item, window, event)
else:
if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \
(id, item, window, event)
# XXX Need a way to get menus as resources and bind them to callbacks
class Menu:
"One menu."
def __init__(self, bar, title, after=0, id=None):
self.bar = bar
self.id, self.menu = self.bar.addmenu(title, after, id)
bar.menus[self.id] = self
self.items = []
self._parent = None
def delete(self):
self.bar.delmenu(self.id)
del self.bar.menus[self.id]
self.menu.DisposeMenu()
del self.bar
del self.items
del self.menu
del self.id
del self._parent
def additem(self, label, shortcut=None, callback=None, kind=None):
self.menu.AppendMenu('x') # add a dummy string
self.items.append((label, shortcut, callback, kind))
item = len(self.items)
if isinstance(label, unicode):
self.menu.SetMenuItemTextWithCFString(item, label)
else:
self.menu.SetMenuItemText(item, label)
if shortcut and type(shortcut) == type(()):
modifiers, char = shortcut[:2]
self.menu.SetItemCmd(item, ord(char))
self.menu.SetMenuItemModifiers(item, modifiers)
if len(shortcut) > 2:
self.menu.SetMenuItemKeyGlyph(item, shortcut[2])
elif shortcut:
self.menu.SetItemCmd(item, ord(shortcut))
return item
def delitem(self, item):
if item != len(self.items):
raise 'Can only delete last item of a menu'
self.menu.DeleteMenuItem(item)
del self.items[item-1]
def addcheck(self, label, shortcut=None, callback=None):
return self.additem(label, shortcut, callback, 'check')
def addradio(self, label, shortcut=None, callback=None):
return self.additem(label, shortcut, callback, 'radio')
def addseparator(self):
self.menu.AppendMenu('(-')
self.items.append(('', None, None, 'separator'))
def addsubmenu(self, label, title=''):
sub = Menu(self.bar, title, -1)
item = self.additem(label, '\x1B', None, 'submenu')
self.menu.SetItemMark(item, sub.id)
sub._parent = self
sub._parent_item = item
return sub
def dispatch(self, id, item, window, event):
title, shortcut, callback, mtype = self.items[item-1]
if callback:
if not self.bar.parent or type(callback) <> types.StringType:
menuhandler = callback
else:
# callback is string
wid = MyFrontWindow()
if wid and self.bar.parent._windows.has_key(wid):
window = self.bar.parent._windows[wid]
if hasattr(window, "domenu_" + callback):
menuhandler = getattr(window, "domenu_" + callback)
elif hasattr(self.bar.parent, "domenu_" + callback):
menuhandler = getattr(self.bar.parent, "domenu_" + callback)
else:
# nothing we can do. we shouldn't have come this far
# since the menu item should have been disabled...
return
elif hasattr(self.bar.parent, "domenu_" + callback):
menuhandler = getattr(self.bar.parent, "domenu_" + callback)
else:
# nothing we can do. we shouldn't have come this far
# since the menu item should have been disabled...
return
menuhandler(id, item, window, event)
def enable(self, onoff):
if onoff:
self.menu.EnableMenuItem(0)
if self._parent:
self._parent.menu.EnableMenuItem(self._parent_item)
else:
self.menu.DisableMenuItem(0)
if self._parent:
self._parent.menu.DisableMenuItem(self._parent_item)
if self.bar and self.bar.parent:
self.bar.parent.needmenubarredraw = 1
class PopupMenu(Menu):
def __init__(self, bar):
Menu.__init__(self, bar, '(popup)', -1)
def popup(self, x, y, event, default=1, window=None):
# NOTE that x and y are global coordinates, and they should probably
# be topleft of the button the user clicked (not mouse-coordinates),
# so the popup nicely overlaps.
reply = self.menu.PopUpMenuSelect(x, y, default)
if not reply:
return
id = (reply >> 16) & 0xffff
item = reply & 0xffff
if not window:
wid = MyFrontWindow()
try:
window = self.bar.parent._windows[wid]
except:
pass # If we can't find the window we pass None
self.dispatch(id, item, window, event)
class MenuItem:
def __init__(self, menu, title, shortcut=None, callback=None, kind=None):
self.item = menu.additem(title, shortcut, callback)
self.menu = menu
def delete(self):
self.menu.delitem(self.item)
del self.menu
del self.item
def check(self, onoff):
self.menu.menu.CheckMenuItem(self.item, onoff)
def enable(self, onoff):
if onoff:
self.menu.menu.EnableMenuItem(self.item)
else:
self.menu.menu.DisableMenuItem(self.item)
def settext(self, text):
self.menu.menu.SetMenuItemText(self.item, text)
def setstyle(self, style):
self.menu.menu.SetItemStyle(self.item, style)
def seticon(self, icon):
self.menu.menu.SetItemIcon(self.item, icon)
def setcmd(self, cmd):
self.menu.menu.SetItemCmd(self.item, cmd)
def setmark(self, cmd):
self.menu.menu.SetItemMark(self.item, cmd)
class RadioItem(MenuItem):
def __init__(self, menu, title, shortcut=None, callback=None):
MenuItem.__init__(self, menu, title, shortcut, callback, 'radio')
class CheckItem(MenuItem):
def __init__(self, menu, title, shortcut=None, callback=None):
MenuItem.__init__(self, menu, title, shortcut, callback, 'check')
def Separator(menu):
menu.addseparator()
def SubMenu(menu, label, title=''):
return menu.addsubmenu(label, title)
class AppleMenu(Menu):
def __init__(self, bar, abouttext="About me...", aboutcallback=None):
Menu.__init__(self, bar, "\024", id=SIOUX_APPLEMENU_ID)
if MacOS.runtimemodel == 'ppc':
self.additem(abouttext, None, aboutcallback)
self.addseparator()
self.menu.AppendResMenu('DRVR')
else:
# Additem()'s tricks do not work for "apple" menu under Carbon
self.menu.InsertMenuItem(abouttext, 0)
self.items.append((abouttext, None, aboutcallback, None))
def dispatch(self, id, item, window, event):
if item == 1:
Menu.dispatch(self, id, item, window, event)
elif MacOS.runtimemodel == 'ppc':
name = self.menu.GetMenuItemText(item)
OpenDeskAcc(name)
class HelpMenu(Menu):
def __init__(self, bar):
# Note we don't call Menu.__init__, we do the necessary things by hand
self.bar = bar
self.menu, index = HMGetHelpMenu()
self.id = self.menu.GetMenuID()
bar.menus[self.id] = self
# The next line caters for the entries the system already handles for us
self.items = [None]*(index-1)
self._parent = None
class Window:
"""A single window belonging to an application"""
def __init__(self, parent):
self.wid = None
self.parent = parent
def open(self, bounds=(40, 40, 400, 400), resid=None):
if resid <> None:
self.wid = GetNewWindow(resid, -1)
else:
self.wid = NewWindow(bounds, self.__class__.__name__, 1,
8, -1, 1, 0) # changed to proc id 8 to include zoom box. jvr
self.do_postopen()
def do_postopen(self):
"""Tell our parent we exist"""
self.parent.appendwindow(self.wid, self)
def close(self):
self.do_postclose()
def do_postclose(self):
self.parent.removewindow(self.wid)
self.parent = None
self.wid = None
def SetPort(self):
# Convinience method
SetPort(self.wid)
def GetWindow(self):
return self.wid
def do_inDrag(self, partcode, window, event):
where = event[3]
window.DragWindow(where, self.draglimit)
draglimit = screenbounds
def do_inGoAway(self, partcode, window, event):
where = event[3]
if window.TrackGoAway(where):
self.close()
def do_inZoom(self, partcode, window, event):
(what, message, when, where, modifiers) = event
if window.TrackBox(where, partcode):
window.ZoomWindow(partcode, 1)
rect = window.GetWindowUserState() # so that zoom really works... jvr
self.do_postresize(rect[2] - rect[0], rect[3] - rect[1], window) # jvr
def do_inZoomIn(self, partcode, window, event):
SetPort(window) # !!!
self.do_inZoom(partcode, window, event)
def do_inZoomOut(self, partcode, window, event):
SetPort(window) # !!!
self.do_inZoom(partcode, window, event)
def do_inGrow(self, partcode, window, event):
(what, message, when, where, modifiers) = event
result = window.GrowWindow(where, self.growlimit)
if result:
height = (result>>16) & 0xffff # Hi word
width = result & 0xffff # Lo word
self.do_resize(width, height, window)
growlimit = (50, 50, screenbounds[2] - screenbounds[0], screenbounds[3] - screenbounds[1]) # jvr
def do_resize(self, width, height, window):
l, t, r, b = self.wid.GetWindowPort().GetPortBounds() # jvr, forGrowIcon
self.SetPort() # jvr
self.wid.InvalWindowRect((r - SCROLLBARWIDTH + 1, b - SCROLLBARWIDTH + 1, r, b)) # jvr
window.SizeWindow(width, height, 1) # changed updateFlag to true jvr
self.do_postresize(width, height, window)
def do_postresize(self, width, height, window):
SetPort(window)
self.wid.InvalWindowRect(window.GetWindowPort().GetPortBounds())
def do_inContent(self, partcode, window, event):
#
# If we're not frontmost, select ourselves and wait for
# the activate event.
#
if MyFrontWindow() <> window:
window.SelectWindow()
return
# We are. Handle the event.
(what, message, when, where, modifiers) = event
SetPort(window)
local = GlobalToLocal(where)
self.do_contentclick(local, modifiers, event)
def do_contentclick(self, local, modifiers, event):
if DEBUG:
print 'Click in contents at %s, modifiers %s'%(local, modifiers)
def do_rawupdate(self, window, event):
if DEBUG: print "raw update for", window
SetPort(window)
window.BeginUpdate()
self.do_update(window, event)
window.EndUpdate()
def do_update(self, window, event):
if DEBUG:
import time
for i in range(8):
time.sleep(0.1)
InvertRgn(window.GetWindowPort().visRgn)
FillRgn(window.GetWindowPort().visRgn, GetQDGlobalsGray())
else:
EraseRgn(window.GetWindowPort().visRgn)
def do_activate(self, activate, event):
if DEBUG: print 'Activate %d for %s'%(activate, self.wid)
class ControlsWindow(Window):
def do_rawupdate(self, window, event):
if DEBUG: print "raw update for", window
SetPort(window)
window.BeginUpdate()
self.do_update(window, event)
#DrawControls(window) # jvr
UpdateControls(window, window.GetWindowPort().visRgn) # jvr
window.DrawGrowIcon()
window.EndUpdate()
def do_controlhit(self, window, control, pcode, event):
if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode
def do_inContent(self, partcode, window, event):
if MyFrontWindow() <> window:
window.SelectWindow()
return
(what, message, when, where, modifiers) = event
SetPort(window) # XXXX Needed?
local = GlobalToLocal(where)
pcode, control = FindControl(local, window)
if pcode and control:
self.do_rawcontrolhit(window, control, pcode, local, event)
else:
if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \
(local, window, pcode, control)
self.do_contentclick(local, modifiers, event)
def do_rawcontrolhit(self, window, control, pcode, local, event):
pcode = control.TrackControl(local)
if pcode:
self.do_controlhit(window, control, pcode, event)
class ScrolledWindow(ControlsWindow):
def __init__(self, parent):
self.barx = self.bary = None
self.barx_enabled = self.bary_enabled = 1
self.activated = 1
ControlsWindow.__init__(self, parent)
def scrollbars(self, wantx=1, wanty=1):
SetPort(self.wid)
self.barx = self.bary = None
self.barx_enabled = self.bary_enabled = 1
x0, y0, x1, y1 = self.wid.GetWindowPort().GetPortBounds()
vx, vy = self.getscrollbarvalues()
if vx == None: self.barx_enabled, vx = 0, 0
if vy == None: self.bary_enabled, vy = 0, 0
if wantx:
rect = x0-1, y1-(SCROLLBARWIDTH-1), x1-(SCROLLBARWIDTH-2), y1+1
self.barx = NewControl(self.wid, rect, "", 1, vx, 0, 32767, 16, 0)
if not self.barx_enabled: self.barx.HiliteControl(255)
## self.wid.InvalWindowRect(rect)
if wanty:
rect = x1-(SCROLLBARWIDTH-1), y0-1, x1+1, y1-(SCROLLBARWIDTH-2)
self.bary = NewControl(self.wid, rect, "", 1, vy, 0, 32767, 16, 0)
if not self.bary_enabled: self.bary.HiliteControl(255)
## self.wid.InvalWindowRect(rect)
def do_postclose(self):
self.barx = self.bary = None
ControlsWindow.do_postclose(self)
def do_activate(self, onoff, event):
self.activated = onoff
if onoff:
if self.barx and self.barx_enabled:
self.barx.ShowControl() # jvr
if self.bary and self.bary_enabled:
self.bary.ShowControl() # jvr
else:
if self.barx:
self.barx.HideControl() # jvr; An inactive window should have *hidden*
# scrollbars, not just dimmed (no matter what
# BBEdit does... look at the Finder)
if self.bary:
self.bary.HideControl() # jvr
self.wid.DrawGrowIcon() # jvr
def do_postresize(self, width, height, window):
l, t, r, b = self.wid.GetWindowPort().GetPortBounds()
self.SetPort()
if self.barx:
self.barx.HideControl() # jvr
self.barx.MoveControl(l-1, b-(SCROLLBARWIDTH-1))
self.barx.SizeControl((r-l)-(SCROLLBARWIDTH-3), SCROLLBARWIDTH) # jvr
if self.bary:
self.bary.HideControl() # jvr
self.bary.MoveControl(r-(SCROLLBARWIDTH-1), t-1)
self.bary.SizeControl(SCROLLBARWIDTH, (b-t)-(SCROLLBARWIDTH-3)) # jvr
if self.barx:
self.barx.ShowControl() # jvr
self.wid.ValidWindowRect((l, b - SCROLLBARWIDTH + 1, r - SCROLLBARWIDTH + 2, b)) # jvr
if self.bary:
self.bary.ShowControl() # jvr
self.wid.ValidWindowRect((r - SCROLLBARWIDTH + 1, t, r, b - SCROLLBARWIDTH + 2)) # jvr
self.wid.InvalWindowRect((r - SCROLLBARWIDTH + 1, b - SCROLLBARWIDTH + 1, r, b)) # jvr, growicon
def do_rawcontrolhit(self, window, control, pcode, local, event):
if control == self.barx:
which = 'x'
elif control == self.bary:
which = 'y'
else:
return 0
if pcode in (inUpButton, inDownButton, inPageUp, inPageDown):
# We do the work for the buttons and grey area in the tracker
dummy = control.TrackControl(local, self.do_controltrack)
else:
# but the thumb is handled here
pcode = control.TrackControl(local)
if pcode == inThumb:
value = control.GetControlValue()
print 'setbars', which, value #DBG
self.scrollbar_callback(which, 'set', value)
self.updatescrollbars()
else:
print 'funny part', pcode #DBG
return 1
def do_controltrack(self, control, pcode):
if control == self.barx:
which = 'x'
elif control == self.bary:
which = 'y'
else:
return
if pcode == inUpButton:
what = '-'
elif pcode == inDownButton:
what = '+'
elif pcode == inPageUp:
what = '--'
elif pcode == inPageDown:
what = '++'
else:
return
self.scrollbar_callback(which, what, None)
self.updatescrollbars()
def updatescrollbars(self):
SetPort(self.wid)
vx, vy = self.getscrollbarvalues()
if self.barx:
if vx == None:
self.barx.HiliteControl(255)
self.barx_enabled = 0
else:
if not self.barx_enabled:
self.barx_enabled = 1
if self.activated:
self.barx.HiliteControl(0)
self.barx.SetControlValue(vx)
if self.bary:
if vy == None:
self.bary.HiliteControl(255)
self.bary_enabled = 0
else:
if not self.bary_enabled:
self.bary_enabled = 1
if self.activated:
self.bary.HiliteControl(0)
self.bary.SetControlValue(vy)
# Auxiliary function: convert standard text/image/etc coordinate
# to something palatable as getscrollbarvalues() return
def scalebarvalue(self, absmin, absmax, curmin, curmax):
if curmin <= absmin and curmax >= absmax:
return None
if curmin <= absmin:
return 0
if curmax >= absmax:
return 32767
perc = float(curmin-absmin)/float(absmax-absmin)
return int(perc*32767)
# To be overridden:
def getscrollbarvalues(self):
return 0, 0
def scrollbar_callback(self, which, what, value):
print 'scroll', which, what, value
class DialogWindow(Window):
"""A modeless dialog window"""
def open(self, resid):
self.dlg = GetNewDialog(resid, -1)
self.wid = self.dlg.GetDialogWindow()
self.do_postopen()
def close(self):
self.do_postclose()
def do_postclose(self):
self.dlg = None
Window.do_postclose(self)
def do_itemhit(self, item, event):
print 'Dialog %s, item %d hit'%(self.dlg, item)
def do_rawupdate(self, window, event):
pass
def ostypecode(x):
"Convert a long int to the 4-character code it really is"
s = ''
for i in range(4):
x, c = divmod(x, 256)
s = chr(c) + s
return s
class TestApp(Application):
"This class is used by the test() function"
def makeusermenus(self):
self.filemenu = m = Menu(self.menubar, "File")
self.saveitem = MenuItem(m, "Save", "S", self.save)
Separator(m)
self.optionsmenu = mm = SubMenu(m, "Options")
self.opt1 = CheckItem(mm, "Arguments", "A")
self.opt2 = CheckItem(mm, "Being hit on the head lessons", (kMenuOptionModifier, "A"))
self.opt3 = CheckItem(mm, "Complaints", (kMenuOptionModifier|kMenuNoCommandModifier, "A"))
Separator(m)
self.itemeh = MenuItem(m, "Enable Help", None, self.enablehelp)
self.itemdbg = MenuItem(m, "Debug", None, self.debug)
Separator(m)
self.quititem = MenuItem(m, "Quit", "Q", self.quit)
def save(self, *args):
print "Save"
def quit(self, *args):
raise self
def enablehelp(self, *args):
hm = self.gethelpmenu()
self.nohelpitem = MenuItem(hm, "There isn't any", None, self.nohelp)
def nohelp(self, *args):
print "I told you there isn't any!"
def debug(self, *args):
import pdb
pdb.set_trace()
def test():
"Test program"
app = TestApp()
app.mainloop()
if __name__ == '__main__':
test()
| Python |
"""tools for BuildApplet and BuildApplication"""
import sys
import os
import string
import imp
import marshal
from Carbon import Res
import Carbon.Files
import Carbon.File
import MacOS
import macostools
import macresource
import EasyDialogs
import shutil
BuildError = "BuildError"
# .pyc file (and 'PYC ' resource magic number)
MAGIC = imp.get_magic()
# Template file (searched on sys.path)
TEMPLATE = "PythonInterpreter"
# Specification of our resource
RESTYPE = 'PYC '
RESNAME = '__main__'
# A resource with this name sets the "owner" (creator) of the destination
# It should also have ID=0. Either of these alone is not enough.
OWNERNAME = "owner resource"
# Default applet creator code
DEFAULT_APPLET_CREATOR="Pyta"
# OpenResFile mode parameters
READ = 1
WRITE = 2
# Parameter for FSOpenResourceFile
RESOURCE_FORK_NAME=Carbon.File.FSGetResourceForkName()
def findtemplate(template=None):
"""Locate the applet template along sys.path"""
if MacOS.runtimemodel == 'macho':
return None
if not template:
template=TEMPLATE
for p in sys.path:
file = os.path.join(p, template)
try:
file, d1, d2 = Carbon.File.FSResolveAliasFile(file, 1)
break
except (Carbon.File.Error, ValueError):
continue
else:
raise BuildError, "Template %r not found on sys.path" % (template,)
file = file.as_pathname()
return file
def process(template, filename, destname, copy_codefragment=0,
rsrcname=None, others=[], raw=0, progress="default", destroot=""):
if progress == "default":
progress = EasyDialogs.ProgressBar("Processing %s..."%os.path.split(filename)[1], 120)
progress.label("Compiling...")
progress.inc(0)
# check for the script name being longer than 32 chars. This may trigger a bug
# on OSX that can destroy your sourcefile.
if '#' in os.path.split(filename)[1]:
raise BuildError, "BuildApplet could destroy your sourcefile on OSX, please rename: %s" % filename
# Read the source and compile it
# (there's no point overwriting the destination if it has a syntax error)
fp = open(filename, 'rU')
text = fp.read()
fp.close()
try:
code = compile(text + '\n', filename, "exec")
except SyntaxError, arg:
raise BuildError, "Syntax error in script %s: %s" % (filename, arg)
except EOFError:
raise BuildError, "End-of-file in script %s" % (filename,)
# Set the destination file name. Note that basename
# does contain the whole filepath, only a .py is stripped.
if string.lower(filename[-3:]) == ".py":
basename = filename[:-3]
if MacOS.runtimemodel != 'macho' and not destname:
destname = basename
else:
basename = filename
if not destname:
if MacOS.runtimemodel == 'macho':
destname = basename + '.app'
else:
destname = basename + '.applet'
if not rsrcname:
rsrcname = basename + '.rsrc'
# Try removing the output file. This fails in MachO, but it should
# do any harm.
try:
os.remove(destname)
except os.error:
pass
process_common(template, progress, code, rsrcname, destname, 0,
copy_codefragment, raw, others, filename, destroot)
def update(template, filename, output):
if MacOS.runtimemodel == 'macho':
raise BuildError, "No updating yet for MachO applets"
if progress:
progress = EasyDialogs.ProgressBar("Updating %s..."%os.path.split(filename)[1], 120)
else:
progress = None
if not output:
output = filename + ' (updated)'
# Try removing the output file
try:
os.remove(output)
except os.error:
pass
process_common(template, progress, None, filename, output, 1, 1)
def process_common(template, progress, code, rsrcname, destname, is_update,
copy_codefragment, raw=0, others=[], filename=None, destroot=""):
if MacOS.runtimemodel == 'macho':
return process_common_macho(template, progress, code, rsrcname, destname,
is_update, raw, others, filename, destroot)
if others:
raise BuildError, "Extra files only allowed for MachoPython applets"
# Create FSSpecs for the various files
template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1)
template = template_fsr.as_pathname()
# Copy data (not resources, yet) from the template
if progress:
progress.label("Copy data fork...")
progress.set(10)
if copy_codefragment:
tmpl = open(template, "rb")
dest = open(destname, "wb")
data = tmpl.read()
if data:
dest.write(data)
dest.close()
tmpl.close()
del dest
del tmpl
# Open the output resource fork
if progress:
progress.label("Copy resources...")
progress.set(20)
try:
output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE)
except MacOS.Error:
destdir, destfile = os.path.split(destname)
Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME)
output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE)
# Copy the resources from the target specific resource template, if any
typesfound, ownertype = [], None
try:
input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ)
except (MacOS.Error, ValueError):
pass
if progress:
progress.inc(50)
else:
if is_update:
skip_oldfile = ['cfrg']
else:
skip_oldfile = []
typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress)
Res.CloseResFile(input)
# Check which resource-types we should not copy from the template
skiptypes = []
if 'vers' in typesfound: skiptypes.append('vers')
if 'SIZE' in typesfound: skiptypes.append('SIZE')
if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4',
'icl8', 'ics4', 'ics8', 'ICN#', 'ics#']
if not copy_codefragment:
skiptypes.append('cfrg')
## skipowner = (ownertype <> None)
# Copy the resources from the template
input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ)
dummy, tmplowner = copyres(input, output, skiptypes, 1, progress)
Res.CloseResFile(input)
## if ownertype == None:
## raise BuildError, "No owner resource found in either resource file or template"
# Make sure we're manipulating the output resource file now
Res.UseResFile(output)
if ownertype == None:
# No owner resource in the template. We have skipped the
# Python owner resource, so we have to add our own. The relevant
# bundle stuff is already included in the interpret/applet template.
newres = Res.Resource('\0')
newres.AddResource(DEFAULT_APPLET_CREATOR, 0, "Owner resource")
ownertype = DEFAULT_APPLET_CREATOR
if code:
# Delete any existing 'PYC ' resource named __main__
try:
res = Res.Get1NamedResource(RESTYPE, RESNAME)
res.RemoveResource()
except Res.Error:
pass
# Create the raw data for the resource from the code object
if progress:
progress.label("Write PYC resource...")
progress.set(120)
data = marshal.dumps(code)
del code
data = (MAGIC + '\0\0\0\0') + data
# Create the resource and write it
id = 0
while id < 128:
id = Res.Unique1ID(RESTYPE)
res = Res.Resource(data)
res.AddResource(RESTYPE, id, RESNAME)
attrs = res.GetResAttrs()
attrs = attrs | 0x04 # set preload
res.SetResAttrs(attrs)
res.WriteResource()
res.ReleaseResource()
# Close the output file
Res.CloseResFile(output)
# Now set the creator, type and bundle bit of the destination.
# Done with FSSpec's, FSRef FInfo isn't good enough yet (2.3a1+)
dest_fss = Carbon.File.FSSpec(destname)
dest_finfo = dest_fss.FSpGetFInfo()
dest_finfo.Creator = ownertype
dest_finfo.Type = 'APPL'
dest_finfo.Flags = dest_finfo.Flags | Carbon.Files.kHasBundle | Carbon.Files.kIsShared
dest_finfo.Flags = dest_finfo.Flags & ~Carbon.Files.kHasBeenInited
dest_fss.FSpSetFInfo(dest_finfo)
macostools.touched(destname)
if progress:
progress.label("Done.")
progress.inc(0)
def process_common_macho(template, progress, code, rsrcname, destname, is_update,
raw=0, others=[], filename=None, destroot=""):
# Check that we have a filename
if filename is None:
raise BuildError, "Need source filename on MacOSX"
# First make sure the name ends in ".app"
if destname[-4:] != '.app':
destname = destname + '.app'
# Now deduce the short name
destdir, shortname = os.path.split(destname)
if shortname[-4:] == '.app':
# Strip the .app suffix
shortname = shortname[:-4]
# And deduce the .plist and .icns names
plistname = None
icnsname = None
if rsrcname and rsrcname[-5:] == '.rsrc':
tmp = rsrcname[:-5]
plistname = tmp + '.plist'
if os.path.exists(plistname):
icnsname = tmp + '.icns'
if not os.path.exists(icnsname):
icnsname = None
else:
plistname = None
if not icnsname:
dft_icnsname = os.path.join(sys.prefix, 'Resources/Python.app/Contents/Resources/PythonApplet.icns')
if os.path.exists(dft_icnsname):
icnsname = dft_icnsname
if not os.path.exists(rsrcname):
rsrcname = None
if progress:
progress.label('Creating bundle...')
import bundlebuilder
builder = bundlebuilder.AppBuilder(verbosity=0)
builder.mainprogram = filename
builder.builddir = destdir
builder.name = shortname
builder.destroot = destroot
if rsrcname:
realrsrcname = macresource.resource_pathname(rsrcname)
builder.files.append((realrsrcname,
os.path.join('Contents/Resources', os.path.basename(rsrcname))))
for o in others:
if type(o) == str:
builder.resources.append(o)
else:
builder.files.append(o)
if plistname:
import plistlib
builder.plist = plistlib.Plist.fromFile(plistname)
if icnsname:
builder.iconfile = icnsname
if not raw:
builder.argv_emulation = 1
builder.setup()
builder.build()
if progress:
progress.label('Done.')
progress.inc(0)
## macostools.touched(dest_fss)
# Copy resources between two resource file descriptors.
# skip a resource named '__main__' or (if skipowner is set) with ID zero.
# Also skip resources with a type listed in skiptypes.
#
def copyres(input, output, skiptypes, skipowner, progress=None):
ctor = None
alltypes = []
Res.UseResFile(input)
ntypes = Res.Count1Types()
progress_type_inc = 50/ntypes
for itype in range(1, 1+ntypes):
type = Res.Get1IndType(itype)
if type in skiptypes:
continue
alltypes.append(type)
nresources = Res.Count1Resources(type)
progress_cur_inc = progress_type_inc/nresources
for ires in range(1, 1+nresources):
res = Res.Get1IndResource(type, ires)
id, type, name = res.GetResInfo()
lcname = string.lower(name)
if lcname == OWNERNAME and id == 0:
if skipowner:
continue # Skip this one
else:
ctor = type
size = res.size
attrs = res.GetResAttrs()
if progress:
progress.label("Copy %s %d %s"%(type, id, name))
progress.inc(progress_cur_inc)
res.LoadResource()
res.DetachResource()
Res.UseResFile(output)
try:
res2 = Res.Get1Resource(type, id)
except MacOS.Error:
res2 = None
if res2:
if progress:
progress.label("Overwrite %s %d %s"%(type, id, name))
progress.inc(0)
res2.RemoveResource()
res.AddResource(type, id, name)
res.WriteResource()
attrs = attrs | res.GetResAttrs()
res.SetResAttrs(attrs)
Res.UseResFile(input)
return alltypes, ctor
def copyapptree(srctree, dsttree, exceptlist=[], progress=None):
names = []
if os.path.exists(dsttree):
shutil.rmtree(dsttree)
os.mkdir(dsttree)
todo = os.listdir(srctree)
while todo:
this, todo = todo[0], todo[1:]
if this in exceptlist:
continue
thispath = os.path.join(srctree, this)
if os.path.isdir(thispath):
thiscontent = os.listdir(thispath)
for t in thiscontent:
todo.append(os.path.join(this, t))
names.append(this)
for this in names:
srcpath = os.path.join(srctree, this)
dstpath = os.path.join(dsttree, this)
if os.path.isdir(srcpath):
os.mkdir(dstpath)
elif os.path.islink(srcpath):
endpoint = os.readlink(srcpath)
os.symlink(endpoint, dstpath)
else:
if progress:
progress.label('Copy '+this)
progress.inc(0)
shutil.copy2(srcpath, dstpath)
def writepycfile(codeobject, cfile):
import marshal
fc = open(cfile, 'wb')
fc.write('\0\0\0\0') # MAGIC placeholder, written later
fc.write('\0\0\0\0') # Timestap placeholder, not needed
marshal.dump(codeobject, fc)
fc.flush()
fc.seek(0, 0)
fc.write(MAGIC)
fc.close()
| Python |
"""IC wrapper module, based on Internet Config 1.3"""
import icglue
import string
import sys
import os
from Carbon import Res
import Carbon.File
import macostools
error=icglue.error
# From ictypes.h:
icPrefNotFoundErr = -666 # preference not found (duh!)
icPermErr = -667 # cannot set preference
icPrefDataErr = -668 # problem with preference data
icInternalErr = -669 # hmm, this is not good
icTruncatedErr = -670 # more data was present than was returned
icNoMoreWritersErr = -671 # you cannot begin a write session because someone else is already doing it */
icNothingToOverrideErr = -672 # no component for the override component to capture
icNoURLErr = -673 # no URL found
icConfigNotFoundErr = -674 # no configuration was found
icConfigInappropriateErr = -675 # incorrect manufacturer code
ICattr_no_change = -1
icNoPerm = 0
icReadOnlyPerm = 1
icReadWritePerm = 2
# End of ictypes.h
class ICOpaqueData:
"""An unparseable IC entry"""
def __init__(self, data):
self.data = data
def __repr__(self):
return "ICOpaqueData(%r)"%(self.data,)
_ICOpaqueDataType=type(ICOpaqueData(''))
def _decode_default(data, key):
if len(data) == 0:
return data
if ord(data[0]) == len(data)-1:
# Assume Pstring
return data[1:]
return ICOpaqueData(data)
def _decode_multistr(data, key):
numstr = ord(data[0]) << 8 | ord(data[1])
rv = []
ptr = 2
for i in range(numstr):
strlen = ord(data[ptr])
str = data[ptr+1:ptr+strlen+1]
rv.append(str)
ptr = ptr + strlen + 1
return rv
def _decode_fontrecord(data, key):
size = ord(data[0]) << 8 | ord(data[1])
face = ord(data[2])
namelen = ord(data[4])
return size, face, data[5:5+namelen]
def _decode_boolean(data, key):
return ord(data[0])
def _decode_text(data, key):
return data
def _decode_charset(data, key):
return data[:256], data[256:]
def _decode_appspec(data, key):
namelen = ord(data[4])
return data[0:4], data[5:5+namelen]
def _code_default(data, key):
return chr(len(data)) + data
def _code_multistr(data, key):
numstr = len(data)
rv = chr((numstr>>8) & 0xff) + chr(numstr & 0xff)
for i in data:
rv = rv + _code_default(i)
return rv
def _code_fontrecord(data, key):
size, face, name = data
return chr((size>>8) & 0xff) + chr(size & 0xff) + chr(face & 0xff) + \
chr(0) + _code_default(name)
def _code_boolean(data, key):
print 'XXXX boolean:', repr(data)
return chr(data)
def _code_text(data, key):
return data
def _code_charset(data, key):
return data[0] + data[1]
def _code_appspec(data, key):
return data[0] + _code_default(data[1])
_decoder_table = {
"ArchieAll" : (_decode_multistr , _code_multistr),
"UMichAll" : (_decode_multistr , _code_multistr),
"InfoMacAll" : (_decode_multistr , _code_multistr),
"ListFont" : (_decode_fontrecord , _code_fontrecord),
"ScreenFont" : (_decode_fontrecord , _code_fontrecord),
"PrinterFont" : (_decode_fontrecord , _code_fontrecord),
# "DownloadFolder" : (_decode_filespec , _code_filespec),
"Signature": (_decode_text , _code_text),
"Plan" : (_decode_text , _code_text),
"MailHeaders" : (_decode_text , _code_text),
"NewsHeaders" : (_decode_text , _code_text),
# "Mapping"
"CharacterSet" : (_decode_charset , _code_charset),
"Helper\245" : (_decode_appspec , _code_appspec),
# "Services" : (_decode_services, ????),
"NewMailFlashIcon" : (_decode_boolean , _code_boolean),
"NewMailDialog" : (_decode_boolean , _code_boolean),
"NewMailPlaySound" : (_decode_boolean , _code_boolean),
# "WebBackgroundColor" : _decode_color,
"NoProxyDomains" : (_decode_multistr , _code_multistr),
"UseHTTPProxy" : (_decode_boolean , _code_boolean),
"UseGopherProxy": (_decode_boolean , _code_boolean),
"UseFTPProxy" : (_decode_boolean , _code_boolean),
"UsePassiveFTP" : (_decode_boolean , _code_boolean),
}
def _decode(data, key):
if '\245' in key:
key2 = key[:string.index(key, '\245')+1]
else:
key2 = key
if _decoder_table.has_key(key2):
decoder = _decoder_table[key2][0]
else:
decoder = _decode_default
return decoder(data, key)
def _code(data, key):
if type(data) == _ICOpaqueDataType:
return data.data
if '\245' in key:
key2 = key[:string.index(key, '\245')+1]
else:
key2 = key
if _decoder_table.has_key(key2):
coder = _decoder_table[key2][1]
else:
coder = _code_default
return coder(data, key)
class IC:
def __init__(self, signature='Pyth', ic=None):
if ic:
self.ic = ic
else:
self.ic = icglue.ICStart(signature)
if hasattr(self.ic, 'ICFindConfigFile'):
self.ic.ICFindConfigFile()
self.h = Res.Resource('')
def keys(self):
rv = []
self.ic.ICBegin(icReadOnlyPerm)
num = self.ic.ICCountPref()
for i in range(num):
rv.append(self.ic.ICGetIndPref(i+1))
self.ic.ICEnd()
return rv
def has_key(self, key):
return self.__contains__(key)
def __contains__(self, key):
try:
dummy = self.ic.ICFindPrefHandle(key, self.h)
except icglue.error:
return 0
return 1
def __getitem__(self, key):
attr = self.ic.ICFindPrefHandle(key, self.h)
return _decode(self.h.data, key)
def __setitem__(self, key, value):
value = _code(value, key)
self.ic.ICSetPref(key, ICattr_no_change, value)
def launchurl(self, url, hint=""):
# Work around a bug in ICLaunchURL: file:/foo does
# not work but file:///foo does.
if url[:6] == 'file:/' and url[6] != '/':
url = 'file:///' + url[6:]
self.ic.ICLaunchURL(hint, url, 0, len(url))
def parseurl(self, data, start=None, end=None, hint=""):
if start == None:
selStart = 0
selEnd = len(data)
else:
selStart = selEnd = start
if end != None:
selEnd = end
selStart, selEnd = self.ic.ICParseURL(hint, data, selStart, selEnd, self.h)
return self.h.data, selStart, selEnd
def mapfile(self, file):
if type(file) != type(''):
file = file.as_tuple()[2]
return self.ic.ICMapFilename(file)
def maptypecreator(self, type, creator, filename=""):
return self.ic.ICMapTypeCreator(type, creator, filename)
def settypecreator(self, file):
file = Carbon.File.pathname(file)
record = self.mapfile(os.path.split(file)[1])
MacOS.SetCreatorAndType(file, record[2], record[1])
macostools.touched(fss)
# Convenience routines
_dft_ic = None
def launchurl(url, hint=""):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.launchurl(url, hint)
def parseurl(data, start=None, end=None, hint=""):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.parseurl(data, start, end, hint)
def mapfile(filename):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.mapfile(filename)
def maptypecreator(type, creator, filename=""):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.maptypecreator(type, creator, filename)
def settypecreator(file):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.settypecreator(file)
def _test():
ic = IC()
for k in ic.keys():
try:
v = ic[k]
except error:
v = '????'
print k, '\t', v
sys.exit(1)
if __name__ == '__main__':
_test()
| Python |
"""Tools for use in AppleEvent clients and servers.
pack(x) converts a Python object to an AEDesc object
unpack(desc) does the reverse
packevent(event, parameters, attributes) sets params and attrs in an AEAppleEvent record
unpackevent(event) returns the parameters and attributes from an AEAppleEvent record
Plus... Lots of classes and routines that help representing AE objects,
ranges, conditionals, logicals, etc., so you can write, e.g.:
x = Character(1, Document("foobar"))
and pack(x) will create an AE object reference equivalent to AppleScript's
character 1 of document "foobar"
Some of the stuff that appears to be exported from this module comes from other
files: the pack stuff from aepack, the objects from aetypes.
"""
from types import *
from Carbon import AE
from Carbon import Evt
from Carbon import AppleEvents
import MacOS
import sys
import time
from aetypes import *
from aepack import packkey, pack, unpack, coerce, AEDescType
Error = 'aetools.Error'
# Amount of time to wait for program to be launched
LAUNCH_MAX_WAIT_TIME=10
# Special code to unpack an AppleEvent (which is *not* a disguised record!)
# Note by Jack: No??!? If I read the docs correctly it *is*....
aekeywords = [
'tran',
'rtid',
'evcl',
'evid',
'addr',
'optk',
'timo',
'inte', # this attribute is read only - will be set in AESend
'esrc', # this attribute is read only
'miss', # this attribute is read only
'from' # new in 1.0.1
]
def missed(ae):
try:
desc = ae.AEGetAttributeDesc('miss', 'keyw')
except AE.Error, msg:
return None
return desc.data
def unpackevent(ae, formodulename=""):
parameters = {}
try:
dirobj = ae.AEGetParamDesc('----', '****')
except AE.Error:
pass
else:
parameters['----'] = unpack(dirobj, formodulename)
del dirobj
# Workaround for what I feel is a bug in OSX 10.2: 'errn' won't show up in missed...
try:
dirobj = ae.AEGetParamDesc('errn', '****')
except AE.Error:
pass
else:
parameters['errn'] = unpack(dirobj, formodulename)
del dirobj
while 1:
key = missed(ae)
if not key: break
parameters[key] = unpack(ae.AEGetParamDesc(key, '****'), formodulename)
attributes = {}
for key in aekeywords:
try:
desc = ae.AEGetAttributeDesc(key, '****')
except (AE.Error, MacOS.Error), msg:
if msg[0] != -1701 and msg[0] != -1704:
raise
continue
attributes[key] = unpack(desc, formodulename)
return parameters, attributes
def packevent(ae, parameters = {}, attributes = {}):
for key, value in parameters.items():
packkey(ae, key, value)
for key, value in attributes.items():
ae.AEPutAttributeDesc(key, pack(value))
#
# Support routine for automatically generated Suite interfaces
# These routines are also useable for the reverse function.
#
def keysubst(arguments, keydict):
"""Replace long name keys by their 4-char counterparts, and check"""
ok = keydict.values()
for k in arguments.keys():
if keydict.has_key(k):
v = arguments[k]
del arguments[k]
arguments[keydict[k]] = v
elif k != '----' and k not in ok:
raise TypeError, 'Unknown keyword argument: %s'%k
def enumsubst(arguments, key, edict):
"""Substitute a single enum keyword argument, if it occurs"""
if not arguments.has_key(key) or edict is None:
return
v = arguments[key]
ok = edict.values()
if edict.has_key(v):
arguments[key] = Enum(edict[v])
elif not v in ok:
raise TypeError, 'Unknown enumerator: %s'%v
def decodeerror(arguments):
"""Create the 'best' argument for a raise MacOS.Error"""
errn = arguments['errn']
err_a1 = errn
if arguments.has_key('errs'):
err_a2 = arguments['errs']
else:
err_a2 = MacOS.GetErrorString(errn)
if arguments.has_key('erob'):
err_a3 = arguments['erob']
else:
err_a3 = None
return (err_a1, err_a2, err_a3)
class TalkTo:
"""An AE connection to an application"""
_signature = None # Can be overridden by subclasses
_moduleName = None # Can be overridden by subclasses
_elemdict = {} # Can be overridden by subclasses
_propdict = {} # Can be overridden by subclasses
__eventloop_initialized = 0
def __ensure_WMAvailable(klass):
if klass.__eventloop_initialized: return 1
if not MacOS.WMAvailable(): return 0
# Workaround for a but in MacOSX 10.2: we must have an event
# loop before we can call AESend.
Evt.WaitNextEvent(0,0)
return 1
__ensure_WMAvailable = classmethod(__ensure_WMAvailable)
def __init__(self, signature=None, start=0, timeout=0):
"""Create a communication channel with a particular application.
Addressing the application is done by specifying either a
4-byte signature, an AEDesc or an object that will __aepack__
to an AEDesc.
"""
self.target_signature = None
if signature is None:
signature = self._signature
if type(signature) == AEDescType:
self.target = signature
elif type(signature) == InstanceType and hasattr(signature, '__aepack__'):
self.target = signature.__aepack__()
elif type(signature) == StringType and len(signature) == 4:
self.target = AE.AECreateDesc(AppleEvents.typeApplSignature, signature)
self.target_signature = signature
else:
raise TypeError, "signature should be 4-char string or AEDesc"
self.send_flags = AppleEvents.kAEWaitReply
self.send_priority = AppleEvents.kAENormalPriority
if timeout:
self.send_timeout = timeout
else:
self.send_timeout = AppleEvents.kAEDefaultTimeout
if start:
self._start()
def _start(self):
"""Start the application, if it is not running yet"""
try:
self.send('ascr', 'noop')
except AE.Error:
_launch(self.target_signature)
for i in range(LAUNCH_MAX_WAIT_TIME):
try:
self.send('ascr', 'noop')
except AE.Error:
pass
else:
break
time.sleep(1)
def start(self):
"""Deprecated, used _start()"""
self._start()
def newevent(self, code, subcode, parameters = {}, attributes = {}):
"""Create a complete structure for an apple event"""
event = AE.AECreateAppleEvent(code, subcode, self.target,
AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
packevent(event, parameters, attributes)
return event
def sendevent(self, event):
"""Send a pre-created appleevent, await the reply and unpack it"""
if not self.__ensure_WMAvailable():
raise RuntimeError, "No window manager access, cannot send AppleEvent"
reply = event.AESend(self.send_flags, self.send_priority,
self.send_timeout)
parameters, attributes = unpackevent(reply, self._moduleName)
return reply, parameters, attributes
def send(self, code, subcode, parameters = {}, attributes = {}):
"""Send an appleevent given code/subcode/pars/attrs and unpack the reply"""
return self.sendevent(self.newevent(code, subcode, parameters, attributes))
#
# The following events are somehow "standard" and don't seem to appear in any
# suite...
#
def activate(self):
"""Send 'activate' command"""
self.send('misc', 'actv')
def _get(self, _object, as=None, _attributes={}):
"""_get: get data from an object
Required argument: the object
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the data
"""
_code = 'core'
_subcode = 'getd'
_arguments = {'----':_object}
if as:
_arguments['rtyp'] = mktype(as)
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise Error, decodeerror(_arguments)
if _arguments.has_key('----'):
return _arguments['----']
if as:
item.__class__ = as
return item
get = _get
_argmap_set = {
'to' : 'data',
}
def _set(self, _object, _attributes={}, **_arguments):
"""set: Set an object's data.
Required argument: the object for the command
Keyword argument to: The new value.
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'core'
_subcode = 'setd'
keysubst(_arguments, self._argmap_set)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.get('errn', 0):
raise Error, decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
set = _set
# Magic glue to allow suite-generated classes to function somewhat
# like the "application" class in OSA.
def __getattr__(self, name):
if self._elemdict.has_key(name):
cls = self._elemdict[name]
return DelayedComponentItem(cls, None)
if self._propdict.has_key(name):
cls = self._propdict[name]
return cls()
raise AttributeError, name
# Tiny Finder class, for local use only
class _miniFinder(TalkTo):
def open(self, _object, _attributes={}, **_arguments):
"""open: Open the specified object(s)
Required argument: list of objects to open
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'odoc'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise Error, decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
#pass
_finder = _miniFinder('MACS')
def _launch(appfile):
"""Open a file thru the finder. Specify file by name or fsspec"""
_finder.open(_application_file(('ID ', appfile)))
class _application_file(ComponentItem):
"""application file - An application's file on disk"""
want = 'appf'
_application_file._propdict = {
}
_application_file._elemdict = {
}
# Test program
# XXXX Should test more, really...
def test():
target = AE.AECreateDesc('sign', 'quil')
ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
print unpackevent(ae)
raw_input(":")
ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
obj = Character(2, Word(1, Document(1)))
print obj
print repr(obj)
packevent(ae, {'----': obj})
params, attrs = unpackevent(ae)
print params['----']
raw_input(":")
if __name__ == '__main__':
test()
sys.exit(1)
| Python |
"""PixMapWrapper - defines the PixMapWrapper class, which wraps an opaque
QuickDraw PixMap data structure in a handy Python class. Also provides
methods to convert to/from pixel data (from, e.g., the img module) or a
Python Imaging Library Image object.
J. Strout <joe@strout.net> February 1999"""
from Carbon import Qd
from Carbon import QuickDraw
import struct
import MacOS
import img
import imgformat
# PixMap data structure element format (as used with struct)
_pmElemFormat = {
'baseAddr':'l', # address of pixel data
'rowBytes':'H', # bytes per row, plus 0x8000
'bounds':'hhhh', # coordinates imposed over pixel data
'top':'h',
'left':'h',
'bottom':'h',
'right':'h',
'pmVersion':'h', # flags for Color QuickDraw
'packType':'h', # format of compression algorithm
'packSize':'l', # size after compression
'hRes':'l', # horizontal pixels per inch
'vRes':'l', # vertical pixels per inch
'pixelType':'h', # pixel format
'pixelSize':'h', # bits per pixel
'cmpCount':'h', # color components per pixel
'cmpSize':'h', # bits per component
'planeBytes':'l', # offset in bytes to next plane
'pmTable':'l', # handle to color table
'pmReserved':'l' # reserved for future use
}
# PixMap data structure element offset
_pmElemOffset = {
'baseAddr':0,
'rowBytes':4,
'bounds':6,
'top':6,
'left':8,
'bottom':10,
'right':12,
'pmVersion':14,
'packType':16,
'packSize':18,
'hRes':22,
'vRes':26,
'pixelType':30,
'pixelSize':32,
'cmpCount':34,
'cmpSize':36,
'planeBytes':38,
'pmTable':42,
'pmReserved':46
}
class PixMapWrapper:
"""PixMapWrapper -- wraps the QD PixMap object in a Python class,
with methods to easily get/set various pixmap fields. Note: Use the
PixMap() method when passing to QD calls."""
def __init__(self):
self.__dict__['data'] = ''
self._header = struct.pack("lhhhhhhhlllhhhhlll",
id(self.data)+MacOS.string_id_to_buffer,
0, # rowBytes
0, 0, 0, 0, # bounds
0, # pmVersion
0, 0, # packType, packSize
72<<16, 72<<16, # hRes, vRes
QuickDraw.RGBDirect, # pixelType
16, # pixelSize
2, 5, # cmpCount, cmpSize,
0, 0, 0) # planeBytes, pmTable, pmReserved
self.__dict__['_pm'] = Qd.RawBitMap(self._header)
def _stuff(self, element, bytes):
offset = _pmElemOffset[element]
fmt = _pmElemFormat[element]
self._header = self._header[:offset] \
+ struct.pack(fmt, bytes) \
+ self._header[offset + struct.calcsize(fmt):]
self.__dict__['_pm'] = None
def _unstuff(self, element):
offset = _pmElemOffset[element]
fmt = _pmElemFormat[element]
return struct.unpack(fmt, self._header[offset:offset+struct.calcsize(fmt)])[0]
def __setattr__(self, attr, val):
if attr == 'baseAddr':
raise 'UseErr', "don't assign to .baseAddr -- assign to .data instead"
elif attr == 'data':
self.__dict__['data'] = val
self._stuff('baseAddr', id(self.data) + MacOS.string_id_to_buffer)
elif attr == 'rowBytes':
# high bit is always set for some odd reason
self._stuff('rowBytes', val | 0x8000)
elif attr == 'bounds':
# assume val is in official Left, Top, Right, Bottom order!
self._stuff('left',val[0])
self._stuff('top',val[1])
self._stuff('right',val[2])
self._stuff('bottom',val[3])
elif attr == 'hRes' or attr == 'vRes':
# 16.16 fixed format, so just shift 16 bits
self._stuff(attr, int(val) << 16)
elif attr in _pmElemFormat.keys():
# any other pm attribute -- just stuff
self._stuff(attr, val)
else:
self.__dict__[attr] = val
def __getattr__(self, attr):
if attr == 'rowBytes':
# high bit is always set for some odd reason
return self._unstuff('rowBytes') & 0x7FFF
elif attr == 'bounds':
# return bounds in official Left, Top, Right, Bottom order!
return ( \
self._unstuff('left'),
self._unstuff('top'),
self._unstuff('right'),
self._unstuff('bottom') )
elif attr == 'hRes' or attr == 'vRes':
# 16.16 fixed format, so just shift 16 bits
return self._unstuff(attr) >> 16
elif attr in _pmElemFormat.keys():
# any other pm attribute -- just unstuff
return self._unstuff(attr)
else:
return self.__dict__[attr]
def PixMap(self):
"Return a QuickDraw PixMap corresponding to this data."
if not self.__dict__['_pm']:
self.__dict__['_pm'] = Qd.RawBitMap(self._header)
return self.__dict__['_pm']
def blit(self, x1=0,y1=0,x2=None,y2=None, port=None):
"""Draw this pixmap into the given (default current) grafport."""
src = self.bounds
dest = [x1,y1,x2,y2]
if x2 == None:
dest[2] = x1 + src[2]-src[0]
if y2 == None:
dest[3] = y1 + src[3]-src[1]
if not port: port = Qd.GetPort()
Qd.CopyBits(self.PixMap(), port.GetPortBitMapForCopyBits(), src, tuple(dest),
QuickDraw.srcCopy, None)
def fromstring(self,s,width,height,format=imgformat.macrgb):
"""Stuff this pixmap with raw pixel data from a string.
Supply width, height, and one of the imgformat specifiers."""
# we only support 16- and 32-bit mac rgb...
# so convert if necessary
if format != imgformat.macrgb and format != imgformat.macrgb16:
# (LATER!)
raise "NotImplementedError", "conversion to macrgb or macrgb16"
self.data = s
self.bounds = (0,0,width,height)
self.cmpCount = 3
self.pixelType = QuickDraw.RGBDirect
if format == imgformat.macrgb:
self.pixelSize = 32
self.cmpSize = 8
else:
self.pixelSize = 16
self.cmpSize = 5
self.rowBytes = width*self.pixelSize/8
def tostring(self, format=imgformat.macrgb):
"""Return raw data as a string in the specified format."""
# is the native format requested? if so, just return data
if (format == imgformat.macrgb and self.pixelSize == 32) or \
(format == imgformat.macrgb16 and self.pixelsize == 16):
return self.data
# otherwise, convert to the requested format
# (LATER!)
raise "NotImplementedError", "data format conversion"
def fromImage(self,im):
"""Initialize this PixMap from a PIL Image object."""
# We need data in ARGB format; PIL can't currently do that,
# but it can do RGBA, which we can use by inserting one null
# up frontpm =
if im.mode != 'RGBA': im = im.convert('RGBA')
data = chr(0) + im.tostring()
self.fromstring(data, im.size[0], im.size[1])
def toImage(self):
"""Return the contents of this PixMap as a PIL Image object."""
import Image
# our tostring() method returns data in ARGB format,
# whereas Image uses RGBA; a bit of slicing fixes this...
data = self.tostring()[1:] + chr(0)
bounds = self.bounds
return Image.fromstring('RGBA',(bounds[2]-bounds[0],bounds[3]-bounds[1]),data)
def test():
import MacOS
import EasyDialogs
import Image
path = EasyDialogs.AskFileForOpen("Image File:")
if not path: return
pm = PixMapWrapper()
pm.fromImage( Image.open(path) )
pm.blit(20,20)
return pm
| Python |
# Emulate sys.argv and run __main__.py or __main__.pyc in an environment that
# is as close to "normal" as possible.
#
# This script is put into __rawmain__.pyc for applets that need argv
# emulation, by BuildApplet and friends.
#
import argvemulator
import os
import sys
import marshal
#
# Make sure we have an argv[0], and make _dir point to the Resources
# directory.
#
if not sys.argv or sys.argv[0][:1] == '-':
# Insert our (guessed) name.
_dir = os.path.split(sys.executable)[0] # removes "python"
_dir = os.path.split(_dir)[0] # Removes "MacOS"
_dir = os.path.join(_dir, 'Resources')
sys.argv.insert(0, '__rawmain__')
else:
_dir = os.path.split(sys.argv[0])[0]
#
# Add the Resources directory to the path. This is where files installed
# by BuildApplet.py with the --extra option show up, and if those files are
# modules this sys.path modification is necessary to be able to import them.
#
sys.path.insert(0, _dir)
#
# Create sys.argv
#
argvemulator.ArgvCollector().mainloop()
#
# Find the real main program to run
#
__file__ = os.path.join(_dir, '__main__.py')
if os.path.exists(__file__):
#
# Setup something resembling a normal environment and go.
#
sys.argv[0] = __file__
del argvemulator, os, sys, _dir
execfile(__file__)
else:
__file__ = os.path.join(_dir, '__main__.pyc')
if os.path.exists(__file__):
#
# If we have only a .pyc file we read the code object from that
#
sys.argv[0] = __file__
_fp = open(__file__, 'rb')
_fp.read(8)
__code__ = marshal.load(_fp)
#
# Again, we create an almost-normal environment (only __code__ is
# funny) and go.
#
del argvemulator, os, sys, marshal, _dir, _fp
exec __code__
else:
sys.stderr.write("%s: neither __main__.py nor __main__.pyc found\n"%sys.argv[0])
sys.exit(1)
| Python |
#!/usr/bin/env python
# This file is meant as an executable script for running applets.
# BuildApplet will use it as the main executable in the .app bundle if
# we are not running in a framework build.
import os
import sys
for name in ["__rawmain__.py", "__rawmain__.pyc", "__main__.py", "__main__.pyc"]:
realmain = os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])),
"Resources", name)
if os.path.exists(realmain):
break
else:
sys.stderr.write("%s: cannot find applet main program\n" % sys.argv[0])
sys.exit(1)
sys.argv.insert(1, realmain)
os.execve(sys.executable, sys.argv, os.environ)
| Python |
#! /usr/bin/env python
"""\
bundlebuilder.py -- Tools to assemble MacOS X (application) bundles.
This module contains two classes to build so called "bundles" for
MacOS X. BundleBuilder is a general tool, AppBuilder is a subclass
specialized in building application bundles.
[Bundle|App]Builder objects are instantiated with a bunch of keyword
arguments, and have a build() method that will do all the work. See
the class doc strings for a description of the constructor arguments.
The module contains a main program that can be used in two ways:
% python bundlebuilder.py [options] build
% python buildapp.py [options] build
Where "buildapp.py" is a user-supplied setup.py-like script following
this model:
from bundlebuilder import buildapp
buildapp(<lots-of-keyword-args>)
"""
__all__ = ["BundleBuilder", "BundleBuilderError", "AppBuilder", "buildapp"]
import sys
import os, errno, shutil
import imp, marshal
import re
from copy import deepcopy
import getopt
from plistlib import Plist
from types import FunctionType as function
class BundleBuilderError(Exception): pass
class Defaults:
"""Class attributes that don't start with an underscore and are
not functions or classmethods are (deep)copied to self.__dict__.
This allows for mutable default values.
"""
def __init__(self, **kwargs):
defaults = self._getDefaults()
defaults.update(kwargs)
self.__dict__.update(defaults)
def _getDefaults(cls):
defaults = {}
for base in cls.__bases__:
if hasattr(base, "_getDefaults"):
defaults.update(base._getDefaults())
for name, value in cls.__dict__.items():
if name[0] != "_" and not isinstance(value,
(function, classmethod)):
defaults[name] = deepcopy(value)
return defaults
_getDefaults = classmethod(_getDefaults)
class BundleBuilder(Defaults):
"""BundleBuilder is a barebones class for assembling bundles. It
knows nothing about executables or icons, it only copies files
and creates the PkgInfo and Info.plist files.
"""
# (Note that Defaults.__init__ (deep)copies these values to
# instance variables. Mutable defaults are therefore safe.)
# Name of the bundle, with or without extension.
name = None
# The property list ("plist")
plist = Plist(CFBundleDevelopmentRegion = "English",
CFBundleInfoDictionaryVersion = "6.0")
# The type of the bundle.
type = "BNDL"
# The creator code of the bundle.
creator = None
# the CFBundleIdentifier (this is used for the preferences file name)
bundle_id = None
# List of files that have to be copied to <bundle>/Contents/Resources.
resources = []
# List of (src, dest) tuples; dest should be a path relative to the bundle
# (eg. "Contents/Resources/MyStuff/SomeFile.ext).
files = []
# List of shared libraries (dylibs, Frameworks) to bundle with the app
# will be placed in Contents/Frameworks
libs = []
# Directory where the bundle will be assembled.
builddir = "build"
# Make symlinks instead copying files. This is handy during debugging, but
# makes the bundle non-distributable.
symlink = 0
# Verbosity level.
verbosity = 1
# Destination root directory
destroot = ""
def setup(self):
# XXX rethink self.name munging, this is brittle.
self.name, ext = os.path.splitext(self.name)
if not ext:
ext = ".bundle"
bundleextension = ext
# misc (derived) attributes
self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
plist = self.plist
plist.CFBundleName = self.name
plist.CFBundlePackageType = self.type
if self.creator is None:
if hasattr(plist, "CFBundleSignature"):
self.creator = plist.CFBundleSignature
else:
self.creator = "????"
plist.CFBundleSignature = self.creator
if self.bundle_id:
plist.CFBundleIdentifier = self.bundle_id
elif not hasattr(plist, "CFBundleIdentifier"):
plist.CFBundleIdentifier = self.name
def build(self):
"""Build the bundle."""
builddir = self.builddir
if builddir and not os.path.exists(builddir):
os.mkdir(builddir)
self.message("Building %s" % repr(self.bundlepath), 1)
if os.path.exists(self.bundlepath):
shutil.rmtree(self.bundlepath)
os.mkdir(self.bundlepath)
self.preProcess()
self._copyFiles()
self._addMetaFiles()
self.postProcess()
self.message("Done.", 1)
def preProcess(self):
"""Hook for subclasses."""
pass
def postProcess(self):
"""Hook for subclasses."""
pass
def _addMetaFiles(self):
contents = pathjoin(self.bundlepath, "Contents")
makedirs(contents)
#
# Write Contents/PkgInfo
assert len(self.type) == len(self.creator) == 4, \
"type and creator must be 4-byte strings."
pkginfo = pathjoin(contents, "PkgInfo")
f = open(pkginfo, "wb")
f.write(self.type + self.creator)
f.close()
#
# Write Contents/Info.plist
infoplist = pathjoin(contents, "Info.plist")
self.plist.write(infoplist)
def _copyFiles(self):
files = self.files[:]
for path in self.resources:
files.append((path, pathjoin("Contents", "Resources",
os.path.basename(path))))
for path in self.libs:
files.append((path, pathjoin("Contents", "Frameworks",
os.path.basename(path))))
if self.symlink:
self.message("Making symbolic links", 1)
msg = "Making symlink from"
else:
self.message("Copying files", 1)
msg = "Copying"
files.sort()
for src, dst in files:
if os.path.isdir(src):
self.message("%s %s/ to %s/" % (msg, src, dst), 2)
else:
self.message("%s %s to %s" % (msg, src, dst), 2)
dst = pathjoin(self.bundlepath, dst)
if self.symlink:
symlink(src, dst, mkdirs=1)
else:
copy(src, dst, mkdirs=1)
def message(self, msg, level=0):
if level <= self.verbosity:
indent = ""
if level > 1:
indent = (level - 1) * " "
sys.stderr.write(indent + msg + "\n")
def report(self):
# XXX something decent
pass
if __debug__:
PYC_EXT = ".pyc"
else:
PYC_EXT = ".pyo"
MAGIC = imp.get_magic()
USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names
# For standalone apps, we have our own minimal site.py. We don't need
# all the cruft of the real site.py.
SITE_PY = """\
import sys
if not %(semi_standalone)s:
del sys.path[1:] # sys.path[0] is Contents/Resources/
"""
if USE_ZIPIMPORT:
ZIP_ARCHIVE = "Modules.zip"
SITE_PY += "sys.path.append(sys.path[0] + '/%s')\n" % ZIP_ARCHIVE
def getPycData(fullname, code, ispkg):
if ispkg:
fullname += ".__init__"
path = fullname.replace(".", os.sep) + PYC_EXT
return path, MAGIC + '\0\0\0\0' + marshal.dumps(code)
#
# Extension modules can't be in the modules zip archive, so a placeholder
# is added instead, that loads the extension from a specified location.
#
EXT_LOADER = """\
def __load():
import imp, sys, os
for p in sys.path:
path = os.path.join(p, "%(filename)s")
if os.path.exists(path):
break
else:
assert 0, "file not found: %(filename)s"
mod = imp.load_dynamic("%(name)s", path)
__load()
del __load
"""
MAYMISS_MODULES = ['mac', 'os2', 'nt', 'ntpath', 'dos', 'dospath',
'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize',
'org.python.core', 'riscos', 'riscosenviron', 'riscospath'
]
STRIP_EXEC = "/usr/bin/strip"
#
# We're using a stock interpreter to run the app, yet we need
# a way to pass the Python main program to the interpreter. The
# bootstrapping script fires up the interpreter with the right
# arguments. os.execve() is used as OSX doesn't like us to
# start a real new process. Also, the executable name must match
# the CFBundleExecutable value in the Info.plist, so we lie
# deliberately with argv[0]. The actual Python executable is
# passed in an environment variable so we can "repair"
# sys.executable later.
#
BOOTSTRAP_SCRIPT = """\
#!%(hashbang)s
import sys, os
execdir = os.path.dirname(sys.argv[0])
executable = os.path.join(execdir, "%(executable)s")
resdir = os.path.join(os.path.dirname(execdir), "Resources")
libdir = os.path.join(os.path.dirname(execdir), "Frameworks")
mainprogram = os.path.join(resdir, "%(mainprogram)s")
sys.argv.insert(1, mainprogram)
if %(standalone)s or %(semi_standalone)s:
os.environ["PYTHONPATH"] = resdir
if %(standalone)s:
os.environ["PYTHONHOME"] = resdir
else:
pypath = os.getenv("PYTHONPATH", "")
if pypath:
pypath = ":" + pypath
os.environ["PYTHONPATH"] = resdir + pypath
os.environ["PYTHONEXECUTABLE"] = executable
os.environ["DYLD_LIBRARY_PATH"] = libdir
os.environ["DYLD_FRAMEWORK_PATH"] = libdir
os.execve(executable, sys.argv, os.environ)
"""
#
# Optional wrapper that converts "dropped files" into sys.argv values.
#
ARGV_EMULATOR = """\
import argvemulator, os
argvemulator.ArgvCollector().mainloop()
execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s"))
"""
#
# When building a standalone app with Python.framework, we need to copy
# a subset from Python.framework to the bundle. The following list
# specifies exactly what items we'll copy.
#
PYTHONFRAMEWORKGOODIES = [
"Python", # the Python core library
"Resources/English.lproj",
"Resources/Info.plist",
"Resources/version.plist",
]
def isFramework():
return sys.exec_prefix.find("Python.framework") > 0
LIB = os.path.join(sys.prefix, "lib", "python" + sys.version[:3])
SITE_PACKAGES = os.path.join(LIB, "site-packages")
class AppBuilder(BundleBuilder):
# Override type of the bundle.
type = "APPL"
# platform, name of the subfolder of Contents that contains the executable.
platform = "MacOS"
# A Python main program. If this argument is given, the main
# executable in the bundle will be a small wrapper that invokes
# the main program. (XXX Discuss why.)
mainprogram = None
# The main executable. If a Python main program is specified
# the executable will be copied to Resources and be invoked
# by the wrapper program mentioned above. Otherwise it will
# simply be used as the main executable.
executable = None
# The name of the main nib, for Cocoa apps. *Must* be specified
# when building a Cocoa app.
nibname = None
# The name of the icon file to be copied to Resources and used for
# the Finder icon.
iconfile = None
# Symlink the executable instead of copying it.
symlink_exec = 0
# If True, build standalone app.
standalone = 0
# If True, build semi-standalone app (only includes third-party modules).
semi_standalone = 0
# If set, use this for #! lines in stead of sys.executable
python = None
# If True, add a real main program that emulates sys.argv before calling
# mainprogram
argv_emulation = 0
# The following attributes are only used when building a standalone app.
# Exclude these modules.
excludeModules = []
# Include these modules.
includeModules = []
# Include these packages.
includePackages = []
# Strip binaries from debug info.
strip = 0
# Found Python modules: [(name, codeobject, ispkg), ...]
pymodules = []
# Modules that modulefinder couldn't find:
missingModules = []
maybeMissingModules = []
def setup(self):
if ((self.standalone or self.semi_standalone)
and self.mainprogram is None):
raise BundleBuilderError, ("must specify 'mainprogram' when "
"building a standalone application.")
if self.mainprogram is None and self.executable is None:
raise BundleBuilderError, ("must specify either or both of "
"'executable' and 'mainprogram'")
self.execdir = pathjoin("Contents", self.platform)
if self.name is not None:
pass
elif self.mainprogram is not None:
self.name = os.path.splitext(os.path.basename(self.mainprogram))[0]
elif executable is not None:
self.name = os.path.splitext(os.path.basename(self.executable))[0]
if self.name[-4:] != ".app":
self.name += ".app"
if self.executable is None:
if not self.standalone and not isFramework():
self.symlink_exec = 1
if self.python:
self.executable = self.python
else:
self.executable = sys.executable
if self.nibname:
self.plist.NSMainNibFile = self.nibname
if not hasattr(self.plist, "NSPrincipalClass"):
self.plist.NSPrincipalClass = "NSApplication"
if self.standalone and isFramework():
self.addPythonFramework()
BundleBuilder.setup(self)
self.plist.CFBundleExecutable = self.name
if self.standalone or self.semi_standalone:
self.findDependencies()
def preProcess(self):
resdir = "Contents/Resources"
if self.executable is not None:
if self.mainprogram is None:
execname = self.name
else:
execname = os.path.basename(self.executable)
execpath = pathjoin(self.execdir, execname)
if not self.symlink_exec:
self.files.append((self.destroot + self.executable, execpath))
self.execpath = execpath
if self.mainprogram is not None:
mainprogram = os.path.basename(self.mainprogram)
self.files.append((self.mainprogram, pathjoin(resdir, mainprogram)))
if self.argv_emulation:
# Change the main program, and create the helper main program (which
# does argv collection and then calls the real main).
# Also update the included modules (if we're creating a standalone
# program) and the plist
realmainprogram = mainprogram
mainprogram = '__argvemulator_' + mainprogram
resdirpath = pathjoin(self.bundlepath, resdir)
mainprogrampath = pathjoin(resdirpath, mainprogram)
makedirs(resdirpath)
open(mainprogrampath, "w").write(ARGV_EMULATOR % locals())
if self.standalone or self.semi_standalone:
self.includeModules.append("argvemulator")
self.includeModules.append("os")
if not self.plist.has_key("CFBundleDocumentTypes"):
self.plist["CFBundleDocumentTypes"] = [
{ "CFBundleTypeOSTypes" : [
"****",
"fold",
"disk"],
"CFBundleTypeRole": "Viewer"}]
# Write bootstrap script
executable = os.path.basename(self.executable)
execdir = pathjoin(self.bundlepath, self.execdir)
bootstrappath = pathjoin(execdir, self.name)
makedirs(execdir)
if self.standalone or self.semi_standalone:
# XXX we're screwed when the end user has deleted
# /usr/bin/python
hashbang = "/usr/bin/python"
elif self.python:
hashbang = self.python
else:
hashbang = os.path.realpath(sys.executable)
standalone = self.standalone
semi_standalone = self.semi_standalone
open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals())
os.chmod(bootstrappath, 0775)
if self.iconfile is not None:
iconbase = os.path.basename(self.iconfile)
self.plist.CFBundleIconFile = iconbase
self.files.append((self.iconfile, pathjoin(resdir, iconbase)))
def postProcess(self):
if self.standalone or self.semi_standalone:
self.addPythonModules()
if self.strip and not self.symlink:
self.stripBinaries()
if self.symlink_exec and self.executable:
self.message("Symlinking executable %s to %s" % (self.executable,
self.execpath), 2)
dst = pathjoin(self.bundlepath, self.execpath)
makedirs(os.path.dirname(dst))
os.symlink(os.path.abspath(self.executable), dst)
if self.missingModules or self.maybeMissingModules:
self.reportMissing()
def addPythonFramework(self):
# If we're building a standalone app with Python.framework,
# include a minimal subset of Python.framework, *unless*
# Python.framework was specified manually in self.libs.
for lib in self.libs:
if os.path.basename(lib) == "Python.framework":
# a Python.framework was specified as a library
return
frameworkpath = sys.exec_prefix[:sys.exec_prefix.find(
"Python.framework") + len("Python.framework")]
version = sys.version[:3]
frameworkpath = pathjoin(frameworkpath, "Versions", version)
destbase = pathjoin("Contents", "Frameworks", "Python.framework",
"Versions", version)
for item in PYTHONFRAMEWORKGOODIES:
src = pathjoin(frameworkpath, item)
dst = pathjoin(destbase, item)
self.files.append((src, dst))
def _getSiteCode(self):
return compile(SITE_PY % {"semi_standalone": self.semi_standalone},
"<-bundlebuilder.py->", "exec")
def addPythonModules(self):
self.message("Adding Python modules", 1)
if USE_ZIPIMPORT:
# Create a zip file containing all modules as pyc.
import zipfile
relpath = pathjoin("Contents", "Resources", ZIP_ARCHIVE)
abspath = pathjoin(self.bundlepath, relpath)
zf = zipfile.ZipFile(abspath, "w", zipfile.ZIP_DEFLATED)
for name, code, ispkg in self.pymodules:
self.message("Adding Python module %s" % name, 2)
path, pyc = getPycData(name, code, ispkg)
zf.writestr(path, pyc)
zf.close()
# add site.pyc
sitepath = pathjoin(self.bundlepath, "Contents", "Resources",
"site" + PYC_EXT)
writePyc(self._getSiteCode(), sitepath)
else:
# Create individual .pyc files.
for name, code, ispkg in self.pymodules:
if ispkg:
name += ".__init__"
path = name.split(".")
path = pathjoin("Contents", "Resources", *path) + PYC_EXT
if ispkg:
self.message("Adding Python package %s" % path, 2)
else:
self.message("Adding Python module %s" % path, 2)
abspath = pathjoin(self.bundlepath, path)
makedirs(os.path.dirname(abspath))
writePyc(code, abspath)
def stripBinaries(self):
if not os.path.exists(STRIP_EXEC):
self.message("Error: can't strip binaries: no strip program at "
"%s" % STRIP_EXEC, 0)
else:
import stat
self.message("Stripping binaries", 1)
def walk(top):
for name in os.listdir(top):
path = pathjoin(top, name)
if os.path.islink(path):
continue
if os.path.isdir(path):
walk(path)
else:
mod = os.stat(path)[stat.ST_MODE]
if not (mod & 0100):
continue
relpath = path[len(self.bundlepath):]
self.message("Stripping %s" % relpath, 2)
inf, outf = os.popen4("%s -S \"%s\"" %
(STRIP_EXEC, path))
output = outf.read().strip()
if output:
# usually not a real problem, like when we're
# trying to strip a script
self.message("Problem stripping %s:" % relpath, 3)
self.message(output, 3)
walk(self.bundlepath)
def findDependencies(self):
self.message("Finding module dependencies", 1)
import modulefinder
mf = modulefinder.ModuleFinder(excludes=self.excludeModules)
if USE_ZIPIMPORT:
# zipimport imports zlib, must add it manually
mf.import_hook("zlib")
# manually add our own site.py
site = mf.add_module("site")
site.__code__ = self._getSiteCode()
mf.scan_code(site.__code__, site)
# warnings.py gets imported implicitly from C
mf.import_hook("warnings")
includeModules = self.includeModules[:]
for name in self.includePackages:
includeModules.extend(findPackageContents(name).keys())
for name in includeModules:
try:
mf.import_hook(name)
except ImportError:
self.missingModules.append(name)
mf.run_script(self.mainprogram)
modules = mf.modules.items()
modules.sort()
for name, mod in modules:
path = mod.__file__
if path and self.semi_standalone:
# skip the standard library
if path.startswith(LIB) and not path.startswith(SITE_PACKAGES):
continue
if path and mod.__code__ is None:
# C extension
filename = os.path.basename(path)
pathitems = name.split(".")[:-1] + [filename]
dstpath = pathjoin(*pathitems)
if USE_ZIPIMPORT:
if name != "zlib":
# neatly pack all extension modules in a subdirectory,
# except zlib, since it's neccesary for bootstrapping.
dstpath = pathjoin("ExtensionModules", dstpath)
# Python modules are stored in a Zip archive, but put
# extensions in Contents/Resources/. Add a tiny "loader"
# program in the Zip archive. Due to Thomas Heller.
source = EXT_LOADER % {"name": name, "filename": dstpath}
code = compile(source, "<dynloader for %s>" % name, "exec")
mod.__code__ = code
self.files.append((path, pathjoin("Contents", "Resources", dstpath)))
if mod.__code__ is not None:
ispkg = mod.__path__ is not None
if not USE_ZIPIMPORT or name != "site":
# Our site.py is doing the bootstrapping, so we must
# include a real .pyc file if USE_ZIPIMPORT is True.
self.pymodules.append((name, mod.__code__, ispkg))
if hasattr(mf, "any_missing_maybe"):
missing, maybe = mf.any_missing_maybe()
else:
missing = mf.any_missing()
maybe = []
self.missingModules.extend(missing)
self.maybeMissingModules.extend(maybe)
def reportMissing(self):
missing = [name for name in self.missingModules
if name not in MAYMISS_MODULES]
if self.maybeMissingModules:
maybe = self.maybeMissingModules
else:
maybe = [name for name in missing if "." in name]
missing = [name for name in missing if "." not in name]
missing.sort()
maybe.sort()
if maybe:
self.message("Warning: couldn't find the following submodules:", 1)
self.message(" (Note that these could be false alarms -- "
"it's not always", 1)
self.message(" possible to distinguish between \"from package "
"import submodule\" ", 1)
self.message(" and \"from package import name\")", 1)
for name in maybe:
self.message(" ? " + name, 1)
if missing:
self.message("Warning: couldn't find the following modules:", 1)
for name in missing:
self.message(" ? " + name, 1)
def report(self):
# XXX something decent
import pprint
pprint.pprint(self.__dict__)
if self.standalone or self.semi_standalone:
self.reportMissing()
#
# Utilities.
#
SUFFIXES = [_suf for _suf, _mode, _tp in imp.get_suffixes()]
identifierRE = re.compile(r"[_a-zA-z][_a-zA-Z0-9]*$")
def findPackageContents(name, searchpath=None):
head = name.split(".")[-1]
if identifierRE.match(head) is None:
return {}
try:
fp, path, (ext, mode, tp) = imp.find_module(head, searchpath)
except ImportError:
return {}
modules = {name: None}
if tp == imp.PKG_DIRECTORY and path:
files = os.listdir(path)
for sub in files:
sub, ext = os.path.splitext(sub)
fullname = name + "." + sub
if sub != "__init__" and fullname not in modules:
modules.update(findPackageContents(fullname, [path]))
return modules
def writePyc(code, path):
f = open(path, "wb")
f.write(MAGIC)
f.write("\0" * 4) # don't bother about a time stamp
marshal.dump(code, f)
f.close()
def copy(src, dst, mkdirs=0):
"""Copy a file or a directory."""
if mkdirs:
makedirs(os.path.dirname(dst))
if os.path.isdir(src):
shutil.copytree(src, dst, symlinks=1)
else:
shutil.copy2(src, dst)
def copytodir(src, dstdir):
"""Copy a file or a directory to an existing directory."""
dst = pathjoin(dstdir, os.path.basename(src))
copy(src, dst)
def makedirs(dir):
"""Make all directories leading up to 'dir' including the leaf
directory. Don't moan if any path element already exists."""
try:
os.makedirs(dir)
except OSError, why:
if why.errno != errno.EEXIST:
raise
def symlink(src, dst, mkdirs=0):
"""Copy a file or a directory."""
if not os.path.exists(src):
raise IOError, "No such file or directory: '%s'" % src
if mkdirs:
makedirs(os.path.dirname(dst))
os.symlink(os.path.abspath(src), dst)
def pathjoin(*args):
"""Safe wrapper for os.path.join: asserts that all but the first
argument are relative paths."""
for seg in args[1:]:
assert seg[0] != "/"
return os.path.join(*args)
cmdline_doc = """\
Usage:
python bundlebuilder.py [options] command
python mybuildscript.py [options] command
Commands:
build build the application
report print a report
Options:
-b, --builddir=DIR the build directory; defaults to "build"
-n, --name=NAME application name
-r, --resource=FILE extra file or folder to be copied to Resources
-f, --file=SRC:DST extra file or folder to be copied into the bundle;
DST must be a path relative to the bundle root
-e, --executable=FILE the executable to be used
-m, --mainprogram=FILE the Python main program
-a, --argv add a wrapper main program to create sys.argv
-p, --plist=FILE .plist file (default: generate one)
--nib=NAME main nib name
-c, --creator=CCCC 4-char creator code (default: '????')
--iconfile=FILE filename of the icon (an .icns file) to be used
as the Finder icon
--bundle-id=ID the CFBundleIdentifier, in reverse-dns format
(eg. org.python.BuildApplet; this is used for
the preferences file name)
-l, --link symlink files/folder instead of copying them
--link-exec symlink the executable instead of copying it
--standalone build a standalone application, which is fully
independent of a Python installation
--semi-standalone build a standalone application, which depends on
an installed Python, yet includes all third-party
modules.
--python=FILE Python to use in #! line in stead of current Python
--lib=FILE shared library or framework to be copied into
the bundle
-x, --exclude=MODULE exclude module (with --(semi-)standalone)
-i, --include=MODULE include module (with --(semi-)standalone)
--package=PACKAGE include a whole package (with --(semi-)standalone)
--strip strip binaries (remove debug info)
-v, --verbose increase verbosity level
-q, --quiet decrease verbosity level
-h, --help print this message
"""
def usage(msg=None):
if msg:
print msg
print cmdline_doc
sys.exit(1)
def main(builder=None):
if builder is None:
builder = AppBuilder(verbosity=1)
shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa"
longopts = ("builddir=", "name=", "resource=", "file=", "executable=",
"mainprogram=", "creator=", "nib=", "plist=", "link",
"link-exec", "help", "verbose", "quiet", "argv", "standalone",
"exclude=", "include=", "package=", "strip", "iconfile=",
"lib=", "python=", "semi-standalone", "bundle-id=", "destroot=")
try:
options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
except getopt.error:
usage()
for opt, arg in options:
if opt in ('-b', '--builddir'):
builder.builddir = arg
elif opt in ('-n', '--name'):
builder.name = arg
elif opt in ('-r', '--resource'):
builder.resources.append(os.path.normpath(arg))
elif opt in ('-f', '--file'):
srcdst = arg.split(':')
if len(srcdst) != 2:
usage("-f or --file argument must be two paths, "
"separated by a colon")
builder.files.append(srcdst)
elif opt in ('-e', '--executable'):
builder.executable = arg
elif opt in ('-m', '--mainprogram'):
builder.mainprogram = arg
elif opt in ('-a', '--argv'):
builder.argv_emulation = 1
elif opt in ('-c', '--creator'):
builder.creator = arg
elif opt == '--bundle-id':
builder.bundle_id = arg
elif opt == '--iconfile':
builder.iconfile = arg
elif opt == "--lib":
builder.libs.append(os.path.normpath(arg))
elif opt == "--nib":
builder.nibname = arg
elif opt in ('-p', '--plist'):
builder.plist = Plist.fromFile(arg)
elif opt in ('-l', '--link'):
builder.symlink = 1
elif opt == '--link-exec':
builder.symlink_exec = 1
elif opt in ('-h', '--help'):
usage()
elif opt in ('-v', '--verbose'):
builder.verbosity += 1
elif opt in ('-q', '--quiet'):
builder.verbosity -= 1
elif opt == '--standalone':
builder.standalone = 1
elif opt == '--semi-standalone':
builder.semi_standalone = 1
elif opt == '--python':
builder.python = arg
elif opt in ('-x', '--exclude'):
builder.excludeModules.append(arg)
elif opt in ('-i', '--include'):
builder.includeModules.append(arg)
elif opt == '--package':
builder.includePackages.append(arg)
elif opt == '--strip':
builder.strip = 1
elif opt == '--destroot':
builder.destroot = arg
if len(args) != 1:
usage("Must specify one command ('build', 'report' or 'help')")
command = args[0]
if command == "build":
builder.setup()
builder.build()
elif command == "report":
builder.setup()
builder.report()
elif command == "help":
usage()
else:
usage("Unknown command '%s'" % command)
def buildapp(**kwargs):
builder = AppBuilder(**kwargs)
main(builder)
if __name__ == "__main__":
main()
| Python |
"""
gensuitemodule - Generate an AE suite module from an aete/aeut resource
Based on aete.py.
Reading and understanding this code is left as an exercise to the reader.
"""
import MacOS
import EasyDialogs
import os
import string
import sys
import types
import StringIO
import keyword
import macresource
import aetools
import distutils.sysconfig
import OSATerminology
from Carbon.Res import *
import Carbon.Folder
import MacOS
import getopt
import plistlib
_MAC_LIB_FOLDER=os.path.dirname(aetools.__file__)
DEFAULT_STANDARD_PACKAGEFOLDER=os.path.join(_MAC_LIB_FOLDER, 'lib-scriptpackages')
DEFAULT_USER_PACKAGEFOLDER=distutils.sysconfig.get_python_lib()
def usage():
sys.stderr.write("Usage: %s [opts] application-or-resource-file\n" % sys.argv[0])
sys.stderr.write("""Options:
--output pkgdir Pathname of the output package (short: -o)
--resource Parse resource file in stead of launching application (-r)
--base package Use another base package in stead of default StdSuites (-b)
--edit old=new Edit suite names, use empty new to skip a suite (-e)
--creator code Set creator code for package (-c)
--dump Dump aete resource to stdout in stead of creating module (-d)
--verbose Tell us what happens (-v)
""")
sys.exit(1)
def main():
if len(sys.argv) > 1:
SHORTOPTS = "rb:o:e:c:dv"
LONGOPTS = ("resource", "base=", "output=", "edit=", "creator=", "dump", "verbose")
try:
opts, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS)
except getopt.GetoptError:
usage()
process_func = processfile
basepkgname = 'StdSuites'
output = None
edit_modnames = []
creatorsignature = None
dump = None
verbose = None
for o, a in opts:
if o in ('-r', '--resource'):
process_func = processfile_fromresource
if o in ('-b', '--base'):
basepkgname = a
if o in ('-o', '--output'):
output = a
if o in ('-e', '--edit'):
split = a.split('=')
if len(split) != 2:
usage()
edit_modnames.append(split)
if o in ('-c', '--creator'):
if len(a) != 4:
sys.stderr.write("creator must be 4-char string\n")
sys.exit(1)
creatorsignature = a
if o in ('-d', '--dump'):
dump = sys.stdout
if o in ('-v', '--verbose'):
verbose = sys.stderr
if output and len(args) > 1:
sys.stderr.write("%s: cannot specify --output with multiple inputs\n" % sys.argv[0])
sys.exit(1)
for filename in args:
process_func(filename, output=output, basepkgname=basepkgname,
edit_modnames=edit_modnames, creatorsignature=creatorsignature,
dump=dump, verbose=verbose)
else:
main_interactive()
def main_interactive(interact=0, basepkgname='StdSuites'):
if interact:
# Ask for save-filename for each module
edit_modnames = None
else:
# Use default filenames for each module
edit_modnames = []
appsfolder = Carbon.Folder.FSFindFolder(-32765, 'apps', 0)
filename = EasyDialogs.AskFileForOpen(
message='Select scriptable application',
dialogOptionFlags=0x1056, # allow selection of .app bundles
defaultLocation=appsfolder)
if not filename:
return
if not is_scriptable(filename):
if EasyDialogs.AskYesNoCancel(
"Warning: application does not seem scriptable",
yes="Continue", default=2, no="") <= 0:
return
try:
processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname,
verbose=sys.stderr)
except MacOS.Error, arg:
print "Error getting terminology:", arg
print "Retry, manually parsing resources"
processfile_fromresource(filename, edit_modnames=edit_modnames,
basepkgname=basepkgname, verbose=sys.stderr)
def is_scriptable(application):
"""Return true if the application is scriptable"""
if os.path.isdir(application):
plistfile = os.path.join(application, 'Contents', 'Info.plist')
if not os.path.exists(plistfile):
return False
plist = plistlib.Plist.fromFile(plistfile)
return plist.get('NSAppleScriptEnabled', False)
# If it is a file test for an aete/aeut resource.
currf = CurResFile()
try:
refno = macresource.open_pathname(application)
except MacOS.Error:
return False
UseResFile(refno)
n_terminology = Count1Resources('aete') + Count1Resources('aeut') + \
Count1Resources('scsz') + Count1Resources('osiz')
CloseResFile(refno)
UseResFile(currf)
return n_terminology > 0
def processfile_fromresource(fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None, verbose=None):
"""Process all resources in a single file"""
if not is_scriptable(fullname) and verbose:
print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
cur = CurResFile()
if verbose:
print >>verbose, "Processing", fullname
rf = macresource.open_pathname(fullname)
try:
UseResFile(rf)
resources = []
for i in range(Count1Resources('aete')):
res = Get1IndResource('aete', 1+i)
resources.append(res)
for i in range(Count1Resources('aeut')):
res = Get1IndResource('aeut', 1+i)
resources.append(res)
if verbose:
print >>verbose, "\nLISTING aete+aeut RESOURCES IN", repr(fullname)
aetelist = []
for res in resources:
if verbose:
print >>verbose, "decoding", res.GetResInfo(), "..."
data = res.data
aete = decode(data, verbose)
aetelist.append((aete, res.GetResInfo()))
finally:
if rf <> cur:
CloseResFile(rf)
UseResFile(cur)
# switch back (needed for dialogs in Python)
UseResFile(cur)
if dump:
dumpaetelist(aetelist, dump)
compileaetelist(aetelist, fullname, output=output,
basepkgname=basepkgname, edit_modnames=edit_modnames,
creatorsignature=creatorsignature, verbose=verbose)
def processfile(fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None,
verbose=None):
"""Ask an application for its terminology and process that"""
if not is_scriptable(fullname) and verbose:
print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
if verbose:
print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname)
try:
aedescobj, launched = OSATerminology.GetAppTerminology(fullname)
except MacOS.Error, arg:
if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound
if verbose:
print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually"
aedata, sig = getappterminology(fullname, verbose=verbose)
if not creatorsignature:
creatorsignature = sig
else:
raise
else:
if launched:
if verbose:
print >>verbose, "Launched", fullname
raw = aetools.unpack(aedescobj)
if not raw:
if verbose:
print >>verbose, 'Unpack returned empty value:', raw
return
if not raw[0].data:
if verbose:
print >>verbose, 'Unpack returned value without data:', raw
return
aedata = raw[0]
aete = decode(aedata.data, verbose)
if dump:
dumpaetelist([aete], dump)
return
compileaete(aete, None, fullname, output=output, basepkgname=basepkgname,
creatorsignature=creatorsignature, edit_modnames=edit_modnames,
verbose=verbose)
def getappterminology(fullname, verbose=None):
"""Get application terminology by sending an AppleEvent"""
# First check that we actually can send AppleEvents
if not MacOS.WMAvailable():
raise RuntimeError, "Cannot send AppleEvents, no access to window manager"
# Next, a workaround for a bug in MacOS 10.2: sending events will hang unless
# you have created an event loop first.
import Carbon.Evt
Carbon.Evt.WaitNextEvent(0,0)
if os.path.isdir(fullname):
# Now get the signature of the application, hoping it is a bundle
pkginfo = os.path.join(fullname, 'Contents', 'PkgInfo')
if not os.path.exists(pkginfo):
raise RuntimeError, "No PkgInfo file found"
tp_cr = open(pkginfo, 'rb').read()
cr = tp_cr[4:8]
else:
# Assume it is a file
cr, tp = MacOS.GetCreatorAndType(fullname)
# Let's talk to it and ask for its AETE
talker = aetools.TalkTo(cr)
try:
talker._start()
except (MacOS.Error, aetools.Error), arg:
if verbose:
print >>verbose, 'Warning: start() failed, continuing anyway:', arg
reply = talker.send("ascr", "gdte")
#reply2 = talker.send("ascr", "gdut")
# Now pick the bits out of the return that we need.
return reply[1]['----'], cr
def compileaetelist(aetelist, fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, verbose=None):
for aete, resinfo in aetelist:
compileaete(aete, resinfo, fullname, output=output,
basepkgname=basepkgname, edit_modnames=edit_modnames,
creatorsignature=creatorsignature, verbose=verbose)
def dumpaetelist(aetelist, output):
import pprint
pprint.pprint(aetelist, output)
def decode(data, verbose=None):
"""Decode a resource into a python data structure"""
f = StringIO.StringIO(data)
aete = generic(getaete, f)
aete = simplify(aete)
processed = f.tell()
unprocessed = len(f.read())
total = f.tell()
if unprocessed and verbose:
verbose.write("%d processed + %d unprocessed = %d total\n" %
(processed, unprocessed, total))
return aete
def simplify(item):
"""Recursively replace singleton tuples by their constituent item"""
if type(item) is types.ListType:
return map(simplify, item)
elif type(item) == types.TupleType and len(item) == 2:
return simplify(item[1])
else:
return item
# Here follows the aete resource decoder.
# It is presented bottom-up instead of top-down because there are direct
# references to the lower-level part-decoders from the high-level part-decoders.
def getbyte(f, *args):
c = f.read(1)
if not c:
raise EOFError, 'in getbyte' + str(args)
return ord(c)
def getword(f, *args):
getalign(f)
s = f.read(2)
if len(s) < 2:
raise EOFError, 'in getword' + str(args)
return (ord(s[0])<<8) | ord(s[1])
def getlong(f, *args):
getalign(f)
s = f.read(4)
if len(s) < 4:
raise EOFError, 'in getlong' + str(args)
return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3])
def getostype(f, *args):
getalign(f)
s = f.read(4)
if len(s) < 4:
raise EOFError, 'in getostype' + str(args)
return s
def getpstr(f, *args):
c = f.read(1)
if len(c) < 1:
raise EOFError, 'in getpstr[1]' + str(args)
nbytes = ord(c)
if nbytes == 0: return ''
s = f.read(nbytes)
if len(s) < nbytes:
raise EOFError, 'in getpstr[2]' + str(args)
return s
def getalign(f):
if f.tell() & 1:
c = f.read(1)
##if c <> '\0':
## print align:', repr(c)
def getlist(f, description, getitem):
count = getword(f)
list = []
for i in range(count):
list.append(generic(getitem, f))
getalign(f)
return list
def alt_generic(what, f, *args):
print "generic", repr(what), args
res = vageneric(what, f, args)
print '->', repr(res)
return res
def generic(what, f, *args):
if type(what) == types.FunctionType:
return apply(what, (f,) + args)
if type(what) == types.ListType:
record = []
for thing in what:
item = apply(generic, thing[:1] + (f,) + thing[1:])
record.append((thing[1], item))
return record
return "BAD GENERIC ARGS: %r" % (what,)
getdata = [
(getostype, "type"),
(getpstr, "description"),
(getword, "flags")
]
getargument = [
(getpstr, "name"),
(getostype, "keyword"),
(getdata, "what")
]
getevent = [
(getpstr, "name"),
(getpstr, "description"),
(getostype, "suite code"),
(getostype, "event code"),
(getdata, "returns"),
(getdata, "accepts"),
(getlist, "optional arguments", getargument)
]
getproperty = [
(getpstr, "name"),
(getostype, "code"),
(getdata, "what")
]
getelement = [
(getostype, "type"),
(getlist, "keyform", getostype)
]
getclass = [
(getpstr, "name"),
(getostype, "class code"),
(getpstr, "description"),
(getlist, "properties", getproperty),
(getlist, "elements", getelement)
]
getcomparison = [
(getpstr, "operator name"),
(getostype, "operator ID"),
(getpstr, "operator comment"),
]
getenumerator = [
(getpstr, "enumerator name"),
(getostype, "enumerator ID"),
(getpstr, "enumerator comment")
]
getenumeration = [
(getostype, "enumeration ID"),
(getlist, "enumerator", getenumerator)
]
getsuite = [
(getpstr, "suite name"),
(getpstr, "suite description"),
(getostype, "suite ID"),
(getword, "suite level"),
(getword, "suite version"),
(getlist, "events", getevent),
(getlist, "classes", getclass),
(getlist, "comparisons", getcomparison),
(getlist, "enumerations", getenumeration)
]
getaete = [
(getword, "major/minor version in BCD"),
(getword, "language code"),
(getword, "script code"),
(getlist, "suites", getsuite)
]
def compileaete(aete, resinfo, fname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, verbose=None):
"""Generate code for a full aete resource. fname passed for doc purposes"""
[version, language, script, suites] = aete
major, minor = divmod(version, 256)
if not creatorsignature:
creatorsignature, dummy = MacOS.GetCreatorAndType(fname)
packagename = identify(os.path.splitext(os.path.basename(fname))[0])
if language:
packagename = packagename+'_lang%d'%language
if script:
packagename = packagename+'_script%d'%script
if len(packagename) > 27:
packagename = packagename[:27]
if output:
# XXXX Put this in site-packages if it isn't a full pathname?
if not os.path.exists(output):
os.mkdir(output)
pathname = output
else:
pathname = EasyDialogs.AskFolder(message='Create and select package folder for %s'%packagename,
defaultLocation=DEFAULT_USER_PACKAGEFOLDER)
output = pathname
if not pathname:
return
packagename = os.path.split(os.path.normpath(pathname))[1]
if not basepkgname:
basepkgname = EasyDialogs.AskFolder(message='Package folder for base suite (usually StdSuites)',
defaultLocation=DEFAULT_STANDARD_PACKAGEFOLDER)
if basepkgname:
dirname, basepkgname = os.path.split(os.path.normpath(basepkgname))
if dirname and not dirname in sys.path:
sys.path.insert(0, dirname)
basepackage = __import__(basepkgname)
else:
basepackage = None
suitelist = []
allprecompinfo = []
allsuites = []
for suite in suites:
compiler = SuiteCompiler(suite, basepackage, output, edit_modnames, verbose)
code, modname, precompinfo = compiler.precompilesuite()
if not code:
continue
allprecompinfo = allprecompinfo + precompinfo
suiteinfo = suite, pathname, modname
suitelist.append((code, modname))
allsuites.append(compiler)
for compiler in allsuites:
compiler.compilesuite(major, minor, language, script, fname, allprecompinfo)
initfilename = os.path.join(output, '__init__.py')
fp = open(initfilename, 'w')
MacOS.SetCreatorAndType(initfilename, 'Pyth', 'TEXT')
fp.write('"""\n')
fp.write("Package generated from %s\n"%ascii(fname))
if resinfo:
fp.write("Resource %s resid %d %s\n"%(ascii(resinfo[1]), resinfo[0], ascii(resinfo[2])))
fp.write('"""\n')
fp.write('import aetools\n')
fp.write('Error = aetools.Error\n')
suitelist.sort()
for code, modname in suitelist:
fp.write("import %s\n" % modname)
fp.write("\n\n_code_to_module = {\n")
for code, modname in suitelist:
fp.write(" '%s' : %s,\n"%(ascii(code), modname))
fp.write("}\n\n")
fp.write("\n\n_code_to_fullname = {\n")
for code, modname in suitelist:
fp.write(" '%s' : ('%s.%s', '%s'),\n"%(ascii(code), packagename, modname, modname))
fp.write("}\n\n")
for code, modname in suitelist:
fp.write("from %s import *\n"%modname)
# Generate property dicts and element dicts for all types declared in this module
fp.write("\ndef getbaseclasses(v):\n")
fp.write(" if not getattr(v, '_propdict', None):\n")
fp.write(" v._propdict = {}\n")
fp.write(" v._elemdict = {}\n")
fp.write(" for superclassname in getattr(v, '_superclassnames', []):\n")
fp.write(" superclass = eval(superclassname)\n")
fp.write(" getbaseclasses(superclass)\n")
fp.write(" v._propdict.update(getattr(superclass, '_propdict', {}))\n")
fp.write(" v._elemdict.update(getattr(superclass, '_elemdict', {}))\n")
fp.write(" v._propdict.update(getattr(v, '_privpropdict', {}))\n")
fp.write(" v._elemdict.update(getattr(v, '_privelemdict', {}))\n")
fp.write("\n")
fp.write("import StdSuites\n")
allprecompinfo.sort()
if allprecompinfo:
fp.write("\n#\n# Set property and element dictionaries now that all classes have been defined\n#\n")
for codenamemapper in allprecompinfo:
for k, v in codenamemapper.getall('class'):
fp.write("getbaseclasses(%s)\n" % v)
# Generate a code-to-name mapper for all of the types (classes) declared in this module
application_class = None
if allprecompinfo:
fp.write("\n#\n# Indices of types declared in this module\n#\n")
fp.write("_classdeclarations = {\n")
for codenamemapper in allprecompinfo:
for k, v in codenamemapper.getall('class'):
fp.write(" %r : %s,\n" % (k, v))
if k == 'capp':
application_class = v
fp.write("}\n")
if suitelist:
fp.write("\n\nclass %s(%s_Events"%(packagename, suitelist[0][1]))
for code, modname in suitelist[1:]:
fp.write(",\n %s_Events"%modname)
fp.write(",\n aetools.TalkTo):\n")
fp.write(" _signature = %r\n\n"%(creatorsignature,))
fp.write(" _moduleName = '%s'\n\n"%packagename)
if application_class:
fp.write(" _elemdict = %s._elemdict\n" % application_class)
fp.write(" _propdict = %s._propdict\n" % application_class)
fp.close()
class SuiteCompiler:
def __init__(self, suite, basepackage, output, edit_modnames, verbose):
self.suite = suite
self.basepackage = basepackage
self.edit_modnames = edit_modnames
self.output = output
self.verbose = verbose
# Set by precompilesuite
self.pathname = None
self.modname = None
# Set by compilesuite
self.fp = None
self.basemodule = None
self.enumsneeded = {}
def precompilesuite(self):
"""Parse a single suite without generating the output. This step is needed
so we can resolve recursive references by suites to enums/comps/etc declared
in other suites"""
[name, desc, code, level, version, events, classes, comps, enums] = self.suite
modname = identify(name)
if len(modname) > 28:
modname = modname[:27]
if self.edit_modnames is None:
self.pathname = EasyDialogs.AskFileForSave(message='Python output file',
savedFileName=modname+'.py')
else:
for old, new in self.edit_modnames:
if old == modname:
modname = new
if modname:
self.pathname = os.path.join(self.output, modname + '.py')
else:
self.pathname = None
if not self.pathname:
return None, None, None
self.modname = os.path.splitext(os.path.split(self.pathname)[1])[0]
if self.basepackage and self.basepackage._code_to_module.has_key(code):
# We are an extension of a baseclass (usually an application extending
# Standard_Suite or so). Import everything from our base module
basemodule = self.basepackage._code_to_module[code]
else:
# We are not an extension.
basemodule = None
self.enumsneeded = {}
for event in events:
self.findenumsinevent(event)
objc = ObjectCompiler(None, self.modname, basemodule, interact=(self.edit_modnames is None),
verbose=self.verbose)
for cls in classes:
objc.compileclass(cls)
for cls in classes:
objc.fillclasspropsandelems(cls)
for comp in comps:
objc.compilecomparison(comp)
for enum in enums:
objc.compileenumeration(enum)
for enum in self.enumsneeded.keys():
objc.checkforenum(enum)
objc.dumpindex()
precompinfo = objc.getprecompinfo(self.modname)
return code, self.modname, precompinfo
def compilesuite(self, major, minor, language, script, fname, precompinfo):
"""Generate code for a single suite"""
[name, desc, code, level, version, events, classes, comps, enums] = self.suite
# Sort various lists, so re-generated source is easier compared
def class_sorter(k1, k2):
"""Sort classes by code, and make sure main class sorts before synonyms"""
# [name, code, desc, properties, elements] = cls
if k1[1] < k2[1]: return -1
if k1[1] > k2[1]: return 1
if not k2[3] or k2[3][0][1] == 'c@#!':
# This is a synonym, the other one is better
return -1
if not k1[3] or k1[3][0][1] == 'c@#!':
# This is a synonym, the other one is better
return 1
return 0
events.sort()
classes.sort(class_sorter)
comps.sort()
enums.sort()
self.fp = fp = open(self.pathname, 'w')
MacOS.SetCreatorAndType(self.pathname, 'Pyth', 'TEXT')
fp.write('"""Suite %s: %s\n' % (ascii(name), ascii(desc)))
fp.write("Level %d, version %d\n\n" % (level, version))
fp.write("Generated from %s\n"%ascii(fname))
fp.write("AETE/AEUT resource version %d/%d, language %d, script %d\n" % \
(major, minor, language, script))
fp.write('"""\n\n')
fp.write('import aetools\n')
fp.write('import MacOS\n\n')
fp.write("_code = %r\n\n"% (code,))
if self.basepackage and self.basepackage._code_to_module.has_key(code):
# We are an extension of a baseclass (usually an application extending
# Standard_Suite or so). Import everything from our base module
fp.write('from %s import *\n'%self.basepackage._code_to_fullname[code][0])
basemodule = self.basepackage._code_to_module[code]
elif self.basepackage and self.basepackage._code_to_module.has_key(code.lower()):
# This is needed by CodeWarrior and some others.
fp.write('from %s import *\n'%self.basepackage._code_to_fullname[code.lower()][0])
basemodule = self.basepackage._code_to_module[code.lower()]
else:
# We are not an extension.
basemodule = None
self.basemodule = basemodule
self.compileclassheader()
self.enumsneeded = {}
if events:
for event in events:
self.compileevent(event)
else:
fp.write(" pass\n\n")
objc = ObjectCompiler(fp, self.modname, basemodule, precompinfo, interact=(self.edit_modnames is None),
verbose=self.verbose)
for cls in classes:
objc.compileclass(cls)
for cls in classes:
objc.fillclasspropsandelems(cls)
for comp in comps:
objc.compilecomparison(comp)
for enum in enums:
objc.compileenumeration(enum)
for enum in self.enumsneeded.keys():
objc.checkforenum(enum)
objc.dumpindex()
def compileclassheader(self):
"""Generate class boilerplate"""
classname = '%s_Events'%self.modname
if self.basemodule:
modshortname = string.split(self.basemodule.__name__, '.')[-1]
baseclassname = '%s_Events'%modshortname
self.fp.write("class %s(%s):\n\n"%(classname, baseclassname))
else:
self.fp.write("class %s:\n\n"%classname)
def compileevent(self, event):
"""Generate code for a single event"""
[name, desc, code, subcode, returns, accepts, arguments] = event
fp = self.fp
funcname = identify(name)
#
# generate name->keyword map
#
if arguments:
fp.write(" _argmap_%s = {\n"%funcname)
for a in arguments:
fp.write(" %r : %r,\n"%(identify(a[0]), a[1]))
fp.write(" }\n\n")
#
# Generate function header
#
has_arg = (not is_null(accepts))
opt_arg = (has_arg and is_optional(accepts))
fp.write(" def %s(self, "%funcname)
if has_arg:
if not opt_arg:
fp.write("_object, ") # Include direct object, if it has one
else:
fp.write("_object=None, ") # Also include if it is optional
else:
fp.write("_no_object=None, ") # For argument checking
fp.write("_attributes={}, **_arguments):\n") # include attribute dict and args
#
# Generate doc string (important, since it may be the only
# available documentation, due to our name-remaping)
#
fp.write(' """%s: %s\n'%(ascii(name), ascii(desc)))
if has_arg:
fp.write(" Required argument: %s\n"%getdatadoc(accepts))
elif opt_arg:
fp.write(" Optional argument: %s\n"%getdatadoc(accepts))
for arg in arguments:
fp.write(" Keyword argument %s: %s\n"%(identify(arg[0]),
getdatadoc(arg[2])))
fp.write(" Keyword argument _attributes: AppleEvent attribute dictionary\n")
if not is_null(returns):
fp.write(" Returns: %s\n"%getdatadoc(returns))
fp.write(' """\n')
#
# Fiddle the args so everything ends up in 'arguments' dictionary
#
fp.write(" _code = %r\n"% (code,))
fp.write(" _subcode = %r\n\n"% (subcode,))
#
# Do keyword name substitution
#
if arguments:
fp.write(" aetools.keysubst(_arguments, self._argmap_%s)\n"%funcname)
else:
fp.write(" if _arguments: raise TypeError, 'No optional args expected'\n")
#
# Stuff required arg (if there is one) into arguments
#
if has_arg:
fp.write(" _arguments['----'] = _object\n")
elif opt_arg:
fp.write(" if _object:\n")
fp.write(" _arguments['----'] = _object\n")
else:
fp.write(" if _no_object != None: raise TypeError, 'No direct arg expected'\n")
fp.write("\n")
#
# Do enum-name substitution
#
for a in arguments:
if is_enum(a[2]):
kname = a[1]
ename = a[2][0]
if ename <> '****':
fp.write(" aetools.enumsubst(_arguments, %r, _Enum_%s)\n" %
(kname, identify(ename)))
self.enumsneeded[ename] = 1
fp.write("\n")
#
# Do the transaction
#
fp.write(" _reply, _arguments, _attributes = self.send(_code, _subcode,\n")
fp.write(" _arguments, _attributes)\n")
#
# Error handling
#
fp.write(" if _arguments.get('errn', 0):\n")
fp.write(" raise aetools.Error, aetools.decodeerror(_arguments)\n")
fp.write(" # XXXX Optionally decode result\n")
#
# Decode result
#
fp.write(" if _arguments.has_key('----'):\n")
if is_enum(returns):
fp.write(" # XXXX Should do enum remapping here...\n")
fp.write(" return _arguments['----']\n")
fp.write("\n")
def findenumsinevent(self, event):
"""Find all enums for a single event"""
[name, desc, code, subcode, returns, accepts, arguments] = event
for a in arguments:
if is_enum(a[2]):
ename = a[2][0]
if ename <> '****':
self.enumsneeded[ename] = 1
#
# This class stores the code<->name translations for a single module. It is used
# to keep the information while we're compiling the module, but we also keep these objects
# around so if one suite refers to, say, an enum in another suite we know where to
# find it. Finally, if we really can't find a code, the user can add modules by
# hand.
#
class CodeNameMapper:
def __init__(self, interact=1, verbose=None):
self.code2name = {
"property" : {},
"class" : {},
"enum" : {},
"comparison" : {},
}
self.name2code = {
"property" : {},
"class" : {},
"enum" : {},
"comparison" : {},
}
self.modulename = None
self.star_imported = 0
self.can_interact = interact
self.verbose = verbose
def addnamecode(self, type, name, code):
self.name2code[type][name] = code
if not self.code2name[type].has_key(code):
self.code2name[type][code] = name
def hasname(self, name):
for dict in self.name2code.values():
if dict.has_key(name):
return True
return False
def hascode(self, type, code):
return self.code2name[type].has_key(code)
def findcodename(self, type, code):
if not self.hascode(type, code):
return None, None, None
name = self.code2name[type][code]
if self.modulename and not self.star_imported:
qualname = '%s.%s'%(self.modulename, name)
else:
qualname = name
return name, qualname, self.modulename
def getall(self, type):
return self.code2name[type].items()
def addmodule(self, module, name, star_imported):
self.modulename = name
self.star_imported = star_imported
for code, name in module._propdeclarations.items():
self.addnamecode('property', name, code)
for code, name in module._classdeclarations.items():
self.addnamecode('class', name, code)
for code in module._enumdeclarations.keys():
self.addnamecode('enum', '_Enum_'+identify(code), code)
for code, name in module._compdeclarations.items():
self.addnamecode('comparison', name, code)
def prepareforexport(self, name=None):
if not self.modulename:
self.modulename = name
return self
class ObjectCompiler:
def __init__(self, fp, modname, basesuite, othernamemappers=None, interact=1,
verbose=None):
self.fp = fp
self.verbose = verbose
self.basesuite = basesuite
self.can_interact = interact
self.modulename = modname
self.namemappers = [CodeNameMapper(self.can_interact, self.verbose)]
if othernamemappers:
self.othernamemappers = othernamemappers[:]
else:
self.othernamemappers = []
if basesuite:
basemapper = CodeNameMapper(self.can_interact, self.verbose)
basemapper.addmodule(basesuite, '', 1)
self.namemappers.append(basemapper)
def getprecompinfo(self, modname):
list = []
for mapper in self.namemappers:
emapper = mapper.prepareforexport(modname)
if emapper:
list.append(emapper)
return list
def findcodename(self, type, code):
while 1:
# First try: check whether we already know about this code.
for mapper in self.namemappers:
if mapper.hascode(type, code):
return mapper.findcodename(type, code)
# Second try: maybe one of the other modules knows about it.
for mapper in self.othernamemappers:
if mapper.hascode(type, code):
self.othernamemappers.remove(mapper)
self.namemappers.append(mapper)
if self.fp:
self.fp.write("import %s\n"%mapper.modulename)
break
else:
# If all this has failed we ask the user for a guess on where it could
# be and retry.
if self.fp:
m = self.askdefinitionmodule(type, code)
else:
m = None
if not m: return None, None, None
mapper = CodeNameMapper(self.can_interact, self.verbose)
mapper.addmodule(m, m.__name__, 0)
self.namemappers.append(mapper)
def hasname(self, name):
for mapper in self.othernamemappers:
if mapper.hasname(name) and mapper.modulename != self.modulename:
if self.verbose:
print >>self.verbose, "Duplicate Python identifier:", name, self.modulename, mapper.modulename
return True
return False
def askdefinitionmodule(self, type, code):
if not self.can_interact:
if self.verbose:
print >>self.verbose, "** No definition for %s '%s' found" % (type, code)
return None
path = EasyDialogs.AskFileForSave(message='Where is %s %s declared?'%(type, code))
if not path: return
path, file = os.path.split(path)
modname = os.path.splitext(file)[0]
if not path in sys.path:
sys.path.insert(0, path)
m = __import__(modname)
self.fp.write("import %s\n"%modname)
return m
def compileclass(self, cls):
[name, code, desc, properties, elements] = cls
pname = identify(name)
if self.namemappers[0].hascode('class', code):
# plural forms and such
othername, dummy, dummy = self.namemappers[0].findcodename('class', code)
if self.fp:
self.fp.write("\n%s = %s\n"%(pname, othername))
else:
if self.fp:
self.fp.write('\nclass %s(aetools.ComponentItem):\n' % pname)
self.fp.write(' """%s - %s """\n' % (ascii(name), ascii(desc)))
self.fp.write(' want = %r\n' % (code,))
self.namemappers[0].addnamecode('class', pname, code)
is_application_class = (code == 'capp')
properties.sort()
for prop in properties:
self.compileproperty(prop, is_application_class)
elements.sort()
for elem in elements:
self.compileelement(elem)
def compileproperty(self, prop, is_application_class=False):
[name, code, what] = prop
if code == 'c@#!':
# Something silly with plurals. Skip it.
return
pname = identify(name)
if self.namemappers[0].hascode('property', code):
# plural forms and such
othername, dummy, dummy = self.namemappers[0].findcodename('property', code)
if pname == othername:
return
if self.fp:
self.fp.write("\n_Prop_%s = _Prop_%s\n"%(pname, othername))
else:
if self.fp:
self.fp.write("class _Prop_%s(aetools.NProperty):\n" % pname)
self.fp.write(' """%s - %s """\n' % (ascii(name), ascii(what[1])))
self.fp.write(" which = %r\n" % (code,))
self.fp.write(" want = %r\n" % (what[0],))
self.namemappers[0].addnamecode('property', pname, code)
if is_application_class and self.fp:
self.fp.write("%s = _Prop_%s()\n" % (pname, pname))
def compileelement(self, elem):
[code, keyform] = elem
if self.fp:
self.fp.write("# element %r as %s\n" % (code, keyform))
def fillclasspropsandelems(self, cls):
[name, code, desc, properties, elements] = cls
cname = identify(name)
if self.namemappers[0].hascode('class', code) and \
self.namemappers[0].findcodename('class', code)[0] != cname:
# This is an other name (plural or so) for something else. Skip.
if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and
properties[0][1] != 'c@#!')):
if self.verbose:
print >>self.verbose, '** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code)
raise RuntimeError, "About to skip non-empty class"
return
plist = []
elist = []
superclasses = []
for prop in properties:
[pname, pcode, what] = prop
if pcode == "c@#^":
superclasses.append(what)
if pcode == 'c@#!':
continue
pname = identify(pname)
plist.append(pname)
superclassnames = []
for superclass in superclasses:
superId, superDesc, dummy = superclass
superclassname, fullyqualifiedname, module = self.findcodename("class", superId)
# I don't think this is correct:
if superclassname == cname:
pass # superclassnames.append(fullyqualifiedname)
else:
superclassnames.append(superclassname)
if self.fp:
self.fp.write("%s._superclassnames = %r\n"%(cname, superclassnames))
for elem in elements:
[ecode, keyform] = elem
if ecode == 'c@#!':
continue
name, ename, module = self.findcodename('class', ecode)
if not name:
if self.fp:
self.fp.write("# XXXX %s element %r not found!!\n"%(cname, ecode))
else:
elist.append((name, ename))
plist.sort()
elist.sort()
if self.fp:
self.fp.write("%s._privpropdict = {\n"%cname)
for n in plist:
self.fp.write(" '%s' : _Prop_%s,\n"%(n, n))
self.fp.write("}\n")
self.fp.write("%s._privelemdict = {\n"%cname)
for n, fulln in elist:
self.fp.write(" '%s' : %s,\n"%(n, fulln))
self.fp.write("}\n")
def compilecomparison(self, comp):
[name, code, comment] = comp
iname = identify(name)
self.namemappers[0].addnamecode('comparison', iname, code)
if self.fp:
self.fp.write("class %s(aetools.NComparison):\n" % iname)
self.fp.write(' """%s - %s """\n' % (ascii(name), ascii(comment)))
def compileenumeration(self, enum):
[code, items] = enum
name = "_Enum_%s" % identify(code)
if self.fp:
self.fp.write("%s = {\n" % name)
for item in items:
self.compileenumerator(item)
self.fp.write("}\n\n")
self.namemappers[0].addnamecode('enum', name, code)
return code
def compileenumerator(self, item):
[name, code, desc] = item
self.fp.write(" %r : %r,\t# %s\n" % (identify(name), code, ascii(desc)))
def checkforenum(self, enum):
"""This enum code is used by an event. Make sure it's available"""
name, fullname, module = self.findcodename('enum', enum)
if not name:
if self.fp:
self.fp.write("_Enum_%s = None # XXXX enum %s not found!!\n"%(identify(enum), ascii(enum)))
return
if module:
if self.fp:
self.fp.write("from %s import %s\n"%(module, name))
def dumpindex(self):
if not self.fp:
return
self.fp.write("\n#\n# Indices of types declared in this module\n#\n")
self.fp.write("_classdeclarations = {\n")
classlist = self.namemappers[0].getall('class')
classlist.sort()
for k, v in classlist:
self.fp.write(" %r : %s,\n" % (k, v))
self.fp.write("}\n")
self.fp.write("\n_propdeclarations = {\n")
proplist = self.namemappers[0].getall('property')
proplist.sort()
for k, v in proplist:
self.fp.write(" %r : _Prop_%s,\n" % (k, v))
self.fp.write("}\n")
self.fp.write("\n_compdeclarations = {\n")
complist = self.namemappers[0].getall('comparison')
complist.sort()
for k, v in complist:
self.fp.write(" %r : %s,\n" % (k, v))
self.fp.write("}\n")
self.fp.write("\n_enumdeclarations = {\n")
enumlist = self.namemappers[0].getall('enum')
enumlist.sort()
for k, v in enumlist:
self.fp.write(" %r : %s,\n" % (k, v))
self.fp.write("}\n")
def compiledata(data):
[type, description, flags] = data
return "%r -- %r %s" % (type, description, compiledataflags(flags))
def is_null(data):
return data[0] == 'null'
def is_optional(data):
return (data[2] & 0x8000)
def is_enum(data):
return (data[2] & 0x2000)
def getdatadoc(data):
[type, descr, flags] = data
if descr:
return ascii(descr)
if type == '****':
return 'anything'
if type == 'obj ':
return 'an AE object reference'
return "undocumented, typecode %r"%(type,)
dataflagdict = {15: "optional", 14: "list", 13: "enum", 12: "mutable"}
def compiledataflags(flags):
bits = []
for i in range(16):
if flags & (1<<i):
if i in dataflagdict.keys():
bits.append(dataflagdict[i])
else:
bits.append(repr(i))
return '[%s]' % string.join(bits)
def ascii(str):
"""Return a string with all non-ascii characters hex-encoded"""
if type(str) != type(''):
return map(ascii, str)
rv = ''
for c in str:
if c in ('\t', '\n', '\r') or ' ' <= c < chr(0x7f):
rv = rv + c
else:
rv = rv + '\\' + 'x%02.2x' % ord(c)
return rv
def identify(str):
"""Turn any string into an identifier:
- replace space by _
- replace other illegal chars by _xx_ (hex code)
- append _ if the result is a python keyword
"""
if not str:
return "empty_ae_name_"
rv = ''
ok = string.ascii_letters + '_'
ok2 = ok + string.digits
for c in str:
if c in ok:
rv = rv + c
elif c == ' ':
rv = rv + '_'
else:
rv = rv + '_%02.2x_'%ord(c)
ok = ok2
if keyword.iskeyword(rv):
rv = rv + '_'
return rv
# Call the main program
if __name__ == '__main__':
main()
sys.exit(1)
| Python |
"""Package Install Manager for Python.
This is currently a MacOSX-only strawman implementation.
Despite other rumours the name stands for "Packman IMPlementation".
Tools to allow easy installation of packages. The idea is that there is
an online XML database per (platform, python-version) containing packages
known to work with that combination. This module contains tools for getting
and parsing the database, testing whether packages are installed, computing
dependencies and installing packages.
There is a minimal main program that works as a command line tool, but the
intention is that the end user will use this through a GUI.
"""
import sys
import os
import popen2
import urllib
import urllib2
import urlparse
import plistlib
import distutils.util
import distutils.sysconfig
import md5
import tarfile
import tempfile
import shutil
import time
__all__ = ["PimpPreferences", "PimpDatabase", "PimpPackage", "main",
"getDefaultDatabase", "PIMP_VERSION", "main"]
_scriptExc_NotInstalled = "pimp._scriptExc_NotInstalled"
_scriptExc_OldInstalled = "pimp._scriptExc_OldInstalled"
_scriptExc_BadInstalled = "pimp._scriptExc_BadInstalled"
NO_EXECUTE=0
PIMP_VERSION="0.5"
# Flavors:
# source: setup-based package
# binary: tar (or other) archive created with setup.py bdist.
# installer: something that can be opened
DEFAULT_FLAVORORDER=['source', 'binary', 'installer']
DEFAULT_DOWNLOADDIR='/tmp'
DEFAULT_BUILDDIR='/tmp'
DEFAULT_INSTALLDIR=distutils.sysconfig.get_python_lib()
DEFAULT_PIMPDATABASE_FMT="http://www.python.org/packman/version-%s/%s-%s-%s-%s-%s.plist"
def getDefaultDatabase(experimental=False):
if experimental:
status = "exp"
else:
status = "prod"
major, minor, micro, state, extra = sys.version_info
pyvers = '%d.%d' % (major, minor)
if micro == 0 and state != 'final':
pyvers = pyvers + '%s%d' % (state, extra)
longplatform = distutils.util.get_platform()
osname, release, machine = longplatform.split('-')
# For some platforms we may want to differentiate between
# installation types
if osname == 'darwin':
if sys.prefix.startswith('/System/Library/Frameworks/Python.framework'):
osname = 'darwin_apple'
elif sys.prefix.startswith('/Library/Frameworks/Python.framework'):
osname = 'darwin_macpython'
# Otherwise we don't know...
# Now we try various URLs by playing with the release string.
# We remove numbers off the end until we find a match.
rel = release
while True:
url = DEFAULT_PIMPDATABASE_FMT % (PIMP_VERSION, status, pyvers, osname, rel, machine)
try:
urllib2.urlopen(url)
except urllib2.HTTPError, arg:
pass
else:
break
if not rel:
# We're out of version numbers to try. Use the
# full release number, this will give a reasonable
# error message later
url = DEFAULT_PIMPDATABASE_FMT % (PIMP_VERSION, status, pyvers, osname, release, machine)
break
idx = rel.rfind('.')
if idx < 0:
rel = ''
else:
rel = rel[:idx]
return url
def _cmd(output, dir, *cmditems):
"""Internal routine to run a shell command in a given directory."""
cmd = ("cd \"%s\"; " % dir) + " ".join(cmditems)
if output:
output.write("+ %s\n" % cmd)
if NO_EXECUTE:
return 0
child = popen2.Popen4(cmd)
child.tochild.close()
while 1:
line = child.fromchild.readline()
if not line:
break
if output:
output.write(line)
return child.wait()
class PimpDownloader:
"""Abstract base class - Downloader for archives"""
def __init__(self, argument,
dir="",
watcher=None):
self.argument = argument
self._dir = dir
self._watcher = watcher
def download(self, url, filename, output=None):
return None
def update(self, str):
if self._watcher:
return self._watcher.update(str)
return True
class PimpCurlDownloader(PimpDownloader):
def download(self, url, filename, output=None):
self.update("Downloading %s..." % url)
exitstatus = _cmd(output, self._dir,
"curl",
"--output", filename,
url)
self.update("Downloading %s: finished" % url)
return (not exitstatus)
class PimpUrllibDownloader(PimpDownloader):
def download(self, url, filename, output=None):
output = open(filename, 'wb')
self.update("Downloading %s: opening connection" % url)
keepgoing = True
download = urllib2.urlopen(url)
if download.headers.has_key("content-length"):
length = long(download.headers['content-length'])
else:
length = -1
data = download.read(4096) #read 4K at a time
dlsize = 0
lasttime = 0
while keepgoing:
dlsize = dlsize + len(data)
if len(data) == 0:
#this is our exit condition
break
output.write(data)
if int(time.time()) != lasttime:
# Update at most once per second
lasttime = int(time.time())
if length == -1:
keepgoing = self.update("Downloading %s: %d bytes..." % (url, dlsize))
else:
keepgoing = self.update("Downloading %s: %d%% (%d bytes)..." % (url, int(100.0*dlsize/length), dlsize))
data = download.read(4096)
if keepgoing:
self.update("Downloading %s: finished" % url)
return keepgoing
class PimpUnpacker:
"""Abstract base class - Unpacker for archives"""
_can_rename = False
def __init__(self, argument,
dir="",
renames=[],
watcher=None):
self.argument = argument
if renames and not self._can_rename:
raise RuntimeError, "This unpacker cannot rename files"
self._dir = dir
self._renames = renames
self._watcher = watcher
def unpack(self, archive, output=None, package=None):
return None
def update(self, str):
if self._watcher:
return self._watcher.update(str)
return True
class PimpCommandUnpacker(PimpUnpacker):
"""Unpack archives by calling a Unix utility"""
_can_rename = False
def unpack(self, archive, output=None, package=None):
cmd = self.argument % archive
if _cmd(output, self._dir, cmd):
return "unpack command failed"
class PimpTarUnpacker(PimpUnpacker):
"""Unpack tarfiles using the builtin tarfile module"""
_can_rename = True
def unpack(self, archive, output=None, package=None):
tf = tarfile.open(archive, "r")
members = tf.getmembers()
skip = []
if self._renames:
for member in members:
for oldprefix, newprefix in self._renames:
if oldprefix[:len(self._dir)] == self._dir:
oldprefix2 = oldprefix[len(self._dir):]
else:
oldprefix2 = None
if member.name[:len(oldprefix)] == oldprefix:
if newprefix is None:
skip.append(member)
#print 'SKIP', member.name
else:
member.name = newprefix + member.name[len(oldprefix):]
print ' ', member.name
break
elif oldprefix2 and member.name[:len(oldprefix2)] == oldprefix2:
if newprefix is None:
skip.append(member)
#print 'SKIP', member.name
else:
member.name = newprefix + member.name[len(oldprefix2):]
#print ' ', member.name
break
else:
skip.append(member)
#print '????', member.name
for member in members:
if member in skip:
self.update("Skipping %s" % member.name)
continue
self.update("Extracting %s" % member.name)
tf.extract(member, self._dir)
if skip:
names = [member.name for member in skip if member.name[-1] != '/']
if package:
names = package.filterExpectedSkips(names)
if names:
return "Not all files were unpacked: %s" % " ".join(names)
ARCHIVE_FORMATS = [
(".tar.Z", PimpTarUnpacker, None),
(".taz", PimpTarUnpacker, None),
(".tar.gz", PimpTarUnpacker, None),
(".tgz", PimpTarUnpacker, None),
(".tar.bz", PimpTarUnpacker, None),
(".zip", PimpCommandUnpacker, "unzip \"%s\""),
]
class PimpPreferences:
"""Container for per-user preferences, such as the database to use
and where to install packages."""
def __init__(self,
flavorOrder=None,
downloadDir=None,
buildDir=None,
installDir=None,
pimpDatabase=None):
if not flavorOrder:
flavorOrder = DEFAULT_FLAVORORDER
if not downloadDir:
downloadDir = DEFAULT_DOWNLOADDIR
if not buildDir:
buildDir = DEFAULT_BUILDDIR
if not pimpDatabase:
pimpDatabase = getDefaultDatabase()
self.setInstallDir(installDir)
self.flavorOrder = flavorOrder
self.downloadDir = downloadDir
self.buildDir = buildDir
self.pimpDatabase = pimpDatabase
self.watcher = None
def setWatcher(self, watcher):
self.watcher = watcher
def setInstallDir(self, installDir=None):
if installDir:
# Installing to non-standard location.
self.installLocations = [
('--install-lib', installDir),
('--install-headers', None),
('--install-scripts', None),
('--install-data', None)]
else:
installDir = DEFAULT_INSTALLDIR
self.installLocations = []
self.installDir = installDir
def isUserInstall(self):
return self.installDir != DEFAULT_INSTALLDIR
def check(self):
"""Check that the preferences make sense: directories exist and are
writable, the install directory is on sys.path, etc."""
rv = ""
RWX_OK = os.R_OK|os.W_OK|os.X_OK
if not os.path.exists(self.downloadDir):
rv += "Warning: Download directory \"%s\" does not exist\n" % self.downloadDir
elif not os.access(self.downloadDir, RWX_OK):
rv += "Warning: Download directory \"%s\" is not writable or not readable\n" % self.downloadDir
if not os.path.exists(self.buildDir):
rv += "Warning: Build directory \"%s\" does not exist\n" % self.buildDir
elif not os.access(self.buildDir, RWX_OK):
rv += "Warning: Build directory \"%s\" is not writable or not readable\n" % self.buildDir
if not os.path.exists(self.installDir):
rv += "Warning: Install directory \"%s\" does not exist\n" % self.installDir
elif not os.access(self.installDir, RWX_OK):
rv += "Warning: Install directory \"%s\" is not writable or not readable\n" % self.installDir
else:
installDir = os.path.realpath(self.installDir)
for p in sys.path:
try:
realpath = os.path.realpath(p)
except:
pass
if installDir == realpath:
break
else:
rv += "Warning: Install directory \"%s\" is not on sys.path\n" % self.installDir
return rv
def compareFlavors(self, left, right):
"""Compare two flavor strings. This is part of your preferences
because whether the user prefers installing from source or binary is."""
if left in self.flavorOrder:
if right in self.flavorOrder:
return cmp(self.flavorOrder.index(left), self.flavorOrder.index(right))
return -1
if right in self.flavorOrder:
return 1
return cmp(left, right)
class PimpDatabase:
"""Class representing a pimp database. It can actually contain
information from multiple databases through inclusion, but the
toplevel database is considered the master, as its maintainer is
"responsible" for the contents."""
def __init__(self, prefs):
self._packages = []
self.preferences = prefs
self._url = ""
self._urllist = []
self._version = ""
self._maintainer = ""
self._description = ""
# Accessor functions
def url(self): return self._url
def version(self): return self._version
def maintainer(self): return self._maintainer
def description(self): return self._description
def close(self):
"""Clean up"""
self._packages = []
self.preferences = None
def appendURL(self, url, included=0):
"""Append packages from the database with the given URL.
Only the first database should specify included=0, so the
global information (maintainer, description) get stored."""
if url in self._urllist:
return
self._urllist.append(url)
fp = urllib2.urlopen(url).fp
plistdata = plistlib.Plist.fromFile(fp)
# Test here for Pimp version, etc
if included:
version = plistdata.get('Version')
if version and version > self._version:
sys.stderr.write("Warning: included database %s is for pimp version %s\n" %
(url, version))
else:
self._version = plistdata.get('Version')
if not self._version:
sys.stderr.write("Warning: database has no Version information\n")
elif self._version > PIMP_VERSION:
sys.stderr.write("Warning: database version %s newer than pimp version %s\n"
% (self._version, PIMP_VERSION))
self._maintainer = plistdata.get('Maintainer', '')
self._description = plistdata.get('Description', '').strip()
self._url = url
self._appendPackages(plistdata['Packages'], url)
others = plistdata.get('Include', [])
for o in others:
o = urllib.basejoin(url, o)
self.appendURL(o, included=1)
def _appendPackages(self, packages, url):
"""Given a list of dictionaries containing package
descriptions create the PimpPackage objects and append them
to our internal storage."""
for p in packages:
p = dict(p)
if p.has_key('Download-URL'):
p['Download-URL'] = urllib.basejoin(url, p['Download-URL'])
flavor = p.get('Flavor')
if flavor == 'source':
pkg = PimpPackage_source(self, p)
elif flavor == 'binary':
pkg = PimpPackage_binary(self, p)
elif flavor == 'installer':
pkg = PimpPackage_installer(self, p)
elif flavor == 'hidden':
pkg = PimpPackage_installer(self, p)
else:
pkg = PimpPackage(self, dict(p))
self._packages.append(pkg)
def list(self):
"""Return a list of all PimpPackage objects in the database."""
return self._packages
def listnames(self):
"""Return a list of names of all packages in the database."""
rv = []
for pkg in self._packages:
rv.append(pkg.fullname())
rv.sort()
return rv
def dump(self, pathOrFile):
"""Dump the contents of the database to an XML .plist file.
The file can be passed as either a file object or a pathname.
All data, including included databases, is dumped."""
packages = []
for pkg in self._packages:
packages.append(pkg.dump())
plistdata = {
'Version': self._version,
'Maintainer': self._maintainer,
'Description': self._description,
'Packages': packages
}
plist = plistlib.Plist(**plistdata)
plist.write(pathOrFile)
def find(self, ident):
"""Find a package. The package can be specified by name
or as a dictionary with name, version and flavor entries.
Only name is obligatory. If there are multiple matches the
best one (higher version number, flavors ordered according to
users' preference) is returned."""
if type(ident) == str:
# Remove ( and ) for pseudo-packages
if ident[0] == '(' and ident[-1] == ')':
ident = ident[1:-1]
# Split into name-version-flavor
fields = ident.split('-')
if len(fields) < 1 or len(fields) > 3:
return None
name = fields[0]
if len(fields) > 1:
version = fields[1]
else:
version = None
if len(fields) > 2:
flavor = fields[2]
else:
flavor = None
else:
name = ident['Name']
version = ident.get('Version')
flavor = ident.get('Flavor')
found = None
for p in self._packages:
if name == p.name() and \
(not version or version == p.version()) and \
(not flavor or flavor == p.flavor()):
if not found or found < p:
found = p
return found
ALLOWED_KEYS = [
"Name",
"Version",
"Flavor",
"Description",
"Home-page",
"Download-URL",
"Install-test",
"Install-command",
"Pre-install-command",
"Post-install-command",
"Prerequisites",
"MD5Sum",
"User-install-skips",
"Systemwide-only",
]
class PimpPackage:
"""Class representing a single package."""
def __init__(self, db, plistdata):
self._db = db
name = plistdata["Name"]
for k in plistdata.keys():
if not k in ALLOWED_KEYS:
sys.stderr.write("Warning: %s: unknown key %s\n" % (name, k))
self._dict = plistdata
def __getitem__(self, key):
return self._dict[key]
def name(self): return self._dict['Name']
def version(self): return self._dict.get('Version')
def flavor(self): return self._dict.get('Flavor')
def description(self): return self._dict['Description'].strip()
def shortdescription(self): return self.description().splitlines()[0]
def homepage(self): return self._dict.get('Home-page')
def downloadURL(self): return self._dict.get('Download-URL')
def systemwideOnly(self): return self._dict.get('Systemwide-only')
def fullname(self):
"""Return the full name "name-version-flavor" of a package.
If the package is a pseudo-package, something that cannot be
installed through pimp, return the name in (parentheses)."""
rv = self._dict['Name']
if self._dict.has_key('Version'):
rv = rv + '-%s' % self._dict['Version']
if self._dict.has_key('Flavor'):
rv = rv + '-%s' % self._dict['Flavor']
if self._dict.get('Flavor') == 'hidden':
# Pseudo-package, show in parentheses
rv = '(%s)' % rv
return rv
def dump(self):
"""Return a dict object containing the information on the package."""
return self._dict
def __cmp__(self, other):
"""Compare two packages, where the "better" package sorts lower."""
if not isinstance(other, PimpPackage):
return cmp(id(self), id(other))
if self.name() != other.name():
return cmp(self.name(), other.name())
if self.version() != other.version():
return -cmp(self.version(), other.version())
return self._db.preferences.compareFlavors(self.flavor(), other.flavor())
def installed(self):
"""Test wheter the package is installed.
Returns two values: a status indicator which is one of
"yes", "no", "old" (an older version is installed) or "bad"
(something went wrong during the install test) and a human
readable string which may contain more details."""
namespace = {
"NotInstalled": _scriptExc_NotInstalled,
"OldInstalled": _scriptExc_OldInstalled,
"BadInstalled": _scriptExc_BadInstalled,
"os": os,
"sys": sys,
}
installTest = self._dict['Install-test'].strip() + '\n'
try:
exec installTest in namespace
except ImportError, arg:
return "no", str(arg)
except _scriptExc_NotInstalled, arg:
return "no", str(arg)
except _scriptExc_OldInstalled, arg:
return "old", str(arg)
except _scriptExc_BadInstalled, arg:
return "bad", str(arg)
except:
sys.stderr.write("-------------------------------------\n")
sys.stderr.write("---- %s: install test got exception\n" % self.fullname())
sys.stderr.write("---- source:\n")
sys.stderr.write(installTest)
sys.stderr.write("---- exception:\n")
import traceback
traceback.print_exc(file=sys.stderr)
if self._db._maintainer:
sys.stderr.write("---- Please copy this and mail to %s\n" % self._db._maintainer)
sys.stderr.write("-------------------------------------\n")
return "bad", "Package install test got exception"
return "yes", ""
def prerequisites(self):
"""Return a list of prerequisites for this package.
The list contains 2-tuples, of which the first item is either
a PimpPackage object or None, and the second is a descriptive
string. The first item can be None if this package depends on
something that isn't pimp-installable, in which case the descriptive
string should tell the user what to do."""
rv = []
if not self._dict.get('Download-URL'):
# For pseudo-packages that are already installed we don't
# return an error message
status, _ = self.installed()
if status == "yes":
return []
return [(None,
"Package %s cannot be installed automatically, see the description" %
self.fullname())]
if self.systemwideOnly() and self._db.preferences.isUserInstall():
return [(None,
"Package %s can only be installed system-wide" %
self.fullname())]
if not self._dict.get('Prerequisites'):
return []
for item in self._dict['Prerequisites']:
if type(item) == str:
pkg = None
descr = str(item)
else:
name = item['Name']
if item.has_key('Version'):
name = name + '-' + item['Version']
if item.has_key('Flavor'):
name = name + '-' + item['Flavor']
pkg = self._db.find(name)
if not pkg:
descr = "Requires unknown %s"%name
else:
descr = pkg.shortdescription()
rv.append((pkg, descr))
return rv
def downloadPackageOnly(self, output=None):
"""Download a single package, if needed.
An MD5 signature is used to determine whether download is needed,
and to test that we actually downloaded what we expected.
If output is given it is a file-like object that will receive a log
of what happens.
If anything unforeseen happened the method returns an error message
string.
"""
scheme, loc, path, query, frag = urlparse.urlsplit(self._dict['Download-URL'])
path = urllib.url2pathname(path)
filename = os.path.split(path)[1]
self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename)
if not self._archiveOK():
if scheme == 'manual':
return "Please download package manually and save as %s" % self.archiveFilename
downloader = PimpUrllibDownloader(None, self._db.preferences.downloadDir,
watcher=self._db.preferences.watcher)
if not downloader.download(self._dict['Download-URL'],
self.archiveFilename, output):
return "download command failed"
if not os.path.exists(self.archiveFilename) and not NO_EXECUTE:
return "archive not found after download"
if not self._archiveOK():
return "archive does not have correct MD5 checksum"
def _archiveOK(self):
"""Test an archive. It should exist and the MD5 checksum should be correct."""
if not os.path.exists(self.archiveFilename):
return 0
if not self._dict.get('MD5Sum'):
sys.stderr.write("Warning: no MD5Sum for %s\n" % self.fullname())
return 1
data = open(self.archiveFilename, 'rb').read()
checksum = md5.new(data).hexdigest()
return checksum == self._dict['MD5Sum']
def unpackPackageOnly(self, output=None):
"""Unpack a downloaded package archive."""
filename = os.path.split(self.archiveFilename)[1]
for ext, unpackerClass, arg in ARCHIVE_FORMATS:
if filename[-len(ext):] == ext:
break
else:
return "unknown extension for archive file: %s" % filename
self.basename = filename[:-len(ext)]
unpacker = unpackerClass(arg, dir=self._db.preferences.buildDir,
watcher=self._db.preferences.watcher)
rv = unpacker.unpack(self.archiveFilename, output=output)
if rv:
return rv
def installPackageOnly(self, output=None):
"""Default install method, to be overridden by subclasses"""
return "%s: This package needs to be installed manually (no support for flavor=\"%s\")" \
% (self.fullname(), self._dict.get(flavor, ""))
def installSinglePackage(self, output=None):
"""Download, unpack and install a single package.
If output is given it should be a file-like object and it
will receive a log of what happened."""
if not self._dict.get('Download-URL'):
return "%s: This package needs to be installed manually (no Download-URL field)" % self.fullname()
msg = self.downloadPackageOnly(output)
if msg:
return "%s: download: %s" % (self.fullname(), msg)
msg = self.unpackPackageOnly(output)
if msg:
return "%s: unpack: %s" % (self.fullname(), msg)
return self.installPackageOnly(output)
def beforeInstall(self):
"""Bookkeeping before installation: remember what we have in site-packages"""
self._old_contents = os.listdir(self._db.preferences.installDir)
def afterInstall(self):
"""Bookkeeping after installation: interpret any new .pth files that have
appeared"""
new_contents = os.listdir(self._db.preferences.installDir)
for fn in new_contents:
if fn in self._old_contents:
continue
if fn[-4:] != '.pth':
continue
fullname = os.path.join(self._db.preferences.installDir, fn)
f = open(fullname)
for line in f.readlines():
if not line:
continue
if line[0] == '#':
continue
if line[:6] == 'import':
exec line
continue
if line[-1] == '\n':
line = line[:-1]
if not os.path.isabs(line):
line = os.path.join(self._db.preferences.installDir, line)
line = os.path.realpath(line)
if not line in sys.path:
sys.path.append(line)
def filterExpectedSkips(self, names):
"""Return a list that contains only unpexpected skips"""
if not self._db.preferences.isUserInstall():
return names
expected_skips = self._dict.get('User-install-skips')
if not expected_skips:
return names
newnames = []
for name in names:
for skip in expected_skips:
if name[:len(skip)] == skip:
break
else:
newnames.append(name)
return newnames
class PimpPackage_binary(PimpPackage):
def unpackPackageOnly(self, output=None):
"""We don't unpack binary packages until installing"""
pass
def installPackageOnly(self, output=None):
"""Install a single source package.
If output is given it should be a file-like object and it
will receive a log of what happened."""
if self._dict.has_key('Install-command'):
return "%s: Binary package cannot have Install-command" % self.fullname()
if self._dict.has_key('Pre-install-command'):
if _cmd(output, '/tmp', self._dict['Pre-install-command']):
return "pre-install %s: running \"%s\" failed" % \
(self.fullname(), self._dict['Pre-install-command'])
self.beforeInstall()
# Install by unpacking
filename = os.path.split(self.archiveFilename)[1]
for ext, unpackerClass, arg in ARCHIVE_FORMATS:
if filename[-len(ext):] == ext:
break
else:
return "%s: unknown extension for archive file: %s" % (self.fullname(), filename)
self.basename = filename[:-len(ext)]
install_renames = []
for k, newloc in self._db.preferences.installLocations:
if not newloc:
continue
if k == "--install-lib":
oldloc = DEFAULT_INSTALLDIR
else:
return "%s: Don't know installLocation %s" % (self.fullname(), k)
install_renames.append((oldloc, newloc))
unpacker = unpackerClass(arg, dir="/", renames=install_renames)
rv = unpacker.unpack(self.archiveFilename, output=output, package=self)
if rv:
return rv
self.afterInstall()
if self._dict.has_key('Post-install-command'):
if _cmd(output, '/tmp', self._dict['Post-install-command']):
return "%s: post-install: running \"%s\" failed" % \
(self.fullname(), self._dict['Post-install-command'])
return None
class PimpPackage_source(PimpPackage):
def unpackPackageOnly(self, output=None):
"""Unpack a source package and check that setup.py exists"""
PimpPackage.unpackPackageOnly(self, output)
# Test that a setup script has been create
self._buildDirname = os.path.join(self._db.preferences.buildDir, self.basename)
setupname = os.path.join(self._buildDirname, "setup.py")
if not os.path.exists(setupname) and not NO_EXECUTE:
return "no setup.py found after unpack of archive"
def installPackageOnly(self, output=None):
"""Install a single source package.
If output is given it should be a file-like object and it
will receive a log of what happened."""
if self._dict.has_key('Pre-install-command'):
if _cmd(output, self._buildDirname, self._dict['Pre-install-command']):
return "pre-install %s: running \"%s\" failed" % \
(self.fullname(), self._dict['Pre-install-command'])
self.beforeInstall()
installcmd = self._dict.get('Install-command')
if installcmd and self._install_renames:
return "Package has install-command and can only be installed to standard location"
# This is the "bit-bucket" for installations: everything we don't
# want. After installation we check that it is actually empty
unwanted_install_dir = None
if not installcmd:
extra_args = ""
for k, v in self._db.preferences.installLocations:
if not v:
# We don't want these files installed. Send them
# to the bit-bucket.
if not unwanted_install_dir:
unwanted_install_dir = tempfile.mkdtemp()
v = unwanted_install_dir
extra_args = extra_args + " %s \"%s\"" % (k, v)
installcmd = '"%s" setup.py install %s' % (sys.executable, extra_args)
if _cmd(output, self._buildDirname, installcmd):
return "install %s: running \"%s\" failed" % \
(self.fullname(), installcmd)
if unwanted_install_dir and os.path.exists(unwanted_install_dir):
unwanted_files = os.listdir(unwanted_install_dir)
if unwanted_files:
rv = "Warning: some files were not installed: %s" % " ".join(unwanted_files)
else:
rv = None
shutil.rmtree(unwanted_install_dir)
return rv
self.afterInstall()
if self._dict.has_key('Post-install-command'):
if _cmd(output, self._buildDirname, self._dict['Post-install-command']):
return "post-install %s: running \"%s\" failed" % \
(self.fullname(), self._dict['Post-install-command'])
return None
class PimpPackage_installer(PimpPackage):
def unpackPackageOnly(self, output=None):
"""We don't unpack dmg packages until installing"""
pass
def installPackageOnly(self, output=None):
"""Install a single source package.
If output is given it should be a file-like object and it
will receive a log of what happened."""
if self._dict.has_key('Post-install-command'):
return "%s: Installer package cannot have Post-install-command" % self.fullname()
if self._dict.has_key('Pre-install-command'):
if _cmd(output, '/tmp', self._dict['Pre-install-command']):
return "pre-install %s: running \"%s\" failed" % \
(self.fullname(), self._dict['Pre-install-command'])
self.beforeInstall()
installcmd = self._dict.get('Install-command')
if installcmd:
if '%' in installcmd:
installcmd = installcmd % self.archiveFilename
else:
installcmd = 'open \"%s\"' % self.archiveFilename
if _cmd(output, "/tmp", installcmd):
return '%s: install command failed (use verbose for details)' % self.fullname()
return '%s: downloaded and opened. Install manually and restart Package Manager' % self.archiveFilename
class PimpInstaller:
"""Installer engine: computes dependencies and installs
packages in the right order."""
def __init__(self, db):
self._todo = []
self._db = db
self._curtodo = []
self._curmessages = []
def __contains__(self, package):
return package in self._todo
def _addPackages(self, packages):
for package in packages:
if not package in self._todo:
self._todo.append(package)
def _prepareInstall(self, package, force=0, recursive=1):
"""Internal routine, recursive engine for prepareInstall.
Test whether the package is installed and (if not installed
or if force==1) prepend it to the temporary todo list and
call ourselves recursively on all prerequisites."""
if not force:
status, message = package.installed()
if status == "yes":
return
if package in self._todo or package in self._curtodo:
return
self._curtodo.insert(0, package)
if not recursive:
return
prereqs = package.prerequisites()
for pkg, descr in prereqs:
if pkg:
self._prepareInstall(pkg, False, recursive)
else:
self._curmessages.append("Problem with dependency: %s" % descr)
def prepareInstall(self, package, force=0, recursive=1):
"""Prepare installation of a package.
If the package is already installed and force is false nothing
is done. If recursive is true prerequisites are installed first.
Returns a list of packages (to be passed to install) and a list
of messages of any problems encountered.
"""
self._curtodo = []
self._curmessages = []
self._prepareInstall(package, force, recursive)
rv = self._curtodo, self._curmessages
self._curtodo = []
self._curmessages = []
return rv
def install(self, packages, output):
"""Install a list of packages."""
self._addPackages(packages)
status = []
for pkg in self._todo:
msg = pkg.installSinglePackage(output)
if msg:
status.append(msg)
return status
def _run(mode, verbose, force, args, prefargs, watcher):
"""Engine for the main program"""
prefs = PimpPreferences(**prefargs)
if watcher:
prefs.setWatcher(watcher)
rv = prefs.check()
if rv:
sys.stdout.write(rv)
db = PimpDatabase(prefs)
db.appendURL(prefs.pimpDatabase)
if mode == 'dump':
db.dump(sys.stdout)
elif mode =='list':
if not args:
args = db.listnames()
print "%-20.20s\t%s" % ("Package", "Description")
print
for pkgname in args:
pkg = db.find(pkgname)
if pkg:
description = pkg.shortdescription()
pkgname = pkg.fullname()
else:
description = 'Error: no such package'
print "%-20.20s\t%s" % (pkgname, description)
if verbose:
print "\tHome page:\t", pkg.homepage()
try:
print "\tDownload URL:\t", pkg.downloadURL()
except KeyError:
pass
description = pkg.description()
description = '\n\t\t\t\t\t'.join(description.splitlines())
print "\tDescription:\t%s" % description
elif mode =='status':
if not args:
args = db.listnames()
print "%-20.20s\t%s\t%s" % ("Package", "Installed", "Message")
print
for pkgname in args:
pkg = db.find(pkgname)
if pkg:
status, msg = pkg.installed()
pkgname = pkg.fullname()
else:
status = 'error'
msg = 'No such package'
print "%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg)
if verbose and status == "no":
prereq = pkg.prerequisites()
for pkg, msg in prereq:
if not pkg:
pkg = ''
else:
pkg = pkg.fullname()
print "%-20.20s\tRequirement: %s %s" % ("", pkg, msg)
elif mode == 'install':
if not args:
print 'Please specify packages to install'
sys.exit(1)
inst = PimpInstaller(db)
for pkgname in args:
pkg = db.find(pkgname)
if not pkg:
print '%s: No such package' % pkgname
continue
list, messages = inst.prepareInstall(pkg, force)
if messages and not force:
print "%s: Not installed:" % pkgname
for m in messages:
print "\t", m
else:
if verbose:
output = sys.stdout
else:
output = None
messages = inst.install(list, output)
if messages:
print "%s: Not installed:" % pkgname
for m in messages:
print "\t", m
def main():
"""Minimal commandline tool to drive pimp."""
import getopt
def _help():
print "Usage: pimp [options] -s [package ...] List installed status"
print " pimp [options] -l [package ...] Show package information"
print " pimp [options] -i package ... Install packages"
print " pimp -d Dump database to stdout"
print " pimp -V Print version number"
print "Options:"
print " -v Verbose"
print " -f Force installation"
print " -D dir Set destination directory"
print " (default: %s)" % DEFAULT_INSTALLDIR
print " -u url URL for database"
sys.exit(1)
class _Watcher:
def update(self, msg):
sys.stderr.write(msg + '\r')
return 1
try:
opts, args = getopt.getopt(sys.argv[1:], "slifvdD:Vu:")
except getopt.GetoptError:
_help()
if not opts and not args:
_help()
mode = None
force = 0
verbose = 0
prefargs = {}
watcher = None
for o, a in opts:
if o == '-s':
if mode:
_help()
mode = 'status'
if o == '-l':
if mode:
_help()
mode = 'list'
if o == '-d':
if mode:
_help()
mode = 'dump'
if o == '-V':
if mode:
_help()
mode = 'version'
if o == '-i':
mode = 'install'
if o == '-f':
force = 1
if o == '-v':
verbose = 1
watcher = _Watcher()
if o == '-D':
prefargs['installDir'] = a
if o == '-u':
prefargs['pimpDatabase'] = a
if not mode:
_help()
if mode == 'version':
print 'Pimp version %s; module name is %s' % (PIMP_VERSION, __name__)
else:
_run(mode, verbose, force, args, prefargs, watcher)
# Finally, try to update ourselves to a newer version.
# If the end-user updates pimp through pimp the new version
# will be called pimp_update and live in site-packages
# or somewhere similar
if __name__ != 'pimp_update':
try:
import pimp_update
except ImportError:
pass
else:
if pimp_update.PIMP_VERSION <= PIMP_VERSION:
import warnings
warnings.warn("pimp_update is version %s, not newer than pimp version %s" %
(pimp_update.PIMP_VERSION, PIMP_VERSION))
else:
from pimp_update import *
if __name__ == '__main__':
main()
| Python |
"""macfs - Pure Python module designed to be backward compatible with
macfs and MACFS.
"""
import sys
import struct
import Carbon.Res
import Carbon.File
import warnings
warnings.warn("macfs is deprecated, use Carbon.File, Carbon.Folder or EasyDialogs",
DeprecationWarning, stacklevel=2)
# First step: ensure we also emulate the MACFS module, which contained
# all the constants
sys.modules['MACFS'] = sys.modules[__name__]
# Import all those constants
from Carbon.Files import *
from Carbon.Folders import *
# For some obscure historical reason these are here too:
READ = 1
WRITE = 2
smAllScripts = -3
#
# Find the epoch conversion for file dates in a way that works on OS9 and OSX
import time
if time.gmtime(0)[0] == 1970:
_EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000L
def _utc2time(utc):
t = utc[1] + _EPOCHCONVERT
return int(t)
def _time2utc(t):
t = int(t) - _EPOCHCONVERT
if t < -0x7fffffff:
t = t + 0x10000000L
return (0, int(t), 0)
else:
def _utc2time(utc):
t = utc[1]
if t < 0:
t = t + 0x100000000L
return t
def _time2utc(t):
if t > 0x7fffffff:
t = t - 0x100000000L
return (0, int(t), 0)
# The old name of the error object:
error = Carbon.File.Error
#
# The various objects macfs used to export. We override them here, because some
# of the method names are subtly different.
#
class FSSpec(Carbon.File.FSSpec):
def as_fsref(self):
return FSRef(self)
def NewAlias(self, src=None):
return Alias(Carbon.File.NewAlias(src, self))
def GetCreatorType(self):
finfo = self.FSpGetFInfo()
return finfo.Creator, finfo.Type
def SetCreatorType(self, ctor, tp):
finfo = self.FSpGetFInfo()
finfo.Creator = ctor
finfo.Type = tp
self.FSpSetFInfo(finfo)
def GetFInfo(self):
return self.FSpGetFInfo()
def SetFInfo(self, info):
return self.FSpSetFInfo(info)
def GetDates(self):
catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
catinfo, d1, d2, d3 = FSRef(self).FSGetCatalogInfo(catInfoFlags)
cdate = catinfo.createDate
mdate = catinfo.contentModDate
bdate = catinfo.backupDate
return _utc2time(cdate), _utc2time(mdate), _utc2time(bdate)
def SetDates(self, cdate, mdate, bdate):
catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
catinfo = Carbon.File.FSCatalogInfo(
createDate = _time2utc(cdate),
contentModDate = _time2utc(mdate),
backupDate = _time2utc(bdate))
FSRef(self).FSSetCatalogInfo(catInfoFlags, catinfo)
class FSRef(Carbon.File.FSRef):
def as_fsspec(self):
return FSSpec(self)
class Alias(Carbon.File.Alias):
def GetInfo(self, index):
return self.GetAliasInfo(index)
def Update(self, *args):
pass # print "Alias.Update not yet implemented"
def Resolve(self, src=None):
fss, changed = self.ResolveAlias(src)
return FSSpec(fss), changed
from Carbon.File import FInfo
# Backward-compatible type names:
FSSpecType = FSSpec
FSRefType = FSRef
AliasType = Alias
FInfoType = FInfo
# Global functions:
def ResolveAliasFile(fss, chain=1):
fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain)
return FSSpec(fss), isdir, isalias
def RawFSSpec(data):
return FSSpec(rawdata=data)
def RawAlias(data):
return Alias(rawdata=data)
def FindApplication(*args):
raise NotImplementedError, "FindApplication no longer implemented"
def NewAliasMinimalFromFullPath(path):
return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', ''))
# Another global function:
from Carbon.Folder import FindFolder
#
# Finally the old Standard File routine emulators.
#
_curfolder = None
def StandardGetFile(*typelist):
"""Ask for an input file, optionally specifying 4-char file types that are
allowable"""
return PromptGetFile('', *typelist)
def PromptGetFile(prompt, *typelist):
"""Ask for an input file giving the user a prompt message. Optionally you can
specifying 4-char file types that are allowable"""
import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
if not typelist:
typelist = None
fss = EasyDialogs.AskFileForOpen(message=prompt, wanted=FSSpec,
typeList=typelist, defaultLocation=_handleSetFolder())
return fss, not fss is None
def StandardPutFile(prompt, default=None):
"""Ask the user for an output file, with a prompt. Optionally you cn supply a
default output filename"""
import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
fss = EasyDialogs.AskFileForSave(wanted=FSSpec, message=prompt,
savedFileName=default, defaultLocation=_handleSetFolder())
return fss, not fss is None
def SetFolder(folder):
global _curfolder
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
if _curfolder:
rv = FSSpec(_curfolder)
else:
rv = None
_curfolder = folder
return rv
def _handleSetFolder():
global _curfolder
rv = _curfolder
_curfolder = None
return rv
def GetDirectory(prompt=None):
"""Ask the user to select a folder. Optionally you can give a prompt."""
import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec,
defaultLocation=_handleSetFolder())
return fss, not fss is None
| Python |
"""plistlib.py -- a tool to generate and parse MacOSX .plist files.
The PropertList (.plist) file format is a simple XML pickle supporting
basic object types, like dictionaries, lists, numbers and strings.
Usually the top level object is a dictionary.
To write out a plist file, use the writePlist(rootObject, pathOrFile)
function. 'rootObject' is the top level object, 'pathOrFile' is a
filename or a (writable) file object.
To parse a plist from a file, use the readPlist(pathOrFile) function,
with a file name or a (readable) file object as the only argument. It
returns the top level object (again, usually a dictionary).
To work with plist data in strings, you can use readPlistFromString()
and writePlistToString().
Values can be strings, integers, floats, booleans, tuples, lists,
dictionaries, Data or datetime.datetime objects. String values (including
dictionary keys) may be unicode strings -- they will be written out as
UTF-8.
The <data> plist type is supported through the Data class. This is a
thin wrapper around a Python string.
Generate Plist example:
pl = dict(
aString="Doodah",
aList=["A", "B", 12, 32.1, [1, 2, 3]],
aFloat = 0.1,
anInt = 728,
aDict=dict(
anotherString="<hello & hi there!>",
aUnicodeValue=u'M\xe4ssig, Ma\xdf',
aTrueValue=True,
aFalseValue=False,
),
someData = Data("<binary gunk>"),
someMoreData = Data("<lots of binary gunk>" * 10),
aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
)
# unicode keys are possible, but a little awkward to use:
pl[u'\xc5benraa'] = "That was a unicode key."
writePlist(pl, fileName)
Parse Plist example:
pl = readPlist(pathOrFile)
print pl["aKey"]
"""
__all__ = [
"readPlist", "writePlist", "readPlistFromString", "writePlistToString",
"readPlistFromResource", "writePlistToResource",
"Plist", "Data", "Dict"
]
# Note: the Plist and Dict classes have been deprecated.
import binascii
import datetime
from cStringIO import StringIO
import re
def readPlist(pathOrFile):
"""Read a .plist file. 'pathOrFile' may either be a file name or a
(readable) file object. Return the unpacked root object (which
usually is a dictionary).
"""
didOpen = 0
if isinstance(pathOrFile, (str, unicode)):
pathOrFile = open(pathOrFile)
didOpen = 1
p = PlistParser()
rootObject = p.parse(pathOrFile)
if didOpen:
pathOrFile.close()
return rootObject
def writePlist(rootObject, pathOrFile):
"""Write 'rootObject' to a .plist file. 'pathOrFile' may either be a
file name or a (writable) file object.
"""
didOpen = 0
if isinstance(pathOrFile, (str, unicode)):
pathOrFile = open(pathOrFile, "w")
didOpen = 1
writer = PlistWriter(pathOrFile)
writer.writeln("<plist version=\"1.0\">")
writer.writeValue(rootObject)
writer.writeln("</plist>")
if didOpen:
pathOrFile.close()
def readPlistFromString(data):
"""Read a plist data from a string. Return the root object.
"""
return readPlist(StringIO(data))
def writePlistToString(rootObject):
"""Return 'rootObject' as a plist-formatted string.
"""
f = StringIO()
writePlist(rootObject, f)
return f.getvalue()
def readPlistFromResource(path, restype='plst', resid=0):
"""Read plst resource from the resource fork of path.
"""
from Carbon.File import FSRef, FSGetResourceForkName
from Carbon.Files import fsRdPerm
from Carbon import Res
fsRef = FSRef(path)
resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm)
Res.UseResFile(resNum)
plistData = Res.Get1Resource(restype, resid).data
Res.CloseResFile(resNum)
return readPlistFromString(plistData)
def writePlistToResource(rootObject, path, restype='plst', resid=0):
"""Write 'rootObject' as a plst resource to the resource fork of path.
"""
from Carbon.File import FSRef, FSGetResourceForkName
from Carbon.Files import fsRdWrPerm
from Carbon import Res
plistData = writePlistToString(rootObject)
fsRef = FSRef(path)
resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdWrPerm)
Res.UseResFile(resNum)
try:
Res.Get1Resource(restype, resid).RemoveResource()
except Res.Error:
pass
res = Res.Resource(plistData)
res.AddResource(restype, resid, '')
res.WriteResource()
Res.CloseResFile(resNum)
class DumbXMLWriter:
def __init__(self, file, indentLevel=0, indent="\t"):
self.file = file
self.stack = []
self.indentLevel = indentLevel
self.indent = indent
def beginElement(self, element):
self.stack.append(element)
self.writeln("<%s>" % element)
self.indentLevel += 1
def endElement(self, element):
assert self.indentLevel > 0
assert self.stack.pop() == element
self.indentLevel -= 1
self.writeln("</%s>" % element)
def simpleElement(self, element, value=None):
if value is not None:
value = _escapeAndEncode(value)
self.writeln("<%s>%s</%s>" % (element, value, element))
else:
self.writeln("<%s/>" % element)
def writeln(self, line):
if line:
self.file.write(self.indentLevel * self.indent + line + "\n")
else:
self.file.write("\n")
# Contents should conform to a subset of ISO 8601
# (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'. Smaller units may be omitted with
# a loss of precision)
_dateParser = re.compile(r"(?P<year>\d\d\d\d)(?:-(?P<month>\d\d)(?:-(?P<day>\d\d)(?:T(?P<hour>\d\d)(?::(?P<minute>\d\d)(?::(?P<second>\d\d))?)?)?)?)?Z")
def _dateFromString(s):
order = ('year', 'month', 'day', 'hour', 'minute', 'second')
gd = _dateParser.match(s).groupdict()
lst = []
for key in order:
val = gd[key]
if val is None:
break
lst.append(int(val))
return datetime.datetime(*lst)
def _dateToString(d):
return '%04d-%02d-%02dT%02d:%02d:%02dZ' % (
d.year, d.month, d.day,
d.hour, d.minute, d.second
)
# Regex to find any control chars, except for \t \n and \r
_controlCharPat = re.compile(
r"[\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f"
r"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]")
def _escapeAndEncode(text):
m = _controlCharPat.search(text)
if m is not None:
raise ValueError("strings can't contains control characters; "
"use plistlib.Data instead")
text = text.replace("\r\n", "\n") # convert DOS line endings
text = text.replace("\r", "\n") # convert Mac line endings
text = text.replace("&", "&") # escape '&'
text = text.replace("<", "<") # escape '<'
text = text.replace(">", ">") # escape '>'
return text.encode("utf-8") # encode as UTF-8
PLISTHEADER = """\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
"""
class PlistWriter(DumbXMLWriter):
def __init__(self, file, indentLevel=0, indent="\t", writeHeader=1):
if writeHeader:
file.write(PLISTHEADER)
DumbXMLWriter.__init__(self, file, indentLevel, indent)
def writeValue(self, value):
if isinstance(value, (str, unicode)):
self.simpleElement("string", value)
elif isinstance(value, bool):
# must switch for bool before int, as bool is a
# subclass of int...
if value:
self.simpleElement("true")
else:
self.simpleElement("false")
elif isinstance(value, int):
self.simpleElement("integer", str(value))
elif isinstance(value, float):
self.simpleElement("real", repr(value))
elif isinstance(value, dict):
self.writeDict(value)
elif isinstance(value, Data):
self.writeData(value)
elif isinstance(value, datetime.datetime):
self.simpleElement("date", _dateToString(value))
elif isinstance(value, (tuple, list)):
self.writeArray(value)
else:
raise TypeError("unsuported type: %s" % type(value))
def writeData(self, data):
self.beginElement("data")
self.indentLevel -= 1
maxlinelength = 76 - len(self.indent.replace("\t", " " * 8) *
self.indentLevel)
for line in data.asBase64(maxlinelength).split("\n"):
if line:
self.writeln(line)
self.indentLevel += 1
self.endElement("data")
def writeDict(self, d):
self.beginElement("dict")
items = d.items()
items.sort()
for key, value in items:
if not isinstance(key, (str, unicode)):
raise TypeError("keys must be strings")
self.simpleElement("key", key)
self.writeValue(value)
self.endElement("dict")
def writeArray(self, array):
self.beginElement("array")
for value in array:
self.writeValue(value)
self.endElement("array")
class _InternalDict(dict):
# This class is needed while Dict is scheduled for deprecation:
# we only need to warn when a *user* instantiates Dict or when
# the "attribute notation for dict keys" is used.
def __getattr__(self, attr):
try:
value = self[attr]
except KeyError:
raise AttributeError, attr
from warnings import warn
warn("Attribute access from plist dicts is deprecated, use d[key] "
"notation instead", PendingDeprecationWarning)
return value
def __setattr__(self, attr, value):
from warnings import warn
warn("Attribute access from plist dicts is deprecated, use d[key] "
"notation instead", PendingDeprecationWarning)
self[attr] = value
def __delattr__(self, attr):
try:
del self[attr]
except KeyError:
raise AttributeError, attr
from warnings import warn
warn("Attribute access from plist dicts is deprecated, use d[key] "
"notation instead", PendingDeprecationWarning)
class Dict(_InternalDict):
def __init__(self, **kwargs):
from warnings import warn
warn("The plistlib.Dict class is deprecated, use builtin dict instead",
PendingDeprecationWarning)
super(Dict, self).__init__(**kwargs)
class Plist(_InternalDict):
"""This class has been deprecated. Use readPlist() and writePlist()
functions instead, together with regular dict objects.
"""
def __init__(self, **kwargs):
from warnings import warn
warn("The Plist class is deprecated, use the readPlist() and "
"writePlist() functions instead", PendingDeprecationWarning)
super(Plist, self).__init__(**kwargs)
def fromFile(cls, pathOrFile):
"""Deprecated. Use the readPlist() function instead."""
rootObject = readPlist(pathOrFile)
plist = cls()
plist.update(rootObject)
return plist
fromFile = classmethod(fromFile)
def write(self, pathOrFile):
"""Deprecated. Use the writePlist() function instead."""
writePlist(self, pathOrFile)
def _encodeBase64(s, maxlinelength=76):
# copied from base64.encodestring(), with added maxlinelength argument
maxbinsize = (maxlinelength//4)*3
pieces = []
for i in range(0, len(s), maxbinsize):
chunk = s[i : i + maxbinsize]
pieces.append(binascii.b2a_base64(chunk))
return "".join(pieces)
class Data:
"""Wrapper for binary data."""
def __init__(self, data):
self.data = data
def fromBase64(cls, data):
# base64.decodestring just calls binascii.a2b_base64;
# it seems overkill to use both base64 and binascii.
return cls(binascii.a2b_base64(data))
fromBase64 = classmethod(fromBase64)
def asBase64(self, maxlinelength=76):
return _encodeBase64(self.data, maxlinelength)
def __cmp__(self, other):
if isinstance(other, self.__class__):
return cmp(self.data, other.data)
elif isinstance(other, str):
return cmp(self.data, other)
else:
return cmp(id(self), id(other))
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, repr(self.data))
class PlistParser:
def __init__(self):
self.stack = []
self.currentKey = None
self.root = None
def parse(self, fileobj):
from xml.parsers.expat import ParserCreate
parser = ParserCreate()
parser.StartElementHandler = self.handleBeginElement
parser.EndElementHandler = self.handleEndElement
parser.CharacterDataHandler = self.handleData
parser.ParseFile(fileobj)
return self.root
def handleBeginElement(self, element, attrs):
self.data = []
handler = getattr(self, "begin_" + element, None)
if handler is not None:
handler(attrs)
def handleEndElement(self, element):
handler = getattr(self, "end_" + element, None)
if handler is not None:
handler()
def handleData(self, data):
self.data.append(data)
def addObject(self, value):
if self.currentKey is not None:
self.stack[-1][self.currentKey] = value
self.currentKey = None
elif not self.stack:
# this is the root object
self.root = value
else:
self.stack[-1].append(value)
def getData(self):
data = "".join(self.data)
try:
data = data.encode("ascii")
except UnicodeError:
pass
self.data = []
return data
# element handlers
def begin_dict(self, attrs):
d = _InternalDict()
self.addObject(d)
self.stack.append(d)
def end_dict(self):
self.stack.pop()
def end_key(self):
self.currentKey = self.getData()
def begin_array(self, attrs):
a = []
self.addObject(a)
self.stack.append(a)
def end_array(self):
self.stack.pop()
def end_true(self):
self.addObject(True)
def end_false(self):
self.addObject(False)
def end_integer(self):
self.addObject(int(self.getData()))
def end_real(self):
self.addObject(float(self.getData()))
def end_string(self):
self.addObject(self.getData())
def end_data(self):
self.addObject(Data.fromBase64(self.getData()))
def end_date(self):
self.addObject(_dateFromString(self.getData()))
| Python |
# Generated from 'WASTE.h'
kPascalStackBased = None # workaround for header parsing
def FOUR_CHAR_CODE(x): return x
weCantUndoErr = -10015
weEmptySelectionErr = -10013
weUnknownObjectTypeErr = -9478
weObjectNotFoundErr = -9477
weReadOnlyErr = -9476
weTextNotFoundErr = -9474
weInvalidTextEncodingErr = -9473
weDuplicateAttributeErr = -9472
weInvalidAttributeSizeErr = -9471
weReadOnlyAttributeErr = -9470
weOddByteCountErr = -9469
weHandlerNotFoundErr = -1717
weNotHandledErr = -1708
weNewerVersionErr = -1706
weCorruptDataErr = -1702
weProtocolErr = -603
weUndefinedSelectorErr = -50
weFlushLeft = -2
weFlushRight = -1
weFlushDefault = 0
weCenter = 1
weJustify = 2
weDirDefault = 1
weDirRightToLeft = -1
weDirLeftToRight = 0
weDoFont = 0x0001
weDoFace = 0x0002
weDoSize = 0x0004
weDoColor = 0x0008
weDoAll = weDoFont | weDoFace | weDoSize | weDoColor
weDoAddSize = 0x0010
weDoToggleFace = 0x0020
weDoReplaceFace = 0x0040
weDoPreserveScript = 0x0080
weDoExtractSubscript = 0x0100
weDoFaceMask = 0x0200
weDoDirection = 0x00000001
weDoAlignment = 0x00000002
weDoLeftIndent = 0x00000004
weDoRightIndent = 0x00000008
weDoFirstLineIndent = 0x00000010
weDoLineSpacing = 0x00000020
weDoSpaceBefore = 0x00000040
weDoSpaceAfter = 0x00000080
weDoBottomBorderStyle = 0x00000400
kLeadingEdge = -1
kTrailingEdge = 0
kObjectEdge = 2
weFAutoScroll = 0
weFOutlineHilite = 2
weFReadOnly = 5
weFUndo = 6
weFIntCutAndPaste = 7
weFDragAndDrop = 8
weFInhibitRecal = 9
weFUseTempMem = 10
weFDrawOffscreen = 11
weFInhibitRedraw = 12
weFMonoStyled = 13
weFMultipleUndo = 14
weFNoKeyboardSync = 29
weFInhibitICSupport = 30
weFInhibitColor = 31
weDoAutoScroll = 1 << weFAutoScroll
weDoOutlineHilite = 1 << weFOutlineHilite
weDoReadOnly = 1 << weFReadOnly
weDoUndo = 1 << weFUndo
weDoIntCutAndPaste = 1 << weFIntCutAndPaste
weDoDragAndDrop = 1 << weFDragAndDrop
weDoInhibitRecal = 1 << weFInhibitRecal
weDoUseTempMem = 1 << weFUseTempMem
weDoDrawOffscreen = 1 << weFDrawOffscreen
weDoInhibitRedraw = 1 << weFInhibitRedraw
weDoMonoStyled = 1 << weFMonoStyled
weDoMultipleUndo = 1 << weFMultipleUndo
weDoNoKeyboardSync = 1 << weFNoKeyboardSync
weDoInhibitICSupport = 1 << weFInhibitICSupport
# weDoInhibitColor = 1 << weFInhibitColor
weBitToggle = -2
weBitTest = -1
weBitClear = 0
weBitSet = 1
weLowerCase = 0
weUpperCase = 1
weFindWholeWords = 0x00000001
weFindCaseInsensitive = 0x00000002
weFindDiacriticalInsensitive = 0x00000004
wePutIntCutAndPaste = 0x00000001
wePutAddToTypingSequence = 0x00000002
wePutDetectUnicodeBOM = 0x00000200
weStreamDestinationKindMask = 0x000000FF
weStreamIncludeObjects = 0x00000100
weGetAddUnicodeBOM = 0x00000200
weGetLittleEndian = 0x00000400
weTagFontFamily = FOUR_CHAR_CODE('font')
weTagFontSize = FOUR_CHAR_CODE('ptsz')
weTagPlain = FOUR_CHAR_CODE('plan')
weTagBold = FOUR_CHAR_CODE('bold')
weTagItalic = FOUR_CHAR_CODE('ital')
weTagUnderline = FOUR_CHAR_CODE('undl')
weTagOutline = FOUR_CHAR_CODE('outl')
weTagShadow = FOUR_CHAR_CODE('shad')
weTagCondensed = FOUR_CHAR_CODE('cond')
weTagExtended = FOUR_CHAR_CODE('pexp')
weTagStrikethrough = FOUR_CHAR_CODE('strk')
weTagTextColor = FOUR_CHAR_CODE('colr')
weTagBackgroundColor = FOUR_CHAR_CODE('pbcl')
weTagTransferMode = FOUR_CHAR_CODE('pptm')
weTagVerticalShift = FOUR_CHAR_CODE('xshf')
weTagAlignment = FOUR_CHAR_CODE('pjst')
weTagDirection = FOUR_CHAR_CODE('LDIR')
weTagLineSpacing = FOUR_CHAR_CODE('ledg')
weTagLeftIndent = FOUR_CHAR_CODE('lein')
weTagRightIndent = FOUR_CHAR_CODE('riin')
weTagFirstLineIndent = FOUR_CHAR_CODE('fidt')
weTagSpaceBefore = FOUR_CHAR_CODE('spbe')
weTagSpaceAfter = FOUR_CHAR_CODE('spaf')
weTagBottomBorderStyle = FOUR_CHAR_CODE('BBRD')
weTagForceFontFamily = FOUR_CHAR_CODE('ffnt')
weTagAddFontSize = FOUR_CHAR_CODE('+siz')
weTagAddVerticalShift = FOUR_CHAR_CODE('+shf')
weTagTextEncoding = FOUR_CHAR_CODE('ptxe')
weTagQDStyles = FOUR_CHAR_CODE('qdst')
weTagTETextStyle = FOUR_CHAR_CODE('tets')
weTagAlignmentDefault = FOUR_CHAR_CODE('deft')
weTagAlignmentLeft = FOUR_CHAR_CODE('left')
weTagAlignmentCenter = FOUR_CHAR_CODE('cent')
weTagAlignmentRight = FOUR_CHAR_CODE('rght')
weTagAlignmentFull = FOUR_CHAR_CODE('full')
weTagDirectionDefault = FOUR_CHAR_CODE('deft')
weTagDirectionLeftToRight = FOUR_CHAR_CODE('L->R')
weTagDirectionRightToLeft = FOUR_CHAR_CODE('R->L')
weTagBorderStyleNone = FOUR_CHAR_CODE('NONE')
weTagBorderStyleThin = FOUR_CHAR_CODE('SLDL')
weTagBorderStyleDotted = FOUR_CHAR_CODE('DTDL')
weTagBorderStyleThick = FOUR_CHAR_CODE('THKL')
weLineSpacingSingle = 0x00000000
weLineSpacingOneAndHalf = 0x00008000
weLineSpacingDouble = 0x00010000
weCharByteHook = FOUR_CHAR_CODE('cbyt')
weCharToPixelHook = FOUR_CHAR_CODE('c2p ')
weCharTypeHook = FOUR_CHAR_CODE('ctyp')
weClickLoop = FOUR_CHAR_CODE('clik')
weCurrentDrag = FOUR_CHAR_CODE('drag')
weDrawTextHook = FOUR_CHAR_CODE('draw')
weDrawTSMHiliteHook = FOUR_CHAR_CODE('dtsm')
weEraseHook = FOUR_CHAR_CODE('eras')
weFontFamilyToNameHook = FOUR_CHAR_CODE('ff2n')
weFontNameToFamilyHook = FOUR_CHAR_CODE('fn2f')
weFluxProc = FOUR_CHAR_CODE('flux')
weHiliteDropAreaHook = FOUR_CHAR_CODE('hidr')
weLineBreakHook = FOUR_CHAR_CODE('lbrk')
wePixelToCharHook = FOUR_CHAR_CODE('p2c ')
wePort = FOUR_CHAR_CODE('port')
wePreTrackDragHook = FOUR_CHAR_CODE('ptrk')
weRefCon = FOUR_CHAR_CODE('refc')
weScrollProc = FOUR_CHAR_CODE('scrl')
weText = FOUR_CHAR_CODE('text')
weTranslateDragHook = FOUR_CHAR_CODE('xdrg')
weTranslucencyThreshold = FOUR_CHAR_CODE('tluc')
weTSMDocumentID = FOUR_CHAR_CODE('tsmd')
weTSMPreUpdate = FOUR_CHAR_CODE('pre ')
weTSMPostUpdate = FOUR_CHAR_CODE('post')
weURLHint = FOUR_CHAR_CODE('urlh')
weWordBreakHook = FOUR_CHAR_CODE('wbrk')
weNewHandler = FOUR_CHAR_CODE('new ')
weDisposeHandler = FOUR_CHAR_CODE('free')
weDrawHandler = FOUR_CHAR_CODE('draw')
weClickHandler = FOUR_CHAR_CODE('clik')
weStreamHandler = FOUR_CHAR_CODE('strm')
weHoverHandler = FOUR_CHAR_CODE('hovr')
kTypeText = FOUR_CHAR_CODE('TEXT')
kTypeStyles = FOUR_CHAR_CODE('styl')
kTypeSoup = FOUR_CHAR_CODE('SOUP')
kTypeFontTable = FOUR_CHAR_CODE('FISH')
kTypeParaFormat = FOUR_CHAR_CODE('WEpf')
kTypeRulerScrap = FOUR_CHAR_CODE('WEru')
kTypeCharFormat = FOUR_CHAR_CODE('WEcf')
kTypeStyleScrap = FOUR_CHAR_CODE('WEst')
kTypeUnicodeText = FOUR_CHAR_CODE('utxt')
kTypeUTF8Text = FOUR_CHAR_CODE('UTF8')
kTypeStyledText = FOUR_CHAR_CODE('STXT')
weAKNone = 0
weAKUnspecified = 1
weAKTyping = 2
weAKCut = 3
weAKPaste = 4
weAKClear = 5
weAKDrag = 6
weAKSetStyle = 7
weAKSetRuler = 8
weAKBackspace = 9
weAKFwdDelete = 10
weAKCaseChange = 11
weAKObjectChange = 12
weToScrap = 0
weToDrag = 1
weToSoup = 2
weMouseEnter = 0
weMouseWithin = 1
weMouseLeave = 2
kCurrentSelection = -1
kNullStyle = -2
| Python |
"""macresource - Locate and open the resources needed for a script."""
from Carbon import Res
import os
import sys
import MacOS
import macostools
class ArgumentError(TypeError): pass
class ResourceFileNotFoundError(ImportError): pass
def need(restype, resid, filename=None, modname=None):
"""Open a resource file, if needed. restype and resid
are required parameters, and identify the resource for which to test. If it
is available we are done. If it is not available we look for a file filename
(default: modname with .rsrc appended) either in the same folder as
where modname was loaded from, or otherwise across sys.path.
Returns the refno of the resource file opened (or None)"""
if modname is None and filename is None:
raise ArgumentError, "Either filename or modname argument (or both) must be given"
if type(resid) is type(1):
try:
h = Res.GetResource(restype, resid)
except Res.Error:
pass
else:
return None
else:
try:
h = Res.GetNamedResource(restype, resid)
except Res.Error:
pass
else:
return None
# Construct a filename if we don't have one
if not filename:
if '.' in modname:
filename = modname.split('.')[-1] + '.rsrc'
else:
filename = modname + '.rsrc'
# Now create a list of folders to search
searchdirs = []
if modname == '__main__':
# If we're main we look in the current directory
searchdirs = [os.curdir]
if sys.modules.has_key(modname):
mod = sys.modules[modname]
if hasattr(mod, '__file__'):
searchdirs = [os.path.dirname(mod.__file__)]
searchdirs.extend(sys.path)
# And look for the file
for dir in searchdirs:
pathname = os.path.join(dir, filename)
if os.path.exists(pathname):
break
else:
raise ResourceFileNotFoundError, filename
refno = open_pathname(pathname)
# And check that the resource exists now
if type(resid) is type(1):
h = Res.GetResource(restype, resid)
else:
h = Res.GetNamedResource(restype, resid)
return refno
def open_pathname(pathname, verbose=0):
"""Open a resource file given by pathname, possibly decoding an
AppleSingle file"""
try:
refno = Res.FSpOpenResFile(pathname, 1)
except Res.Error, arg:
if arg[0] in (-37, -39):
# No resource fork. We may be on OSX, and this may be either
# a data-fork based resource file or a AppleSingle file
# from the CVS repository.
try:
refno = Res.FSOpenResourceFile(pathname, u'', 1)
except Res.Error, arg:
if arg[0] != -199:
# -199 is "bad resource map"
raise
else:
return refno
# Finally try decoding an AppleSingle file
pathname = _decode(pathname, verbose=verbose)
refno = Res.FSOpenResourceFile(pathname, u'', 1)
else:
raise
return refno
def resource_pathname(pathname, verbose=0):
"""Return the pathname for a resource file (either DF or RF based).
If the pathname given already refers to such a file simply return it,
otherwise first decode it."""
try:
refno = Res.FSpOpenResFile(pathname, 1)
Res.CloseResFile(refno)
except Res.Error, arg:
if arg[0] in (-37, -39):
# No resource fork. We may be on OSX, and this may be either
# a data-fork based resource file or a AppleSingle file
# from the CVS repository.
try:
refno = Res.FSOpenResourceFile(pathname, u'', 1)
except Res.Error, arg:
if arg[0] != -199:
# -199 is "bad resource map"
raise
else:
return refno
# Finally try decoding an AppleSingle file
pathname = _decode(pathname, verbose=verbose)
else:
raise
return pathname
def open_error_resource():
"""Open the resource file containing the error code to error message
mapping."""
need('Estr', 1, filename="errors.rsrc", modname=__name__)
def _decode(pathname, verbose=0):
# Decode an AppleSingle resource file, return the new pathname.
newpathname = pathname + '.df.rsrc'
if os.path.exists(newpathname) and \
os.stat(newpathname).st_mtime >= os.stat(pathname).st_mtime:
return newpathname
if hasattr(os, 'access') and not \
os.access(os.path.dirname(pathname), os.W_OK|os.X_OK):
# The destination directory isn't writeable. Create the file in
# a temporary directory
import tempfile
fd, newpathname = tempfile.mkstemp(".rsrc")
if verbose:
print 'Decoding', pathname, 'to', newpathname
import applesingle
applesingle.decode(pathname, newpathname, resonly=1)
return newpathname
| Python |
# Video file reader, using QuickTime
#
# This module was quickly ripped out of another software package, so there is a good
# chance that it does not work as-is and it needs some hacking.
#
# Jack Jansen, August 2000
#
import sys
from Carbon import Qt
from Carbon import QuickTime
from Carbon import Qd
from Carbon import Qdoffs
from Carbon import QDOffscreen
from Carbon import Res
try:
import MediaDescr
except ImportError:
def _audiodescr(data):
return None
else:
def _audiodescr(data):
return MediaDescr.SoundDescription.decode(data)
try:
from imgformat import macrgb
except ImportError:
macrgb = "Macintosh RGB format"
import os
# import audio.format
class VideoFormat:
def __init__(self, name, descr, width, height, format):
self.__name = name
self.__descr = descr
self.__width = width
self.__height = height
self.__format = format
def getname(self):
return self.__name
def getdescr(self):
return self.__descr
def getsize(self):
return self.__width, self.__height
def getformat(self):
return self.__format
class _Reader:
def __init__(self, path):
fd = Qt.OpenMovieFile(path, 0)
self.movie, d1, d2 = Qt.NewMovieFromFile(fd, 0, 0)
self.movietimescale = self.movie.GetMovieTimeScale()
try:
self.audiotrack = self.movie.GetMovieIndTrackType(1,
QuickTime.AudioMediaCharacteristic, QuickTime.movieTrackCharacteristic)
self.audiomedia = self.audiotrack.GetTrackMedia()
except Qt.Error:
self.audiotrack = self.audiomedia = None
self.audiodescr = {}
else:
handle = Res.Handle('')
n = self.audiomedia.GetMediaSampleDescriptionCount()
self.audiomedia.GetMediaSampleDescription(1, handle)
self.audiodescr = _audiodescr(handle.data)
self.audiotimescale = self.audiomedia.GetMediaTimeScale()
del handle
try:
self.videotrack = self.movie.GetMovieIndTrackType(1,
QuickTime.VisualMediaCharacteristic, QuickTime.movieTrackCharacteristic)
self.videomedia = self.videotrack.GetTrackMedia()
except Qt.Error:
self.videotrack = self.videomedia = self.videotimescale = None
if self.videotrack:
self.videotimescale = self.videomedia.GetMediaTimeScale()
x0, y0, x1, y1 = self.movie.GetMovieBox()
self.videodescr = {'width':(x1-x0), 'height':(y1-y0)}
self._initgworld()
self.videocurtime = None
self.audiocurtime = None
def __del__(self):
self.audiomedia = None
self.audiotrack = None
self.videomedia = None
self.videotrack = None
self.movie = None
def _initgworld(self):
old_port, old_dev = Qdoffs.GetGWorld()
try:
movie_w = self.videodescr['width']
movie_h = self.videodescr['height']
movie_rect = (0, 0, movie_w, movie_h)
self.gworld = Qdoffs.NewGWorld(32, movie_rect, None, None, QDOffscreen.keepLocal)
self.pixmap = self.gworld.GetGWorldPixMap()
Qdoffs.LockPixels(self.pixmap)
Qdoffs.SetGWorld(self.gworld.as_GrafPtr(), None)
Qd.EraseRect(movie_rect)
self.movie.SetMovieGWorld(self.gworld.as_GrafPtr(), None)
self.movie.SetMovieBox(movie_rect)
self.movie.SetMovieActive(1)
self.movie.MoviesTask(0)
self.movie.SetMoviePlayHints(QuickTime.hintsHighQuality, QuickTime.hintsHighQuality)
# XXXX framerate
finally:
Qdoffs.SetGWorld(old_port, old_dev)
def _gettrackduration_ms(self, track):
tracktime = track.GetTrackDuration()
return self._movietime_to_ms(tracktime)
def _movietime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.movietimescale, None), 1000)
return value
def _videotime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.videotimescale, None), 1000)
return value
def _audiotime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.audiotimescale, None), 1000)
return value
def _videotime_to_movietime(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.videotimescale, None),
self.movietimescale)
return value
def HasAudio(self):
return not self.audiotrack is None
def HasVideo(self):
return not self.videotrack is None
def GetAudioDuration(self):
if not self.audiotrack:
return 0
return self._gettrackduration_ms(self.audiotrack)
def GetVideoDuration(self):
if not self.videotrack:
return 0
return self._gettrackduration_ms(self.videotrack)
def GetAudioFormat(self):
if not self.audiodescr:
return None, None, None, None, None
bps = self.audiodescr['sampleSize']
nch = self.audiodescr['numChannels']
if nch == 1:
channels = ['mono']
elif nch == 2:
channels = ['left', 'right']
else:
channels = map(lambda x: str(x+1), range(nch))
if bps % 8:
# Funny bits-per sample. We pretend not to understand
blocksize = 0
fpb = 0
else:
# QuickTime is easy (for as far as we support it): samples are always a whole
# number of bytes, so frames are nchannels*samplesize, and there's one frame per block.
blocksize = (bps/8)*nch
fpb = 1
if self.audiodescr['dataFormat'] == 'raw ':
encoding = 'linear-excess'
elif self.audiodescr['dataFormat'] == 'twos':
encoding = 'linear-signed'
else:
encoding = 'quicktime-coding-%s'%self.audiodescr['dataFormat']
## return audio.format.AudioFormatLinear('quicktime_audio', 'QuickTime Audio Format',
## channels, encoding, blocksize=blocksize, fpb=fpb, bps=bps)
return channels, encoding, blocksize, fpb, bps
def GetAudioFrameRate(self):
if not self.audiodescr:
return None
return int(self.audiodescr['sampleRate'])
def GetVideoFormat(self):
width = self.videodescr['width']
height = self.videodescr['height']
return VideoFormat('dummy_format', 'Dummy Video Format', width, height, macrgb)
def GetVideoFrameRate(self):
tv = self.videocurtime
if tv == None:
tv = 0
flags = QuickTime.nextTimeStep|QuickTime.nextTimeEdgeOK
tv, dur = self.videomedia.GetMediaNextInterestingTime(flags, tv, 1.0)
dur = self._videotime_to_ms(dur)
return int((1000.0/dur)+0.5)
def ReadAudio(self, nframes, time=None):
if not time is None:
self.audiocurtime = time
flags = QuickTime.nextTimeStep|QuickTime.nextTimeEdgeOK
if self.audiocurtime == None:
self.audiocurtime = 0
tv = self.audiomedia.GetMediaNextInterestingTimeOnly(flags, self.audiocurtime, 1.0)
if tv < 0 or (self.audiocurtime and tv < self.audiocurtime):
return self._audiotime_to_ms(self.audiocurtime), None
h = Res.Handle('')
desc_h = Res.Handle('')
size, actualtime, sampleduration, desc_index, actualcount, flags = \
self.audiomedia.GetMediaSample(h, 0, tv, desc_h, nframes)
self.audiocurtime = actualtime + actualcount*sampleduration
return self._audiotime_to_ms(actualtime), h.data
def ReadVideo(self, time=None):
if not time is None:
self.videocurtime = time
flags = QuickTime.nextTimeStep
if self.videocurtime == None:
flags = flags | QuickTime.nextTimeEdgeOK
self.videocurtime = 0
tv = self.videomedia.GetMediaNextInterestingTimeOnly(flags, self.videocurtime, 1.0)
if tv < 0 or (self.videocurtime and tv <= self.videocurtime):
return self._videotime_to_ms(self.videocurtime), None
self.videocurtime = tv
moviecurtime = self._videotime_to_movietime(self.videocurtime)
self.movie.SetMovieTimeValue(moviecurtime)
self.movie.MoviesTask(0)
return self._videotime_to_ms(self.videocurtime), self._getpixmapcontent()
def _getpixmapcontent(self):
"""Shuffle the offscreen PixMap data, because it may have funny stride values"""
rowbytes = Qdoffs.GetPixRowBytes(self.pixmap)
width = self.videodescr['width']
height = self.videodescr['height']
start = 0
rv = ''
for i in range(height):
nextline = Qdoffs.GetPixMapBytes(self.pixmap, start, width*4)
start = start + rowbytes
rv = rv + nextline
return rv
def reader(url):
try:
rdr = _Reader(url)
except IOError:
return None
return rdr
def _test():
import EasyDialogs
try:
import img
except ImportError:
img = None
import MacOS
Qt.EnterMovies()
path = EasyDialogs.AskFileForOpen(message='Video to convert')
if not path: sys.exit(0)
rdr = reader(path)
if not rdr:
sys.exit(1)
dstdir = EasyDialogs.AskFileForSave(message='Name for output folder')
if not dstdir: sys.exit(0)
num = 0
os.mkdir(dstdir)
videofmt = rdr.GetVideoFormat()
imgfmt = videofmt.getformat()
imgw, imgh = videofmt.getsize()
timestamp, data = rdr.ReadVideo()
while data:
fname = 'frame%04.4d.jpg'%num
num = num+1
pname = os.path.join(dstdir, fname)
if not img: print 'Not',
print 'Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data))
if img:
wrt = img.writer(imgfmt, pname)
wrt.width = imgw
wrt.height = imgh
wrt.write(data)
timestamp, data = rdr.ReadVideo()
MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG')
if num > 20:
print 'stopping at 20 frames so your disk does not fill up:-)'
break
print 'Total frames:', num
if __name__ == '__main__':
_test()
sys.exit(1)
| Python |
"""macostools - Various utility functions for MacOS.
mkalias(src, dst) - Create a finder alias 'dst' pointing to 'src'
copy(src, dst) - Full copy of 'src' to 'dst'
"""
from Carbon import Res
from Carbon import File, Files
import os
import sys
import MacOS
import time
try:
openrf = MacOS.openrf
except AttributeError:
# Backward compatability
openrf = open
Error = 'macostools.Error'
BUFSIZ=0x80000 # Copy in 0.5Mb chunks
COPY_FLAGS = (Files.kIsStationary|Files.kNameLocked|Files.kHasBundle|
Files.kIsInvisible|Files.kIsAlias)
#
# Not guaranteed to be correct or stay correct (Apple doesn't tell you
# how to do this), but it seems to work.
#
def mkalias(src, dst, relative=None):
"""Create a finder alias"""
srcfsr = File.FSRef(src)
# The next line will fail under unix-Python if the destination
# doesn't exist yet. We should change this code to be fsref-based.
dstdir, dstname = os.path.split(dst)
if not dstdir: dstdir = os.curdir
dstdirfsr = File.FSRef(dstdir)
if relative:
relativefsr = File.FSRef(relative)
# ik mag er geen None in stoppen :-(
alias = File.FSNewAlias(relativefsr, srcfsr)
else:
alias = srcfsr.FSNewAliasMinimal()
dstfsr, dstfss = Res.FSCreateResourceFile(dstdirfsr, unicode(dstname),
File.FSGetResourceForkName())
h = Res.FSOpenResourceFile(dstfsr, File.FSGetResourceForkName(), 3)
resource = Res.Resource(alias.data)
resource.AddResource('alis', 0, '')
Res.CloseResFile(h)
dstfinfo = dstfss.FSpGetFInfo()
dstfinfo.Flags = dstfinfo.Flags|0x8000 # Alias flag
dstfss.FSpSetFInfo(dstfinfo)
def mkdirs(dst):
"""Make directories leading to 'dst' if they don't exist yet"""
if dst == '' or os.path.exists(dst):
return
head, tail = os.path.split(dst)
if os.sep == ':' and not ':' in head:
head = head + ':'
mkdirs(head)
os.mkdir(dst, 0777)
def touched(dst):
"""Tell the finder a file has changed. No-op on MacOSX."""
if sys.platform != 'mac': return
import warnings
warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__)
import macfs
file_fss = macfs.FSSpec(dst)
vRefNum, dirID, name = file_fss.as_tuple()
dir_fss = macfs.FSSpec((vRefNum, dirID, ''))
crdate, moddate, bkdate = dir_fss.GetDates()
now = time.time()
if now == moddate:
now = now + 1
try:
dir_fss.SetDates(crdate, now, bkdate)
except macfs.error:
pass
def touched_ae(dst):
"""Tell the finder a file has changed"""
pardir = os.path.split(dst)[0]
if not pardir:
pardir = os.curdir
import Finder
f = Finder.Finder()
f.update(File.FSRef(pardir))
def copy(src, dst, createpath=0, copydates=1, forcetype=None):
"""Copy a file, including finder info, resource fork, etc"""
src = File.pathname(src)
dst = File.pathname(dst)
if createpath:
mkdirs(os.path.split(dst)[0])
ifp = open(src, 'rb')
ofp = open(dst, 'wb')
d = ifp.read(BUFSIZ)
while d:
ofp.write(d)
d = ifp.read(BUFSIZ)
ifp.close()
ofp.close()
ifp = openrf(src, '*rb')
ofp = openrf(dst, '*wb')
d = ifp.read(BUFSIZ)
while d:
ofp.write(d)
d = ifp.read(BUFSIZ)
ifp.close()
ofp.close()
srcfss = File.FSSpec(src)
dstfss = File.FSSpec(dst)
sf = srcfss.FSpGetFInfo()
df = dstfss.FSpGetFInfo()
df.Creator, df.Type = sf.Creator, sf.Type
if forcetype != None:
df.Type = forcetype
df.Flags = (sf.Flags & COPY_FLAGS)
dstfss.FSpSetFInfo(df)
if copydates:
srcfsr = File.FSRef(src)
dstfsr = File.FSRef(dst)
catinfo, _, _, _ = srcfsr.FSGetCatalogInfo(Files.kFSCatInfoAllDates)
dstfsr.FSSetCatalogInfo(Files.kFSCatInfoAllDates, catinfo)
touched(dstfss)
def copytree(src, dst, copydates=1):
"""Copy a complete file tree to a new destination"""
if os.path.isdir(src):
mkdirs(dst)
files = os.listdir(src)
for f in files:
copytree(os.path.join(src, f), os.path.join(dst, f), copydates)
else:
copy(src, dst, 1, copydates)
| Python |
QSIZE = 100000
error='Audio_mac.error'
class Play_Audio_mac:
def __init__(self, qsize=QSIZE):
self._chan = None
self._qsize = qsize
self._outrate = 22254
self._sampwidth = 1
self._nchannels = 1
self._gc = []
self._usercallback = None
def __del__(self):
self.stop()
self._usercallback = None
def wait(self):
import time
while self.getfilled():
time.sleep(0.1)
self._chan = None
self._gc = []
def stop(self, quietNow = 1):
##chan = self._chan
self._chan = None
##chan.SndDisposeChannel(1)
self._gc = []
def setoutrate(self, outrate):
self._outrate = outrate
def setsampwidth(self, sampwidth):
self._sampwidth = sampwidth
def setnchannels(self, nchannels):
self._nchannels = nchannels
def writeframes(self, data):
import time
from Carbon.Sound import bufferCmd, callBackCmd, extSH
import struct
import MacOS
if not self._chan:
from Carbon import Snd
self._chan = Snd.SndNewChannel(5, 0, self._callback)
nframes = len(data) / self._nchannels / self._sampwidth
if len(data) != nframes * self._nchannels * self._sampwidth:
raise error, 'data is not a whole number of frames'
while self._gc and \
self.getfilled() + nframes > \
self._qsize / self._nchannels / self._sampwidth:
time.sleep(0.1)
if self._sampwidth == 1:
import audioop
data = audioop.add(data, '\x80'*len(data), 1)
h1 = struct.pack('llHhllbbl',
id(data)+MacOS.string_id_to_buffer,
self._nchannels,
self._outrate, 0,
0,
0,
extSH,
60,
nframes)
h2 = 22*'\0'
h3 = struct.pack('hhlll',
self._sampwidth*8,
0,
0,
0,
0)
header = h1+h2+h3
self._gc.append((header, data))
self._chan.SndDoCommand((bufferCmd, 0, header), 0)
self._chan.SndDoCommand((callBackCmd, 0, 0), 0)
def _callback(self, *args):
del self._gc[0]
if self._usercallback:
self._usercallback()
def setcallback(self, callback):
self._usercallback = callback
def getfilled(self):
filled = 0
for header, data in self._gc:
filled = filled + len(data)
return filled / self._nchannels / self._sampwidth
def getfillable(self):
return (self._qsize / self._nchannels / self._sampwidth) - self.getfilled()
def ulaw2lin(self, data):
import audioop
return audioop.ulaw2lin(data, 2)
def test():
import aifc
import EasyDialogs
fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile", typeList=("AIFF",))
if not fn: return
af = aifc.open(fn, 'r')
print af.getparams()
p = Play_Audio_mac()
p.setoutrate(af.getframerate())
p.setsampwidth(af.getsampwidth())
p.setnchannels(af.getnchannels())
BUFSIZ = 10000
while 1:
data = af.readframes(BUFSIZ)
if not data: break
p.writeframes(data)
print 'wrote', len(data), 'space', p.getfillable()
p.wait()
if __name__ == '__main__':
test()
| Python |
#!/usr/bin/env python
# This file is meant as an executable script for running applets.
# BuildApplet will use it as the main executable in the .app bundle if
# we are not running in a framework build.
import os
import sys
for name in ["__rawmain__.py", "__rawmain__.pyc", "__main__.py", "__main__.pyc"]:
realmain = os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])),
"Resources", name)
if os.path.exists(realmain):
break
else:
sys.stderr.write("%s: cannot find applet main program\n" % sys.argv[0])
sys.exit(1)
sys.argv.insert(1, realmain)
os.execve(sys.executable, sys.argv, os.environ)
| Python |
# Symbols from <gl/get.h>
BCKBUFFER = 0x1
FRNTBUFFER = 0x2
DRAWZBUFFER = 0x4
DMRGB = 0
DMSINGLE = 1
DMDOUBLE = 2
DMRGBDOUBLE = 5
HZ30 = 0
HZ60 = 1
NTSC = 2
HDTV = 3
VGA = 4
IRIS3K = 5
PR60 = 6
PAL = 9
HZ30_SG = 11
A343 = 14
STR_RECT = 15
VOF0 = 16
VOF1 = 17
VOF2 = 18
VOF3 = 19
SGI0 = 20
SGI1 = 21
SGI2 = 22
HZ72 = 23
GL_VIDEO_REG = 0x00800000
GLV_GENLOCK = 0x00000001
GLV_UNBLANK = 0x00000002
GLV_SRED = 0x00000004
GLV_SGREEN = 0x00000008
GLV_SBLUE = 0x00000010
GLV_SALPHA = 0x00000020
GLV_TTLGENLOCK = 0x00000080
GLV_TTLSYNC = GLV_TTLGENLOCK
GLV_GREENGENLOCK = 0x0000100
LEFTPLANE = 0x0001
RIGHTPLANE = 0x0002
BOTTOMPLANE = 0x0004
TOPPLANE = 0x0008
NEARPLANE = 0x0010
FARPLANE = 0x0020
## GETDEF = __GL_GET_H__
NOBUFFER = 0x0
BOTHBUFFERS = 0x3
DMINTENSITYSINGLE = 3
DMINTENSITYDOUBLE = 4
MONSPECIAL = 0x20
HZ50 = 3
MONA = 5
MONB = 6
MONC = 7
MOND = 8
MON_ALL = 12
MON_GEN_ALL = 13
CMAPMULTI = 0
CMAPONE = 1
| Python |
# Implement 'jpeg' interface using SGI's compression library
# XXX Options 'smooth' and 'optimize' are ignored.
# XXX It appears that compressing grayscale images doesn't work right;
# XXX the resulting file causes weirdness.
class error(Exception):
pass
options = {'quality': 75, 'optimize': 0, 'smooth': 0, 'forcegray': 0}
comp = None
decomp = None
def compress(imgdata, width, height, bytesperpixel):
global comp
import cl
if comp is None: comp = cl.OpenCompressor(cl.JPEG)
if bytesperpixel == 1:
format = cl.GRAYSCALE
elif bytesperpixel == 4:
format = cl.RGBX
if options['forcegray']:
iformat = cl.GRAYSCALE
else:
iformat = cl.YUV
# XXX How to support 'optimize'?
params = [cl.IMAGE_WIDTH, width, cl.IMAGE_HEIGHT, height, \
cl.ORIGINAL_FORMAT, format, \
cl.ORIENTATION, cl.BOTTOM_UP, \
cl.QUALITY_FACTOR, options['quality'], \
cl.INTERNAL_FORMAT, iformat, \
]
comp.SetParams(params)
jpegdata = comp.Compress(1, imgdata)
return jpegdata
def decompress(jpegdata):
global decomp
import cl
if decomp is None: decomp = cl.OpenDecompressor(cl.JPEG)
headersize = decomp.ReadHeader(jpegdata)
params = [cl.IMAGE_WIDTH, 0, cl.IMAGE_HEIGHT, 0, cl.INTERNAL_FORMAT, 0]
decomp.GetParams(params)
width, height, format = params[1], params[3], params[5]
if format == cl.GRAYSCALE or options['forcegray']:
format = cl.GRAYSCALE
bytesperpixel = 1
else:
format = cl.RGBX
bytesperpixel = 4
# XXX How to support 'smooth'?
params = [cl.ORIGINAL_FORMAT, format, \
cl.ORIENTATION, cl.BOTTOM_UP, \
cl.FRAME_BUFFER_SIZE, width*height*bytesperpixel]
decomp.SetParams(params)
imgdata = decomp.Decompress(1, jpegdata)
return imgdata, width, height, bytesperpixel
def setoption(name, value):
if type(value) is not type(0):
raise TypeError, 'jpeg.setoption: numeric options only'
if name == 'forcegrey':
name = 'forcegray'
if not options.has_key(name):
raise KeyError, 'jpeg.setoption: unknown option name'
options[name] = int(value)
def test():
import sys
if sys.argv[1:2] == ['-g']:
del sys.argv[1]
setoption('forcegray', 1)
if not sys.argv[1:]:
sys.argv.append('/usr/local/images/data/jpg/asterix.jpg')
for file in sys.argv[1:]:
show(file)
def show(file):
import gl, GL, DEVICE
jpegdata = open(file, 'r').read()
imgdata, width, height, bytesperpixel = decompress(jpegdata)
gl.foreground()
gl.prefsize(width, height)
win = gl.winopen(file)
if bytesperpixel == 1:
gl.cmode()
gl.pixmode(GL.PM_SIZE, 8)
gl.gconfig()
for i in range(256):
gl.mapcolor(i, i, i, i)
else:
gl.RGBmode()
gl.pixmode(GL.PM_SIZE, 32)
gl.gconfig()
gl.qdevice(DEVICE.REDRAW)
gl.qdevice(DEVICE.ESCKEY)
gl.qdevice(DEVICE.WINQUIT)
gl.qdevice(DEVICE.WINSHUT)
gl.lrectwrite(0, 0, width-1, height-1, imgdata)
while 1:
dev, val = gl.qread()
if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT):
break
if dev == DEVICE.REDRAW:
gl.lrectwrite(0, 0, width-1, height-1, imgdata)
gl.winclose(win)
# Now test the compression and write the result to a fixed filename
newjpegdata = compress(imgdata, width, height, bytesperpixel)
open('/tmp/j.jpg', 'w').write(newjpegdata)
| Python |
# This file implements a class which forms an interface to the .cdplayerrc
# file that is maintained by SGI's cdplayer program.
#
# Usage is as follows:
#
# import readcd
# r = readcd.Readcd()
# c = Cdplayer(r.gettrackinfo())
#
# Now you can use c.artist, c.title and c.track[trackno] (where trackno
# starts at 1). When the CD is not recognized, all values will be the empty
# string.
# It is also possible to set the above mentioned variables to new values.
# You can then use c.write() to write out the changed values to the
# .cdplayerrc file.
cdplayerrc = '.cdplayerrc'
class Cdplayer:
def __init__(self, tracklist):
import string
self.artist = ''
self.title = ''
if type(tracklist) == type(''):
t = []
for i in range(2, len(tracklist), 4):
t.append((None, \
(string.atoi(tracklist[i:i+2]), \
string.atoi(tracklist[i+2:i+4]))))
tracklist = t
self.track = [None] + [''] * len(tracklist)
self.id = 'd' + string.zfill(len(tracklist), 2)
for track in tracklist:
start, length = track
self.id = self.id + string.zfill(length[0], 2) + \
string.zfill(length[1], 2)
try:
import posix
f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r')
except IOError:
return
import re
reg = re.compile(r'^([^:]*):\t(.*)')
s = self.id + '.'
l = len(s)
while 1:
line = f.readline()
if line == '':
break
if line[:l] == s:
line = line[l:]
match = reg.match(line)
if not match:
print 'syntax error in ~/' + cdplayerrc
continue
name, value = match.group(1, 2)
if name == 'title':
self.title = value
elif name == 'artist':
self.artist = value
elif name[:5] == 'track':
trackno = string.atoi(name[6:])
self.track[trackno] = value
f.close()
def write(self):
import posix
filename = posix.environ['HOME'] + '/' + cdplayerrc
try:
old = open(filename, 'r')
except IOError:
old = open('/dev/null', 'r')
new = open(filename + '.new', 'w')
s = self.id + '.'
l = len(s)
while 1:
line = old.readline()
if line == '':
break
if line[:l] != s:
new.write(line)
new.write(self.id + '.title:\t' + self.title + '\n')
new.write(self.id + '.artist:\t' + self.artist + '\n')
for i in range(1, len(self.track)):
new.write('%s.track.%r:\t%s\n' % (self.id, i, self.track[i]))
old.close()
new.close()
posix.rename(filename + '.new', filename)
| Python |
#
# flp - Module to load fl forms from fd files
#
# Jack Jansen, December 1991
#
import string
import os
import sys
import FL
SPLITLINE = '--------------------'
FORMLINE = '=============== FORM ==============='
ENDLINE = '=============================='
class error(Exception):
pass
##################################################################
# Part 1 - The parsing routines #
##################################################################
#
# Externally visible function. Load form.
#
def parse_form(filename, formname):
forms = checkcache(filename)
if forms is None:
forms = parse_forms(filename)
if forms.has_key(formname):
return forms[formname]
else:
raise error, 'No such form in fd file'
#
# Externally visible function. Load all forms.
#
def parse_forms(filename):
forms = checkcache(filename)
if forms is not None: return forms
fp = _open_formfile(filename)
nforms = _parse_fd_header(fp)
forms = {}
for i in range(nforms):
form = _parse_fd_form(fp, None)
forms[form[0].Name] = form
writecache(filename, forms)
return forms
#
# Internal: see if a cached version of the file exists
#
MAGIC = '.fdc'
_internal_cache = {} # Used by frozen scripts only
def checkcache(filename):
if _internal_cache.has_key(filename):
altforms = _internal_cache[filename]
return _unpack_cache(altforms)
import marshal
fp, filename = _open_formfile2(filename)
fp.close()
cachename = filename + 'c'
try:
fp = open(cachename, 'r')
except IOError:
#print 'flp: no cache file', cachename
return None
try:
if fp.read(4) != MAGIC:
print 'flp: bad magic word in cache file', cachename
return None
cache_mtime = rdlong(fp)
file_mtime = getmtime(filename)
if cache_mtime != file_mtime:
#print 'flp: outdated cache file', cachename
return None
#print 'flp: valid cache file', cachename
altforms = marshal.load(fp)
return _unpack_cache(altforms)
finally:
fp.close()
def _unpack_cache(altforms):
forms = {}
for name in altforms.keys():
altobj, altlist = altforms[name]
obj = _newobj()
obj.make(altobj)
list = []
for altobj in altlist:
nobj = _newobj()
nobj.make(altobj)
list.append(nobj)
forms[name] = obj, list
return forms
def rdlong(fp):
s = fp.read(4)
if len(s) != 4: return None
a, b, c, d = s[0], s[1], s[2], s[3]
return ord(a)<<24 | ord(b)<<16 | ord(c)<<8 | ord(d)
def wrlong(fp, x):
a, b, c, d = (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff
fp.write(chr(a) + chr(b) + chr(c) + chr(d))
def getmtime(filename):
import os
from stat import ST_MTIME
try:
return os.stat(filename)[ST_MTIME]
except os.error:
return None
#
# Internal: write cached version of the form (parsing is too slow!)
#
def writecache(filename, forms):
import marshal
fp, filename = _open_formfile2(filename)
fp.close()
cachename = filename + 'c'
try:
fp = open(cachename, 'w')
except IOError:
print 'flp: can\'t create cache file', cachename
return # Never mind
fp.write('\0\0\0\0') # Seek back and write MAGIC when done
wrlong(fp, getmtime(filename))
altforms = _pack_cache(forms)
marshal.dump(altforms, fp)
fp.seek(0)
fp.write(MAGIC)
fp.close()
#print 'flp: wrote cache file', cachename
#
# External: print some statements that set up the internal cache.
# This is for use with the "freeze" script. You should call
# flp.freeze(filename) for all forms used by the script, and collect
# the output on a file in a module file named "frozenforms.py". Then
# in the main program of the script import frozenforms.
# (Don't forget to take this out when using the unfrozen version of
# the script!)
#
def freeze(filename):
forms = parse_forms(filename)
altforms = _pack_cache(forms)
print 'import flp'
print 'flp._internal_cache[', repr(filename), '] =', altforms
#
# Internal: create the data structure to be placed in the cache
#
def _pack_cache(forms):
altforms = {}
for name in forms.keys():
obj, list = forms[name]
altobj = obj.__dict__
altlist = []
for obj in list: altlist.append(obj.__dict__)
altforms[name] = altobj, altlist
return altforms
#
# Internal: Locate form file (using PYTHONPATH) and open file
#
def _open_formfile(filename):
return _open_formfile2(filename)[0]
def _open_formfile2(filename):
if filename[-3:] != '.fd':
filename = filename + '.fd'
if filename[0] == '/':
try:
fp = open(filename,'r')
except IOError:
fp = None
else:
for pc in sys.path:
pn = os.path.join(pc, filename)
try:
fp = open(pn, 'r')
filename = pn
break
except IOError:
fp = None
if fp is None:
raise error, 'Cannot find forms file ' + filename
return fp, filename
#
# Internal: parse the fd file header, return number of forms
#
def _parse_fd_header(file):
# First read the magic header line
datum = _parse_1_line(file)
if datum != ('Magic', 12321):
raise error, 'Not a forms definition file'
# Now skip until we know number of forms
while 1:
datum = _parse_1_line(file)
if type(datum) == type(()) and datum[0] == 'Numberofforms':
break
return datum[1]
#
# Internal: parse fd form, or skip if name doesn't match.
# the special value None means 'always parse it'.
#
def _parse_fd_form(file, name):
datum = _parse_1_line(file)
if datum != FORMLINE:
raise error, 'Missing === FORM === line'
form = _parse_object(file)
if form.Name == name or name is None:
objs = []
for j in range(form.Numberofobjects):
obj = _parse_object(file)
objs.append(obj)
return (form, objs)
else:
for j in range(form.Numberofobjects):
_skip_object(file)
return None
#
# Internal class: a convenient place to store object info fields
#
class _newobj:
def add(self, name, value):
self.__dict__[name] = value
def make(self, dict):
for name in dict.keys():
self.add(name, dict[name])
#
# Internal parsing routines.
#
def _parse_string(str):
if '\\' in str:
s = '\'' + str + '\''
try:
return eval(s)
except:
pass
return str
def _parse_num(str):
return eval(str)
def _parse_numlist(str):
slist = string.split(str)
nlist = []
for i in slist:
nlist.append(_parse_num(i))
return nlist
# This dictionary maps item names to parsing routines.
# If no routine is given '_parse_num' is default.
_parse_func = { \
'Name': _parse_string, \
'Box': _parse_numlist, \
'Colors': _parse_numlist, \
'Label': _parse_string, \
'Name': _parse_string, \
'Callback': _parse_string, \
'Argument': _parse_string }
# This function parses a line, and returns either
# a string or a tuple (name,value)
import re
prog = re.compile('^([^:]*): *(.*)')
def _parse_line(line):
match = prog.match(line)
if not match:
return line
name, value = match.group(1, 2)
if name[0] == 'N':
name = string.join(string.split(name),'')
name = string.lower(name)
name = string.capitalize(name)
try:
pf = _parse_func[name]
except KeyError:
pf = _parse_num
value = pf(value)
return (name, value)
def _readline(file):
line = file.readline()
if not line:
raise EOFError
return line[:-1]
def _parse_1_line(file):
line = _readline(file)
while line == '':
line = _readline(file)
return _parse_line(line)
def _skip_object(file):
line = ''
while not line in (SPLITLINE, FORMLINE, ENDLINE):
pos = file.tell()
line = _readline(file)
if line == FORMLINE:
file.seek(pos)
def _parse_object(file):
obj = _newobj()
while 1:
pos = file.tell()
datum = _parse_1_line(file)
if datum in (SPLITLINE, FORMLINE, ENDLINE):
if datum == FORMLINE:
file.seek(pos)
return obj
if type(datum) is not type(()) or len(datum) != 2:
raise error, 'Parse error, illegal line in object: '+datum
obj.add(datum[0], datum[1])
#################################################################
# Part 2 - High-level object/form creation routines #
#################################################################
#
# External - Create a form an link to an instance variable.
#
def create_full_form(inst, (fdata, odatalist)):
form = create_form(fdata)
exec 'inst.'+fdata.Name+' = form\n'
for odata in odatalist:
create_object_instance(inst, form, odata)
#
# External - Merge a form into an existing form in an instance
# variable.
#
def merge_full_form(inst, form, (fdata, odatalist)):
exec 'inst.'+fdata.Name+' = form\n'
if odatalist[0].Class != FL.BOX:
raise error, 'merge_full_form() expects FL.BOX as first obj'
for odata in odatalist[1:]:
create_object_instance(inst, form, odata)
#################################################################
# Part 3 - Low-level object/form creation routines #
#################################################################
#
# External Create_form - Create form from parameters
#
def create_form(fdata):
import fl
return fl.make_form(FL.NO_BOX, fdata.Width, fdata.Height)
#
# External create_object - Create an object. Make sure there are
# no callbacks. Returns the object created.
#
def create_object(form, odata):
obj = _create_object(form, odata)
if odata.Callback:
raise error, 'Creating free object with callback'
return obj
#
# External create_object_instance - Create object in an instance.
#
def create_object_instance(inst, form, odata):
obj = _create_object(form, odata)
if odata.Callback:
cbfunc = eval('inst.'+odata.Callback)
obj.set_call_back(cbfunc, odata.Argument)
if odata.Name:
exec 'inst.' + odata.Name + ' = obj\n'
#
# Internal _create_object: Create the object and fill options
#
def _create_object(form, odata):
crfunc = _select_crfunc(form, odata.Class)
obj = crfunc(odata.Type, odata.Box[0], odata.Box[1], odata.Box[2], \
odata.Box[3], odata.Label)
if not odata.Class in (FL.BEGIN_GROUP, FL.END_GROUP):
obj.boxtype = odata.Boxtype
obj.col1 = odata.Colors[0]
obj.col2 = odata.Colors[1]
obj.align = odata.Alignment
obj.lstyle = odata.Style
obj.lsize = odata.Size
obj.lcol = odata.Lcol
return obj
#
# Internal crfunc: helper function that returns correct create function
#
def _select_crfunc(fm, cl):
if cl == FL.BEGIN_GROUP: return fm.bgn_group
elif cl == FL.END_GROUP: return fm.end_group
elif cl == FL.BITMAP: return fm.add_bitmap
elif cl == FL.BOX: return fm.add_box
elif cl == FL.BROWSER: return fm.add_browser
elif cl == FL.BUTTON: return fm.add_button
elif cl == FL.CHART: return fm.add_chart
elif cl == FL.CHOICE: return fm.add_choice
elif cl == FL.CLOCK: return fm.add_clock
elif cl == FL.COUNTER: return fm.add_counter
elif cl == FL.DIAL: return fm.add_dial
elif cl == FL.FREE: return fm.add_free
elif cl == FL.INPUT: return fm.add_input
elif cl == FL.LIGHTBUTTON: return fm.add_lightbutton
elif cl == FL.MENU: return fm.add_menu
elif cl == FL.POSITIONER: return fm.add_positioner
elif cl == FL.ROUNDBUTTON: return fm.add_roundbutton
elif cl == FL.SLIDER: return fm.add_slider
elif cl == FL.VALSLIDER: return fm.add_valslider
elif cl == FL.TEXT: return fm.add_text
elif cl == FL.TIMER: return fm.add_timer
else:
raise error, 'Unknown object type: %r' % (cl,)
def test():
import time
t0 = time.time()
if len(sys.argv) == 2:
forms = parse_forms(sys.argv[1])
t1 = time.time()
print 'parse time:', 0.001*(t1-t0), 'sec.'
keys = forms.keys()
keys.sort()
for i in keys:
_printform(forms[i])
elif len(sys.argv) == 3:
form = parse_form(sys.argv[1], sys.argv[2])
t1 = time.time()
print 'parse time:', round(t1-t0, 3), 'sec.'
_printform(form)
else:
print 'Usage: test fdfile [form]'
def _printform(form):
f = form[0]
objs = form[1]
print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects
for i in objs:
print ' Obj ', i.Name, ' type ', i.Class, i.Type
print ' Box ', i.Box, ' btype ', i.Boxtype
print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment
print ' cols ', i.Colors
print ' cback ', i.Callback, i.Argument
| Python |
NOERROR = 0
NOCONTEXT = -1
NODISPLAY = -2
NOWINDOW = -3
NOGRAPHICS = -4
NOTTOP = -5
NOVISUAL = -6
BUFSIZE = -7
BADWINDOW = -8
ALREADYBOUND = -100
BINDFAILED = -101
SETFAILED = -102
| Python |
# Convert "arbitrary" image files to rgb files (SGI's image format).
# Input may be compressed.
# The uncompressed file type may be PBM, PGM, PPM, GIF, TIFF, or Sun raster.
# An exception is raised if the file is not of a recognized type.
# Returned filename is either the input filename or a temporary filename;
# in the latter case the caller must ensure that it is removed.
# Other temporary files used are removed by the function.
import os
import tempfile
import pipes
import imghdr
table = {}
t = pipes.Template()
t.append('fromppm $IN $OUT', 'ff')
table['ppm'] = t
t = pipes.Template()
t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--')
t.append('fromppm $IN $OUT', 'ff')
table['pnm'] = t
table['pgm'] = t
table['pbm'] = t
t = pipes.Template()
t.append('fromgif $IN $OUT', 'ff')
table['gif'] = t
t = pipes.Template()
t.append('tifftopnm', '--')
t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--')
t.append('fromppm $IN $OUT', 'ff')
table['tiff'] = t
t = pipes.Template()
t.append('rasttopnm', '--')
t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--')
t.append('fromppm $IN $OUT', 'ff')
table['rast'] = t
t = pipes.Template()
t.append('djpeg', '--')
t.append('(PATH=$PATH:/ufs/guido/bin/sgi; exec pnmtoppm)', '--')
t.append('fromppm $IN $OUT', 'ff')
table['jpeg'] = t
uncompress = pipes.Template()
uncompress.append('uncompress', '--')
class error(Exception):
pass
def torgb(filename):
temps = []
ret = None
try:
ret = _torgb(filename, temps)
finally:
for temp in temps[:]:
if temp != ret:
try:
os.unlink(temp)
except os.error:
pass
temps.remove(temp)
return ret
def _torgb(filename, temps):
if filename[-2:] == '.Z':
(fd, fname) = tempfile.mkstemp()
os.close(fd)
temps.append(fname)
sts = uncompress.copy(filename, fname)
if sts:
raise error, filename + ': uncompress failed'
else:
fname = filename
try:
ftype = imghdr.what(fname)
except IOError, msg:
if type(msg) == type(()) and len(msg) == 2 and \
type(msg[0]) == type(0) and type(msg[1]) == type(''):
msg = msg[1]
if type(msg) is not type(''):
msg = repr(msg)
raise error, filename + ': ' + msg
if ftype == 'rgb':
return fname
if ftype is None or not table.has_key(ftype):
raise error, '%s: unsupported image file type %r' % (filename, ftype)
(fd, temp) = tempfile.mkstemp()
os.close(fd)
sts = table[ftype].copy(fname, temp)
if sts:
raise error, filename + ': conversion to rgb failed'
return temp
| Python |
# Backward compatible module CL.
# All relevant symbols are now defined in the module cl.
try:
from cl import *
except ImportError:
from CL_old import *
else:
del CompressImage
del DecompressImage
del GetAlgorithmName
del OpenCompressor
del OpenDecompressor
del QueryAlgorithms
del QueryMaxHeaderSize
del QueryScheme
del QuerySchemeFromName
del SetDefault
del SetMax
del SetMin
try:
del cvt_type
except NameError:
pass
del error
| Python |
# Constants used by the FORMS library (module fl).
# This corresponds to "forms.h".
# Recommended use: import FL; ... FL.NORMAL_BOX ... etc.
# Alternate use: from FL import *; ... NORMAL_BOX ... etc.
_v20 = 1
_v21 = 1
##import fl
##try:
## _v20 = (fl.get_rgbmode is not None)
##except:
## _v20 = 0
##del fl
NULL = 0
FALSE = 0
TRUE = 1
EVENT = -1
LABEL_SIZE = 64
if _v20:
SHORTCUT_SIZE = 32
PLACE_FREE = 0
PLACE_SIZE = 1
PLACE_ASPECT = 2
PLACE_MOUSE = 3
PLACE_CENTER = 4
PLACE_POSITION = 5
FL_PLACE_FULLSCREEN = 6
FIND_INPUT = 0
FIND_AUTOMATIC = 1
FIND_MOUSE = 2
BEGIN_GROUP = 10000
END_GROUP = 20000
ALIGN_TOP = 0
ALIGN_BOTTOM = 1
ALIGN_LEFT = 2
ALIGN_RIGHT = 3
ALIGN_CENTER = 4
NO_BOX = 0
UP_BOX = 1
DOWN_BOX = 2
FLAT_BOX = 3
BORDER_BOX = 4
SHADOW_BOX = 5
FRAME_BOX = 6
ROUNDED_BOX = 7
RFLAT_BOX = 8
RSHADOW_BOX = 9
TOP_BOUND_COL = 51
LEFT_BOUND_COL = 55
BOT_BOUND_COL = 40
RIGHT_BOUND_COL = 35
COL1 = 47
MCOL = 49
LCOL = 0
BOUND_WIDTH = 3.0
DRAW = 0
PUSH = 1
RELEASE = 2
ENTER = 3
LEAVE = 4
MOUSE = 5
FOCUS = 6
UNFOCUS = 7
KEYBOARD = 8
STEP = 9
MOVE = 10
FONT_NAME = 'Helvetica'
FONT_BOLDNAME = 'Helvetica-Bold'
FONT_ITALICNAME = 'Helvetica-Oblique'
FONT_FIXEDNAME = 'Courier'
FONT_ICONNAME = 'Icon'
SMALL_FONT = 8.0
NORMAL_FONT = 11.0
LARGE_FONT = 20.0
NORMAL_STYLE = 0
BOLD_STYLE = 1
ITALIC_STYLE = 2
FIXED_STYLE = 3
ENGRAVED_STYLE = 4
ICON_STYLE = 5
BITMAP = 3
NORMAL_BITMAP = 0
BITMAP_BOXTYPE = NO_BOX
BITMAP_COL1 = 0
BITMAP_COL2 = COL1
BITMAP_LCOL = LCOL
BITMAP_ALIGN = ALIGN_BOTTOM
BITMAP_MAXSIZE = 128*128
BITMAP_BW = BOUND_WIDTH
BOX = 1
BOX_BOXTYPE = UP_BOX
BOX_COL1 = COL1
BOX_LCOL = LCOL
BOX_ALIGN = ALIGN_CENTER
BOX_BW = BOUND_WIDTH
BROWSER = 71
NORMAL_BROWSER = 0
SELECT_BROWSER = 1
HOLD_BROWSER = 2
MULTI_BROWSER = 3
BROWSER_BOXTYPE = DOWN_BOX
BROWSER_COL1 = COL1
BROWSER_COL2 = 3
BROWSER_LCOL = LCOL
BROWSER_ALIGN = ALIGN_BOTTOM
BROWSER_SLCOL = COL1
BROWSER_BW = BOUND_WIDTH
BROWSER_LINELENGTH = 128
BROWSER_MAXLINE = 512
BUTTON = 11
NORMAL_BUTTON = 0
PUSH_BUTTON = 1
RADIO_BUTTON = 2
HIDDEN_BUTTON = 3
TOUCH_BUTTON = 4
INOUT_BUTTON = 5
RETURN_BUTTON = 6
if _v20:
HIDDEN_RET_BUTTON = 7
BUTTON_BOXTYPE = UP_BOX
BUTTON_COL1 = COL1
BUTTON_COL2 = COL1
BUTTON_LCOL = LCOL
BUTTON_ALIGN = ALIGN_CENTER
BUTTON_MCOL1 = MCOL
BUTTON_MCOL2 = MCOL
BUTTON_BW = BOUND_WIDTH
if _v20:
CHART = 4
BAR_CHART = 0
HORBAR_CHART = 1
LINE_CHART = 2
FILLED_CHART = 3
SPIKE_CHART = 4
PIE_CHART = 5
SPECIALPIE_CHART = 6
CHART_BOXTYPE = BORDER_BOX
CHART_COL1 = COL1
CHART_LCOL = LCOL
CHART_ALIGN = ALIGN_BOTTOM
CHART_BW = BOUND_WIDTH
CHART_MAX = 128
CHOICE = 42
NORMAL_CHOICE = 0
CHOICE_BOXTYPE = DOWN_BOX
CHOICE_COL1 = COL1
CHOICE_COL2 = LCOL
CHOICE_LCOL = LCOL
CHOICE_ALIGN = ALIGN_LEFT
CHOICE_BW = BOUND_WIDTH
CHOICE_MCOL = MCOL
CHOICE_MAXITEMS = 128
CHOICE_MAXSTR = 64
CLOCK = 61
SQUARE_CLOCK = 0
ROUND_CLOCK = 1
CLOCK_BOXTYPE = UP_BOX
CLOCK_COL1 = 37
CLOCK_COL2 = 42
CLOCK_LCOL = LCOL
CLOCK_ALIGN = ALIGN_BOTTOM
CLOCK_TOPCOL = COL1
CLOCK_BW = BOUND_WIDTH
COUNTER = 25
NORMAL_COUNTER = 0
SIMPLE_COUNTER = 1
COUNTER_BOXTYPE = UP_BOX
COUNTER_COL1 = COL1
COUNTER_COL2 = 4
COUNTER_LCOL = LCOL
COUNTER_ALIGN = ALIGN_BOTTOM
if _v20:
COUNTER_BW = BOUND_WIDTH
else:
DEFAULT = 51
RETURN_DEFAULT = 0
ALWAYS_DEFAULT = 1
DIAL = 22
NORMAL_DIAL = 0
LINE_DIAL = 1
DIAL_BOXTYPE = NO_BOX
DIAL_COL1 = COL1
DIAL_COL2 = 37
DIAL_LCOL = LCOL
DIAL_ALIGN = ALIGN_BOTTOM
DIAL_TOPCOL = COL1
DIAL_BW = BOUND_WIDTH
FREE = 101
NORMAL_FREE = 1
SLEEPING_FREE = 2
INPUT_FREE = 3
CONTINUOUS_FREE = 4
ALL_FREE = 5
INPUT = 31
NORMAL_INPUT = 0
if _v20:
FLOAT_INPUT = 1
INT_INPUT = 2
HIDDEN_INPUT = 3
if _v21:
MULTILINE_INPUT = 4
SECRET_INPUT = 5
else:
ALWAYS_INPUT = 1
INPUT_BOXTYPE = DOWN_BOX
INPUT_COL1 = 13
INPUT_COL2 = 5
INPUT_LCOL = LCOL
INPUT_ALIGN = ALIGN_LEFT
INPUT_TCOL = LCOL
INPUT_CCOL = 4
INPUT_BW = BOUND_WIDTH
INPUT_MAX = 128
LIGHTBUTTON = 12
LIGHTBUTTON_BOXTYPE = UP_BOX
LIGHTBUTTON_COL1 = 39
LIGHTBUTTON_COL2 = 3
LIGHTBUTTON_LCOL = LCOL
LIGHTBUTTON_ALIGN = ALIGN_CENTER
LIGHTBUTTON_TOPCOL = COL1
LIGHTBUTTON_MCOL = MCOL
LIGHTBUTTON_BW1 = BOUND_WIDTH
LIGHTBUTTON_BW2 = BOUND_WIDTH/2.0
LIGHTBUTTON_MINSIZE = 12.0
MENU = 41
TOUCH_MENU = 0
PUSH_MENU = 1
MENU_BOXTYPE = BORDER_BOX
MENU_COL1 = 55
MENU_COL2 = 37
MENU_LCOL = LCOL
MENU_ALIGN = ALIGN_CENTER
MENU_BW = BOUND_WIDTH
MENU_MAX = 300
POSITIONER = 23
NORMAL_POSITIONER = 0
POSITIONER_BOXTYPE = DOWN_BOX
POSITIONER_COL1 = COL1
POSITIONER_COL2 = 1
POSITIONER_LCOL = LCOL
POSITIONER_ALIGN = ALIGN_BOTTOM
POSITIONER_BW = BOUND_WIDTH
ROUNDBUTTON = 13
ROUNDBUTTON_BOXTYPE = NO_BOX
ROUNDBUTTON_COL1 = 7
ROUNDBUTTON_COL2 = 3
ROUNDBUTTON_LCOL = LCOL
ROUNDBUTTON_ALIGN = ALIGN_CENTER
ROUNDBUTTON_TOPCOL = COL1
ROUNDBUTTON_MCOL = MCOL
ROUNDBUTTON_BW = BOUND_WIDTH
SLIDER = 21
VALSLIDER = 24
VERT_SLIDER = 0
HOR_SLIDER = 1
VERT_FILL_SLIDER = 2
HOR_FILL_SLIDER = 3
VERT_NICE_SLIDER = 4
HOR_NICE_SLIDER = 5
SLIDER_BOXTYPE = DOWN_BOX
SLIDER_COL1 = COL1
SLIDER_COL2 = COL1
SLIDER_LCOL = LCOL
SLIDER_ALIGN = ALIGN_BOTTOM
SLIDER_BW1 = BOUND_WIDTH
SLIDER_BW2 = BOUND_WIDTH*0.75
SLIDER_FINE = 0.05
SLIDER_WIDTH = 0.08
TEXT = 2
NORMAL_TEXT = 0
TEXT_BOXTYPE = NO_BOX
TEXT_COL1 = COL1
TEXT_LCOL = LCOL
TEXT_ALIGN = ALIGN_LEFT
TEXT_BW = BOUND_WIDTH
TIMER = 62
NORMAL_TIMER = 0
VALUE_TIMER = 1
HIDDEN_TIMER = 2
TIMER_BOXTYPE = DOWN_BOX
TIMER_COL1 = COL1
TIMER_COL2 = 1
TIMER_LCOL = LCOL
TIMER_ALIGN = ALIGN_CENTER
TIMER_BW = BOUND_WIDTH
TIMER_BLINKRATE = 0.2
| Python |
ERROR = 0
NODISC = 1
READY = 2
PLAYING = 3
PAUSED = 4
STILL = 5
AUDIO = 0
PNUM = 1
INDEX = 2
PTIME = 3
ATIME = 4
CATALOG = 5
IDENT = 6
CONTROL = 7
CDDA_DATASIZE = 2352
##CDDA_SUBCODESIZE = (sizeof(struct subcodeQ))
##CDDA_BLOCKSIZE = (sizeof(struct cdframe))
##CDDA_NUMSAMPLES = (CDDA_DATASIZE/2)
##
##CDQ_PREEMP_MASK = 0xd
##CDQ_COPY_MASK = 0xb
##CDQ_DDATA_MASK = 0xd
##CDQ_BROADCAST_MASK = 0x8
##CDQ_PREEMPHASIS = 0x1
##CDQ_COPY_PERMITTED = 0x2
##CDQ_DIGITAL_DATA = 0x4
##CDQ_BROADCAST_USE = 0x8
##
##CDQ_MODE1 = 0x1
##CDQ_MODE2 = 0x2
##CDQ_MODE3 = 0x3
| Python |
#
# cl.h - Compression Library typedefs and prototypes
#
# 01/07/92 Cleanup by Brian Knittel
# 02/18/92 Original Version by Brian Knittel
#
#
# originalFormat parameter values
#
MAX_NUMBER_OF_ORIGINAL_FORMATS = 32
# Audio
MONO = 0
STEREO_INTERLEAVED = 1
# Video
# YUV is defined to be the same thing as YCrCb (luma and two chroma components).
# 422 is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2
# horizontally, packed as U Y1 V Y2 (byte order).
# 422HC is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2
# vertically in addition to horizontally, and is packed the same as
# 422 except that U & V are not valid on the second line.
#
RGB = 0
RGBX = 1
RGBA = 2
RGB332 = 3
GRAYSCALE = 4
Y = 4
YUV = 5
YCbCr = 5
YUV422 = 6 # 4:2:2 sampling
YCbCr422 = 6 # 4:2:2 sampling
YUV422HC = 7 # 4:1:1 sampling
YCbCr422HC = 7 # 4:1:1 sampling
YUV422DC = 7 # 4:1:1 sampling
YCbCr422DC = 7 # 4:1:1 sampling
BEST_FIT = -1
def BytesPerSample(s):
if s in (MONO, YUV):
return 2
elif s == STEREO_INTERLEAVED:
return 4
else:
return 0
def BytesPerPixel(f):
if f in (RGB, YUV):
return 3
elif f in (RGBX, RGBA):
return 4
elif f in (RGB332, GRAYSCALE):
return 1
else:
return 2
def AudioFormatName(f):
if f == MONO:
return 'MONO'
elif f == STEREO_INTERLEAVED:
return 'STEREO_INTERLEAVED'
else:
return 'Not a valid format'
def VideoFormatName(f):
if f == RGB:
return 'RGB'
elif f == RGBX:
return 'RGBX'
elif f == RGBA:
return 'RGBA'
elif f == RGB332:
return 'RGB332'
elif f == GRAYSCALE:
return 'GRAYSCALE'
elif f == YUV:
return 'YUV'
elif f == YUV422:
return 'YUV422'
elif f == YUV422DC:
return 'YUV422DC'
else:
return 'Not a valid format'
MAX_NUMBER_OF_AUDIO_ALGORITHMS = 32
MAX_NUMBER_OF_VIDEO_ALGORITHMS = 32
#
# Algorithm types
#
AUDIO = 0
VIDEO = 1
def AlgorithmNumber(scheme):
return scheme & 0x7fff
def AlgorithmType(scheme):
return (scheme >> 15) & 1
def Algorithm(type, n):
return n | ((type & 1) << 15)
#
# "compressionScheme" argument values
#
UNKNOWN_SCHEME = -1
UNCOMPRESSED_AUDIO = Algorithm(AUDIO, 0)
G711_ULAW = Algorithm(AUDIO, 1)
ULAW = Algorithm(AUDIO, 1)
G711_ALAW = Algorithm(AUDIO, 2)
ALAW = Algorithm(AUDIO, 2)
AWARE_MPEG_AUDIO = Algorithm(AUDIO, 3)
AWARE_MULTIRATE = Algorithm(AUDIO, 4)
UNCOMPRESSED = Algorithm(VIDEO, 0)
UNCOMPRESSED_VIDEO = Algorithm(VIDEO, 0)
RLE = Algorithm(VIDEO, 1)
JPEG = Algorithm(VIDEO, 2)
MPEG_VIDEO = Algorithm(VIDEO, 3)
MVC1 = Algorithm(VIDEO, 4)
RTR = Algorithm(VIDEO, 5)
RTR1 = Algorithm(VIDEO, 5)
#
# Parameters
#
MAX_NUMBER_OF_PARAMS = 256
# Default Parameters
IMAGE_WIDTH = 0
IMAGE_HEIGHT = 1
ORIGINAL_FORMAT = 2
INTERNAL_FORMAT = 3
COMPONENTS = 4
BITS_PER_COMPONENT = 5
FRAME_RATE = 6
COMPRESSION_RATIO = 7
EXACT_COMPRESSION_RATIO = 8
FRAME_BUFFER_SIZE = 9
COMPRESSED_BUFFER_SIZE = 10
BLOCK_SIZE = 11
PREROLL = 12
FRAME_TYPE = 13
ALGORITHM_ID = 14
ALGORITHM_VERSION = 15
ORIENTATION = 16
NUMBER_OF_FRAMES = 17
SPEED = 18
LAST_FRAME_INDEX = 19
NUMBER_OF_PARAMS = 20
# JPEG Specific Parameters
QUALITY_FACTOR = NUMBER_OF_PARAMS + 0
# MPEG Specific Parameters
END_OF_SEQUENCE = NUMBER_OF_PARAMS + 0
# RTR Specific Parameters
QUALITY_LEVEL = NUMBER_OF_PARAMS + 0
ZOOM_X = NUMBER_OF_PARAMS + 1
ZOOM_Y = NUMBER_OF_PARAMS + 2
#
# Parameter value types
#
ENUM_VALUE = 0 # only certain constant values are valid
RANGE_VALUE = 1 # any value in a given range is valid
FLOATING_ENUM_VALUE = 2 # only certain constant floating point values are valid
FLOATING_RANGE_VALUE = 3 # any value in a given floating point range is valid
#
# Algorithm Functionality
#
DECOMPRESSOR = 1
COMPRESSOR = 2
CODEC = 3
#
# Buffer types
#
NONE = 0
FRAME = 1
DATA = 2
#
# Frame types
#
NONE = 0
KEYFRAME = 1
INTRA = 1
PREDICTED = 2
BIDIRECTIONAL = 3
#
# Orientations
#
TOP_DOWN = 0
BOTTOM_UP = 1
#
# SGI Proprietary Algorithm Header Start Code
#
HEADER_START_CODE = 0xc1C0DEC
#
# error codes
#
BAD_NO_BUFFERSPACE = -2 # no space for internal buffers
BAD_PVBUFFER = -3 # param/val buffer doesn't make sense
BAD_BUFFERLENGTH_NEG = -4 # negative buffer length
BAD_BUFFERLENGTH_ODD = -5 # odd length parameter/value buffer
BAD_PARAM = -6 # invalid parameter
BAD_COMPRESSION_SCHEME = -7 # compression scheme parameter invalid
BAD_COMPRESSOR_HANDLE = -8 # compression handle parameter invalid
BAD_COMPRESSOR_HANDLE_POINTER = -9 # compression handle pointer invalid
BAD_BUFFER_HANDLE = -10 # buffer handle invalid
BAD_BUFFER_QUERY_SIZE = -11 # buffer query size too large
JPEG_ERROR = -12 # error from libjpeg
BAD_FRAME_SIZE = -13 # frame size invalid
PARAM_OUT_OF_RANGE = -14 # parameter out of range
ADDED_ALGORITHM_ERROR = -15 # added algorithm had a unique error
BAD_ALGORITHM_TYPE = -16 # bad algorithm type
BAD_ALGORITHM_NAME = -17 # bad algorithm name
BAD_BUFFERING = -18 # bad buffering calls
BUFFER_NOT_CREATED = -19 # buffer not created
BAD_BUFFER_EXISTS = -20 # buffer already created
BAD_INTERNAL_FORMAT = -21 # invalid internal format
BAD_BUFFER_POINTER = -22 # invalid buffer pointer
FRAME_BUFFER_SIZE_ZERO = -23 # frame buffer has zero size
BAD_STREAM_HEADER = -24 # invalid stream header
BAD_LICENSE = -25 # netls license not valid
AWARE_ERROR = -26 # error from libawcmp
| Python |
# This file implements a class which forms an interface to the .cddb
# directory that is maintained by SGI's cdman program.
#
# Usage is as follows:
#
# import readcd
# r = readcd.Readcd()
# c = Cddb(r.gettrackinfo())
#
# Now you can use c.artist, c.title and c.track[trackno] (where trackno
# starts at 1). When the CD is not recognized, all values will be the empty
# string.
# It is also possible to set the above mentioned variables to new values.
# You can then use c.write() to write out the changed values to the
# .cdplayerrc file.
import string, posix, os
_cddbrc = '.cddb'
_DB_ID_NTRACKS = 5
_dbid_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@_=+abcdefghijklmnopqrstuvwxyz'
def _dbid(v):
if v >= len(_dbid_map):
return string.zfill(v, 2)
else:
return _dbid_map[v]
def tochash(toc):
if type(toc) == type(''):
tracklist = []
for i in range(2, len(toc), 4):
tracklist.append((None,
(int(toc[i:i+2]),
int(toc[i+2:i+4]))))
else:
tracklist = toc
ntracks = len(tracklist)
hash = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
if ntracks <= _DB_ID_NTRACKS:
nidtracks = ntracks
else:
nidtracks = _DB_ID_NTRACKS - 1
min = 0
sec = 0
for track in tracklist:
start, length = track
min = min + length[0]
sec = sec + length[1]
min = min + sec / 60
sec = sec % 60
hash = hash + _dbid(min) + _dbid(sec)
for i in range(nidtracks):
start, length = tracklist[i]
hash = hash + _dbid(length[0]) + _dbid(length[1])
return hash
class Cddb:
def __init__(self, tracklist):
if os.environ.has_key('CDDB_PATH'):
path = os.environ['CDDB_PATH']
cddb_path = path.split(',')
else:
home = os.environ['HOME']
cddb_path = [home + '/' + _cddbrc]
self._get_id(tracklist)
for dir in cddb_path:
file = dir + '/' + self.id + '.rdb'
try:
f = open(file, 'r')
self.file = file
break
except IOError:
pass
ntracks = int(self.id[:2], 16)
self.artist = ''
self.title = ''
self.track = [None] + [''] * ntracks
self.trackartist = [None] + [''] * ntracks
self.notes = []
if not hasattr(self, 'file'):
return
import re
reg = re.compile(r'^([^.]*)\.([^:]*):[\t ]+(.*)')
while 1:
line = f.readline()
if not line:
break
match = reg.match(line)
if not match:
print 'syntax error in ' + file
continue
name1, name2, value = match.group(1, 2, 3)
if name1 == 'album':
if name2 == 'artist':
self.artist = value
elif name2 == 'title':
self.title = value
elif name2 == 'toc':
if not self.toc:
self.toc = value
if self.toc != value:
print 'toc\'s don\'t match'
elif name2 == 'notes':
self.notes.append(value)
elif name1[:5] == 'track':
try:
trackno = int(name1[5:])
except strings.atoi_error:
print 'syntax error in ' + file
continue
if trackno > ntracks:
print 'track number %r in file %r out of range' % (trackno, file)
continue
if name2 == 'title':
self.track[trackno] = value
elif name2 == 'artist':
self.trackartist[trackno] = value
f.close()
for i in range(2, len(self.track)):
track = self.track[i]
# if track title starts with `,', use initial part
# of previous track's title
if track and track[0] == ',':
try:
off = self.track[i - 1].index(',')
except ValueError:
pass
else:
self.track[i] = self.track[i-1][:off] \
+ track
def _get_id(self, tracklist):
# fill in self.id and self.toc.
# if the argument is a string ending in .rdb, the part
# upto the suffix is taken as the id.
if type(tracklist) == type(''):
if tracklist[-4:] == '.rdb':
self.id = tracklist[:-4]
self.toc = ''
return
t = []
for i in range(2, len(tracklist), 4):
t.append((None, \
(int(tracklist[i:i+2]), \
int(tracklist[i+2:i+4]))))
tracklist = t
ntracks = len(tracklist)
self.id = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
if ntracks <= _DB_ID_NTRACKS:
nidtracks = ntracks
else:
nidtracks = _DB_ID_NTRACKS - 1
min = 0
sec = 0
for track in tracklist:
start, length = track
min = min + length[0]
sec = sec + length[1]
min = min + sec / 60
sec = sec % 60
self.id = self.id + _dbid(min) + _dbid(sec)
for i in range(nidtracks):
start, length = tracklist[i]
self.id = self.id + _dbid(length[0]) + _dbid(length[1])
self.toc = string.zfill(ntracks, 2)
for track in tracklist:
start, length = track
self.toc = self.toc + string.zfill(length[0], 2) + \
string.zfill(length[1], 2)
def write(self):
import posixpath
if os.environ.has_key('CDDB_WRITE_DIR'):
dir = os.environ['CDDB_WRITE_DIR']
else:
dir = os.environ['HOME'] + '/' + _cddbrc
file = dir + '/' + self.id + '.rdb'
if posixpath.exists(file):
# make backup copy
posix.rename(file, file + '~')
f = open(file, 'w')
f.write('album.title:\t' + self.title + '\n')
f.write('album.artist:\t' + self.artist + '\n')
f.write('album.toc:\t' + self.toc + '\n')
for note in self.notes:
f.write('album.notes:\t' + note + '\n')
prevpref = None
for i in range(1, len(self.track)):
if self.trackartist[i]:
f.write('track%r.artist:\t%s\n' % (i, self.trackartist[i]))
track = self.track[i]
try:
off = track.index(',')
except ValuError:
prevpref = None
else:
if prevpref and track[:off] == prevpref:
track = track[off:]
else:
prevpref = track[:off]
f.write('track%r.title:\t%s\n' % (i, track))
f.close()
| Python |
NULL = 0
FALSE = 0
TRUE = 1
ATTRIBSTACKDEPTH = 10
VPSTACKDEPTH = 8
MATRIXSTACKDEPTH = 32
NAMESTACKDEPTH = 1025
STARTTAG = -2
ENDTAG = -3
BLACK = 0
RED = 1
GREEN = 2
YELLOW = 3
BLUE = 4
MAGENTA = 5
CYAN = 6
WHITE = 7
PUP_CLEAR = 0
PUP_COLOR = 1
PUP_BLACK = 2
PUP_WHITE = 3
NORMALDRAW = 0x010
PUPDRAW = 0x020
OVERDRAW = 0x040
UNDERDRAW = 0x080
CURSORDRAW = 0x100
DUALDRAW = 0x200
PATTERN_16 = 16
PATTERN_32 = 32
PATTERN_64 = 64
PATTERN_16_SIZE = 16
PATTERN_32_SIZE = 64
PATTERN_64_SIZE = 256
SRC_AUTO = 0
SRC_FRONT = 1
SRC_BACK = 2
SRC_ZBUFFER = 3
SRC_PUP = 4
SRC_OVER = 5
SRC_UNDER = 6
SRC_FRAMEGRABBER = 7
BF_ZERO = 0
BF_ONE = 1
BF_DC = 2
BF_SC = 2
BF_MDC = 3
BF_MSC = 3
BF_SA = 4
BF_MSA = 5
BF_DA = 6
BF_MDA = 7
BF_MIN_SA_MDA = 8
AF_NEVER = 0
AF_LESS = 1
AF_EQUAL = 2
AF_LEQUAL = 3
AF_GREATER = 4
AF_NOTEQUAL = 5
AF_GEQUAL = 6
AF_ALWAYS = 7
ZF_NEVER = 0
ZF_LESS = 1
ZF_EQUAL = 2
ZF_LEQUAL = 3
ZF_GREATER = 4
ZF_NOTEQUAL = 5
ZF_GEQUAL = 6
ZF_ALWAYS = 7
ZSRC_DEPTH = 0
ZSRC_COLOR = 1
SMP_OFF = 0x0
SMP_ON = 0x1
SMP_SMOOTHER = 0x2
SML_OFF = 0x0
SML_ON = 0x1
SML_SMOOTHER = 0x2
SML_END_CORRECT = 0x4
PYSM_OFF = 0
PYSM_ON = 1
PYSM_SHRINK = 2
DT_OFF = 0
DT_ON = 1
PUP_NONE = 0
PUP_GREY = 0x1
PUP_BOX = 0x2
PUP_CHECK = 0x4
GLC_OLDPOLYGON = 0
GLC_ZRANGEMAP = 1
GLC_MQUEUERATE = 2
GLC_SOFTATTACH = 3
GLC_MANAGEBG = 4
GLC_SLOWMAPCOLORS = 5
GLC_INPUTCHANGEBUG = 6
GLC_NOBORDERBUG = 7
GLC_SET_VSYNC = 8
GLC_GET_VSYNC = 9
GLC_VSYNC_SLEEP = 10
GLC_COMPATRATE = 15
C16X1 = 0
C16X2 = 1
C32X1 = 2
C32X2 = 3
CCROSS = 4
FLAT = 0
GOURAUD = 1
LO_ZERO = 0x0
LO_AND = 0x1
LO_ANDR = 0x2
LO_SRC = 0x3
LO_ANDI = 0x4
LO_DST = 0x5
LO_XOR = 0x6
LO_OR = 0x7
LO_NOR = 0x8
LO_XNOR = 0x9
LO_NDST = 0xa
LO_ORR = 0xb
LO_NSRC = 0xc
LO_ORI = 0xd
LO_NAND = 0xe
LO_ONE = 0xf
INFOCUSSCRN = -2
ST_KEEP = 0
ST_ZERO = 1
ST_REPLACE = 2
ST_INCR = 3
ST_DECR = 4
ST_INVERT = 5
SF_NEVER = 0
SF_LESS = 1
SF_EQUAL = 2
SF_LEQUAL = 3
SF_GREATER = 4
SF_NOTEQUAL = 5
SF_GEQUAL = 6
SF_ALWAYS = 7
SS_OFF = 0
SS_DEPTH = 1
PYM_FILL = 1
PYM_POINT = 2
PYM_LINE = 3
PYM_HOLLOW = 4
PYM_LINE_FAST = 5
FG_OFF = 0
FG_ON = 1
FG_DEFINE = 2
FG_VTX_EXP = 2
FG_VTX_LIN = 3
FG_PIX_EXP = 4
FG_PIX_LIN = 5
FG_VTX_EXP2 = 6
FG_PIX_EXP2 = 7
PM_SHIFT = 0
PM_EXPAND = 1
PM_C0 = 2
PM_C1 = 3
PM_ADD24 = 4
PM_SIZE = 5
PM_OFFSET = 6
PM_STRIDE = 7
PM_TTOB = 8
PM_RTOL = 9
PM_ZDATA = 10
PM_WARP = 11
PM_RDX = 12
PM_RDY = 13
PM_CDX = 14
PM_CDY = 15
PM_XSTART = 16
PM_YSTART = 17
PM_VO1 = 1000
NAUTO = 0
NNORMALIZE = 1
AC_CLEAR = 0
AC_ACCUMULATE = 1
AC_CLEAR_ACCUMULATE = 2
AC_RETURN = 3
AC_MULT = 4
AC_ADD = 5
CP_OFF = 0
CP_ON = 1
CP_DEFINE = 2
SB_RESET = 0
SB_TRACK = 1
SB_HOLD = 2
RD_FREEZE = 0x00000001
RD_ALPHAONE = 0x00000002
RD_IGNORE_UNDERLAY = 0x00000004
RD_IGNORE_OVERLAY = 0x00000008
RD_IGNORE_PUP = 0x00000010
RD_OFFSCREEN = 0x00000020
GD_XPMAX = 0
GD_YPMAX = 1
GD_XMMAX = 2
GD_YMMAX = 3
GD_ZMIN = 4
GD_ZMAX = 5
GD_BITS_NORM_SNG_RED = 6
GD_BITS_NORM_SNG_GREEN = 7
GD_BITS_NORM_SNG_BLUE = 8
GD_BITS_NORM_DBL_RED = 9
GD_BITS_NORM_DBL_GREEN = 10
GD_BITS_NORM_DBL_BLUE = 11
GD_BITS_NORM_SNG_CMODE = 12
GD_BITS_NORM_DBL_CMODE = 13
GD_BITS_NORM_SNG_MMAP = 14
GD_BITS_NORM_DBL_MMAP = 15
GD_BITS_NORM_ZBUFFER = 16
GD_BITS_OVER_SNG_CMODE = 17
GD_BITS_UNDR_SNG_CMODE = 18
GD_BITS_PUP_SNG_CMODE = 19
GD_BITS_NORM_SNG_ALPHA = 21
GD_BITS_NORM_DBL_ALPHA = 22
GD_BITS_CURSOR = 23
GD_OVERUNDER_SHARED = 24
GD_BLEND = 25
GD_CIFRACT = 26
GD_CROSSHAIR_CINDEX = 27
GD_DITHER = 28
GD_LINESMOOTH_CMODE = 30
GD_LINESMOOTH_RGB = 31
GD_LOGICOP = 33
GD_NSCRNS = 35
GD_NURBS_ORDER = 36
GD_NBLINKS = 37
GD_NVERTEX_POLY = 39
GD_PATSIZE_64 = 40
GD_PNTSMOOTH_CMODE = 41
GD_PNTSMOOTH_RGB = 42
GD_PUP_TO_OVERUNDER = 43
GD_READSOURCE = 44
GD_READSOURCE_ZBUFFER = 48
GD_STEREO = 50
GD_SUBPIXEL_LINE = 51
GD_SUBPIXEL_PNT = 52
GD_SUBPIXEL_POLY = 53
GD_TRIMCURVE_ORDER = 54
GD_WSYS = 55
GD_ZDRAW_GEOM = 57
GD_ZDRAW_PIXELS = 58
GD_SCRNTYPE = 61
GD_TEXTPORT = 62
GD_NMMAPS = 63
GD_FRAMEGRABBER = 64
GD_TIMERHZ = 66
GD_DBBOX = 67
GD_AFUNCTION = 68
GD_ALPHA_OVERUNDER = 69
GD_BITS_ACBUF = 70
GD_BITS_ACBUF_HW = 71
GD_BITS_STENCIL = 72
GD_CLIPPLANES = 73
GD_FOGVERTEX = 74
GD_LIGHTING_TWOSIDE = 76
GD_POLYMODE = 77
GD_POLYSMOOTH = 78
GD_SCRBOX = 79
GD_TEXTURE = 80
GD_FOGPIXEL = 81
GD_TEXTURE_PERSP = 82
GD_MUXPIPES = 83
GD_NOLIMIT = -2
GD_WSYS_NONE = 0
GD_WSYS_4S = 1
GD_SCRNTYPE_WM = 0
GD_SCRNTYPE_NOWM = 1
N_PIXEL_TOLERANCE = 1
N_CULLING = 2
N_DISPLAY = 3
N_ERRORCHECKING = 4
N_SUBDIVISIONS = 5
N_S_STEPS = 6
N_T_STEPS = 7
N_TILES = 8
N_TMP1 = 9
N_TMP2 = 10
N_TMP3 = 11
N_TMP4 = 12
N_TMP5 = 13
N_TMP6 = 14
N_FILL = 1.0
N_OUTLINE_POLY = 2.0
N_OUTLINE_PATCH = 5.0
N_ISOLINE_S = 12.0
N_ST = 0x8
N_STW = 0xd
N_XYZ = 0x4c
N_XYZW = 0x51
N_TEX = 0x88
N_TEXW = 0x8d
N_RGBA = 0xd0
N_RGBAW = 0xd5
N_P2D = 0x8
N_P2DR = 0xd
N_V3D = 0x4c
N_V3DR = 0x51
N_T2D = 0x88
N_T2DR = 0x8d
N_C4D = 0xd0
N_C4DR = 0xd5
LMNULL = 0.0
MSINGLE = 0
MPROJECTION = 1
MVIEWING = 2
MTEXTURE = 3
MAXLIGHTS = 8
MAXRESTRICTIONS = 4
DEFMATERIAL = 0
EMISSION = 1
AMBIENT = 2
DIFFUSE = 3
SPECULAR = 4
SHININESS = 5
COLORINDEXES = 6
ALPHA = 7
DEFLIGHT = 100
LCOLOR = 101
POSITION = 102
SPOTDIRECTION = 103
SPOTLIGHT = 104
DEFLMODEL = 200
LOCALVIEWER = 201
ATTENUATION = 202
ATTENUATION2 = 203
TWOSIDE = 204
MATERIAL = 1000
BACKMATERIAL = 1001
LIGHT0 = 1100
LIGHT1 = 1101
LIGHT2 = 1102
LIGHT3 = 1103
LIGHT4 = 1104
LIGHT5 = 1105
LIGHT6 = 1106
LIGHT7 = 1107
LMODEL = 1200
LMC_COLOR = 0
LMC_EMISSION = 1
LMC_AMBIENT = 2
LMC_DIFFUSE = 3
LMC_SPECULAR = 4
LMC_AD = 5
LMC_NULL = 6
TX_MINFILTER = 0x100
TX_MAGFILTER = 0x200
TX_WRAP = 0x300
TX_WRAP_S = 0x310
TX_WRAP_T = 0x320
TX_TILE = 0x400
TX_BORDER = 0x500
TX_NULL = 0x000
TX_POINT = 0x110
TX_BILINEAR = 0x220
TX_MIPMAP = 0x120
TX_MIPMAP_POINT = 0x121
TX_MIPMAP_LINEAR = 0x122
TX_MIPMAP_BILINEAR = 0x123
TX_MIPMAP_TRILINEAR = 0x124
TX_REPEAT = 0x301
TX_CLAMP = 0x302
TX_SELECT = 0x303
TX_TEXTURE_0 = 0
TV_MODULATE = 0x101
TV_BLEND = 0x102
TV_DECAL = 0x103
TV_COLOR = 0x200
TV_NULL = 0x000
TV_ENV0 = 0
TX_S = 0
TX_T = 1
TG_OFF = 0
TG_ON = 1
TG_CONTOUR = 2
TG_LINEAR = 3
TG_SPHEREMAP = 4
TG_REFRACTMAP = 5
DGLSINK = 0
DGLLOCAL = 1
DGLTSOCKET = 2
DGL4DDN = 3
PUP_CURSOR = PUP_COLOR
FATAL = 1
WARNING = 2
ASK_CONT = 3
ASK_RESTART = 4
XMAXSCREEN = 1279
YMAXSCREEN = 1023
XMAXMEDIUM = 1023
YMAXMEDIUM = 767
XMAX170 = 645
YMAX170 = 484
XMAXPAL = 779
YMAXPAL = 574
| Python |
NTSC_XMAX = 640
NTSC_YMAX = 480
PAL_XMAX = 768
PAL_YMAX = 576
BLANKING_BUFFER_SIZE = 2
MAX_SOURCES = 2
# mode parameter for Bind calls
IN_OFF = 0 # No Video
IN_OVER = 1 # Video over graphics
IN_UNDER = 2 # Video under graphics
IN_REPLACE = 3 # Video replaces entire win
# mode parameters for LoadMap calls. Specifies buffer, always 256 entries
INPUT_COLORMAP = 0 # tuples of 8-bit RGB
CHROMA_KEY_MAP = 1 # tuples of 8-bit RGB
COLOR_SPACE_MAP = 2 # tuples of 8-bit RGB
GAMMA_MAP = 3 # tuples of 24-bit red values
# mode parameters for UseExclusive calls
INPUT = 0
OUTPUT = 1
IN_OUT = 2
# Format constants for the capture routines
RGB8_FRAMES = 0 # noninterleaved 8 bit 3:2:3 RBG fields
RGB32_FRAMES = 1 # 32-bit 8:8:8 RGB frames
YUV411_FRAMES = 2 # interleaved, 8:2:2 YUV format
YUV411_FRAMES_AND_BLANKING_BUFFER = 3
#
# sv.SetParam is passed variable length argument lists,
# consisting of <name, value> pairs. The following
# constants identify argument names.
#
_NAME_BASE = 1000
SOURCE = (_NAME_BASE + 0)
SOURCE1 = 0
SOURCE2 = 1
SOURCE3 = 2
COLOR = (_NAME_BASE + 1)
DEFAULT_COLOR = 0
USER_COLOR = 1
MONO = 2
OUTPUTMODE = (_NAME_BASE + 2)
LIVE_OUTPUT = 0
STILL24_OUT = 1
FREEZE = (_NAME_BASE + 3)
DITHER = (_NAME_BASE + 4)
OUTPUT_FILTER = (_NAME_BASE + 5)
HUE = (_NAME_BASE + 6)
GENLOCK = (_NAME_BASE + 7)
GENLOCK_OFF = 0
GENLOCK_ON = 1
GENLOCK_HOUSE = 2
BROADCAST = (_NAME_BASE + 8)
NTSC = 0
PAL = 1
VIDEO_MODE = (_NAME_BASE + 9)
COMP = 0
SVIDEO = 1
INPUT_BYPASS = (_NAME_BASE + 10)
FIELDDROP = (_NAME_BASE + 11)
SLAVE = (_NAME_BASE + 12)
APERTURE_FACTOR = (_NAME_BASE + 13)
AFACTOR_0 = 0
AFACTOR_QTR = 1
AFACTOR_HLF = 2
AFACTOR_ONE = 3
CORING = (_NAME_BASE + 14)
COR_OFF = 0
COR_1LSB = 1
COR_2LSB = 2
COR_3LSB = 3
APERTURE_BANDPASS = (_NAME_BASE + 15)
ABAND_F0 = 0
ABAND_F1 = 1
ABAND_F2 = 2
ABAND_F3 = 3
PREFILTER = (_NAME_BASE + 16)
CHROMA_TRAP = (_NAME_BASE + 17)
CK_THRESHOLD = (_NAME_BASE + 18)
PAL_SENSITIVITY = (_NAME_BASE + 19)
GAIN_CONTROL = (_NAME_BASE + 20)
GAIN_SLOW = 0
GAIN_MEDIUM = 1
GAIN_FAST = 2
GAIN_FROZEN = 3
AUTO_CKILL = (_NAME_BASE + 21)
VTR_MODE = (_NAME_BASE + 22)
VTR_INPUT = 0
CAMERA_INPUT = 1
LUMA_DELAY = (_NAME_BASE + 23)
VNOISE = (_NAME_BASE + 24)
VNOISE_NORMAL = 0
VNOISE_SEARCH = 1
VNOISE_AUTO = 2
VNOISE_BYPASS = 3
CHCV_PAL = (_NAME_BASE + 25)
CHCV_NTSC = (_NAME_BASE + 26)
CCIR_LEVELS = (_NAME_BASE + 27)
STD_CHROMA = (_NAME_BASE + 28)
DENC_VTBYPASS = (_NAME_BASE + 29)
FAST_TIMECONSTANT = (_NAME_BASE + 30)
GENLOCK_DELAY = (_NAME_BASE + 31)
PHASE_SYNC = (_NAME_BASE + 32)
VIDEO_OUTPUT = (_NAME_BASE + 33)
CHROMA_PHASEOUT = (_NAME_BASE + 34)
CHROMA_CENTER = (_NAME_BASE + 35)
YUV_TO_RGB_INVERT = (_NAME_BASE + 36)
SOURCE1_BROADCAST = (_NAME_BASE + 37)
SOURCE1_MODE = (_NAME_BASE + 38)
SOURCE2_BROADCAST = (_NAME_BASE + 39)
SOURCE2_MODE = (_NAME_BASE + 40)
SOURCE3_BROADCAST = (_NAME_BASE + 41)
SOURCE3_MODE = (_NAME_BASE + 42)
SIGNAL_STD = (_NAME_BASE + 43)
NOSIGNAL = 2
SIGNAL_COLOR = (_NAME_BASE + 44)
| Python |
# Class interface to the CD module.
import cd, CD
class Error(Exception):
pass
class _Stop(Exception):
pass
def _doatime(self, cb_type, data):
if ((data[0] * 60) + data[1]) * 75 + data[2] > self.end:
## print 'done with list entry', repr(self.listindex)
raise _Stop
func, arg = self.callbacks[cb_type]
if func:
func(arg, cb_type, data)
def _dopnum(self, cb_type, data):
if data > self.end:
## print 'done with list entry', repr(self.listindex)
raise _Stop
func, arg = self.callbacks[cb_type]
if func:
func(arg, cb_type, data)
class Readcd:
def __init__(self, *arg):
if len(arg) == 0:
self.player = cd.open()
elif len(arg) == 1:
self.player = cd.open(arg[0])
elif len(arg) == 2:
self.player = cd.open(arg[0], arg[1])
else:
raise Error, 'bad __init__ call'
self.list = []
self.callbacks = [(None, None)] * 8
self.parser = cd.createparser()
self.playing = 0
self.end = 0
self.status = None
self.trackinfo = None
def eject(self):
self.player.eject()
self.list = []
self.end = 0
self.listindex = 0
self.status = None
self.trackinfo = None
if self.playing:
## print 'stop playing from eject'
raise _Stop
def pmsf2msf(self, track, min, sec, frame):
if not self.status:
self.cachestatus()
if track < self.status[5] or track > self.status[6]:
raise Error, 'track number out of range'
if not self.trackinfo:
self.cacheinfo()
start, total = self.trackinfo[track]
start = ((start[0] * 60) + start[1]) * 75 + start[2]
total = ((total[0] * 60) + total[1]) * 75 + total[2]
block = ((min * 60) + sec) * 75 + frame
if block > total:
raise Error, 'out of range'
block = start + block
min, block = divmod(block, 75*60)
sec, frame = divmod(block, 75)
return min, sec, frame
def reset(self):
self.list = []
def appendtrack(self, track):
self.appendstretch(track, track)
def appendstretch(self, start, end):
if not self.status:
self.cachestatus()
if not start:
start = 1
if not end:
end = self.status[6]
if type(end) == type(0):
if end < self.status[5] or end > self.status[6]:
raise Error, 'range error'
else:
l = len(end)
if l == 4:
prog, min, sec, frame = end
if prog < self.status[5] or prog > self.status[6]:
raise Error, 'range error'
end = self.pmsf2msf(prog, min, sec, frame)
elif l != 3:
raise Error, 'syntax error'
if type(start) == type(0):
if start < self.status[5] or start > self.status[6]:
raise Error, 'range error'
if len(self.list) > 0:
s, e = self.list[-1]
if type(e) == type(0):
if start == e+1:
start = s
del self.list[-1]
else:
l = len(start)
if l == 4:
prog, min, sec, frame = start
if prog < self.status[5] or prog > self.status[6]:
raise Error, 'range error'
start = self.pmsf2msf(prog, min, sec, frame)
elif l != 3:
raise Error, 'syntax error'
self.list.append((start, end))
def settracks(self, list):
self.list = []
for track in list:
self.appendtrack(track)
def setcallback(self, cb_type, func, arg):
if cb_type < 0 or cb_type >= 8:
raise Error, 'type out of range'
self.callbacks[cb_type] = (func, arg)
if self.playing:
start, end = self.list[self.listindex]
if type(end) == type(0):
if cb_type != CD.PNUM:
self.parser.setcallback(cb_type, func, arg)
else:
if cb_type != CD.ATIME:
self.parser.setcallback(cb_type, func, arg)
def removecallback(self, cb_type):
if cb_type < 0 or cb_type >= 8:
raise Error, 'type out of range'
self.callbacks[cb_type] = (None, None)
if self.playing:
start, end = self.list[self.listindex]
if type(end) == type(0):
if cb_type != CD.PNUM:
self.parser.removecallback(cb_type)
else:
if cb_type != CD.ATIME:
self.parser.removecallback(cb_type)
def gettrackinfo(self, *arg):
if not self.status:
self.cachestatus()
if not self.trackinfo:
self.cacheinfo()
if len(arg) == 0:
return self.trackinfo[self.status[5]:self.status[6]+1]
result = []
for i in arg:
if i < self.status[5] or i > self.status[6]:
raise Error, 'range error'
result.append(self.trackinfo[i])
return result
def cacheinfo(self):
if not self.status:
self.cachestatus()
self.trackinfo = []
for i in range(self.status[5]):
self.trackinfo.append(None)
for i in range(self.status[5], self.status[6]+1):
self.trackinfo.append(self.player.gettrackinfo(i))
def cachestatus(self):
self.status = self.player.getstatus()
if self.status[0] == CD.NODISC:
self.status = None
raise Error, 'no disc in player'
def getstatus(self):
return self.player.getstatus()
def play(self):
if not self.status:
self.cachestatus()
size = self.player.bestreadsize()
self.listindex = 0
self.playing = 0
for i in range(8):
func, arg = self.callbacks[i]
if func:
self.parser.setcallback(i, func, arg)
else:
self.parser.removecallback(i)
if len(self.list) == 0:
for i in range(self.status[5], self.status[6]+1):
self.appendtrack(i)
try:
while 1:
if not self.playing:
if self.listindex >= len(self.list):
return
start, end = self.list[self.listindex]
if type(start) == type(0):
dummy = self.player.seektrack(
start)
else:
min, sec, frame = start
dummy = self.player.seek(
min, sec, frame)
if type(end) == type(0):
self.parser.setcallback(
CD.PNUM, _dopnum, self)
self.end = end
func, arg = \
self.callbacks[CD.ATIME]
if func:
self.parser.setcallback(CD.ATIME, func, arg)
else:
self.parser.removecallback(CD.ATIME)
else:
min, sec, frame = end
self.parser.setcallback(
CD.ATIME, _doatime,
self)
self.end = (min * 60 + sec) * \
75 + frame
func, arg = \
self.callbacks[CD.PNUM]
if func:
self.parser.setcallback(CD.PNUM, func, arg)
else:
self.parser.removecallback(CD.PNUM)
self.playing = 1
data = self.player.readda(size)
if data == '':
self.playing = 0
self.listindex = self.listindex + 1
continue
try:
self.parser.parseframe(data)
except _Stop:
self.playing = 0
self.listindex = self.listindex + 1
finally:
self.playing = 0
| Python |
# Module 'panel'
#
# Support for the Panel library.
# Uses built-in module 'pnl'.
# Applications should use 'panel.function' instead of 'pnl.function';
# most 'pnl' functions are transparently exported by 'panel',
# but dopanel() is overridden and you have to use this version
# if you want to use callbacks.
import pnl
debug = 0
# Test if an object is a list.
#
def is_list(x):
return type(x) == type([])
# Reverse a list.
#
def reverse(list):
res = []
for item in list:
res.insert(0, item)
return res
# Get an attribute of a list, which may itself be another list.
# Don't use 'prop' for name.
#
def getattrlist(list, name):
for item in list:
if item and is_list(item) and item[0] == name:
return item[1:]
return []
# Get a property of a list, which may itself be another list.
#
def getproplist(list, name):
for item in list:
if item and is_list(item) and item[0] == 'prop':
if len(item) > 1 and item[1] == name:
return item[2:]
return []
# Test if an actuator description contains the property 'end-of-group'
#
def is_endgroup(list):
x = getproplist(list, 'end-of-group')
return (x and x[0] == '#t')
# Neatly display an actuator definition given as S-expression
# the prefix string is printed before each line.
#
def show_actuator(prefix, a):
for item in a:
if not is_list(item):
print prefix, item
elif item and item[0] == 'al':
print prefix, 'Subactuator list:'
for a in item[1:]:
show_actuator(prefix + ' ', a)
elif len(item) == 2:
print prefix, item[0], '=>', item[1]
elif len(item) == 3 and item[0] == 'prop':
print prefix, 'Prop', item[1], '=>',
print item[2]
else:
print prefix, '?', item
# Neatly display a panel.
#
def show_panel(prefix, p):
for item in p:
if not is_list(item):
print prefix, item
elif item and item[0] == 'al':
print prefix, 'Actuator list:'
for a in item[1:]:
show_actuator(prefix + ' ', a)
elif len(item) == 2:
print prefix, item[0], '=>', item[1]
elif len(item) == 3 and item[0] == 'prop':
print prefix, 'Prop', item[1], '=>',
print item[2]
else:
print prefix, '?', item
# Exception raised by build_actuator or build_panel.
#
panel_error = 'panel error'
# Dummy callback used to initialize the callbacks.
#
def dummy_callback(arg):
pass
# Assign attributes to members of the target.
# Attribute names in exclist are ignored.
# The member name is the attribute name prefixed with the prefix.
#
def assign_members(target, attrlist, exclist, prefix):
for item in attrlist:
if is_list(item) and len(item) == 2 and item[0] not in exclist:
name, value = item[0], item[1]
ok = 1
if value[0] in '-0123456789':
value = eval(value)
elif value[0] == '"':
value = value[1:-1]
elif value == 'move-then-resize':
# Strange default set by Panel Editor...
ok = 0
else:
print 'unknown value', value, 'for', name
ok = 0
if ok:
lhs = 'target.' + prefix + name
stmt = lhs + '=' + repr(value)
if debug: print 'exec', stmt
try:
exec stmt + '\n'
except KeyboardInterrupt: # Don't catch this!
raise KeyboardInterrupt
except:
print 'assign failed:', stmt
# Build a real actuator from an actuator description.
# Return a pair (actuator, name).
#
def build_actuator(descr):
namelist = getattrlist(descr, 'name')
if namelist:
# Assume it is a string
actuatorname = namelist[0][1:-1]
else:
actuatorname = ''
type = descr[0]
if type[:4] == 'pnl_': type = type[4:]
act = pnl.mkact(type)
act.downfunc = act.activefunc = act.upfunc = dummy_callback
#
assign_members(act, descr[1:], ['al', 'data', 'name'], '')
#
# Treat actuator-specific data
#
datalist = getattrlist(descr, 'data')
prefix = ''
if type[-4:] == 'puck':
prefix = 'puck_'
elif type == 'mouse':
prefix = 'mouse_'
assign_members(act, datalist, [], prefix)
#
return act, actuatorname
# Build all sub-actuators and add them to the super-actuator.
# The super-actuator must already have been added to the panel.
# Sub-actuators with defined names are added as members to the panel
# so they can be referenced as p.name.
#
# Note: I have no idea how panel.endgroup() works when applied
# to a sub-actuator.
#
def build_subactuators(panel, super_act, al):
#
# This is nearly the same loop as below in build_panel(),
# except a call is made to addsubact() instead of addact().
#
for a in al:
act, name = build_actuator(a)
act.addsubact(super_act)
if name:
stmt = 'panel.' + name + ' = act'
if debug: print 'exec', stmt
exec stmt + '\n'
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')
if sub_al:
build_subactuators(panel, act, sub_al)
#
# Fix the actuator to which whe just added subactuators.
# This can't hurt (I hope) and is needed for the scroll actuator.
#
super_act.fixact()
# Build a real panel from a panel definition.
# Return a panel object p, where for each named actuator a, p.name is a
# reference to a.
#
def build_panel(descr):
#
# Sanity check
#
if (not descr) or descr[0] != 'panel':
raise panel_error, 'panel description must start with "panel"'
#
if debug: show_panel('', descr)
#
# Create an empty panel
#
panel = pnl.mkpanel()
#
# Assign panel attributes
#
assign_members(panel, descr[1:], ['al'], '')
#
# Look for actuator list
#
al = getattrlist(descr, 'al')
#
# The order in which actuators are created is important
# because of the endgroup() operator.
# Unfortunately the Panel Editor outputs the actuator list
# in reverse order, so we reverse it here.
#
al = reverse(al)
#
for a in al:
act, name = build_actuator(a)
act.addact(panel)
if name:
stmt = 'panel.' + name + ' = act'
exec stmt + '\n'
if is_endgroup(a):
panel.endgroup()
sub_al = getattrlist(a, 'al')
if sub_al:
build_subactuators(panel, act, sub_al)
#
return panel
# Wrapper around pnl.dopanel() which calls call-back functions.
#
def my_dopanel():
# Extract only the first 4 elements to allow for future expansion
a, down, active, up = pnl.dopanel()[:4]
if down:
down.downfunc(down)
if active:
active.activefunc(active)
if up:
up.upfunc(up)
return a
# Create one or more panels from a description file (S-expressions)
# generated by the Panel Editor.
#
def defpanellist(file):
import panelparser
descrlist = panelparser.parse_file(open(file, 'r'))
panellist = []
for descr in descrlist:
panellist.append(build_panel(descr))
return panellist
# Import everything from built-in method pnl, so the user can always
# use panel.foo() instead of pnl.foo().
# This gives *no* performance penalty once this module is imported.
#
from pnl import * # for export
dopanel = my_dopanel # override pnl.dopanel
| Python |
NULLDEV = 0
BUTOFFSET = 1
VALOFFSET = 256
PSEUDOFFSET = 512
BUT2OFFSET = 3840
TIMOFFSET = 515
XKBDOFFSET = 143
BUTCOUNT = 255
VALCOUNT = 256
TIMCOUNT = 4
XKBDCOUNT = 28
USERBUTOFFSET = 4096
USERVALOFFSET = 12288
USERPSEUDOFFSET = 16384
BUT0 = 1
BUT1 = 2
BUT2 = 3
BUT3 = 4
BUT4 = 5
BUT5 = 6
BUT6 = 7
BUT7 = 8
BUT8 = 9
BUT9 = 10
BUT10 = 11
BUT11 = 12
BUT12 = 13
BUT13 = 14
BUT14 = 15
BUT15 = 16
BUT16 = 17
BUT17 = 18
BUT18 = 19
BUT19 = 20
BUT20 = 21
BUT21 = 22
BUT22 = 23
BUT23 = 24
BUT24 = 25
BUT25 = 26
BUT26 = 27
BUT27 = 28
BUT28 = 29
BUT29 = 30
BUT30 = 31
BUT31 = 32
BUT32 = 33
BUT33 = 34
BUT34 = 35
BUT35 = 36
BUT36 = 37
BUT37 = 38
BUT38 = 39
BUT39 = 40
BUT40 = 41
BUT41 = 42
BUT42 = 43
BUT43 = 44
BUT44 = 45
BUT45 = 46
BUT46 = 47
BUT47 = 48
BUT48 = 49
BUT49 = 50
BUT50 = 51
BUT51 = 52
BUT52 = 53
BUT53 = 54
BUT54 = 55
BUT55 = 56
BUT56 = 57
BUT57 = 58
BUT58 = 59
BUT59 = 60
BUT60 = 61
BUT61 = 62
BUT62 = 63
BUT63 = 64
BUT64 = 65
BUT65 = 66
BUT66 = 67
BUT67 = 68
BUT68 = 69
BUT69 = 70
BUT70 = 71
BUT71 = 72
BUT72 = 73
BUT73 = 74
BUT74 = 75
BUT75 = 76
BUT76 = 77
BUT77 = 78
BUT78 = 79
BUT79 = 80
BUT80 = 81
BUT81 = 82
BUT82 = 83
MAXKBDBUT = 83
BUT100 = 101
BUT101 = 102
BUT102 = 103
BUT103 = 104
BUT104 = 105
BUT105 = 106
BUT106 = 107
BUT107 = 108
BUT108 = 109
BUT109 = 110
BUT110 = 111
BUT111 = 112
BUT112 = 113
BUT113 = 114
BUT114 = 115
BUT115 = 116
BUT116 = 117
BUT117 = 118
BUT118 = 119
BUT119 = 120
BUT120 = 121
BUT121 = 122
BUT122 = 123
BUT123 = 124
BUT124 = 125
BUT125 = 126
BUT126 = 127
BUT127 = 128
BUT128 = 129
BUT129 = 130
BUT130 = 131
BUT131 = 132
BUT132 = 133
BUT133 = 134
BUT134 = 135
BUT135 = 136
BUT136 = 137
BUT137 = 138
BUT138 = 139
BUT139 = 140
BUT140 = 141
BUT141 = 142
BUT142 = 143
BUT143 = 144
BUT144 = 145
BUT145 = 146
BUT146 = 147
BUT147 = 148
BUT148 = 149
BUT149 = 150
BUT150 = 151
BUT151 = 152
BUT152 = 153
BUT153 = 154
BUT154 = 155
BUT155 = 156
BUT156 = 157
BUT157 = 158
BUT158 = 159
BUT159 = 160
BUT160 = 161
BUT161 = 162
BUT162 = 163
BUT163 = 164
BUT164 = 165
BUT165 = 166
BUT166 = 167
BUT167 = 168
BUT168 = 169
BUT181 = 182
BUT182 = 183
BUT183 = 184
BUT184 = 185
BUT185 = 186
BUT186 = 187
BUT187 = 188
BUT188 = 189
BUT189 = 190
MOUSE1 = 101
MOUSE2 = 102
MOUSE3 = 103
LEFTMOUSE = 103
MIDDLEMOUSE = 102
RIGHTMOUSE = 101
LPENBUT = 104
BPAD0 = 105
BPAD1 = 106
BPAD2 = 107
BPAD3 = 108
LPENVALID = 109
SWBASE = 111
SW0 = 111
SW1 = 112
SW2 = 113
SW3 = 114
SW4 = 115
SW5 = 116
SW6 = 117
SW7 = 118
SW8 = 119
SW9 = 120
SW10 = 121
SW11 = 122
SW12 = 123
SW13 = 124
SW14 = 125
SW15 = 126
SW16 = 127
SW17 = 128
SW18 = 129
SW19 = 130
SW20 = 131
SW21 = 132
SW22 = 133
SW23 = 134
SW24 = 135
SW25 = 136
SW26 = 137
SW27 = 138
SW28 = 139
SW29 = 140
SW30 = 141
SW31 = 142
SBBASE = 182
SBPICK = 182
SBBUT1 = 183
SBBUT2 = 184
SBBUT3 = 185
SBBUT4 = 186
SBBUT5 = 187
SBBUT6 = 188
SBBUT7 = 189
SBBUT8 = 190
AKEY = 11
BKEY = 36
CKEY = 28
DKEY = 18
EKEY = 17
FKEY = 19
GKEY = 26
HKEY = 27
IKEY = 40
JKEY = 34
KKEY = 35
LKEY = 42
MKEY = 44
NKEY = 37
OKEY = 41
PKEY = 48
QKEY = 10
RKEY = 24
SKEY = 12
TKEY = 25
UKEY = 33
VKEY = 29
WKEY = 16
XKEY = 21
YKEY = 32
ZKEY = 20
ZEROKEY = 46
ONEKEY = 8
TWOKEY = 14
THREEKEY = 15
FOURKEY = 22
FIVEKEY = 23
SIXKEY = 30
SEVENKEY = 31
EIGHTKEY = 38
NINEKEY = 39
BREAKKEY = 1
SETUPKEY = 2
CTRLKEY = 3
LEFTCTRLKEY = CTRLKEY
CAPSLOCKKEY = 4
RIGHTSHIFTKEY = 5
LEFTSHIFTKEY = 6
NOSCRLKEY = 13
ESCKEY = 7
TABKEY = 9
RETKEY = 51
SPACEKEY = 83
LINEFEEDKEY = 60
BACKSPACEKEY = 61
DELKEY = 62
SEMICOLONKEY = 43
PERIODKEY = 52
COMMAKEY = 45
QUOTEKEY = 50
ACCENTGRAVEKEY = 55
MINUSKEY = 47
VIRGULEKEY = 53
BACKSLASHKEY = 57
EQUALKEY = 54
LEFTBRACKETKEY = 49
RIGHTBRACKETKEY = 56
LEFTARROWKEY = 73
DOWNARROWKEY = 74
RIGHTARROWKEY = 80
UPARROWKEY = 81
PAD0 = 59
PAD1 = 58
PAD2 = 64
PAD3 = 65
PAD4 = 63
PAD5 = 69
PAD6 = 70
PAD7 = 67
PAD8 = 68
PAD9 = 75
PADPF1 = 72
PADPF2 = 71
PADPF3 = 79
PADPF4 = 78
PADPERIOD = 66
PADMINUS = 76
PADCOMMA = 77
PADENTER = 82
LEFTALTKEY = 143
RIGHTALTKEY = 144
RIGHTCTRLKEY = 145
F1KEY = 146
F2KEY = 147
F3KEY = 148
F4KEY = 149
F5KEY = 150
F6KEY = 151
F7KEY = 152
F8KEY = 153
F9KEY = 154
F10KEY = 155
F11KEY = 156
F12KEY = 157
PRINTSCREENKEY = 158
SCROLLLOCKKEY = 159
PAUSEKEY = 160
INSERTKEY = 161
HOMEKEY = 162
PAGEUPKEY = 163
ENDKEY = 164
PAGEDOWNKEY = 165
NUMLOCKKEY = 166
PADVIRGULEKEY = 167
PADASTERKEY = 168
PADPLUSKEY = 169
SGIRESERVED = 256
DIAL0 = 257
DIAL1 = 258
DIAL2 = 259
DIAL3 = 260
DIAL4 = 261
DIAL5 = 262
DIAL6 = 263
DIAL7 = 264
DIAL8 = 265
MOUSEX = 266
MOUSEY = 267
LPENX = 268
LPENY = 269
BPADX = 270
BPADY = 271
CURSORX = 272
CURSORY = 273
GHOSTX = 274
GHOSTY = 275
SBTX = 276
SBTY = 277
SBTZ = 278
SBRX = 279
SBRY = 280
SBRZ = 281
SBPERIOD = 282
TIMER0 = 515
TIMER1 = 516
TIMER2 = 517
TIMER3 = 518
KEYBD = 513
RAWKEYBD = 514
VALMARK = 523
REDRAW = 528
INPUTCHANGE = 534
QFULL = 535
QREADERROR = 538
WINFREEZE = 539
WINTHAW = 540
REDRAWICONIC = 541
WINQUIT = 542
DEPTHCHANGE = 543
WINSHUT = 546
DRAWOVERLAY = 547
VIDEO = 548
MENUBUTTON = RIGHTMOUSE
WINCLOSE = 537
KEYBDFNAMES = 544
KEYBDFSTRINGS = 545
MAXSGIDEVICE = 20000
GERROR = 524
WMSEND = 529
WMREPLY = 530
WMGFCLOSE = 531
WMTXCLOSE = 532
MODECHANGE = 533
PIECECHANGE = 536
| Python |
RATE_48000 = 48000
RATE_44100 = 44100
RATE_32000 = 32000
RATE_22050 = 22050
RATE_16000 = 16000
RATE_11025 = 11025
RATE_8000 = 8000
SAMPFMT_TWOSCOMP= 1
SAMPFMT_FLOAT = 32
SAMPFMT_DOUBLE = 64
SAMPLE_8 = 1
SAMPLE_16 = 2
# SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits
SAMPLE_24 = 4
MONO = 1
STEREO = 2
QUADRO = 4 # 4CHANNEL is not a legal Python name
INPUT_LINE = 0
INPUT_MIC = 1
INPUT_DIGITAL = 2
MONITOR_OFF = 0
MONITOR_ON = 1
ERROR_NUMBER = 0
ERROR_TYPE = 1
ERROR_LOCATION_LSP = 2
ERROR_LOCATION_MSP = 3
ERROR_LENGTH = 4
ERROR_INPUT_UNDERFLOW = 0
ERROR_OUTPUT_OVERFLOW = 1
# These seem to be not supported anymore:
##HOLD, RELEASE = 0, 1
##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3
DEFAULT_DEVICE = 1
INPUT_SOURCE = 0
LEFT_INPUT_ATTEN = 1
RIGHT_INPUT_ATTEN = 2
INPUT_RATE = 3
OUTPUT_RATE = 4
LEFT_SPEAKER_GAIN = 5
RIGHT_SPEAKER_GAIN = 6
INPUT_COUNT = 7
OUTPUT_COUNT = 8
UNUSED_COUNT = 9
SYNC_INPUT_TO_AES = 10
SYNC_OUTPUT_TO_AES = 11
MONITOR_CTL = 12
LEFT_MONITOR_ATTEN = 13
RIGHT_MONITOR_ATTEN = 14
ENUM_VALUE = 0 # only certain values are valid
RANGE_VALUE = 1 # any value in range is valid
| Python |
# Module 'parser'
#
# Parse S-expressions output by the Panel Editor
# (which is written in Scheme so it can't help writing S-expressions).
#
# See notes at end of file.
whitespace = ' \t\n'
operators = '()\''
separators = operators + whitespace + ';' + '"'
# Tokenize a string.
# Return a list of tokens (strings).
#
def tokenize_string(s):
tokens = []
while s:
c = s[:1]
if c in whitespace:
s = s[1:]
elif c == ';':
s = ''
elif c == '"':
n = len(s)
i = 1
while i < n:
c = s[i]
i = i+1
if c == '"': break
if c == '\\': i = i+1
tokens.append(s[:i])
s = s[i:]
elif c in operators:
tokens.append(c)
s = s[1:]
else:
n = len(s)
i = 1
while i < n:
if s[i] in separators: break
i = i+1
tokens.append(s[:i])
s = s[i:]
return tokens
# Tokenize a whole file (given as file object, not as file name).
# Return a list of tokens (strings).
#
def tokenize_file(fp):
tokens = []
while 1:
line = fp.readline()
if not line: break
tokens = tokens + tokenize_string(line)
return tokens
# Exception raised by parse_exr.
#
syntax_error = 'syntax error'
# Parse an S-expression.
# Input is a list of tokens as returned by tokenize_*().
# Return a pair (expr, tokens)
# where expr is a list representing the s-expression,
# and tokens contains the remaining tokens.
# May raise syntax_error.
#
def parse_expr(tokens):
if (not tokens) or tokens[0] != '(':
raise syntax_error, 'expected "("'
tokens = tokens[1:]
expr = []
while 1:
if not tokens:
raise syntax_error, 'missing ")"'
if tokens[0] == ')':
return expr, tokens[1:]
elif tokens[0] == '(':
subexpr, tokens = parse_expr(tokens)
expr.append(subexpr)
else:
expr.append(tokens[0])
tokens = tokens[1:]
# Parse a file (given as file object, not as file name).
# Return a list of parsed S-expressions found at the top level.
#
def parse_file(fp):
tokens = tokenize_file(fp)
exprlist = []
while tokens:
expr, tokens = parse_expr(tokens)
exprlist.append(expr)
return exprlist
# EXAMPLE:
#
# The input
# '(hip (hop hur-ray))'
#
# passed to tokenize_string() returns the token list
# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')']
#
# When this is passed to parse_expr() it returns the expression
# ['hip', ['hop', 'hur-ray']]
# plus an empty token list (because there are no tokens left.
#
# When a file containing the example is passed to parse_file() it returns
# a list whose only element is the output of parse_expr() above:
# [['hip', ['hop', 'hur-ray']]]
# TOKENIZING:
#
# Comments start with semicolon (;) and continue till the end of the line.
#
# Tokens are separated by whitespace, except the following characters
# always form a separate token (outside strings):
# ( ) '
# Strings are enclosed in double quotes (") and backslash (\) is used
# as escape character in strings.
| Python |
"""A dumb and slow but simple dbm clone.
For database spam, spam.dir contains the index (a text file),
spam.bak *may* contain a backup of the index (also a text file),
while spam.dat contains the data (a binary file).
XXX TO DO:
- seems to contain a bug when updating...
- reclaim free space (currently, space once occupied by deleted or expanded
items is never reused)
- support concurrent access (currently, if two processes take turns making
updates, they can mess up the index)
- support efficient access to large databases (currently, the whole index
is read when the database is opened, and some updates rewrite the whole index)
- support opening for read-only (flag = 'm')
"""
import os as _os
import __builtin__
import UserDict
_open = __builtin__.open
_BLOCKSIZE = 512
error = IOError # For anydbm
class _Database(UserDict.DictMixin):
# The on-disk directory and data files can remain in mutually
# inconsistent states for an arbitrarily long time (see comments
# at the end of __setitem__). This is only repaired when _commit()
# gets called. One place _commit() gets called is from __del__(),
# and if that occurs at program shutdown time, module globals may
# already have gotten rebound to None. Since it's crucial that
# _commit() finish successfully, we can't ignore shutdown races
# here, and _commit() must not reference any globals.
_os = _os # for _commit()
_open = _open # for _commit()
def __init__(self, filebasename, mode):
self._mode = mode
# The directory file is a text file. Each line looks like
# "%r, (%d, %d)\n" % (key, pos, siz)
# where key is the string key, pos is the offset into the dat
# file of the associated value's first byte, and siz is the number
# of bytes in the associated value.
self._dirfile = filebasename + _os.extsep + 'dir'
# The data file is a binary file pointed into by the directory
# file, and holds the values associated with keys. Each value
# begins at a _BLOCKSIZE-aligned byte offset, and is a raw
# binary 8-bit string value.
self._datfile = filebasename + _os.extsep + 'dat'
self._bakfile = filebasename + _os.extsep + 'bak'
# The index is an in-memory dict, mirroring the directory file.
self._index = None # maps keys to (pos, siz) pairs
# Mod by Jack: create data file if needed
try:
f = _open(self._datfile, 'r')
except IOError:
f = _open(self._datfile, 'w', self._mode)
f.close()
self._update()
# Read directory file into the in-memory index dict.
def _update(self):
self._index = {}
try:
f = _open(self._dirfile)
except IOError:
pass
else:
for line in f:
key, pos_and_siz_pair = eval(line)
self._index[key] = pos_and_siz_pair
f.close()
# Write the index dict to the directory file. The original directory
# file (if any) is renamed with a .bak extension first. If a .bak
# file currently exists, it's deleted.
def _commit(self):
# CAUTION: It's vital that _commit() succeed, and _commit() can
# be called from __del__(). Therefore we must never reference a
# global in this routine.
if self._index is None:
return # nothing to do
try:
self._os.unlink(self._bakfile)
except self._os.error:
pass
try:
self._os.rename(self._dirfile, self._bakfile)
except self._os.error:
pass
f = self._open(self._dirfile, 'w', self._mode)
for key, pos_and_siz_pair in self._index.iteritems():
f.write("%r, %r\n" % (key, pos_and_siz_pair))
f.close()
sync = _commit
def __getitem__(self, key):
pos, siz = self._index[key] # may raise KeyError
f = _open(self._datfile, 'rb')
f.seek(pos)
dat = f.read(siz)
f.close()
return dat
# Append val to the data file, starting at a _BLOCKSIZE-aligned
# offset. The data file is first padded with NUL bytes (if needed)
# to get to an aligned offset. Return pair
# (starting offset of val, len(val))
def _addval(self, val):
f = _open(self._datfile, 'rb+')
f.seek(0, 2)
pos = int(f.tell())
npos = ((pos + _BLOCKSIZE - 1) // _BLOCKSIZE) * _BLOCKSIZE
f.write('\0'*(npos-pos))
pos = npos
f.write(val)
f.close()
return (pos, len(val))
# Write val to the data file, starting at offset pos. The caller
# is responsible for ensuring that there's enough room starting at
# pos to hold val, without overwriting some other value. Return
# pair (pos, len(val)).
def _setval(self, pos, val):
f = _open(self._datfile, 'rb+')
f.seek(pos)
f.write(val)
f.close()
return (pos, len(val))
# key is a new key whose associated value starts in the data file
# at offset pos and with length siz. Add an index record to
# the in-memory index dict, and append one to the directory file.
def _addkey(self, key, pos_and_siz_pair):
self._index[key] = pos_and_siz_pair
f = _open(self._dirfile, 'a', self._mode)
f.write("%r, %r\n" % (key, pos_and_siz_pair))
f.close()
def __setitem__(self, key, val):
if not type(key) == type('') == type(val):
raise TypeError, "keys and values must be strings"
if key not in self._index:
self._addkey(key, self._addval(val))
else:
# See whether the new value is small enough to fit in the
# (padded) space currently occupied by the old value.
pos, siz = self._index[key]
oldblocks = (siz + _BLOCKSIZE - 1) // _BLOCKSIZE
newblocks = (len(val) + _BLOCKSIZE - 1) // _BLOCKSIZE
if newblocks <= oldblocks:
self._index[key] = self._setval(pos, val)
else:
# The new value doesn't fit in the (padded) space used
# by the old value. The blocks used by the old value are
# forever lost.
self._index[key] = self._addval(val)
# Note that _index may be out of synch with the directory
# file now: _setval() and _addval() don't update the directory
# file. This also means that the on-disk directory and data
# files are in a mutually inconsistent state, and they'll
# remain that way until _commit() is called. Note that this
# is a disaster (for the database) if the program crashes
# (so that _commit() never gets called).
def __delitem__(self, key):
# The blocks used by the associated value are lost.
del self._index[key]
# XXX It's unclear why we do a _commit() here (the code always
# XXX has, so I'm not changing it). _setitem__ doesn't try to
# XXX keep the directory file in synch. Why should we? Or
# XXX why shouldn't __setitem__?
self._commit()
def keys(self):
return self._index.keys()
def has_key(self, key):
return key in self._index
def __contains__(self, key):
return key in self._index
def iterkeys(self):
return self._index.iterkeys()
__iter__ = iterkeys
def __len__(self):
return len(self._index)
def close(self):
self._commit()
self._index = self._datfile = self._dirfile = self._bakfile = None
__del__ = close
def open(file, flag=None, mode=0666):
"""Open the database file, filename, and return corresponding object.
The flag argument, used to control how the database is opened in the
other DBM implementations, is ignored in the dumbdbm module; the
database is always opened for update, and will be created if it does
not exist.
The optional mode argument is the UNIX mode of the file, used only when
the database has to be created. It defaults to octal code 0666 (and
will be modified by the prevailing umask).
"""
# flag argument is currently ignored
return _Database(file, mode)
| Python |
"""HTML 2.0 parser.
See the HTML 2.0 specification:
http://www.w3.org/hypertext/WWW/MarkUp/html-spec/html-spec_toc.html
"""
import sgmllib
from formatter import AS_IS
__all__ = ["HTMLParser", "HTMLParseError"]
class HTMLParseError(sgmllib.SGMLParseError):
"""Error raised when an HTML document can't be parsed."""
class HTMLParser(sgmllib.SGMLParser):
"""This is the basic HTML parser class.
It supports all entity names required by the XHTML 1.0 Recommendation.
It also defines handlers for all HTML 2.0 and many HTML 3.0 and 3.2
elements.
"""
from htmlentitydefs import entitydefs
def __init__(self, formatter, verbose=0):
"""Creates an instance of the HTMLParser class.
The formatter parameter is the formatter instance associated with
the parser.
"""
sgmllib.SGMLParser.__init__(self, verbose)
self.formatter = formatter
def error(self, message):
raise HTMLParseError(message)
def reset(self):
sgmllib.SGMLParser.reset(self)
self.savedata = None
self.isindex = 0
self.title = None
self.base = None
self.anchor = None
self.anchorlist = []
self.nofill = 0
self.list_stack = []
# ------ Methods used internally; some may be overridden
# --- Formatter interface, taking care of 'savedata' mode;
# shouldn't need to be overridden
def handle_data(self, data):
if self.savedata is not None:
self.savedata = self.savedata + data
else:
if self.nofill:
self.formatter.add_literal_data(data)
else:
self.formatter.add_flowing_data(data)
# --- Hooks to save data; shouldn't need to be overridden
def save_bgn(self):
"""Begins saving character data in a buffer instead of sending it
to the formatter object.
Retrieve the stored data via the save_end() method. Use of the
save_bgn() / save_end() pair may not be nested.
"""
self.savedata = ''
def save_end(self):
"""Ends buffering character data and returns all data saved since
the preceding call to the save_bgn() method.
If the nofill flag is false, whitespace is collapsed to single
spaces. A call to this method without a preceding call to the
save_bgn() method will raise a TypeError exception.
"""
data = self.savedata
self.savedata = None
if not self.nofill:
data = ' '.join(data.split())
return data
# --- Hooks for anchors; should probably be overridden
def anchor_bgn(self, href, name, type):
"""This method is called at the start of an anchor region.
The arguments correspond to the attributes of the <A> tag with
the same names. The default implementation maintains a list of
hyperlinks (defined by the HREF attribute for <A> tags) within
the document. The list of hyperlinks is available as the data
attribute anchorlist.
"""
self.anchor = href
if self.anchor:
self.anchorlist.append(href)
def anchor_end(self):
"""This method is called at the end of an anchor region.
The default implementation adds a textual footnote marker using an
index into the list of hyperlinks created by the anchor_bgn()method.
"""
if self.anchor:
self.handle_data("[%d]" % len(self.anchorlist))
self.anchor = None
# --- Hook for images; should probably be overridden
def handle_image(self, src, alt, *args):
"""This method is called to handle images.
The default implementation simply passes the alt value to the
handle_data() method.
"""
self.handle_data(alt)
# --------- Top level elememts
def start_html(self, attrs): pass
def end_html(self): pass
def start_head(self, attrs): pass
def end_head(self): pass
def start_body(self, attrs): pass
def end_body(self): pass
# ------ Head elements
def start_title(self, attrs):
self.save_bgn()
def end_title(self):
self.title = self.save_end()
def do_base(self, attrs):
for a, v in attrs:
if a == 'href':
self.base = v
def do_isindex(self, attrs):
self.isindex = 1
def do_link(self, attrs):
pass
def do_meta(self, attrs):
pass
def do_nextid(self, attrs): # Deprecated
pass
# ------ Body elements
# --- Headings
def start_h1(self, attrs):
self.formatter.end_paragraph(1)
self.formatter.push_font(('h1', 0, 1, 0))
def end_h1(self):
self.formatter.end_paragraph(1)
self.formatter.pop_font()
def start_h2(self, attrs):
self.formatter.end_paragraph(1)
self.formatter.push_font(('h2', 0, 1, 0))
def end_h2(self):
self.formatter.end_paragraph(1)
self.formatter.pop_font()
def start_h3(self, attrs):
self.formatter.end_paragraph(1)
self.formatter.push_font(('h3', 0, 1, 0))
def end_h3(self):
self.formatter.end_paragraph(1)
self.formatter.pop_font()
def start_h4(self, attrs):
self.formatter.end_paragraph(1)
self.formatter.push_font(('h4', 0, 1, 0))
def end_h4(self):
self.formatter.end_paragraph(1)
self.formatter.pop_font()
def start_h5(self, attrs):
self.formatter.end_paragraph(1)
self.formatter.push_font(('h5', 0, 1, 0))
def end_h5(self):
self.formatter.end_paragraph(1)
self.formatter.pop_font()
def start_h6(self, attrs):
self.formatter.end_paragraph(1)
self.formatter.push_font(('h6', 0, 1, 0))
def end_h6(self):
self.formatter.end_paragraph(1)
self.formatter.pop_font()
# --- Block Structuring Elements
def do_p(self, attrs):
self.formatter.end_paragraph(1)
def start_pre(self, attrs):
self.formatter.end_paragraph(1)
self.formatter.push_font((AS_IS, AS_IS, AS_IS, 1))
self.nofill = self.nofill + 1
def end_pre(self):
self.formatter.end_paragraph(1)
self.formatter.pop_font()
self.nofill = max(0, self.nofill - 1)
def start_xmp(self, attrs):
self.start_pre(attrs)
self.setliteral('xmp') # Tell SGML parser
def end_xmp(self):
self.end_pre()
def start_listing(self, attrs):
self.start_pre(attrs)
self.setliteral('listing') # Tell SGML parser
def end_listing(self):
self.end_pre()
def start_address(self, attrs):
self.formatter.end_paragraph(0)
self.formatter.push_font((AS_IS, 1, AS_IS, AS_IS))
def end_address(self):
self.formatter.end_paragraph(0)
self.formatter.pop_font()
def start_blockquote(self, attrs):
self.formatter.end_paragraph(1)
self.formatter.push_margin('blockquote')
def end_blockquote(self):
self.formatter.end_paragraph(1)
self.formatter.pop_margin()
# --- List Elements
def start_ul(self, attrs):
self.formatter.end_paragraph(not self.list_stack)
self.formatter.push_margin('ul')
self.list_stack.append(['ul', '*', 0])
def end_ul(self):
if self.list_stack: del self.list_stack[-1]
self.formatter.end_paragraph(not self.list_stack)
self.formatter.pop_margin()
def do_li(self, attrs):
self.formatter.end_paragraph(0)
if self.list_stack:
[dummy, label, counter] = top = self.list_stack[-1]
top[2] = counter = counter+1
else:
label, counter = '*', 0
self.formatter.add_label_data(label, counter)
def start_ol(self, attrs):
self.formatter.end_paragraph(not self.list_stack)
self.formatter.push_margin('ol')
label = '1.'
for a, v in attrs:
if a == 'type':
if len(v) == 1: v = v + '.'
label = v
self.list_stack.append(['ol', label, 0])
def end_ol(self):
if self.list_stack: del self.list_stack[-1]
self.formatter.end_paragraph(not self.list_stack)
self.formatter.pop_margin()
def start_menu(self, attrs):
self.start_ul(attrs)
def end_menu(self):
self.end_ul()
def start_dir(self, attrs):
self.start_ul(attrs)
def end_dir(self):
self.end_ul()
def start_dl(self, attrs):
self.formatter.end_paragraph(1)
self.list_stack.append(['dl', '', 0])
def end_dl(self):
self.ddpop(1)
if self.list_stack: del self.list_stack[-1]
def do_dt(self, attrs):
self.ddpop()
def do_dd(self, attrs):
self.ddpop()
self.formatter.push_margin('dd')
self.list_stack.append(['dd', '', 0])
def ddpop(self, bl=0):
self.formatter.end_paragraph(bl)
if self.list_stack:
if self.list_stack[-1][0] == 'dd':
del self.list_stack[-1]
self.formatter.pop_margin()
# --- Phrase Markup
# Idiomatic Elements
def start_cite(self, attrs): self.start_i(attrs)
def end_cite(self): self.end_i()
def start_code(self, attrs): self.start_tt(attrs)
def end_code(self): self.end_tt()
def start_em(self, attrs): self.start_i(attrs)
def end_em(self): self.end_i()
def start_kbd(self, attrs): self.start_tt(attrs)
def end_kbd(self): self.end_tt()
def start_samp(self, attrs): self.start_tt(attrs)
def end_samp(self): self.end_tt()
def start_strong(self, attrs): self.start_b(attrs)
def end_strong(self): self.end_b()
def start_var(self, attrs): self.start_i(attrs)
def end_var(self): self.end_i()
# Typographic Elements
def start_i(self, attrs):
self.formatter.push_font((AS_IS, 1, AS_IS, AS_IS))
def end_i(self):
self.formatter.pop_font()
def start_b(self, attrs):
self.formatter.push_font((AS_IS, AS_IS, 1, AS_IS))
def end_b(self):
self.formatter.pop_font()
def start_tt(self, attrs):
self.formatter.push_font((AS_IS, AS_IS, AS_IS, 1))
def end_tt(self):
self.formatter.pop_font()
def start_a(self, attrs):
href = ''
name = ''
type = ''
for attrname, value in attrs:
value = value.strip()
if attrname == 'href':
href = value
if attrname == 'name':
name = value
if attrname == 'type':
type = value.lower()
self.anchor_bgn(href, name, type)
def end_a(self):
self.anchor_end()
# --- Line Break
def do_br(self, attrs):
self.formatter.add_line_break()
# --- Horizontal Rule
def do_hr(self, attrs):
self.formatter.add_hor_rule()
# --- Image
def do_img(self, attrs):
align = ''
alt = '(image)'
ismap = ''
src = ''
width = 0
height = 0
for attrname, value in attrs:
if attrname == 'align':
align = value
if attrname == 'alt':
alt = value
if attrname == 'ismap':
ismap = value
if attrname == 'src':
src = value
if attrname == 'width':
try: width = int(value)
except ValueError: pass
if attrname == 'height':
try: height = int(value)
except ValueError: pass
self.handle_image(src, alt, ismap, align, width, height)
# --- Really Old Unofficial Deprecated Stuff
def do_plaintext(self, attrs):
self.start_pre(attrs)
self.setnomoretags() # Tell SGML parser
# --- Unhandled tags
def unknown_starttag(self, tag, attrs):
pass
def unknown_endtag(self, tag):
pass
def test(args = None):
import sys, formatter
if not args:
args = sys.argv[1:]
silent = args and args[0] == '-s'
if silent:
del args[0]
if args:
file = args[0]
else:
file = 'test.html'
if file == '-':
f = sys.stdin
else:
try:
f = open(file, 'r')
except IOError, msg:
print file, ":", msg
sys.exit(1)
data = f.read()
if f is not sys.stdin:
f.close()
if silent:
f = formatter.NullFormatter()
else:
f = formatter.AbstractFormatter(formatter.DumbWriter())
p = HTMLParser(f)
p.feed(data)
p.close()
if __name__ == '__main__':
test()
| Python |
"""
opcode module - potentially shared between dis and other modules which
operate on bytecodes (e.g. peephole optimizers).
"""
__all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs",
"haslocal", "hascompare", "hasfree", "opname", "opmap",
"HAVE_ARGUMENT", "EXTENDED_ARG"]
cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is',
'is not', 'exception match', 'BAD')
hasconst = []
hasname = []
hasjrel = []
hasjabs = []
haslocal = []
hascompare = []
hasfree = []
opmap = {}
opname = [''] * 256
for op in range(256): opname[op] = '<%r>' % (op,)
del op
def def_op(name, op):
opname[op] = name
opmap[name] = op
def name_op(name, op):
def_op(name, op)
hasname.append(op)
def jrel_op(name, op):
def_op(name, op)
hasjrel.append(op)
def jabs_op(name, op):
def_op(name, op)
hasjabs.append(op)
# Instruction opcodes for compiled code
def_op('STOP_CODE', 0)
def_op('POP_TOP', 1)
def_op('ROT_TWO', 2)
def_op('ROT_THREE', 3)
def_op('DUP_TOP', 4)
def_op('ROT_FOUR', 5)
def_op('NOP', 9)
def_op('UNARY_POSITIVE', 10)
def_op('UNARY_NEGATIVE', 11)
def_op('UNARY_NOT', 12)
def_op('UNARY_CONVERT', 13)
def_op('UNARY_INVERT', 15)
def_op('LIST_APPEND', 18)
def_op('BINARY_POWER', 19)
def_op('BINARY_MULTIPLY', 20)
def_op('BINARY_DIVIDE', 21)
def_op('BINARY_MODULO', 22)
def_op('BINARY_ADD', 23)
def_op('BINARY_SUBTRACT', 24)
def_op('BINARY_SUBSCR', 25)
def_op('BINARY_FLOOR_DIVIDE', 26)
def_op('BINARY_TRUE_DIVIDE', 27)
def_op('INPLACE_FLOOR_DIVIDE', 28)
def_op('INPLACE_TRUE_DIVIDE', 29)
def_op('SLICE+0', 30)
def_op('SLICE+1', 31)
def_op('SLICE+2', 32)
def_op('SLICE+3', 33)
def_op('STORE_SLICE+0', 40)
def_op('STORE_SLICE+1', 41)
def_op('STORE_SLICE+2', 42)
def_op('STORE_SLICE+3', 43)
def_op('DELETE_SLICE+0', 50)
def_op('DELETE_SLICE+1', 51)
def_op('DELETE_SLICE+2', 52)
def_op('DELETE_SLICE+3', 53)
def_op('INPLACE_ADD', 55)
def_op('INPLACE_SUBTRACT', 56)
def_op('INPLACE_MULTIPLY', 57)
def_op('INPLACE_DIVIDE', 58)
def_op('INPLACE_MODULO', 59)
def_op('STORE_SUBSCR', 60)
def_op('DELETE_SUBSCR', 61)
def_op('BINARY_LSHIFT', 62)
def_op('BINARY_RSHIFT', 63)
def_op('BINARY_AND', 64)
def_op('BINARY_XOR', 65)
def_op('BINARY_OR', 66)
def_op('INPLACE_POWER', 67)
def_op('GET_ITER', 68)
def_op('PRINT_EXPR', 70)
def_op('PRINT_ITEM', 71)
def_op('PRINT_NEWLINE', 72)
def_op('PRINT_ITEM_TO', 73)
def_op('PRINT_NEWLINE_TO', 74)
def_op('INPLACE_LSHIFT', 75)
def_op('INPLACE_RSHIFT', 76)
def_op('INPLACE_AND', 77)
def_op('INPLACE_XOR', 78)
def_op('INPLACE_OR', 79)
def_op('BREAK_LOOP', 80)
def_op('LOAD_LOCALS', 82)
def_op('RETURN_VALUE', 83)
def_op('IMPORT_STAR', 84)
def_op('EXEC_STMT', 85)
def_op('YIELD_VALUE', 86)
def_op('POP_BLOCK', 87)
def_op('END_FINALLY', 88)
def_op('BUILD_CLASS', 89)
HAVE_ARGUMENT = 90 # Opcodes from here have an argument:
name_op('STORE_NAME', 90) # Index in name list
name_op('DELETE_NAME', 91) # ""
def_op('UNPACK_SEQUENCE', 92) # Number of tuple items
jrel_op('FOR_ITER', 93)
name_op('STORE_ATTR', 95) # Index in name list
name_op('DELETE_ATTR', 96) # ""
name_op('STORE_GLOBAL', 97) # ""
name_op('DELETE_GLOBAL', 98) # ""
def_op('DUP_TOPX', 99) # number of items to duplicate
def_op('LOAD_CONST', 100) # Index in const list
hasconst.append(100)
name_op('LOAD_NAME', 101) # Index in name list
def_op('BUILD_TUPLE', 102) # Number of tuple items
def_op('BUILD_LIST', 103) # Number of list items
def_op('BUILD_MAP', 104) # Always zero for now
name_op('LOAD_ATTR', 105) # Index in name list
def_op('COMPARE_OP', 106) # Comparison operator
hascompare.append(106)
name_op('IMPORT_NAME', 107) # Index in name list
name_op('IMPORT_FROM', 108) # Index in name list
jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip
jrel_op('JUMP_IF_FALSE', 111) # ""
jrel_op('JUMP_IF_TRUE', 112) # ""
jabs_op('JUMP_ABSOLUTE', 113) # Target byte offset from beginning of code
name_op('LOAD_GLOBAL', 116) # Index in name list
jabs_op('CONTINUE_LOOP', 119) # Target address
jrel_op('SETUP_LOOP', 120) # Distance to target address
jrel_op('SETUP_EXCEPT', 121) # ""
jrel_op('SETUP_FINALLY', 122) # ""
def_op('LOAD_FAST', 124) # Local variable number
haslocal.append(124)
def_op('STORE_FAST', 125) # Local variable number
haslocal.append(125)
def_op('DELETE_FAST', 126) # Local variable number
haslocal.append(126)
def_op('RAISE_VARARGS', 130) # Number of raise arguments (1, 2, or 3)
def_op('CALL_FUNCTION', 131) # #args + (#kwargs << 8)
def_op('MAKE_FUNCTION', 132) # Number of args with default values
def_op('BUILD_SLICE', 133) # Number of items
def_op('MAKE_CLOSURE', 134)
def_op('LOAD_CLOSURE', 135)
hasfree.append(135)
def_op('LOAD_DEREF', 136)
hasfree.append(136)
def_op('STORE_DEREF', 137)
hasfree.append(137)
def_op('CALL_FUNCTION_VAR', 140) # #args + (#kwargs << 8)
def_op('CALL_FUNCTION_KW', 141) # #args + (#kwargs << 8)
def_op('CALL_FUNCTION_VAR_KW', 142) # #args + (#kwargs << 8)
def_op('EXTENDED_ARG', 143)
EXTENDED_ARG = 143
del def_op, name_op, jrel_op, jabs_op
| Python |
# 'grep'
import regex
from regex_syntax import *
opt_show_where = 0
opt_show_filename = 0
opt_show_lineno = 1
def grep(pat, *files):
return ggrep(RE_SYNTAX_GREP, pat, files)
def egrep(pat, *files):
return ggrep(RE_SYNTAX_EGREP, pat, files)
def emgrep(pat, *files):
return ggrep(RE_SYNTAX_EMACS, pat, files)
def ggrep(syntax, pat, files):
if len(files) == 1 and type(files[0]) == type([]):
files = files[0]
global opt_show_filename
opt_show_filename = (len(files) != 1)
syntax = regex.set_syntax(syntax)
try:
prog = regex.compile(pat)
finally:
syntax = regex.set_syntax(syntax)
for filename in files:
fp = open(filename, 'r')
lineno = 0
while 1:
line = fp.readline()
if not line: break
lineno = lineno + 1
if prog.search(line) >= 0:
showline(filename, lineno, line, prog)
fp.close()
def pgrep(pat, *files):
if len(files) == 1 and type(files[0]) == type([]):
files = files[0]
global opt_show_filename
opt_show_filename = (len(files) != 1)
import re
prog = re.compile(pat)
for filename in files:
fp = open(filename, 'r')
lineno = 0
while 1:
line = fp.readline()
if not line: break
lineno = lineno + 1
if prog.search(line):
showline(filename, lineno, line, prog)
fp.close()
def showline(filename, lineno, line, prog):
if line[-1:] == '\n': line = line[:-1]
if opt_show_lineno:
prefix = `lineno`.rjust(3) + ': '
else:
prefix = ''
if opt_show_filename:
prefix = filename + ': ' + prefix
print prefix + line
if opt_show_where:
start, end = prog.regs()[0]
line = line[:start]
if '\t' not in line:
prefix = ' ' * (len(prefix) + start)
else:
prefix = ' ' * len(prefix)
for c in line:
if c != '\t': c = ' '
prefix = prefix + c
if start == end: prefix = prefix + '\\'
else: prefix = prefix + '^'*(end-start)
print prefix
| Python |
"""Efficiently compare files, boolean outcome only (equal / not equal).
Tricks (used in this order):
- Files with identical type, size & mtime are assumed to be clones
- Files with different type or size cannot be identical
- We keep a cache of outcomes of earlier comparisons
- We don't fork a process to run 'cmp' but read the files ourselves
"""
import os
cache = {}
def cmp(f1, f2, shallow=1):
"""Compare two files, use the cache if possible.
Return 1 for identical files, 0 for different.
Raise exceptions if either file could not be statted, read, etc."""
s1, s2 = sig(os.stat(f1)), sig(os.stat(f2))
if s1[0] != 8 or s2[0] != 8:
# Either is a not a plain file -- always report as different
return 0
if shallow and s1 == s2:
# type, size & mtime match -- report same
return 1
if s1[:2] != s2[:2]: # Types or sizes differ, don't bother
# types or sizes differ -- report different
return 0
# same type and size -- look in the cache
key = (f1, f2)
try:
cs1, cs2, outcome = cache[key]
# cache hit
if s1 == cs1 and s2 == cs2:
# cached signatures match
return outcome
# stale cached signature(s)
except KeyError:
# cache miss
pass
# really compare
outcome = do_cmp(f1, f2)
cache[key] = s1, s2, outcome
return outcome
def sig(st):
"""Return signature (i.e., type, size, mtime) from raw stat data
0-5: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid
6-9: st_size, st_atime, st_mtime, st_ctime"""
type = st[0] / 4096
size = st[6]
mtime = st[8]
return type, size, mtime
def do_cmp(f1, f2):
"""Compare two files, really."""
bufsize = 8*1024 # Could be tuned
fp1 = open(f1, 'rb')
fp2 = open(f2, 'rb')
while 1:
b1 = fp1.read(bufsize)
b2 = fp2.read(bufsize)
if b1 != b2: return 0
if not b1: return 1
| Python |
# A subroutine for extracting a function name from a code object
# (with cache)
import sys
from stat import *
import string
import os
import linecache
# XXX The functions getcodename() and getfuncname() are now obsolete
# XXX as code and function objects now have a name attribute --
# XXX co.co_name and f.func_name.
# XXX getlineno() is now also obsolete because of the new attribute
# XXX of code objects, co.co_firstlineno.
# Extract the function or class name from a code object.
# This is a bit of a hack, since a code object doesn't contain
# the name directly. So what do we do:
# - get the filename (which *is* in the code object)
# - look in the code string to find the first SET_LINENO instruction
# (this must be the first instruction)
# - get the line from the file
# - if the line starts with 'class' or 'def' (after possible whitespace),
# extract the following identifier
#
# This breaks apart when the function was read from <stdin>
# or constructed by exec(), when the file is not accessible,
# and also when the file has been modified or when a line is
# continued with a backslash before the function or class name.
#
# Because this is a pretty expensive hack, a cache is kept.
SET_LINENO = 127 # The opcode (see "opcode.h" in the Python source)
identchars = string.ascii_letters + string.digits + '_' # Identifier characters
_namecache = {} # The cache
def getcodename(co):
try:
return co.co_name
except AttributeError:
pass
key = `co` # arbitrary but uniquely identifying string
if _namecache.has_key(key): return _namecache[key]
filename = co.co_filename
code = co.co_code
name = ''
if ord(code[0]) == SET_LINENO:
lineno = ord(code[1]) | ord(code[2]) << 8
line = linecache.getline(filename, lineno)
words = line.split()
if len(words) >= 2 and words[0] in ('def', 'class'):
name = words[1]
for i in range(len(name)):
if name[i] not in identchars:
name = name[:i]
break
_namecache[key] = name
return name
# Use the above routine to find a function's name.
def getfuncname(func):
try:
return func.func_name
except AttributeError:
pass
return getcodename(func.func_code)
# A part of the above code to extract just the line number from a code object.
def getlineno(co):
try:
return co.co_firstlineno
except AttributeError:
pass
code = co.co_code
if ord(code[0]) == SET_LINENO:
return ord(code[1]) | ord(code[2]) << 8
else:
return -1
| Python |
# Module 'dump'
#
# Print python code that reconstructs a variable.
# This only works in certain cases.
#
# It works fine for:
# - ints and floats (except NaNs and other weird things)
# - strings
# - compounds and lists, provided it works for all their elements
# - imported modules, provided their name is the module name
#
# It works for top-level dictionaries but not for dictionaries
# contained in other objects (could be made to work with some hassle
# though).
#
# It does not work for functions (all sorts), classes, class objects,
# windows, files etc.
#
# Finally, objects referenced by more than one name or contained in more
# than one other object lose their sharing property (this is bad for
# strings used as exception identifiers, for instance).
# Dump a whole symbol table
#
def dumpsymtab(dict):
for key in dict.keys():
dumpvar(key, dict[key])
# Dump a single variable
#
def dumpvar(name, x):
import sys
t = type(x)
if t == type({}):
print name, '= {}'
for key in x.keys():
item = x[key]
if not printable(item):
print '#',
print name, '[', `key`, '] =', `item`
elif t in (type(''), type(0), type(0.0), type([]), type(())):
if not printable(x):
print '#',
print name, '=', `x`
elif t == type(sys):
print 'import', name, '#', x
else:
print '#', name, '=', x
# check if a value is printable in a way that can be read back with input()
#
def printable(x):
t = type(x)
if t in (type(''), type(0), type(0.0)):
return 1
if t in (type([]), type(())):
for item in x:
if not printable(item):
return 0
return 1
if x == {}:
return 1
return 0
| Python |
# Module 'rand'
# Don't use unless you want compatibility with C's rand()!
import whrandom
def srand(seed):
whrandom.seed(seed%256, seed/256%256, seed/65536%256)
def rand():
return int(whrandom.random() * 32768.0) % 32768
def choice(seq):
return seq[rand() % len(seq)]
| Python |
"""A class to build directory diff tools on."""
import os
import dircache
import cmpcache
import statcache
from stat import *
class dircmp:
"""Directory comparison class."""
def new(self, a, b):
"""Initialize."""
self.a = a
self.b = b
# Properties that caller may change before calling self.run():
self.hide = [os.curdir, os.pardir] # Names never to be shown
self.ignore = ['RCS', 'tags'] # Names ignored in comparison
return self
def run(self):
"""Compare everything except common subdirectories."""
self.a_list = filter(dircache.listdir(self.a), self.hide)
self.b_list = filter(dircache.listdir(self.b), self.hide)
self.a_list.sort()
self.b_list.sort()
self.phase1()
self.phase2()
self.phase3()
def phase1(self):
"""Compute common names."""
self.a_only = []
self.common = []
for x in self.a_list:
if x in self.b_list:
self.common.append(x)
else:
self.a_only.append(x)
self.b_only = []
for x in self.b_list:
if x not in self.common:
self.b_only.append(x)
def phase2(self):
"""Distinguish files, directories, funnies."""
self.common_dirs = []
self.common_files = []
self.common_funny = []
for x in self.common:
a_path = os.path.join(self.a, x)
b_path = os.path.join(self.b, x)
ok = 1
try:
a_stat = statcache.stat(a_path)
except os.error, why:
# print 'Can\'t stat', a_path, ':', why[1]
ok = 0
try:
b_stat = statcache.stat(b_path)
except os.error, why:
# print 'Can\'t stat', b_path, ':', why[1]
ok = 0
if ok:
a_type = S_IFMT(a_stat[ST_MODE])
b_type = S_IFMT(b_stat[ST_MODE])
if a_type != b_type:
self.common_funny.append(x)
elif S_ISDIR(a_type):
self.common_dirs.append(x)
elif S_ISREG(a_type):
self.common_files.append(x)
else:
self.common_funny.append(x)
else:
self.common_funny.append(x)
def phase3(self):
"""Find out differences between common files."""
xx = cmpfiles(self.a, self.b, self.common_files)
self.same_files, self.diff_files, self.funny_files = xx
def phase4(self):
"""Find out differences between common subdirectories.
A new dircmp object is created for each common subdirectory,
these are stored in a dictionary indexed by filename.
The hide and ignore properties are inherited from the parent."""
self.subdirs = {}
for x in self.common_dirs:
a_x = os.path.join(self.a, x)
b_x = os.path.join(self.b, x)
self.subdirs[x] = newdd = dircmp().new(a_x, b_x)
newdd.hide = self.hide
newdd.ignore = self.ignore
newdd.run()
def phase4_closure(self):
"""Recursively call phase4() on subdirectories."""
self.phase4()
for x in self.subdirs.keys():
self.subdirs[x].phase4_closure()
def report(self):
"""Print a report on the differences between a and b."""
# Assume that phases 1 to 3 have been executed
# Output format is purposely lousy
print 'diff', self.a, self.b
if self.a_only:
print 'Only in', self.a, ':', self.a_only
if self.b_only:
print 'Only in', self.b, ':', self.b_only
if self.same_files:
print 'Identical files :', self.same_files
if self.diff_files:
print 'Differing files :', self.diff_files
if self.funny_files:
print 'Trouble with common files :', self.funny_files
if self.common_dirs:
print 'Common subdirectories :', self.common_dirs
if self.common_funny:
print 'Common funny cases :', self.common_funny
def report_closure(self):
"""Print reports on self and on subdirs.
If phase 4 hasn't been done, no subdir reports are printed."""
self.report()
try:
x = self.subdirs
except AttributeError:
return # No subdirectories computed
for x in self.subdirs.keys():
print
self.subdirs[x].report_closure()
def report_phase4_closure(self):
"""Report and do phase 4 recursively."""
self.report()
self.phase4()
for x in self.subdirs.keys():
print
self.subdirs[x].report_phase4_closure()
def cmpfiles(a, b, common):
"""Compare common files in two directories.
Return:
- files that compare equal
- files that compare different
- funny cases (can't stat etc.)"""
res = ([], [], [])
for x in common:
res[cmp(os.path.join(a, x), os.path.join(b, x))].append(x)
return res
def cmp(a, b):
"""Compare two files.
Return:
0 for equal
1 for different
2 for funny cases (can't stat, etc.)"""
try:
if cmpcache.cmp(a, b): return 0
return 1
except os.error:
return 2
def filter(list, skip):
"""Return a copy with items that occur in skip removed."""
result = []
for item in list:
if item not in skip: result.append(item)
return result
def demo():
"""Demonstration and testing."""
import sys
import getopt
options, args = getopt.getopt(sys.argv[1:], 'r')
if len(args) != 2:
raise getopt.error, 'need exactly two args'
dd = dircmp().new(args[0], args[1])
dd.run()
if ('-r', '') in options:
dd.report_phase4_closure()
else:
dd.report()
if __name__ == "__main__":
demo()
| Python |
# Print tracebacks, with a dump of local variables.
# Also an interactive stack trace browser.
# Note -- this module is obsolete -- use pdb.pm() instead.
import sys
import os
from stat import *
import linecache
def br(): browser(sys.last_traceback)
def tb(): printtb(sys.last_traceback)
def browser(tb):
if not tb:
print 'No traceback.'
return
tblist = []
while tb:
tblist.append(tb)
tb = tb.tb_next
ptr = len(tblist)-1
tb = tblist[ptr]
while 1:
if tb != tblist[ptr]:
tb = tblist[ptr]
print `ptr` + ':',
printtbheader(tb)
try:
line = raw_input('TB: ')
except KeyboardInterrupt:
print '\n[Interrupted]'
break
except EOFError:
print '\n[EOF]'
break
cmd = line.strip()
if cmd:
if cmd == 'quit':
break
elif cmd == 'list':
browserlist(tb)
elif cmd == 'up':
if ptr-1 >= 0: ptr = ptr-1
else: print 'Bottom of stack.'
elif cmd == 'down':
if ptr+1 < len(tblist): ptr = ptr+1
else: print 'Top of stack.'
elif cmd == 'locals':
printsymbols(tb.tb_frame.f_locals)
elif cmd == 'globals':
printsymbols(tb.tb_frame.f_globals)
elif cmd in ('?', 'help'):
browserhelp()
else:
browserexec(tb, cmd)
def browserlist(tb):
filename = tb.tb_frame.f_code.co_filename
lineno = tb.tb_lineno
last = lineno
first = max(1, last-10)
for i in range(first, last+1):
if i == lineno: prefix = '***' + `i`.rjust(4) + ':'
else: prefix = `i`.rjust(7) + ':'
line = linecache.getline(filename, i)
if line[-1:] == '\n': line = line[:-1]
print prefix + line
def browserexec(tb, cmd):
locals = tb.tb_frame.f_locals
globals = tb.tb_frame.f_globals
try:
exec cmd+'\n' in globals, locals
except:
t, v = sys.exc_info()[:2]
print '*** Exception:',
if type(t) is type(''):
print t,
else:
print t.__name__,
if v is not None:
print ':', v,
print
print 'Type help to get help.'
def browserhelp():
print
print ' This is the traceback browser. Commands are:'
print ' up : move one level up in the call stack'
print ' down : move one level down in the call stack'
print ' locals : print all local variables at this level'
print ' globals : print all global variables at this level'
print ' list : list source code around the failure'
print ' help : print help (what you are reading now)'
print ' quit : back to command interpreter'
print ' Typing any other 1-line statement will execute it'
print ' using the current level\'s symbol tables'
print
def printtb(tb):
while tb:
print1tb(tb)
tb = tb.tb_next
def print1tb(tb):
printtbheader(tb)
if tb.tb_frame.f_locals is not tb.tb_frame.f_globals:
printsymbols(tb.tb_frame.f_locals)
def printtbheader(tb):
filename = tb.tb_frame.f_code.co_filename
lineno = tb.tb_lineno
info = '"' + filename + '"(' + `lineno` + ')'
line = linecache.getline(filename, lineno)
if line:
info = info + ': ' + line.strip()
print info
def printsymbols(d):
keys = d.keys()
keys.sort()
for name in keys:
print ' ' + name.ljust(12) + ':',
printobject(d[name], 4)
print
def printobject(v, maxlevel):
if v is None:
print 'None',
elif type(v) in (type(0), type(0.0)):
print v,
elif type(v) is type(''):
if len(v) > 20:
print `v[:17] + '...'`,
else:
print `v`,
elif type(v) is type(()):
print '(',
printlist(v, maxlevel)
print ')',
elif type(v) is type([]):
print '[',
printlist(v, maxlevel)
print ']',
elif type(v) is type({}):
print '{',
printdict(v, maxlevel)
print '}',
else:
print v,
def printlist(v, maxlevel):
n = len(v)
if n == 0: return
if maxlevel <= 0:
print '...',
return
for i in range(min(6, n)):
printobject(v[i], maxlevel-1)
if i+1 < n: print ',',
if n > 6: print '...',
def printdict(v, maxlevel):
keys = v.keys()
n = len(keys)
if n == 0: return
if maxlevel <= 0:
print '...',
return
keys.sort()
for i in range(min(6, n)):
key = keys[i]
print `key` + ':',
printobject(v[key], maxlevel-1)
if i+1 < n: print ',',
if n > 6: print '...',
| Python |
from sndhdr import *
| Python |
# Module 'packmail' -- create a self-unpacking shell archive.
# This module works on UNIX and on the Mac; the archives can unpack
# themselves only on UNIX.
import os
from stat import ST_MTIME
# Print help
def help():
print 'All fns have a file open for writing as first parameter'
print 'pack(f, fullname, name): pack fullname as name'
print 'packsome(f, directory, namelist): selected files from directory'
print 'packall(f, directory): pack all files from directory'
print 'packnotolder(f, directory, name): pack all files from directory'
print ' that are not older than a file there'
print 'packtree(f, directory): pack entire directory tree'
# Pack one file
def pack(outfp, file, name):
fp = open(file, 'r')
outfp.write('echo ' + name + '\n')
outfp.write('sed "s/^X//" >"' + name + '" <<"!"\n')
while 1:
line = fp.readline()
if not line: break
if line[-1:] != '\n':
line = line + '\n'
outfp.write('X' + line)
outfp.write('!\n')
fp.close()
# Pack some files from a directory
def packsome(outfp, dirname, names):
for name in names:
print name
file = os.path.join(dirname, name)
pack(outfp, file, name)
# Pack all files from a directory
def packall(outfp, dirname):
names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
names.sort()
packsome(outfp, dirname, names)
# Pack all files from a directory that are not older than a give one
def packnotolder(outfp, dirname, oldest):
names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
oldest = os.path.join(dirname, oldest)
st = os.stat(oldest)
mtime = st[ST_MTIME]
todo = []
for name in names:
print name, '...',
st = os.stat(os.path.join(dirname, name))
if st[ST_MTIME] >= mtime:
print 'Yes.'
todo.append(name)
else:
print 'No.'
todo.sort()
packsome(outfp, dirname, todo)
# Pack a whole tree (no exceptions)
def packtree(outfp, dirname):
print 'packtree', dirname
outfp.write('mkdir ' + unixfix(dirname) + '\n')
names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
subdirs = []
for name in names:
fullname = os.path.join(dirname, name)
if os.path.isdir(fullname):
subdirs.append(fullname)
else:
print 'pack', fullname
pack(outfp, fullname, unixfix(fullname))
for subdirname in subdirs:
packtree(outfp, subdirname)
def unixfix(name):
comps = name.split(os.sep)
res = ''
for comp in comps:
if comp:
if res: res = res + '/'
res = res + comp
return res
| Python |
"""Efficiently compare files, boolean outcome only (equal / not equal).
Tricks (used in this order):
- Use the statcache module to avoid statting files more than once
- Files with identical type, size & mtime are assumed to be clones
- Files with different type or size cannot be identical
- We keep a cache of outcomes of earlier comparisons
- We don't fork a process to run 'cmp' but read the files ourselves
"""
import os
from stat import *
import statcache
# The cache.
#
cache = {}
def cmp(f1, f2, shallow=1):
"""Compare two files, use the cache if possible.
May raise os.error if a stat or open of either fails.
Return 1 for identical files, 0 for different.
Raise exceptions if either file could not be statted, read, etc."""
s1, s2 = sig(statcache.stat(f1)), sig(statcache.stat(f2))
if not S_ISREG(s1[0]) or not S_ISREG(s2[0]):
# Either is a not a plain file -- always report as different
return 0
if shallow and s1 == s2:
# type, size & mtime match -- report same
return 1
if s1[:2] != s2[:2]: # Types or sizes differ, don't bother
# types or sizes differ -- report different
return 0
# same type and size -- look in the cache
key = f1 + ' ' + f2
if cache.has_key(key):
cs1, cs2, outcome = cache[key]
# cache hit
if s1 == cs1 and s2 == cs2:
# cached signatures match
return outcome
# stale cached signature(s)
# really compare
outcome = do_cmp(f1, f2)
cache[key] = s1, s2, outcome
return outcome
def sig(st):
"""Return signature (i.e., type, size, mtime) from raw stat data."""
return S_IFMT(st[ST_MODE]), st[ST_SIZE], st[ST_MTIME]
def do_cmp(f1, f2):
"""Compare two files, really."""
#print ' cmp', f1, f2 # XXX remove when debugged
bufsize = 8*1024 # Could be tuned
fp1 = open(f1, 'rb')
fp2 = open(f2, 'rb')
while 1:
b1 = fp1.read(bufsize)
b2 = fp2.read(bufsize)
if b1 != b2: return 0
if not b1: return 1
| Python |
# module 'zmod'
# Compute properties of mathematical "fields" formed by taking
# Z/n (the whole numbers modulo some whole number n) and an
# irreducible polynomial (i.e., a polynomial with only complex zeros),
# e.g., Z/5 and X**2 + 2.
#
# The field is formed by taking all possible linear combinations of
# a set of d base vectors (where d is the degree of the polynomial).
#
# Note that this procedure doesn't yield a field for all combinations
# of n and p: it may well be that some numbers have more than one
# inverse and others have none. This is what we check.
#
# Remember that a field is a ring where each element has an inverse.
# A ring has commutative addition and multiplication, a zero and a one:
# 0*x = x*0 = 0, 0+x = x+0 = x, 1*x = x*1 = x. Also, the distributive
# property holds: a*(b+c) = a*b + b*c.
# (XXX I forget if this is an axiom or follows from the rules.)
import poly
# Example N and polynomial
N = 5
P = poly.plus(poly.one(0, 2), poly.one(2, 1)) # 2 + x**2
# Return x modulo y. Returns >= 0 even if x < 0.
def mod(x, y):
return divmod(x, y)[1]
# Normalize a polynomial modulo n and modulo p.
def norm(a, n, p):
a = poly.modulo(a, p)
a = a[:]
for i in range(len(a)): a[i] = mod(a[i], n)
a = poly.normalize(a)
return a
# Make a list of all n^d elements of the proposed field.
def make_all(mat):
all = []
for row in mat:
for a in row:
all.append(a)
return all
def make_elements(n, d):
if d == 0: return [poly.one(0, 0)]
sub = make_elements(n, d-1)
all = []
for a in sub:
for i in range(n):
all.append(poly.plus(a, poly.one(d-1, i)))
return all
def make_inv(all, n, p):
x = poly.one(1, 1)
inv = []
for a in all:
inv.append(norm(poly.times(a, x), n, p))
return inv
def checkfield(n, p):
all = make_elements(n, len(p)-1)
inv = make_inv(all, n, p)
all1 = all[:]
inv1 = inv[:]
all1.sort()
inv1.sort()
if all1 == inv1: print 'BINGO!'
else:
print 'Sorry:', n, p
print all
print inv
def rj(s, width):
if type(s) is not type(''): s = `s`
n = len(s)
if n >= width: return s
return ' '*(width - n) + s
def lj(s, width):
if type(s) is not type(''): s = `s`
n = len(s)
if n >= width: return s
return s + ' '*(width - n)
| Python |
import struct, fcntl
def writelock(f):
_lock(f, fcntl.F_WRLCK)
def readlock(f):
_lock(f, fcntl.F_RDLCK)
def unlock(f):
_lock(f, fcntl.F_UNLCK)
def _lock(f, op):
dummy = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW,
struct.pack('2h8l', op,
0, 0, 0, 0, 0, 0, 0, 0, 0))
| Python |
# Module 'util' -- some useful functions that don't fit elsewhere
# NB: These are now built-in functions, but this module is provided
# for compatibility. Don't use in new programs unless you need backward
# compatibility (i.e. need to run with old interpreters).
# Remove an item from a list.
# No complaints if it isn't in the list at all.
# If it occurs more than once, remove the first occurrence.
#
def remove(item, list):
if item in list: list.remove(item)
# Return a string containing a file's contents.
#
def readfile(fn):
return readopenfile(open(fn, 'r'))
# Read an open file until EOF.
#
def readopenfile(fp):
return fp.read()
| Python |
import fnmatch
import os
_debug = 0
_prune = ['(*)']
def find(pattern, dir = os.curdir):
list = []
names = os.listdir(dir)
names.sort()
for name in names:
if name in (os.curdir, os.pardir):
continue
fullname = os.path.join(dir, name)
if fnmatch.fnmatch(name, pattern):
list.append(fullname)
if os.path.isdir(fullname) and not os.path.islink(fullname):
for p in _prune:
if fnmatch.fnmatch(name, p):
if _debug: print "skip", `fullname`
break
else:
if _debug: print "descend into", `fullname`
list = list + find(pattern, fullname)
return list
| Python |
# Text formatting abstractions
# Note -- this module is obsolete, it's too slow anyway
# Oft-used type object
Int = type(0)
# Represent a paragraph. This is a list of words with associated
# font and size information, plus indents and justification for the
# entire paragraph.
# Once the words have been added to a paragraph, it can be laid out
# for different line widths. Once laid out, it can be rendered at
# different screen locations. Once rendered, it can be queried
# for mouse hits, and parts of the text can be highlighted
class Para:
#
def __init__(self):
self.words = [] # The words
self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c'
self.indent_left = self.indent_right = self.indent_hang = 0
# Final lay-out parameters, may change
self.left = self.top = self.right = self.bottom = \
self.width = self.height = self.lines = None
#
# Add a word, computing size information for it.
# Words may also be added manually by appending to self.words
# Each word should be a 7-tuple:
# (font, text, width, space, stretch, ascent, descent)
def addword(self, d, font, text, space, stretch):
if font is not None:
d.setfont(font)
width = d.textwidth(text)
ascent = d.baseline()
descent = d.lineheight() - ascent
spw = d.textwidth(' ')
space = space * spw
stretch = stretch * spw
tuple = (font, text, width, space, stretch, ascent, descent)
self.words.append(tuple)
#
# Hooks to begin and end anchors -- insert numbers in the word list!
def bgn_anchor(self, id):
self.words.append(id)
#
def end_anchor(self, id):
self.words.append(0)
#
# Return the total length (width) of the text added so far, in pixels
def getlength(self):
total = 0
for word in self.words:
if type(word) is not Int:
total = total + word[2] + word[3]
return total
#
# Tab to a given position (relative to the current left indent):
# remove all stretch, add fixed space up to the new indent.
# If the current position is already at the tab stop,
# don't add any new space (but still remove the stretch)
def tabto(self, tab):
total = 0
as, de = 1, 0
for i in range(len(self.words)):
word = self.words[i]
if type(word) is Int: continue
(fo, te, wi, sp, st, as, de) = word
self.words[i] = (fo, te, wi, sp, 0, as, de)
total = total + wi + sp
if total < tab:
self.words.append((None, '', 0, tab-total, 0, as, de))
#
# Make a hanging tag: tab to hang, increment indent_left by hang,
# and reset indent_hang to -hang
def makehangingtag(self, hang):
self.tabto(hang)
self.indent_left = self.indent_left + hang
self.indent_hang = -hang
#
# Decide where the line breaks will be given some screen width
def layout(self, linewidth):
self.width = linewidth
height = 0
self.lines = lines = []
avail1 = self.width - self.indent_left - self.indent_right
avail = avail1 - self.indent_hang
words = self.words
i = 0
n = len(words)
lastfont = None
while i < n:
firstfont = lastfont
charcount = 0
width = 0
stretch = 0
ascent = 0
descent = 0
lsp = 0
j = i
while i < n:
word = words[i]
if type(word) is Int:
if word > 0 and width >= avail:
break
i = i+1
continue
fo, te, wi, sp, st, as, de = word
if width + wi > avail and width > 0 and wi > 0:
break
if fo is not None:
lastfont = fo
if width == 0:
firstfont = fo
charcount = charcount + len(te) + (sp > 0)
width = width + wi + sp
lsp = sp
stretch = stretch + st
lst = st
ascent = max(ascent, as)
descent = max(descent, de)
i = i+1
while i > j and type(words[i-1]) is Int and \
words[i-1] > 0: i = i-1
width = width - lsp
if i < n:
stretch = stretch - lst
else:
stretch = 0
tuple = i-j, firstfont, charcount, width, stretch, \
ascent, descent
lines.append(tuple)
height = height + ascent + descent
avail = avail1
self.height = height
#
# Call a function for all words in a line
def visit(self, wordfunc, anchorfunc):
avail1 = self.width - self.indent_left - self.indent_right
avail = avail1 - self.indent_hang
v = self.top
i = 0
for tuple in self.lines:
wordcount, firstfont, charcount, width, stretch, \
ascent, descent = tuple
h = self.left + self.indent_left
if i == 0: h = h + self.indent_hang
extra = 0
if self.just == 'r': h = h + avail - width
elif self.just == 'c': h = h + (avail - width) / 2
elif self.just == 'lr' and stretch > 0:
extra = avail - width
v2 = v + ascent + descent
for j in range(i, i+wordcount):
word = self.words[j]
if type(word) is Int:
ok = anchorfunc(self, tuple, word, \
h, v)
if ok is not None: return ok
continue
fo, te, wi, sp, st, as, de = word
if extra > 0 and stretch > 0:
ex = extra * st / stretch
extra = extra - ex
stretch = stretch - st
else:
ex = 0
h2 = h + wi + sp + ex
ok = wordfunc(self, tuple, word, h, v, \
h2, v2, (j==i), (j==i+wordcount-1))
if ok is not None: return ok
h = h2
v = v2
i = i + wordcount
avail = avail1
#
# Render a paragraph in "drawing object" d, using the rectangle
# given by (left, top, right) with an unspecified bottom.
# Return the computed bottom of the text.
def render(self, d, left, top, right):
if self.width != right-left:
self.layout(right-left)
self.left = left
self.top = top
self.right = right
self.bottom = self.top + self.height
self.anchorid = 0
try:
self.d = d
self.visit(self.__class__._renderword, \
self.__class__._renderanchor)
finally:
self.d = None
return self.bottom
#
def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast):
if word[0] is not None: self.d.setfont(word[0])
baseline = v + tuple[5]
self.d.text((h, baseline - word[5]), word[1])
if self.anchorid > 0:
self.d.line((h, baseline+2), (h2, baseline+2))
#
def _renderanchor(self, tuple, word, h, v):
self.anchorid = word
#
# Return which anchor(s) was hit by the mouse
def hitcheck(self, mouseh, mousev):
self.mouseh = mouseh
self.mousev = mousev
self.anchorid = 0
self.hits = []
self.visit(self.__class__._hitcheckword, \
self.__class__._hitcheckanchor)
return self.hits
#
def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast):
if self.anchorid > 0 and h <= self.mouseh <= h2 and \
v <= self.mousev <= v2:
self.hits.append(self.anchorid)
#
def _hitcheckanchor(self, tuple, word, h, v):
self.anchorid = word
#
# Return whether the given anchor id is present
def hasanchor(self, id):
return id in self.words or -id in self.words
#
# Extract the raw text from the word list, substituting one space
# for non-empty inter-word space, and terminating with '\n'
def extract(self):
text = ''
for w in self.words:
if type(w) is not Int:
word = w[1]
if w[3]: word = word + ' '
text = text + word
return text + '\n'
#
# Return which character position was hit by the mouse, as
# an offset in the entire text as returned by extract().
# Return None if the mouse was not in this paragraph
def whereis(self, d, mouseh, mousev):
if mousev < self.top or mousev > self.bottom:
return None
self.mouseh = mouseh
self.mousev = mousev
self.lastfont = None
self.charcount = 0
try:
self.d = d
return self.visit(self.__class__._whereisword, \
self.__class__._whereisanchor)
finally:
self.d = None
#
def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
fo, te, wi, sp, st, as, de = word
if fo is not None: self.lastfont = fo
h = h1
if isfirst: h1 = 0
if islast: h2 = 999999
if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2):
self.charcount = self.charcount + len(te) + (sp > 0)
return
if self.lastfont is not None:
self.d.setfont(self.lastfont)
cc = 0
for c in te:
cw = self.d.textwidth(c)
if self.mouseh <= h + cw/2:
return self.charcount + cc
cc = cc+1
h = h+cw
self.charcount = self.charcount + cc
if self.mouseh <= (h+h2) / 2:
return self.charcount
else:
return self.charcount + 1
#
def _whereisanchor(self, tuple, word, h, v):
pass
#
# Return screen position corresponding to position in paragraph.
# Return tuple (h, vtop, vbaseline, vbottom).
# This is more or less the inverse of whereis()
def screenpos(self, d, pos):
if pos < 0:
ascent, descent = self.lines[0][5:7]
return self.left, self.top, self.top + ascent, \
self.top + ascent + descent
self.pos = pos
self.lastfont = None
try:
self.d = d
ok = self.visit(self.__class__._screenposword, \
self.__class__._screenposanchor)
finally:
self.d = None
if ok is None:
ascent, descent = self.lines[-1][5:7]
ok = self.right, self.bottom - ascent - descent, \
self.bottom - descent, self.bottom
return ok
#
def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
fo, te, wi, sp, st, as, de = word
if fo is not None: self.lastfont = fo
cc = len(te) + (sp > 0)
if self.pos > cc:
self.pos = self.pos - cc
return
if self.pos < cc:
self.d.setfont(self.lastfont)
h = h1 + self.d.textwidth(te[:self.pos])
else:
h = h2
ascent, descent = tuple[5:7]
return h, v1, v1+ascent, v2
#
def _screenposanchor(self, tuple, word, h, v):
pass
#
# Invert the stretch of text between pos1 and pos2.
# If pos1 is None, the beginning is implied;
# if pos2 is None, the end is implied.
# Undoes its own effect when called again with the same arguments
def invert(self, d, pos1, pos2):
if pos1 is None:
pos1 = self.left, self.top, self.top, self.top
else:
pos1 = self.screenpos(d, pos1)
if pos2 is None:
pos2 = self.right, self.bottom,self.bottom,self.bottom
else:
pos2 = self.screenpos(d, pos2)
h1, top1, baseline1, bottom1 = pos1
h2, top2, baseline2, bottom2 = pos2
if bottom1 <= top2:
d.invert((h1, top1), (self.right, bottom1))
h1 = self.left
if bottom1 < top2:
d.invert((h1, bottom1), (self.right, top2))
top1, bottom1 = top2, bottom2
d.invert((h1, top1), (h2, bottom2))
| Python |
"""New import scheme with package support.
Quick Reference
---------------
- To enable package support, execute "import ni" before importing any
packages. Importing this module automatically installs the relevant
import hooks.
- To create a package named spam containing sub-modules ham, bacon and
eggs, create a directory spam somewhere on Python's module search
path (i.e. spam's parent directory must be one of the directories in
sys.path or $PYTHONPATH); then create files ham.py, bacon.py and
eggs.py inside spam.
- To import module ham from package spam and use function hamneggs()
from that module, you can either do
import spam.ham # *not* "import spam" !!!
spam.ham.hamneggs()
or
from spam import ham
ham.hamneggs()
or
from spam.ham import hamneggs
hamneggs()
- Importing just "spam" does not do what you expect: it creates an
empty package named spam if one does not already exist, but it does
not import spam's submodules. The only submodule that is guaranteed
to be imported is spam.__init__, if it exists. Note that
spam.__init__ is a submodule of package spam. It can reference to
spam's namespace via the '__.' prefix, for instance
__.spam_inited = 1 # Set a package-level variable
Theory of Operation
-------------------
A Package is a module that can contain other modules. Packages can be
nested. Package introduce dotted names for modules, like P.Q.M, which
could correspond to a file P/Q/M.py found somewhere on sys.path. It
is possible to import a package itself, though this makes little sense
unless the package contains a module called __init__.
A package has two variables that control the namespace used for
packages and modules, both initialized to sensible defaults the first
time the package is referenced.
(1) A package's *module search path*, contained in the per-package
variable __path__, defines a list of *directories* where submodules or
subpackages of the package are searched. It is initialized to the
directory containing the package. Setting this variable to None makes
the module search path default to sys.path (this is not quite the same
as setting it to sys.path, since the latter won't track later
assignments to sys.path).
(2) A package's *import domain*, contained in the per-package variable
__domain__, defines a list of *packages* that are searched (using
their respective module search paths) to satisfy imports. It is
initialized to the list consisting of the package itself, its parent
package, its parent's parent, and so on, ending with the root package
(the nameless package containing all top-level packages and modules,
whose module search path is None, implying sys.path).
The default domain implements a search algorithm called "expanding
search". An alternative search algorithm called "explicit search"
fixes the import search path to contain only the root package,
requiring the modules in the package to name all imported modules by
their full name. The convention of using '__' to refer to the current
package (both as a per-module variable and in module names) can be
used by packages using explicit search to refer to modules in the same
package; this combination is known as "explicit-relative search".
The PackageImporter and PackageLoader classes together implement the
following policies:
- There is a root package, whose name is ''. It cannot be imported
directly but may be referenced, e.g. by using '__' from a top-level
module.
- In each module or package, the variable '__' contains a reference to
the parent package; in the root package, '__' points to itself.
- In the name for imported modules (e.g. M in "import M" or "from M
import ..."), a leading '__' refers to the current package (i.e.
the package containing the current module); leading '__.__' and so
on refer to the current package's parent, and so on. The use of
'__' elsewhere in the module name is not supported.
- Modules are searched using the "expanding search" algorithm by
virtue of the default value for __domain__.
- If A.B.C is imported, A is searched using __domain__; then
subpackage B is searched in A using its __path__, and so on.
- Built-in modules have priority: even if a file sys.py exists in a
package, "import sys" imports the built-in sys module.
- The same holds for frozen modules, for better or for worse.
- Submodules and subpackages are not automatically loaded when their
parent packages is loaded.
- The construct "from package import *" is illegal. (It can still be
used to import names from a module.)
- When "from package import module1, module2, ..." is used, those
modules are explicitly loaded.
- When a package is loaded, if it has a submodule __init__, that
module is loaded. This is the place where required submodules can
be loaded, the __path__ variable extended, etc. The __init__ module
is loaded even if the package was loaded only in order to create a
stub for a sub-package: if "import P.Q.R" is the first reference to
P, and P has a submodule __init__, P.__init__ is loaded before P.Q
is even searched.
Caveats:
- It is possible to import a package that has no __init__ submodule;
this is not particularly useful but there may be useful applications
for it (e.g. to manipulate its search paths from the outside!).
- There are no special provisions for os.chdir(). If you plan to use
os.chdir() before you have imported all your modules, it is better
not to have relative pathnames in sys.path. (This could actually be
fixed by changing the implementation of path_join() in the hook to
absolutize paths.)
- Packages and modules are introduced in sys.modules as soon as their
loading is started. When the loading is terminated by an exception,
the sys.modules entries remain around.
- There are no special measures to support mutually recursive modules,
but it will work under the same conditions where it works in the
flat module space system.
- Sometimes dummy entries (whose value is None) are entered in
sys.modules, to indicate that a particular module does not exist --
this is done to speed up the expanding search algorithm when a
module residing at a higher level is repeatedly imported (Python
promises that importing a previously imported module is cheap!)
- Although dynamically loaded extensions are allowed inside packages,
the current implementation (hardcoded in the interpreter) of their
initialization may cause problems if an extension invokes the
interpreter during its initialization.
- reload() may find another version of the module only if it occurs on
the package search path. Thus, it keeps the connection to the
package to which the module belongs, but may find a different file.
XXX Need to have an explicit name for '', e.g. '__root__'.
"""
import imp
import sys
import __builtin__
import ihooks
from ihooks import ModuleLoader, ModuleImporter
class PackageLoader(ModuleLoader):
"""A subclass of ModuleLoader with package support.
find_module_in_dir() will succeed if there's a subdirectory with
the given name; load_module() will create a stub for a package and
load its __init__ module if it exists.
"""
def find_module_in_dir(self, name, dir):
if dir is not None:
dirname = self.hooks.path_join(dir, name)
if self.hooks.path_isdir(dirname):
return None, dirname, ('', '', 'PACKAGE')
return ModuleLoader.find_module_in_dir(self, name, dir)
def load_module(self, name, stuff):
file, filename, info = stuff
suff, mode, type = info
if type == 'PACKAGE':
return self.load_package(name, stuff)
if sys.modules.has_key(name):
m = sys.modules[name]
else:
sys.modules[name] = m = imp.new_module(name)
self.set_parent(m)
if type == imp.C_EXTENSION and '.' in name:
return self.load_dynamic(name, stuff)
else:
return ModuleLoader.load_module(self, name, stuff)
def load_dynamic(self, name, stuff):
file, filename, (suff, mode, type) = stuff
# Hack around restriction in imp.load_dynamic()
i = name.rfind('.')
tail = name[i+1:]
if sys.modules.has_key(tail):
save = sys.modules[tail]
else:
save = None
sys.modules[tail] = imp.new_module(name)
try:
m = imp.load_dynamic(tail, filename, file)
finally:
if save:
sys.modules[tail] = save
else:
del sys.modules[tail]
sys.modules[name] = m
return m
def load_package(self, name, stuff):
file, filename, info = stuff
if sys.modules.has_key(name):
package = sys.modules[name]
else:
sys.modules[name] = package = imp.new_module(name)
package.__path__ = [filename]
self.init_package(package)
return package
def init_package(self, package):
self.set_parent(package)
self.set_domain(package)
self.call_init_module(package)
def set_parent(self, m):
name = m.__name__
if '.' in name:
name = name[:name.rfind('.')]
else:
name = ''
m.__ = sys.modules[name]
def set_domain(self, package):
name = package.__name__
package.__domain__ = domain = [name]
while '.' in name:
name = name[:name.rfind('.')]
domain.append(name)
if name:
domain.append('')
def call_init_module(self, package):
stuff = self.find_module('__init__', package.__path__)
if stuff:
m = self.load_module(package.__name__ + '.__init__', stuff)
package.__init__ = m
class PackageImporter(ModuleImporter):
"""Importer that understands packages and '__'."""
def __init__(self, loader = None, verbose = 0):
ModuleImporter.__init__(self,
loader or PackageLoader(None, verbose), verbose)
def import_module(self, name, globals={}, locals={}, fromlist=[]):
if globals.has_key('__'):
package = globals['__']
else:
# No calling context, assume in root package
package = sys.modules['']
if name[:3] in ('__.', '__'):
p = package
name = name[3:]
while name[:3] in ('__.', '__'):
p = p.__
name = name[3:]
if not name:
return self.finish(package, p, '', fromlist)
if '.' in name:
i = name.find('.')
name, tail = name[:i], name[i:]
else:
tail = ''
mname = p.__name__ and p.__name__+'.'+name or name
m = self.get1(mname)
return self.finish(package, m, tail, fromlist)
if '.' in name:
i = name.find('.')
name, tail = name[:i], name[i:]
else:
tail = ''
for pname in package.__domain__:
mname = pname and pname+'.'+name or name
m = self.get0(mname)
if m: break
else:
raise ImportError, "No such module %s" % name
return self.finish(m, m, tail, fromlist)
def finish(self, module, m, tail, fromlist):
# Got ....A; now get ....A.B.C.D
yname = m.__name__
if tail and sys.modules.has_key(yname + tail): # Fast path
yname, tail = yname + tail, ''
m = self.get1(yname)
while tail:
i = tail.find('.', 1)
if i > 0:
head, tail = tail[:i], tail[i:]
else:
head, tail = tail, ''
yname = yname + head
m = self.get1(yname)
# Got ....A.B.C.D; now finalize things depending on fromlist
if not fromlist:
return module
if '__' in fromlist:
raise ImportError, "Can't import __ from anywhere"
if not hasattr(m, '__path__'): return m
if '*' in fromlist:
raise ImportError, "Can't import * from a package"
for f in fromlist:
if hasattr(m, f): continue
fname = yname + '.' + f
self.get1(fname)
return m
def get1(self, name):
m = self.get(name)
if not m:
raise ImportError, "No module named %s" % name
return m
def get0(self, name):
m = self.get(name)
if not m:
sys.modules[name] = None
return m
def get(self, name):
# Internal routine to get or load a module when its parent exists
if sys.modules.has_key(name):
return sys.modules[name]
if '.' in name:
i = name.rfind('.')
head, tail = name[:i], name[i+1:]
else:
head, tail = '', name
path = sys.modules[head].__path__
stuff = self.loader.find_module(tail, path)
if not stuff:
return None
sys.modules[name] = m = self.loader.load_module(name, stuff)
if head:
setattr(sys.modules[head], tail, m)
return m
def reload(self, module):
name = module.__name__
if '.' in name:
i = name.rfind('.')
head, tail = name[:i], name[i+1:]
path = sys.modules[head].__path__
else:
tail = name
path = sys.modules[''].__path__
stuff = self.loader.find_module(tail, path)
if not stuff:
raise ImportError, "No module named %s" % name
return self.loader.load_module(name, stuff)
def unload(self, module):
if hasattr(module, '__path__'):
raise ImportError, "don't know how to unload packages yet"
PackageImporter.unload(self, module)
def install(self):
if not sys.modules.has_key(''):
sys.modules[''] = package = imp.new_module('')
package.__path__ = None
self.loader.init_package(package)
for m in sys.modules.values():
if not m: continue
if not hasattr(m, '__'):
self.loader.set_parent(m)
ModuleImporter.install(self)
def install(v = 0):
ihooks.install(PackageImporter(None, v))
def uninstall():
ihooks.uninstall()
def ni(v = 0):
install(v)
def no():
uninstall()
def test():
import pdb
try:
testproper()
except:
sys.last_type, sys.last_value, sys.last_traceback = sys.exc_info()
print
print sys.last_type, ':', sys.last_value
print
pdb.pm()
def testproper():
install(1)
try:
import mactest
print dir(mactest)
raw_input('OK?')
finally:
uninstall()
if __name__ == '__main__':
test()
else:
install()
| Python |
# This module provides standard support for "packages".
#
# The idea is that large groups of related modules can be placed in
# their own subdirectory, which can be added to the Python search path
# in a relatively easy way.
#
# The current version takes a package name and searches the Python
# search path for a directory by that name, and if found adds it to
# the module search path (sys.path). It maintains a list of packages
# that have already been added so adding the same package many times
# is OK.
#
# It is intended to be used in a fairly stylized manner: each module
# that wants to use a particular package, say 'Foo', is supposed to
# contain the following code:
#
# from addpack import addpack
# addpack('Foo')
# <import modules from package Foo>
#
# Additional arguments, when present, provide additional places where
# to look for the package before trying sys.path (these may be either
# strings or lists/tuples of strings). Also, if the package name is a
# full pathname, first the last component is tried in the usual way,
# then the full pathname is tried last. If the package name is a
# *relative* pathname (UNIX: contains a slash but doesn't start with
# one), then nothing special is done. The packages "/foo/bar/bletch"
# and "bletch" are considered the same, but unrelated to "bar/bletch".
#
# If the algorithm finds more than one suitable subdirectory, all are
# added to the search path -- this makes it possible to override part
# of a package. The same path will not be added more than once.
#
# If no directory is found, ImportError is raised.
_packs = {} # {pack: [pathname, ...], ...}
def addpack(pack, *locations):
import os
if os.path.isabs(pack):
base = os.path.basename(pack)
else:
base = pack
if _packs.has_key(base):
return
import sys
path = []
for loc in _flatten(locations) + sys.path:
fn = os.path.join(loc, base)
if fn not in path and os.path.isdir(fn):
path.append(fn)
if pack != base and pack not in path and os.path.isdir(pack):
path.append(pack)
if not path: raise ImportError, 'package ' + pack + ' not found'
_packs[base] = path
for fn in path:
if fn not in sys.path:
sys.path.append(fn)
def _flatten(locations):
locs = []
for loc in locations:
if type(loc) == type(''):
locs.append(loc)
else:
locs = locs + _flatten(loc)
return locs
| Python |
# New dir() function
# This should be the new dir(), except that it should still list
# the current local name space by default
def listattrs(x):
try:
dictkeys = x.__dict__.keys()
except (AttributeError, TypeError):
dictkeys = []
#
try:
methods = x.__methods__
except (AttributeError, TypeError):
methods = []
#
try:
members = x.__members__
except (AttributeError, TypeError):
members = []
#
try:
the_class = x.__class__
except (AttributeError, TypeError):
the_class = None
#
try:
bases = x.__bases__
except (AttributeError, TypeError):
bases = ()
#
total = dictkeys + methods + members
if the_class:
# It's a class instace; add the class's attributes
# that are functions (methods)...
class_attrs = listattrs(the_class)
class_methods = []
for name in class_attrs:
if is_function(getattr(the_class, name)):
class_methods.append(name)
total = total + class_methods
elif bases:
# It's a derived class; add the base class attributes
for base in bases:
base_attrs = listattrs(base)
total = total + base_attrs
total.sort()
return total
i = 0
while i+1 < len(total):
if total[i] == total[i+1]:
del total[i+1]
else:
i = i+1
return total
# Helper to recognize functions
def is_function(x):
return type(x) == type(is_function)
# Approximation of builtin dir(); but note that this lists the user's
# variables by default, not the current local name space.
def dir(x = None):
if x is not None:
return listattrs(x)
else:
import __main__
return listattrs(__main__)
| Python |
# Text formatting abstractions
# Note -- this module is obsolete, it's too slow anyway
import string
import Para
# A formatter back-end object has one method that is called by the formatter:
# addpara(p), where p is a paragraph object. For example:
# Formatter back-end to do nothing at all with the paragraphs
class NullBackEnd:
#
def __init__(self):
pass
#
def addpara(self, p):
pass
#
def bgn_anchor(self, id):
pass
#
def end_anchor(self, id):
pass
# Formatter back-end to collect the paragraphs in a list
class SavingBackEnd(NullBackEnd):
#
def __init__(self):
self.paralist = []
#
def addpara(self, p):
self.paralist.append(p)
#
def hitcheck(self, h, v):
hits = []
for p in self.paralist:
if p.top <= v <= p.bottom:
for id in p.hitcheck(h, v):
if id not in hits:
hits.append(id)
return hits
#
def extract(self):
text = ''
for p in self.paralist:
text = text + (p.extract())
return text
#
def extractpart(self, long1, long2):
if long1 > long2: long1, long2 = long2, long1
para1, pos1 = long1
para2, pos2 = long2
text = ''
while para1 < para2:
ptext = self.paralist[para1].extract()
text = text + ptext[pos1:]
pos1 = 0
para1 = para1 + 1
ptext = self.paralist[para2].extract()
return text + ptext[pos1:pos2]
#
def whereis(self, d, h, v):
total = 0
for i in range(len(self.paralist)):
p = self.paralist[i]
result = p.whereis(d, h, v)
if result is not None:
return i, result
return None
#
def roundtowords(self, long1, long2):
i, offset = long1
text = self.paralist[i].extract()
while offset > 0 and text[offset-1] != ' ': offset = offset-1
long1 = i, offset
#
i, offset = long2
text = self.paralist[i].extract()
n = len(text)
while offset < n-1 and text[offset] != ' ': offset = offset+1
long2 = i, offset
#
return long1, long2
#
def roundtoparagraphs(self, long1, long2):
long1 = long1[0], 0
long2 = long2[0], len(self.paralist[long2[0]].extract())
return long1, long2
# Formatter back-end to send the text directly to the drawing object
class WritingBackEnd(NullBackEnd):
#
def __init__(self, d, width):
self.d = d
self.width = width
self.lineno = 0
#
def addpara(self, p):
self.lineno = p.render(self.d, 0, self.lineno, self.width)
# A formatter receives a stream of formatting instructions and assembles
# these into a stream of paragraphs on to a back-end. The assembly is
# parametrized by a text measurement object, which must match the output
# operations of the back-end. The back-end is responsible for splitting
# paragraphs up in lines of a given maximum width. (This is done because
# in a windowing environment, when the window size changes, there is no
# need to redo the assembly into paragraphs, but the splitting into lines
# must be done taking the new window size into account.)
# Formatter base class. Initialize it with a text measurement object,
# which is used for text measurements, and a back-end object,
# which receives the completed paragraphs. The formatting methods are:
# setfont(font)
# setleftindent(nspaces)
# setjust(type) where type is 'l', 'c', 'r', or 'lr'
# flush()
# vspace(nlines)
# needvspace(nlines)
# addword(word, nspaces)
class BaseFormatter:
#
def __init__(self, d, b):
# Drawing object used for text measurements
self.d = d
#
# BackEnd object receiving completed paragraphs
self.b = b
#
# Parameters of the formatting model
self.leftindent = 0
self.just = 'l'
self.font = None
self.blanklines = 0
#
# Parameters derived from the current font
self.space = d.textwidth(' ')
self.line = d.lineheight()
self.ascent = d.baseline()
self.descent = self.line - self.ascent
#
# Parameter derived from the default font
self.n_space = self.space
#
# Current paragraph being built
self.para = None
self.nospace = 1
#
# Font to set on the next word
self.nextfont = None
#
def newpara(self):
return Para.Para()
#
def setfont(self, font):
if font is None: return
self.font = self.nextfont = font
d = self.d
d.setfont(font)
self.space = d.textwidth(' ')
self.line = d.lineheight()
self.ascent = d.baseline()
self.descent = self.line - self.ascent
#
def setleftindent(self, nspaces):
self.leftindent = int(self.n_space * nspaces)
if self.para:
hang = self.leftindent - self.para.indent_left
if hang > 0 and self.para.getlength() <= hang:
self.para.makehangingtag(hang)
self.nospace = 1
else:
self.flush()
#
def setrightindent(self, nspaces):
self.rightindent = int(self.n_space * nspaces)
if self.para:
self.para.indent_right = self.rightindent
self.flush()
#
def setjust(self, just):
self.just = just
if self.para:
self.para.just = self.just
#
def flush(self):
if self.para:
self.b.addpara(self.para)
self.para = None
if self.font is not None:
self.d.setfont(self.font)
self.nospace = 1
#
def vspace(self, nlines):
self.flush()
if nlines > 0:
self.para = self.newpara()
tuple = None, '', 0, 0, 0, int(nlines*self.line), 0
self.para.words.append(tuple)
self.flush()
self.blanklines = self.blanklines + nlines
#
def needvspace(self, nlines):
self.flush() # Just to be sure
if nlines > self.blanklines:
self.vspace(nlines - self.blanklines)
#
def addword(self, text, space):
if self.nospace and not text:
return
self.nospace = 0
self.blanklines = 0
if not self.para:
self.para = self.newpara()
self.para.indent_left = self.leftindent
self.para.just = self.just
self.nextfont = self.font
space = int(space * self.space)
self.para.words.append((self.nextfont, text,
self.d.textwidth(text), space, space,
self.ascent, self.descent))
self.nextfont = None
#
def bgn_anchor(self, id):
if not self.para:
self.nospace = 0
self.addword('', 0)
self.para.bgn_anchor(id)
#
def end_anchor(self, id):
if not self.para:
self.nospace = 0
self.addword('', 0)
self.para.end_anchor(id)
# Measuring object for measuring text as viewed on a tty
class NullMeasurer:
#
def __init__(self):
pass
#
def setfont(self, font):
pass
#
def textwidth(self, text):
return len(text)
#
def lineheight(self):
return 1
#
def baseline(self):
return 0
# Drawing object for writing plain ASCII text to a file
class FileWriter:
#
def __init__(self, fp):
self.fp = fp
self.lineno, self.colno = 0, 0
#
def setfont(self, font):
pass
#
def text(self, (h, v), str):
if not str: return
if '\n' in str:
raise ValueError, 'can\'t write \\n'
while self.lineno < v:
self.fp.write('\n')
self.colno, self.lineno = 0, self.lineno + 1
while self.lineno > v:
# XXX This should never happen...
self.fp.write('\033[A') # ANSI up arrow
self.lineno = self.lineno - 1
if self.colno < h:
self.fp.write(' ' * (h - self.colno))
elif self.colno > h:
self.fp.write('\b' * (self.colno - h))
self.colno = h
self.fp.write(str)
self.colno = h + len(str)
# Formatting class to do nothing at all with the data
class NullFormatter(BaseFormatter):
#
def __init__(self):
d = NullMeasurer()
b = NullBackEnd()
BaseFormatter.__init__(self, d, b)
# Formatting class to write directly to a file
class WritingFormatter(BaseFormatter):
#
def __init__(self, fp, width):
dm = NullMeasurer()
dw = FileWriter(fp)
b = WritingBackEnd(dw, width)
BaseFormatter.__init__(self, dm, b)
self.blanklines = 1
#
# Suppress multiple blank lines
def needvspace(self, nlines):
BaseFormatter.needvspace(self, min(1, nlines))
# A "FunnyFormatter" writes ASCII text with a twist: *bold words*,
# _italic text_ and _underlined words_, and `quoted text'.
# It assumes that the fonts are 'r', 'i', 'b', 'u', 'q': (roman,
# italic, bold, underline, quote).
# Moreover, if the font is in upper case, the text is converted to
# UPPER CASE.
class FunnyFormatter(WritingFormatter):
#
def flush(self):
if self.para: finalize(self.para)
WritingFormatter.flush(self)
# Surrounds *bold words* and _italic text_ in a paragraph with
# appropriate markers, fixing the size (assuming these characters'
# width is 1).
openchar = \
{'b':'*', 'i':'_', 'u':'_', 'q':'`', 'B':'*', 'I':'_', 'U':'_', 'Q':'`'}
closechar = \
{'b':'*', 'i':'_', 'u':'_', 'q':'\'', 'B':'*', 'I':'_', 'U':'_', 'Q':'\''}
def finalize(para):
oldfont = curfont = 'r'
para.words.append(('r', '', 0, 0, 0, 0)) # temporary, deleted at end
for i in range(len(para.words)):
fo, te, wi = para.words[i][:3]
if fo is not None: curfont = fo
if curfont != oldfont:
if closechar.has_key(oldfont):
c = closechar[oldfont]
j = i-1
while j > 0 and para.words[j][1] == '': j = j-1
fo1, te1, wi1 = para.words[j][:3]
te1 = te1 + c
wi1 = wi1 + len(c)
para.words[j] = (fo1, te1, wi1) + \
para.words[j][3:]
if openchar.has_key(curfont) and te:
c = openchar[curfont]
te = c + te
wi = len(c) + wi
para.words[i] = (fo, te, wi) + \
para.words[i][3:]
if te: oldfont = curfont
else: oldfont = 'r'
if curfont in string.uppercase:
te = string.upper(te)
para.words[i] = (fo, te, wi) + para.words[i][3:]
del para.words[-1]
# Formatter back-end to draw the text in a window.
# This has an option to draw while the paragraphs are being added,
# to minimize the delay before the user sees anything.
# This manages the entire "document" of the window.
class StdwinBackEnd(SavingBackEnd):
#
def __init__(self, window, drawnow):
self.window = window
self.drawnow = drawnow
self.width = window.getwinsize()[0]
self.selection = None
self.height = 0
window.setorigin(0, 0)
window.setdocsize(0, 0)
self.d = window.begindrawing()
SavingBackEnd.__init__(self)
#
def finish(self):
self.d.close()
self.d = None
self.window.setdocsize(0, self.height)
#
def addpara(self, p):
self.paralist.append(p)
if self.drawnow:
self.height = \
p.render(self.d, 0, self.height, self.width)
else:
p.layout(self.width)
p.left = 0
p.top = self.height
p.right = self.width
p.bottom = self.height + p.height
self.height = p.bottom
#
def resize(self):
self.window.change((0, 0), (self.width, self.height))
self.width = self.window.getwinsize()[0]
self.height = 0
for p in self.paralist:
p.layout(self.width)
p.left = 0
p.top = self.height
p.right = self.width
p.bottom = self.height + p.height
self.height = p.bottom
self.window.change((0, 0), (self.width, self.height))
self.window.setdocsize(0, self.height)
#
def redraw(self, area):
d = self.window.begindrawing()
(left, top), (right, bottom) = area
d.erase(area)
d.cliprect(area)
for p in self.paralist:
if top < p.bottom and p.top < bottom:
v = p.render(d, p.left, p.top, p.right)
if self.selection:
self.invert(d, self.selection)
d.close()
#
def setselection(self, new):
if new:
long1, long2 = new
pos1 = long1[:3]
pos2 = long2[:3]
new = pos1, pos2
if new != self.selection:
d = self.window.begindrawing()
if self.selection:
self.invert(d, self.selection)
if new:
self.invert(d, new)
d.close()
self.selection = new
#
def getselection(self):
return self.selection
#
def extractselection(self):
if self.selection:
a, b = self.selection
return self.extractpart(a, b)
else:
return None
#
def invert(self, d, region):
long1, long2 = region
if long1 > long2: long1, long2 = long2, long1
para1, pos1 = long1
para2, pos2 = long2
while para1 < para2:
self.paralist[para1].invert(d, pos1, None)
pos1 = None
para1 = para1 + 1
self.paralist[para2].invert(d, pos1, pos2)
#
def search(self, prog):
import re, string
if type(prog) is type(''):
prog = re.compile(string.lower(prog))
if self.selection:
iold = self.selection[0][0]
else:
iold = -1
hit = None
for i in range(len(self.paralist)):
if i == iold or i < iold and hit:
continue
p = self.paralist[i]
text = string.lower(p.extract())
match = prog.search(text)
if match:
a, b = match.group(0)
long1 = i, a
long2 = i, b
hit = long1, long2
if i > iold:
break
if hit:
self.setselection(hit)
i = hit[0][0]
p = self.paralist[i]
self.window.show((p.left, p.top), (p.right, p.bottom))
return 1
else:
return 0
#
def showanchor(self, id):
for i in range(len(self.paralist)):
p = self.paralist[i]
if p.hasanchor(id):
long1 = i, 0
long2 = i, len(p.extract())
hit = long1, long2
self.setselection(hit)
self.window.show(
(p.left, p.top), (p.right, p.bottom))
break
# GL extensions
class GLFontCache:
#
def __init__(self):
self.reset()
self.setfont('')
#
def reset(self):
self.fontkey = None
self.fonthandle = None
self.fontinfo = None
self.fontcache = {}
#
def close(self):
self.reset()
#
def setfont(self, fontkey):
if fontkey == '':
fontkey = 'Times-Roman 12'
elif ' ' not in fontkey:
fontkey = fontkey + ' 12'
if fontkey == self.fontkey:
return
if self.fontcache.has_key(fontkey):
handle = self.fontcache[fontkey]
else:
import string
i = string.index(fontkey, ' ')
name, sizestr = fontkey[:i], fontkey[i:]
size = eval(sizestr)
key1 = name + ' 1'
key = name + ' ' + `size`
# NB key may differ from fontkey!
if self.fontcache.has_key(key):
handle = self.fontcache[key]
else:
if self.fontcache.has_key(key1):
handle = self.fontcache[key1]
else:
import fm
handle = fm.findfont(name)
self.fontcache[key1] = handle
handle = handle.scalefont(size)
self.fontcache[fontkey] = \
self.fontcache[key] = handle
self.fontkey = fontkey
if self.fonthandle != handle:
self.fonthandle = handle
self.fontinfo = handle.getfontinfo()
handle.setfont()
class GLMeasurer(GLFontCache):
#
def textwidth(self, text):
return self.fonthandle.getstrwidth(text)
#
def baseline(self):
return self.fontinfo[6] - self.fontinfo[3]
#
def lineheight(self):
return self.fontinfo[6]
class GLWriter(GLFontCache):
#
# NOTES:
# (1) Use gl.ortho2 to use X pixel coordinates!
#
def text(self, (h, v), text):
import gl, fm
gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3])
fm.prstr(text)
#
def setfont(self, fontkey):
oldhandle = self.fonthandle
GLFontCache.setfont(fontkey)
if self.fonthandle != oldhandle:
handle.setfont()
class GLMeasurerWriter(GLMeasurer, GLWriter):
pass
class GLBackEnd(SavingBackEnd):
#
def __init__(self, wid):
import gl
gl.winset(wid)
self.wid = wid
self.width = gl.getsize()[1]
self.height = 0
self.d = GLMeasurerWriter()
SavingBackEnd.__init__(self)
#
def finish(self):
pass
#
def addpara(self, p):
self.paralist.append(p)
self.height = p.render(self.d, 0, self.height, self.width)
#
def redraw(self):
import gl
gl.winset(self.wid)
width = gl.getsize()[1]
if width != self.width:
setdocsize = 1
self.width = width
for p in self.paralist:
p.top = p.bottom = None
d = self.d
v = 0
for p in self.paralist:
v = p.render(d, 0, v, width)
| Python |
# module 'poly' -- Polynomials
# A polynomial is represented by a list of coefficients, e.g.,
# [1, 10, 5] represents 1*x**0 + 10*x**1 + 5*x**2 (or 1 + 10x + 5x**2).
# There is no way to suppress internal zeros; trailing zeros are
# taken out by normalize().
def normalize(p): # Strip unnecessary zero coefficients
n = len(p)
while n:
if p[n-1]: return p[:n]
n = n-1
return []
def plus(a, b):
if len(a) < len(b): a, b = b, a # make sure a is the longest
res = a[:] # make a copy
for i in range(len(b)):
res[i] = res[i] + b[i]
return normalize(res)
def minus(a, b):
neg_b = map(lambda x: -x, b[:])
return plus(a, neg_b)
def one(power, coeff): # Representation of coeff * x**power
res = []
for i in range(power): res.append(0)
return res + [coeff]
def times(a, b):
res = []
for i in range(len(a)):
for j in range(len(b)):
res = plus(res, one(i+j, a[i]*b[j]))
return res
def power(a, n): # Raise polynomial a to the positive integral power n
if n == 0: return [1]
if n == 1: return a
if n/2*2 == n:
b = power(a, n/2)
return times(b, b)
return times(power(a, n-1), a)
def der(a): # First derivative
res = a[1:]
for i in range(len(res)):
res[i] = res[i] * (i+1)
return res
# Computing a primitive function would require rational arithmetic...
| Python |
#! /usr/bin/env python
"""A Python debugger."""
# (See pdb.doc for documentation.)
import sys
import linecache
import cmd
import bdb
from repr import Repr
import os
import re
import pprint
import traceback
# Create a custom safe Repr instance and increase its maxstring.
# The default of 30 truncates error messages too easily.
_repr = Repr()
_repr.maxstring = 200
_saferepr = _repr.repr
__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace",
"post_mortem", "help"]
def find_function(funcname, filename):
cre = re.compile(r'def\s+%s\s*[(]' % funcname)
try:
fp = open(filename)
except IOError:
return None
# consumer of this info expects the first line to be 1
lineno = 1
answer = None
while 1:
line = fp.readline()
if line == '':
break
if cre.match(line):
answer = funcname, filename, lineno
break
lineno = lineno + 1
fp.close()
return answer
# Interaction prompt line will separate file and call info from code
# text using value of line_prefix string. A newline and arrow may
# be to your liking. You can set it once pdb is imported using the
# command "pdb.line_prefix = '\n% '".
# line_prefix = ': ' # Use this to get the old situation back
line_prefix = '\n-> ' # Probably a better default
class Pdb(bdb.Bdb, cmd.Cmd):
def __init__(self):
bdb.Bdb.__init__(self)
cmd.Cmd.__init__(self)
self.prompt = '(Pdb) '
self.aliases = {}
self.mainpyfile = ''
self._wait_for_mainpyfile = 0
# Try to load readline if it exists
try:
import readline
except ImportError:
pass
# Read $HOME/.pdbrc and ./.pdbrc
self.rcLines = []
if 'HOME' in os.environ:
envHome = os.environ['HOME']
try:
rcFile = open(os.path.join(envHome, ".pdbrc"))
except IOError:
pass
else:
for line in rcFile.readlines():
self.rcLines.append(line)
rcFile.close()
try:
rcFile = open(".pdbrc")
except IOError:
pass
else:
for line in rcFile.readlines():
self.rcLines.append(line)
rcFile.close()
def reset(self):
bdb.Bdb.reset(self)
self.forget()
def forget(self):
self.lineno = None
self.stack = []
self.curindex = 0
self.curframe = None
def setup(self, f, t):
self.forget()
self.stack, self.curindex = self.get_stack(f, t)
self.curframe = self.stack[self.curindex][0]
self.execRcLines()
# Can be executed earlier than 'setup' if desired
def execRcLines(self):
if self.rcLines:
# Make local copy because of recursion
rcLines = self.rcLines
# executed only once
self.rcLines = []
for line in rcLines:
line = line[:-1]
if len(line) > 0 and line[0] != '#':
self.onecmd(line)
# Override Bdb methods
def user_call(self, frame, argument_list):
"""This method is called when there is the remote possibility
that we ever need to stop in this function."""
if self._wait_for_mainpyfile:
return
if self.stop_here(frame):
print '--Call--'
self.interaction(frame, None)
def user_line(self, frame):
"""This function is called when we stop or break at this line."""
if self._wait_for_mainpyfile:
if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
or frame.f_lineno<= 0):
return
self._wait_for_mainpyfile = 0
self.interaction(frame, None)
def user_return(self, frame, return_value):
"""This function is called when a return trap is set here."""
frame.f_locals['__return__'] = return_value
print '--Return--'
self.interaction(frame, None)
def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
"""This function is called if an exception occurs,
but only if we are to stop at or just below this level."""
frame.f_locals['__exception__'] = exc_type, exc_value
if type(exc_type) == type(''):
exc_type_name = exc_type
else: exc_type_name = exc_type.__name__
print exc_type_name + ':', _saferepr(exc_value)
self.interaction(frame, exc_traceback)
# General interaction function
def interaction(self, frame, traceback):
self.setup(frame, traceback)
self.print_stack_entry(self.stack[self.curindex])
self.cmdloop()
self.forget()
def default(self, line):
if line[:1] == '!': line = line[1:]
locals = self.curframe.f_locals
globals = self.curframe.f_globals
try:
code = compile(line + '\n', '<stdin>', 'single')
exec code in globals, locals
except:
t, v = sys.exc_info()[:2]
if type(t) == type(''):
exc_type_name = t
else: exc_type_name = t.__name__
print '***', exc_type_name + ':', v
def precmd(self, line):
"""Handle alias expansion and ';;' separator."""
if not line.strip():
return line
args = line.split()
while args[0] in self.aliases:
line = self.aliases[args[0]]
ii = 1
for tmpArg in args[1:]:
line = line.replace("%" + str(ii),
tmpArg)
ii = ii + 1
line = line.replace("%*", ' '.join(args[1:]))
args = line.split()
# split into ';;' separated commands
# unless it's an alias command
if args[0] != 'alias':
marker = line.find(';;')
if marker >= 0:
# queue up everything after marker
next = line[marker+2:].lstrip()
self.cmdqueue.append(next)
line = line[:marker].rstrip()
return line
# Command definitions, called by cmdloop()
# The argument is the remaining string on the command line
# Return true to exit from the command loop
do_h = cmd.Cmd.do_help
def do_break(self, arg, temporary = 0):
# break [ ([filename:]lineno | function) [, "condition"] ]
if not arg:
if self.breaks: # There's at least one
print "Num Type Disp Enb Where"
for bp in bdb.Breakpoint.bpbynumber:
if bp:
bp.bpprint()
return
# parse arguments; comma has lowest precedence
# and cannot occur in filename
filename = None
lineno = None
cond = None
comma = arg.find(',')
if comma > 0:
# parse stuff after comma: "condition"
cond = arg[comma+1:].lstrip()
arg = arg[:comma].rstrip()
# parse stuff before comma: [filename:]lineno | function
colon = arg.rfind(':')
funcname = None
if colon >= 0:
filename = arg[:colon].rstrip()
f = self.lookupmodule(filename)
if not f:
print '*** ', repr(filename),
print 'not found from sys.path'
return
else:
filename = f
arg = arg[colon+1:].lstrip()
try:
lineno = int(arg)
except ValueError, msg:
print '*** Bad lineno:', arg
return
else:
# no colon; can be lineno or function
try:
lineno = int(arg)
except ValueError:
try:
func = eval(arg,
self.curframe.f_globals,
self.curframe.f_locals)
except:
func = arg
try:
if hasattr(func, 'im_func'):
func = func.im_func
code = func.func_code
#use co_name to identify the bkpt (function names
#could be aliased, but co_name is invariant)
funcname = code.co_name
lineno = code.co_firstlineno
filename = code.co_filename
except:
# last thing to try
(ok, filename, ln) = self.lineinfo(arg)
if not ok:
print '*** The specified object',
print repr(arg),
print 'is not a function'
print ('or was not found '
'along sys.path.')
return
funcname = ok # ok contains a function name
lineno = int(ln)
if not filename:
filename = self.defaultFile()
# Check for reasonable breakpoint
line = self.checkline(filename, lineno)
if line:
# now set the break point
err = self.set_break(filename, line, temporary, cond, funcname)
if err: print '***', err
else:
bp = self.get_breaks(filename, line)[-1]
print "Breakpoint %d at %s:%d" % (bp.number,
bp.file,
bp.line)
# To be overridden in derived debuggers
def defaultFile(self):
"""Produce a reasonable default."""
filename = self.curframe.f_code.co_filename
if filename == '<string>' and self.mainpyfile:
filename = self.mainpyfile
return filename
do_b = do_break
def do_tbreak(self, arg):
self.do_break(arg, 1)
def lineinfo(self, identifier):
failed = (None, None, None)
# Input is identifier, may be in single quotes
idstring = identifier.split("'")
if len(idstring) == 1:
# not in single quotes
id = idstring[0].strip()
elif len(idstring) == 3:
# quoted
id = idstring[1].strip()
else:
return failed
if id == '': return failed
parts = id.split('.')
# Protection for derived debuggers
if parts[0] == 'self':
del parts[0]
if len(parts) == 0:
return failed
# Best first guess at file to look at
fname = self.defaultFile()
if len(parts) == 1:
item = parts[0]
else:
# More than one part.
# First is module, second is method/class
f = self.lookupmodule(parts[0])
if f:
fname = f
item = parts[1]
answer = find_function(item, fname)
return answer or failed
def checkline(self, filename, lineno):
"""Check whether specified line seems to be executable.
Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
line or EOF). Warning: testing is not comprehensive.
"""
line = linecache.getline(filename, lineno)
if not line:
print 'End of file'
return 0
line = line.strip()
# Don't allow setting breakpoint at a blank line
if (not line or (line[0] == '#') or
(line[:3] == '"""') or line[:3] == "'''"):
print '*** Blank or comment'
return 0
return lineno
def do_enable(self, arg):
args = arg.split()
for i in args:
try:
i = int(i)
except ValueError:
print 'Breakpoint index %r is not a number' % i
continue
if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
print 'No breakpoint numbered', i
continue
bp = bdb.Breakpoint.bpbynumber[i]
if bp:
bp.enable()
def do_disable(self, arg):
args = arg.split()
for i in args:
try:
i = int(i)
except ValueError:
print 'Breakpoint index %r is not a number' % i
continue
if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
print 'No breakpoint numbered', i
continue
bp = bdb.Breakpoint.bpbynumber[i]
if bp:
bp.disable()
def do_condition(self, arg):
# arg is breakpoint number and condition
args = arg.split(' ', 1)
bpnum = int(args[0].strip())
try:
cond = args[1]
except:
cond = None
bp = bdb.Breakpoint.bpbynumber[bpnum]
if bp:
bp.cond = cond
if not cond:
print 'Breakpoint', bpnum,
print 'is now unconditional.'
def do_ignore(self,arg):
"""arg is bp number followed by ignore count."""
args = arg.split()
bpnum = int(args[0].strip())
try:
count = int(args[1].strip())
except:
count = 0
bp = bdb.Breakpoint.bpbynumber[bpnum]
if bp:
bp.ignore = count
if count > 0:
reply = 'Will ignore next '
if count > 1:
reply = reply + '%d crossings' % count
else:
reply = reply + '1 crossing'
print reply + ' of breakpoint %d.' % bpnum
else:
print 'Will stop next time breakpoint',
print bpnum, 'is reached.'
def do_clear(self, arg):
"""Three possibilities, tried in this order:
clear -> clear all breaks, ask for confirmation
clear file:lineno -> clear all breaks at file:lineno
clear bpno bpno ... -> clear breakpoints by number"""
if not arg:
try:
reply = raw_input('Clear all breaks? ')
except EOFError:
reply = 'no'
reply = reply.strip().lower()
if reply in ('y', 'yes'):
self.clear_all_breaks()
return
if ':' in arg:
# Make sure it works for "clear C:\foo\bar.py:12"
i = arg.rfind(':')
filename = arg[:i]
arg = arg[i+1:]
try:
lineno = int(arg)
except:
err = "Invalid line number (%s)" % arg
else:
err = self.clear_break(filename, lineno)
if err: print '***', err
return
numberlist = arg.split()
for i in numberlist:
err = self.clear_bpbynumber(i)
if err:
print '***', err
else:
print 'Deleted breakpoint %s ' % (i,)
do_cl = do_clear # 'c' is already an abbreviation for 'continue'
def do_where(self, arg):
self.print_stack_trace()
do_w = do_where
do_bt = do_where
def do_up(self, arg):
if self.curindex == 0:
print '*** Oldest frame'
else:
self.curindex = self.curindex - 1
self.curframe = self.stack[self.curindex][0]
self.print_stack_entry(self.stack[self.curindex])
self.lineno = None
do_u = do_up
def do_down(self, arg):
if self.curindex + 1 == len(self.stack):
print '*** Newest frame'
else:
self.curindex = self.curindex + 1
self.curframe = self.stack[self.curindex][0]
self.print_stack_entry(self.stack[self.curindex])
self.lineno = None
do_d = do_down
def do_step(self, arg):
self.set_step()
return 1
do_s = do_step
def do_next(self, arg):
self.set_next(self.curframe)
return 1
do_n = do_next
def do_return(self, arg):
self.set_return(self.curframe)
return 1
do_r = do_return
def do_continue(self, arg):
self.set_continue()
return 1
do_c = do_cont = do_continue
def do_jump(self, arg):
if self.curindex + 1 != len(self.stack):
print "*** You can only jump within the bottom frame"
return
try:
arg = int(arg)
except ValueError:
print "*** The 'jump' command requires a line number."
else:
try:
# Do the jump, fix up our copy of the stack, and display the
# new position
self.curframe.f_lineno = arg
self.stack[self.curindex] = self.stack[self.curindex][0], arg
self.print_stack_entry(self.stack[self.curindex])
except ValueError, e:
print '*** Jump failed:', e
do_j = do_jump
def do_debug(self, arg):
sys.settrace(None)
globals = self.curframe.f_globals
locals = self.curframe.f_locals
p = Pdb()
p.prompt = "(%s) " % self.prompt.strip()
print "ENTERING RECURSIVE DEBUGGER"
sys.call_tracing(p.run, (arg, globals, locals))
print "LEAVING RECURSIVE DEBUGGER"
sys.settrace(self.trace_dispatch)
self.lastcmd = p.lastcmd
def do_quit(self, arg):
self._user_requested_quit = 1
self.set_quit()
return 1
do_q = do_quit
do_exit = do_quit
def do_EOF(self, arg):
print
self._user_requested_quit = 1
self.set_quit()
return 1
def do_args(self, arg):
f = self.curframe
co = f.f_code
dict = f.f_locals
n = co.co_argcount
if co.co_flags & 4: n = n+1
if co.co_flags & 8: n = n+1
for i in range(n):
name = co.co_varnames[i]
print name, '=',
if name in dict: print dict[name]
else: print "*** undefined ***"
do_a = do_args
def do_retval(self, arg):
if '__return__' in self.curframe.f_locals:
print self.curframe.f_locals['__return__']
else:
print '*** Not yet returned!'
do_rv = do_retval
def _getval(self, arg):
try:
return eval(arg, self.curframe.f_globals,
self.curframe.f_locals)
except:
t, v = sys.exc_info()[:2]
if isinstance(t, str):
exc_type_name = t
else: exc_type_name = t.__name__
print '***', exc_type_name + ':', repr(v)
raise
def do_p(self, arg):
try:
print repr(self._getval(arg))
except:
pass
def do_pp(self, arg):
try:
pprint.pprint(self._getval(arg))
except:
pass
def do_list(self, arg):
self.lastcmd = 'list'
last = None
if arg:
try:
x = eval(arg, {}, {})
if type(x) == type(()):
first, last = x
first = int(first)
last = int(last)
if last < first:
# Assume it's a count
last = first + last
else:
first = max(1, int(x) - 5)
except:
print '*** Error in argument:', repr(arg)
return
elif self.lineno is None:
first = max(1, self.curframe.f_lineno - 5)
else:
first = self.lineno + 1
if last is None:
last = first + 10
filename = self.curframe.f_code.co_filename
breaklist = self.get_file_breaks(filename)
try:
for lineno in range(first, last+1):
line = linecache.getline(filename, lineno)
if not line:
print '[EOF]'
break
else:
s = repr(lineno).rjust(3)
if len(s) < 4: s = s + ' '
if lineno in breaklist: s = s + 'B'
else: s = s + ' '
if lineno == self.curframe.f_lineno:
s = s + '->'
print s + '\t' + line,
self.lineno = lineno
except KeyboardInterrupt:
pass
do_l = do_list
def do_whatis(self, arg):
try:
value = eval(arg, self.curframe.f_globals,
self.curframe.f_locals)
except:
t, v = sys.exc_info()[:2]
if type(t) == type(''):
exc_type_name = t
else: exc_type_name = t.__name__
print '***', exc_type_name + ':', repr(v)
return
code = None
# Is it a function?
try: code = value.func_code
except: pass
if code:
print 'Function', code.co_name
return
# Is it an instance method?
try: code = value.im_func.func_code
except: pass
if code:
print 'Method', code.co_name
return
# None of the above...
print type(value)
def do_alias(self, arg):
args = arg.split()
if len(args) == 0:
keys = self.aliases.keys()
keys.sort()
for alias in keys:
print "%s = %s" % (alias, self.aliases[alias])
return
if args[0] in self.aliases and len(args) == 1:
print "%s = %s" % (args[0], self.aliases[args[0]])
else:
self.aliases[args[0]] = ' '.join(args[1:])
def do_unalias(self, arg):
args = arg.split()
if len(args) == 0: return
if args[0] in self.aliases:
del self.aliases[args[0]]
# Print a traceback starting at the top stack frame.
# The most recently entered frame is printed last;
# this is different from dbx and gdb, but consistent with
# the Python interpreter's stack trace.
# It is also consistent with the up/down commands (which are
# compatible with dbx and gdb: up moves towards 'main()'
# and down moves towards the most recent stack frame).
def print_stack_trace(self):
try:
for frame_lineno in self.stack:
self.print_stack_entry(frame_lineno)
except KeyboardInterrupt:
pass
def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
frame, lineno = frame_lineno
if frame is self.curframe:
print '>',
else:
print ' ',
print self.format_stack_entry(frame_lineno, prompt_prefix)
# Help methods (derived from pdb.doc)
def help_help(self):
self.help_h()
def help_h(self):
print """h(elp)
Without argument, print the list of available commands.
With a command name as argument, print help about that command
"help pdb" pipes the full documentation file to the $PAGER
"help exec" gives help on the ! command"""
def help_where(self):
self.help_w()
def help_w(self):
print """w(here)
Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the "current frame", which determines the
context of most commands. 'bt' is an alias for this command."""
help_bt = help_w
def help_down(self):
self.help_d()
def help_d(self):
print """d(own)
Move the current frame one level down in the stack trace
(to a newer frame)."""
def help_up(self):
self.help_u()
def help_u(self):
print """u(p)
Move the current frame one level up in the stack trace
(to an older frame)."""
def help_break(self):
self.help_b()
def help_b(self):
print """b(reak) ([file:]lineno | function) [, condition]
With a line number argument, set a break there in the current
file. With a function name, set a break at first executable line
of that function. Without argument, list all breaks. If a second
argument is present, it is a string specifying an expression
which must evaluate to true before the breakpoint is honored.
The line number may be prefixed with a filename and a colon,
to specify a breakpoint in another file (probably one that
hasn't been loaded yet). The file is searched for on sys.path;
the .py suffix may be omitted."""
def help_clear(self):
self.help_cl()
def help_cl(self):
print "cl(ear) filename:lineno"
print """cl(ear) [bpnumber [bpnumber...]]
With a space separated list of breakpoint numbers, clear
those breakpoints. Without argument, clear all breaks (but
first ask confirmation). With a filename:lineno argument,
clear all breaks at that line in that file.
Note that the argument is different from previous versions of
the debugger (in python distributions 1.5.1 and before) where
a linenumber was used instead of either filename:lineno or
breakpoint numbers."""
def help_tbreak(self):
print """tbreak same arguments as break, but breakpoint is
removed when first hit."""
def help_enable(self):
print """enable bpnumber [bpnumber ...]
Enables the breakpoints given as a space separated list of
bp numbers."""
def help_disable(self):
print """disable bpnumber [bpnumber ...]
Disables the breakpoints given as a space separated list of
bp numbers."""
def help_ignore(self):
print """ignore bpnumber count
Sets the ignore count for the given breakpoint number. A breakpoint
becomes active when the ignore count is zero. When non-zero, the
count is decremented each time the breakpoint is reached and the
breakpoint is not disabled and any associated condition evaluates
to true."""
def help_condition(self):
print """condition bpnumber str_condition
str_condition is a string specifying an expression which
must evaluate to true before the breakpoint is honored.
If str_condition is absent, any existing condition is removed;
i.e., the breakpoint is made unconditional."""
def help_step(self):
self.help_s()
def help_s(self):
print """s(tep)
Execute the current line, stop at the first possible occasion
(either in a function that is called or in the current function)."""
def help_next(self):
self.help_n()
def help_n(self):
print """n(ext)
Continue execution until the next line in the current function
is reached or it returns."""
def help_return(self):
self.help_r()
def help_r(self):
print """r(eturn)
Continue execution until the current function returns."""
def help_continue(self):
self.help_c()
def help_cont(self):
self.help_c()
def help_c(self):
print """c(ont(inue))
Continue execution, only stop when a breakpoint is encountered."""
def help_jump(self):
self.help_j()
def help_j(self):
print """j(ump) lineno
Set the next line that will be executed."""
def help_debug(self):
print """debug code
Enter a recursive debugger that steps through the code argument
(which is an arbitrary expression or statement to be executed
in the current environment)."""
def help_list(self):
self.help_l()
def help_l(self):
print """l(ist) [first [,last]]
List source code for the current file.
Without arguments, list 11 lines around the current line
or continue the previous listing.
With one argument, list 11 lines starting at that line.
With two arguments, list the given range;
if the second argument is less than the first, it is a count."""
def help_args(self):
self.help_a()
def help_a(self):
print """a(rgs)
Print the arguments of the current function."""
def help_p(self):
print """p expression
Print the value of the expression."""
def help_pp(self):
print """pp expression
Pretty-print the value of the expression."""
def help_exec(self):
print """(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
(Pdb)"""
def help_quit(self):
self.help_q()
def help_q(self):
print """q(uit) or exit - Quit from the debugger.
The program being executed is aborted."""
help_exit = help_q
def help_whatis(self):
print """whatis arg
Prints the type of the argument."""
def help_EOF(self):
print """EOF
Handles the receipt of EOF as a command."""
def help_alias(self):
print """alias [name [command [parameter parameter ...] ]]
Creates an alias called 'name' the executes 'command'. The command
must *not* be enclosed in quotes. Replaceable parameters are
indicated by %1, %2, and so on, while %* is replaced by all the
parameters. If no command is given, the current alias for name
is shown. If no name is given, all aliases are listed.
Aliases may be nested and can contain anything that can be
legally typed at the pdb prompt. Note! You *can* override
internal pdb commands with aliases! Those internal commands
are then hidden until the alias is removed. Aliasing is recursively
applied to the first word of the command line; all other words
in the line are left alone.
Some useful aliases (especially when placed in the .pdbrc file) are:
#Print instance variables (usage "pi classInst")
alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
#Print instance variables in self
alias ps pi self
"""
def help_unalias(self):
print """unalias name
Deletes the specified alias."""
def help_pdb(self):
help()
def lookupmodule(self, filename):
"""Helper function for break/clear parsing -- may be overridden.
lookupmodule() translates (possibly incomplete) file or module name
into an absolute file name.
"""
if os.path.isabs(filename) and os.path.exists(filename):
return filename
f = os.path.join(sys.path[0], filename)
if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
return f
root, ext = os.path.splitext(filename)
if ext == '':
filename = filename + '.py'
if os.path.isabs(filename):
return filename
for dirname in sys.path:
while os.path.islink(dirname):
dirname = os.readlink(dirname)
fullname = os.path.join(dirname, filename)
if os.path.exists(fullname):
return fullname
return None
def _runscript(self, filename):
# Start with fresh empty copy of globals and locals and tell the script
# that it's being run as __main__ to avoid scripts being able to access
# the pdb.py namespace.
globals_ = {"__name__" : "__main__"}
locals_ = globals_
# When bdb sets tracing, a number of call and line events happens
# BEFORE debugger even reaches user's code (and the exact sequence of
# events depends on python version). So we take special measures to
# avoid stopping before we reach the main script (see user_line and
# user_call for details).
self._wait_for_mainpyfile = 1
self.mainpyfile = self.canonic(filename)
self._user_requested_quit = 0
statement = 'execfile( "%s")' % filename
self.run(statement, globals=globals_, locals=locals_)
# Simplified interface
def run(statement, globals=None, locals=None):
Pdb().run(statement, globals, locals)
def runeval(expression, globals=None, locals=None):
return Pdb().runeval(expression, globals, locals)
def runctx(statement, globals, locals):
# B/W compatibility
run(statement, globals, locals)
def runcall(*args, **kwds):
return Pdb().runcall(*args, **kwds)
def set_trace():
Pdb().set_trace(sys._getframe().f_back)
# Post-Mortem interface
def post_mortem(t):
p = Pdb()
p.reset()
while t.tb_next is not None:
t = t.tb_next
p.interaction(t.tb_frame, t)
def pm():
post_mortem(sys.last_traceback)
# Main program for testing
TESTCMD = 'import x; x.main()'
def test():
run(TESTCMD)
# print help
def help():
for dirname in sys.path:
fullname = os.path.join(dirname, 'pdb.doc')
if os.path.exists(fullname):
sts = os.system('${PAGER-more} '+fullname)
if sts: print '*** Pager exit status:', sts
break
else:
print 'Sorry, can\'t find the help file "pdb.doc"',
print 'along the Python search path'
def main():
if not sys.argv[1:]:
print "usage: pdb.py scriptfile [arg] ..."
sys.exit(2)
mainpyfile = sys.argv[1] # Get script filename
if not os.path.exists(mainpyfile):
print 'Error:', mainpyfile, 'does not exist'
sys.exit(1)
del sys.argv[0] # Hide "pdb.py" from argument list
# Replace pdb's dir with script's dir in front of module search path.
sys.path[0] = os.path.dirname(mainpyfile)
# Note on saving/restoring sys.argv: it's a good idea when sys.argv was
# modified by the script being debugged. It's a bad idea when it was
# changed by the user from the command line. The best approach would be to
# have a "restart" command which would allow explicit specification of
# command line arguments.
pdb = Pdb()
while 1:
try:
pdb._runscript(mainpyfile)
if pdb._user_requested_quit:
break
print "The program finished and will be restarted"
except SystemExit:
# In most cases SystemExit does not warrant a post-mortem session.
print "The program exited via sys.exit(). Exit status: ",
print sys.exc_info()[1]
except:
traceback.print_exc()
print "Uncaught exception. Entering post mortem debugging"
print "Running 'cont' or 'step' will restart the program"
t = sys.exc_info()[2]
while t.tb_next is not None:
t = t.tb_next
pdb.interaction(t.tb_frame,t)
print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
# When invoked as main program, invoke the debugger on a script
if __name__=='__main__':
main()
| Python |
#! /usr/bin/env python
"""Conversions to/from quoted-printable transport encoding as per RFC 1521."""
# (Dec 1991 version).
__all__ = ["encode", "decode", "encodestring", "decodestring"]
ESCAPE = '='
MAXLINESIZE = 76
HEX = '0123456789ABCDEF'
EMPTYSTRING = ''
try:
from binascii import a2b_qp, b2a_qp
except ImportError:
a2b_qp = None
b2a_qp = None
def needsquoting(c, quotetabs, header):
"""Decide whether a particular character needs to be quoted.
The 'quotetabs' flag indicates whether embedded tabs and spaces should be
quoted. Note that line-ending tabs and spaces are always encoded, as per
RFC 1521.
"""
if c in ' \t':
return quotetabs
# if header, we have to escape _ because _ is used to escape space
if c == '_':
return header
return c == ESCAPE or not (' ' <= c <= '~')
def quote(c):
"""Quote a single character."""
i = ord(c)
return ESCAPE + HEX[i//16] + HEX[i%16]
def encode(input, output, quotetabs, header = 0):
"""Read 'input', apply quoted-printable encoding, and write to 'output'.
'input' and 'output' are files with readline() and write() methods.
The 'quotetabs' flag indicates whether embedded tabs and spaces should be
quoted. Note that line-ending tabs and spaces are always encoded, as per
RFC 1521.
The 'header' flag indicates whether we are encoding spaces as _ as per
RFC 1522.
"""
if b2a_qp is not None:
data = input.read()
odata = b2a_qp(data, quotetabs = quotetabs, header = header)
output.write(odata)
return
def write(s, output=output, lineEnd='\n'):
# RFC 1521 requires that the line ending in a space or tab must have
# that trailing character encoded.
if s and s[-1:] in ' \t':
output.write(s[:-1] + quote(s[-1]) + lineEnd)
elif s == '.':
output.write(quote(s) + lineEnd)
else:
output.write(s + lineEnd)
prevline = None
while 1:
line = input.readline()
if not line:
break
outline = []
# Strip off any readline induced trailing newline
stripped = ''
if line[-1:] == '\n':
line = line[:-1]
stripped = '\n'
# Calculate the un-length-limited encoded line
for c in line:
if needsquoting(c, quotetabs, header):
c = quote(c)
if header and c == ' ':
outline.append('_')
else:
outline.append(c)
# First, write out the previous line
if prevline is not None:
write(prevline)
# Now see if we need any soft line breaks because of RFC-imposed
# length limitations. Then do the thisline->prevline dance.
thisline = EMPTYSTRING.join(outline)
while len(thisline) > MAXLINESIZE:
# Don't forget to include the soft line break `=' sign in the
# length calculation!
write(thisline[:MAXLINESIZE-1], lineEnd='=\n')
thisline = thisline[MAXLINESIZE-1:]
# Write out the current line
prevline = thisline
# Write out the last line, without a trailing newline
if prevline is not None:
write(prevline, lineEnd=stripped)
def encodestring(s, quotetabs = 0, header = 0):
if b2a_qp is not None:
return b2a_qp(s, quotetabs = quotetabs, header = header)
from cStringIO import StringIO
infp = StringIO(s)
outfp = StringIO()
encode(infp, outfp, quotetabs, header)
return outfp.getvalue()
def decode(input, output, header = 0):
"""Read 'input', apply quoted-printable decoding, and write to 'output'.
'input' and 'output' are files with readline() and write() methods.
If 'header' is true, decode underscore as space (per RFC 1522)."""
if a2b_qp is not None:
data = input.read()
odata = a2b_qp(data, header = header)
output.write(odata)
return
new = ''
while 1:
line = input.readline()
if not line: break
i, n = 0, len(line)
if n > 0 and line[n-1] == '\n':
partial = 0; n = n-1
# Strip trailing whitespace
while n > 0 and line[n-1] in " \t\r":
n = n-1
else:
partial = 1
while i < n:
c = line[i]
if c == '_' and header:
new = new + ' '; i = i+1
elif c != ESCAPE:
new = new + c; i = i+1
elif i+1 == n and not partial:
partial = 1; break
elif i+1 < n and line[i+1] == ESCAPE:
new = new + ESCAPE; i = i+2
elif i+2 < n and ishex(line[i+1]) and ishex(line[i+2]):
new = new + chr(unhex(line[i+1:i+3])); i = i+3
else: # Bad escape sequence -- leave it in
new = new + c; i = i+1
if not partial:
output.write(new + '\n')
new = ''
if new:
output.write(new)
def decodestring(s, header = 0):
if a2b_qp is not None:
return a2b_qp(s, header = header)
from cStringIO import StringIO
infp = StringIO(s)
outfp = StringIO()
decode(infp, outfp, header = header)
return outfp.getvalue()
# Other helper functions
def ishex(c):
"""Return true if the character 'c' is a hexadecimal digit."""
return '0' <= c <= '9' or 'a' <= c <= 'f' or 'A' <= c <= 'F'
def unhex(s):
"""Get the integer value of a hexadecimal number."""
bits = 0
for c in s:
if '0' <= c <= '9':
i = ord('0')
elif 'a' <= c <= 'f':
i = ord('a')-10
elif 'A' <= c <= 'F':
i = ord('A')-10
else:
break
bits = bits*16 + (ord(c) - i)
return bits
def main():
import sys
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'td')
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print "usage: quopri [-t | -d] [file] ..."
print "-t: quote tabs"
print "-d: decode; default encode"
sys.exit(2)
deco = 0
tabs = 0
for o, a in opts:
if o == '-t': tabs = 1
if o == '-d': deco = 1
if tabs and deco:
sys.stdout = sys.stderr
print "-t and -d are mutually exclusive"
sys.exit(2)
if not args: args = ['-']
sts = 0
for file in args:
if file == '-':
fp = sys.stdin
else:
try:
fp = open(file)
except IOError, msg:
sys.stderr.write("%s: can't open (%s)\n" % (file, msg))
sts = 1
continue
if deco:
decode(fp, sys.stdout)
else:
encode(fp, sys.stdout, tabs)
if fp is not sys.stdin:
fp.close()
if sts:
sys.exit(sts)
if __name__ == '__main__':
main()
| Python |
"""Load / save to libwww-perl (LWP) format files.
Actually, the format is slightly extended from that used by LWP's
(libwww-perl's) HTTP::Cookies, to avoid losing some RFC 2965 information
not recorded by LWP.
It uses the version string "2.0", though really there isn't an LWP Cookies
2.0 format. This indicates that there is extra information in here
(domain_dot and # port_spec) while still being compatible with
libwww-perl, I hope.
"""
import time, re, logging
from cookielib import (reraise_unmasked_exceptions, FileCookieJar, Cookie,
MISSING_FILENAME_TEXT, join_header_words, split_header_words,
iso2time, time2isoz)
def lwp_cookie_str(cookie):
"""Return string representation of Cookie in an the LWP cookie file format.
Actually, the format is extended a bit -- see module docstring.
"""
h = [(cookie.name, cookie.value),
("path", cookie.path),
("domain", cookie.domain)]
if cookie.port is not None: h.append(("port", cookie.port))
if cookie.path_specified: h.append(("path_spec", None))
if cookie.port_specified: h.append(("port_spec", None))
if cookie.domain_initial_dot: h.append(("domain_dot", None))
if cookie.secure: h.append(("secure", None))
if cookie.expires: h.append(("expires",
time2isoz(float(cookie.expires))))
if cookie.discard: h.append(("discard", None))
if cookie.comment: h.append(("comment", cookie.comment))
if cookie.comment_url: h.append(("commenturl", cookie.comment_url))
keys = cookie._rest.keys()
keys.sort()
for k in keys:
h.append((k, str(cookie._rest[k])))
h.append(("version", str(cookie.version)))
return join_header_words([h])
class LWPCookieJar(FileCookieJar):
"""
The LWPCookieJar saves a sequence of"Set-Cookie3" lines.
"Set-Cookie3" is the format used by the libwww-perl libary, not known
to be compatible with any browser, but which is easy to read and
doesn't lose information about RFC 2965 cookies.
Additional methods
as_lwp_str(ignore_discard=True, ignore_expired=True)
"""
def as_lwp_str(self, ignore_discard=True, ignore_expires=True):
"""Return cookies as a string of "\n"-separated "Set-Cookie3" headers.
ignore_discard and ignore_expires: see docstring for FileCookieJar.save
"""
now = time.time()
r = []
for cookie in self:
if not ignore_discard and cookie.discard:
continue
if not ignore_expires and cookie.is_expired(now):
continue
r.append("Set-Cookie3: %s" % lwp_cookie_str(cookie))
return "\n".join(r+[""])
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename, "w")
try:
# There really isn't an LWP Cookies 2.0 format, but this indicates
# that there is extra information in here (domain_dot and
# port_spec) while still being compatible with libwww-perl, I hope.
f.write("#LWP-Cookies-2.0\n")
f.write(self.as_lwp_str(ignore_discard, ignore_expires))
finally:
f.close()
def _really_load(self, f, filename, ignore_discard, ignore_expires):
magic = f.readline()
if not re.search(self.magic_re, magic):
msg = "%s does not seem to contain cookies" % filename
raise IOError(msg)
now = time.time()
header = "Set-Cookie3:"
boolean_attrs = ("port_spec", "path_spec", "domain_dot",
"secure", "discard")
value_attrs = ("version",
"port", "path", "domain",
"expires",
"comment", "commenturl")
try:
while 1:
line = f.readline()
if line == "": break
if not line.startswith(header):
continue
line = line[len(header):].strip()
for data in split_header_words([line]):
name, value = data[0]
standard = {}
rest = {}
for k in boolean_attrs:
standard[k] = False
for k, v in data[1:]:
if k is not None:
lc = k.lower()
else:
lc = None
# don't lose case distinction for unknown fields
if (lc in value_attrs) or (lc in boolean_attrs):
k = lc
if k in boolean_attrs:
if v is None: v = True
standard[k] = v
elif k in value_attrs:
standard[k] = v
else:
rest[k] = v
h = standard.get
expires = h("expires")
discard = h("discard")
if expires is not None:
expires = iso2time(expires)
if expires is None:
discard = True
domain = h("domain")
domain_specified = domain.startswith(".")
c = Cookie(h("version"), name, value,
h("port"), h("port_spec"),
domain, domain_specified, h("domain_dot"),
h("path"), h("path_spec"),
h("secure"),
expires,
discard,
h("comment"),
h("commenturl"),
rest)
if not ignore_discard and c.discard:
continue
if not ignore_expires and c.is_expired(now):
continue
self.set_cookie(c)
except:
reraise_unmasked_exceptions((IOError,))
raise IOError("invalid Set-Cookie3 format file %s" % filename)
| Python |
"""Strptime-related classes and functions.
CLASSES:
LocaleTime -- Discovers and stores locale-specific time information
TimeRE -- Creates regexes for pattern matching a string of text containing
time information
FUNCTIONS:
_getlang -- Figure out what language is being used for the locale
strptime -- Calculates the time struct represented by the passed-in string
"""
import time
import locale
import calendar
from re import compile as re_compile
from re import IGNORECASE
from re import escape as re_escape
from datetime import date as datetime_date
try:
from thread import allocate_lock as _thread_allocate_lock
except:
from dummy_thread import allocate_lock as _thread_allocate_lock
__author__ = "Brett Cannon"
__email__ = "brett@python.org"
__all__ = ['strptime']
def _getlang():
# Figure out what the current language is set to.
return locale.getlocale(locale.LC_TIME)
class LocaleTime(object):
"""Stores and handles locale-specific information related to time.
ATTRIBUTES:
f_weekday -- full weekday names (7-item list)
a_weekday -- abbreviated weekday names (7-item list)
f_month -- full month names (13-item list; dummy value in [0], which
is added by code)
a_month -- abbreviated month names (13-item list, dummy value in
[0], which is added by code)
am_pm -- AM/PM representation (2-item list)
LC_date_time -- format string for date/time representation (string)
LC_date -- format string for date representation (string)
LC_time -- format string for time representation (string)
timezone -- daylight- and non-daylight-savings timezone representation
(2-item list of sets)
lang -- Language used by instance (2-item tuple)
"""
def __init__(self):
"""Set all attributes.
Order of methods called matters for dependency reasons.
The locale language is set at the offset and then checked again before
exiting. This is to make sure that the attributes were not set with a
mix of information from more than one locale. This would most likely
happen when using threads where one thread calls a locale-dependent
function while another thread changes the locale while the function in
the other thread is still running. Proper coding would call for
locks to prevent changing the locale while locale-dependent code is
running. The check here is done in case someone does not think about
doing this.
Only other possible issue is if someone changed the timezone and did
not call tz.tzset . That is an issue for the programmer, though,
since changing the timezone is worthless without that call.
"""
self.lang = _getlang()
self.__calc_weekday()
self.__calc_month()
self.__calc_am_pm()
self.__calc_timezone()
self.__calc_date_time()
if _getlang() != self.lang:
raise ValueError("locale changed during initialization")
def __pad(self, seq, front):
# Add '' to seq to either the front (is True), else the back.
seq = list(seq)
if front:
seq.insert(0, '')
else:
seq.append('')
return seq
def __calc_weekday(self):
# Set self.a_weekday and self.f_weekday using the calendar
# module.
a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
f_weekday = [calendar.day_name[i].lower() for i in range(7)]
self.a_weekday = a_weekday
self.f_weekday = f_weekday
def __calc_month(self):
# Set self.f_month and self.a_month using the calendar module.
a_month = [calendar.month_abbr[i].lower() for i in range(13)]
f_month = [calendar.month_name[i].lower() for i in range(13)]
self.a_month = a_month
self.f_month = f_month
def __calc_am_pm(self):
# Set self.am_pm by using time.strftime().
# The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
# magical; just happened to have used it everywhere else where a
# static date was needed.
am_pm = []
for hour in (01,22):
time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
am_pm.append(time.strftime("%p", time_tuple).lower())
self.am_pm = am_pm
def __calc_date_time(self):
# Set self.date_time, self.date, & self.time by using
# time.strftime().
# Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of
# overloaded numbers is minimized. The order in which searches for
# values within the format string is very important; it eliminates
# possible ambiguity for what something represents.
time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))
date_time = [None, None, None]
date_time[0] = time.strftime("%c", time_tuple).lower()
date_time[1] = time.strftime("%x", time_tuple).lower()
date_time[2] = time.strftime("%X", time_tuple).lower()
replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'),
(self.f_month[3], '%B'), (self.a_weekday[2], '%a'),
(self.a_month[3], '%b'), (self.am_pm[1], '%p'),
('1999', '%Y'), ('99', '%y'), ('22', '%H'),
('44', '%M'), ('55', '%S'), ('76', '%j'),
('17', '%d'), ('03', '%m'), ('3', '%m'),
# '3' needed for when no leading zero.
('2', '%w'), ('10', '%I')]
replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone
for tz in tz_values])
for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')):
current_format = date_time[offset]
for old, new in replacement_pairs:
# Must deal with possible lack of locale info
# manifesting itself as the empty string (e.g., Swedish's
# lack of AM/PM info) or a platform returning a tuple of empty
# strings (e.g., MacOS 9 having timezone as ('','')).
if old:
current_format = current_format.replace(old, new)
time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0))
if time.strftime(directive, time_tuple).find('00'):
U_W = '%U'
else:
U_W = '%W'
date_time[offset] = current_format.replace('11', U_W)
self.LC_date_time = date_time[0]
self.LC_date = date_time[1]
self.LC_time = date_time[2]
def __calc_timezone(self):
# Set self.timezone by using time.tzname.
# Do not worry about possibility of time.tzname[0] == timetzname[1]
# and time.daylight; handle that in strptime .
try:
time.tzset()
except AttributeError:
pass
no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
if time.daylight:
has_saving = frozenset([time.tzname[1].lower()])
else:
has_saving = frozenset()
self.timezone = (no_saving, has_saving)
class TimeRE(dict):
"""Handle conversion from format directives to regexes."""
def __init__(self, locale_time=None):
"""Create keys/values.
Order of execution is important for dependency reasons.
"""
if locale_time:
self.locale_time = locale_time
else:
self.locale_time = LocaleTime()
base = super(TimeRE, self)
base.__init__({
# The " \d" part of the regex is to make %c from ANSI C work
'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
'H': r"(?P<H>2[0-3]|[0-1]\d|\d)",
'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])",
'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])",
'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",
'M': r"(?P<M>[0-5]\d|\d)",
'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",
'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",
'w': r"(?P<w>[0-6])",
# W is set below by using 'U'
'y': r"(?P<y>\d\d)",
#XXX: Does 'Y' need to worry about having less or more than
# 4 digits?
'Y': r"(?P<Y>\d\d\d\d)",
'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),
'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'),
'p': self.__seqToRE(self.locale_time.am_pm, 'p'),
'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone
for tz in tz_names),
'Z'),
'%': '%'})
base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
base.__setitem__('x', self.pattern(self.locale_time.LC_date))
base.__setitem__('X', self.pattern(self.locale_time.LC_time))
def __seqToRE(self, to_convert, directive):
"""Convert a list to a regex string for matching a directive.
Want possible matching values to be from longest to shortest. This
prevents the possibility of a match occuring for a value that also
a substring of a larger value that should have matched (e.g., 'abc'
matching when 'abcdef' should have been the match).
"""
to_convert = sorted(to_convert, key=len, reverse=True)
for value in to_convert:
if value != '':
break
else:
return ''
regex = '|'.join(re_escape(stuff) for stuff in to_convert)
regex = '(?P<%s>%s' % (directive, regex)
return '%s)' % regex
def pattern(self, format):
"""Return regex pattern for the format string.
Need to make sure that any characters that might be interpreted as
regex syntax are escaped.
"""
processed_format = ''
# The sub() call escapes all characters that might be misconstrued
# as regex syntax. Cannot use re.escape since we have to deal with
# format directives (%m, etc.).
regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])")
format = regex_chars.sub(r"\\\1", format)
whitespace_replacement = re_compile('\s+')
format = whitespace_replacement.sub('\s*', format)
while '%' in format:
directive_index = format.index('%')+1
processed_format = "%s%s%s" % (processed_format,
format[:directive_index-1],
self[format[directive_index]])
format = format[directive_index+1:]
return "%s%s" % (processed_format, format)
def compile(self, format):
"""Return a compiled re object for the format string."""
return re_compile(self.pattern(format), IGNORECASE)
_cache_lock = _thread_allocate_lock()
# DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock
# first!
_TimeRE_cache = TimeRE()
_CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache
_regex_cache = {}
def strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
"""Return a time struct based on the input string and the format string."""
global _TimeRE_cache
_cache_lock.acquire()
try:
time_re = _TimeRE_cache
locale_time = time_re.locale_time
if _getlang() != locale_time.lang:
_TimeRE_cache = TimeRE()
if len(_regex_cache) > _CACHE_MAX_SIZE:
_regex_cache.clear()
format_regex = _regex_cache.get(format)
if not format_regex:
format_regex = time_re.compile(format)
_regex_cache[format] = format_regex
finally:
_cache_lock.release()
found = format_regex.match(data_string)
if not found:
raise ValueError("time data did not match format: data=%s fmt=%s" %
(data_string, format))
if len(data_string) != found.end():
raise ValueError("unconverted data remains: %s" %
data_string[found.end():])
year = 1900
month = day = 1
hour = minute = second = 0
tz = -1
# Default to -1 to signify that values not known; not critical to have,
# though
week_of_year = -1
week_of_year_start = -1
# weekday and julian defaulted to -1 so as to signal need to calculate
# values
weekday = julian = -1
found_dict = found.groupdict()
for group_key in found_dict.iterkeys():
# Directives not explicitly handled below:
# c, x, X
# handled by making out of other directives
# U, W
# worthless without day of the week
if group_key == 'y':
year = int(found_dict['y'])
# Open Group specification for strptime() states that a %y
#value in the range of [00, 68] is in the century 2000, while
#[69,99] is in the century 1900
if year <= 68:
year += 2000
else:
year += 1900
elif group_key == 'Y':
year = int(found_dict['Y'])
elif group_key == 'm':
month = int(found_dict['m'])
elif group_key == 'B':
month = locale_time.f_month.index(found_dict['B'].lower())
elif group_key == 'b':
month = locale_time.a_month.index(found_dict['b'].lower())
elif group_key == 'd':
day = int(found_dict['d'])
elif group_key == 'H':
hour = int(found_dict['H'])
elif group_key == 'I':
hour = int(found_dict['I'])
ampm = found_dict.get('p', '').lower()
# If there was no AM/PM indicator, we'll treat this like AM
if ampm in ('', locale_time.am_pm[0]):
# We're in AM so the hour is correct unless we're
# looking at 12 midnight.
# 12 midnight == 12 AM == hour 0
if hour == 12:
hour = 0
elif ampm == locale_time.am_pm[1]:
# We're in PM so we need to add 12 to the hour unless
# we're looking at 12 noon.
# 12 noon == 12 PM == hour 12
if hour != 12:
hour += 12
elif group_key == 'M':
minute = int(found_dict['M'])
elif group_key == 'S':
second = int(found_dict['S'])
elif group_key == 'A':
weekday = locale_time.f_weekday.index(found_dict['A'].lower())
elif group_key == 'a':
weekday = locale_time.a_weekday.index(found_dict['a'].lower())
elif group_key == 'w':
weekday = int(found_dict['w'])
if weekday == 0:
weekday = 6
else:
weekday -= 1
elif group_key == 'j':
julian = int(found_dict['j'])
elif group_key in ('U', 'W'):
week_of_year = int(found_dict[group_key])
if group_key == 'U':
# U starts week on Sunday
week_of_year_start = 6
else:
# W starts week on Monday
week_of_year_start = 0
elif group_key == 'Z':
# Since -1 is default value only need to worry about setting tz if
# it can be something other than -1.
found_zone = found_dict['Z'].lower()
for value, tz_values in enumerate(locale_time.timezone):
if found_zone in tz_values:
# Deal with bad locale setup where timezone names are the
# same and yet time.daylight is true; too ambiguous to
# be able to tell what timezone has daylight savings
if (time.tzname[0] == time.tzname[1] and
time.daylight and found_zone not in ("utc", "gmt")):
break
else:
tz = value
break
# If we know the week of the year and what day of that week, we can figure
# out the Julian day of the year
# Calculations below assume 0 is a Monday
if julian == -1 and week_of_year != -1 and weekday != -1:
# Calculate how many days in week 0
first_weekday = datetime_date(year, 1, 1).weekday()
preceeding_days = 7 - first_weekday
if preceeding_days == 7:
preceeding_days = 0
# Adjust for U directive so that calculations are not dependent on
# directive used to figure out week of year
if weekday == 6 and week_of_year_start == 6:
week_of_year -= 1
# If a year starts and ends on a Monday but a week is specified to
# start on a Sunday we need to up the week to counter-balance the fact
# that with %W that first Monday starts week 1 while with %U that is
# week 0 and thus shifts everything by a week
if weekday == 0 and first_weekday == 0 and week_of_year_start == 6:
week_of_year += 1
# If in week 0, then just figure out how many days from Jan 1 to day of
# week specified, else calculate by multiplying week of year by 7,
# adding in days in week 0, and the number of days from Monday to the
# day of the week
if week_of_year == 0:
julian = 1 + weekday - first_weekday
else:
days_to_week = preceeding_days + (7 * (week_of_year - 1))
julian = 1 + days_to_week + weekday
# Cannot pre-calculate datetime_date() since can change in Julian
#calculation and thus could have different value for the day of the week
#calculation
if julian == -1:
# Need to add 1 to result since first day of the year is 1, not 0.
julian = datetime_date(year, month, day).toordinal() - \
datetime_date(year, 1, 1).toordinal() + 1
else: # Assume that if they bothered to include Julian day it will
#be accurate
datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
year = datetime_result.year
month = datetime_result.month
day = datetime_result.day
if weekday == -1:
weekday = datetime_date(year, month, day).weekday()
return time.struct_time((year, month, day,
hour, minute, second,
weekday, julian, tz))
| Python |
"""
This module contains the core classes of version 2.0 of SAX for Python.
This file provides only default classes with absolutely minimum
functionality, from which drivers and applications can be subclassed.
Many of these classes are empty and are included only as documentation
of the interfaces.
$Id: handler.py,v 1.11 2004/05/06 03:47:48 fdrake Exp $
"""
version = '2.0beta'
#============================================================================
#
# HANDLER INTERFACES
#
#============================================================================
# ===== ERRORHANDLER =====
class ErrorHandler:
"""Basic interface for SAX error handlers.
If you create an object that implements this interface, then
register the object with your XMLReader, the parser will call the
methods in your object to report all warnings and errors. There
are three levels of errors available: warnings, (possibly)
recoverable errors, and unrecoverable errors. All methods take a
SAXParseException as the only parameter."""
def error(self, exception):
"Handle a recoverable error."
raise exception
def fatalError(self, exception):
"Handle a non-recoverable error."
raise exception
def warning(self, exception):
"Handle a warning."
print exception
# ===== CONTENTHANDLER =====
class ContentHandler:
"""Interface for receiving logical document content events.
This is the main callback interface in SAX, and the one most
important to applications. The order of events in this interface
mirrors the order of the information in the document."""
def __init__(self):
self._locator = None
def setDocumentLocator(self, locator):
"""Called by the parser to give the application a locator for
locating the origin of document events.
SAX parsers are strongly encouraged (though not absolutely
required) to supply a locator: if it does so, it must supply
the locator to the application by invoking this method before
invoking any of the other methods in the DocumentHandler
interface.
The locator allows the application to determine the end
position of any document-related event, even if the parser is
not reporting an error. Typically, the application will use
this information for reporting its own errors (such as
character content that does not match an application's
business rules). The information returned by the locator is
probably not sufficient for use with a search engine.
Note that the locator will return correct information only
during the invocation of the events in this interface. The
application should not attempt to use it at any other time."""
self._locator = locator
def startDocument(self):
"""Receive notification of the beginning of a document.
The SAX parser will invoke this method only once, before any
other methods in this interface or in DTDHandler (except for
setDocumentLocator)."""
def endDocument(self):
"""Receive notification of the end of a document.
The SAX parser will invoke this method only once, and it will
be the last method invoked during the parse. The parser shall
not invoke this method until it has either abandoned parsing
(because of an unrecoverable error) or reached the end of
input."""
def startPrefixMapping(self, prefix, uri):
"""Begin the scope of a prefix-URI Namespace mapping.
The information from this event is not necessary for normal
Namespace processing: the SAX XML reader will automatically
replace prefixes for element and attribute names when the
http://xml.org/sax/features/namespaces feature is true (the
default).
There are cases, however, when applications need to use
prefixes in character data or in attribute values, where they
cannot safely be expanded automatically; the
start/endPrefixMapping event supplies the information to the
application to expand prefixes in those contexts itself, if
necessary.
Note that start/endPrefixMapping events are not guaranteed to
be properly nested relative to each-other: all
startPrefixMapping events will occur before the corresponding
startElement event, and all endPrefixMapping events will occur
after the corresponding endElement event, but their order is
not guaranteed."""
def endPrefixMapping(self, prefix):
"""End the scope of a prefix-URI mapping.
See startPrefixMapping for details. This event will always
occur after the corresponding endElement event, but the order
of endPrefixMapping events is not otherwise guaranteed."""
def startElement(self, name, attrs):
"""Signals the start of an element in non-namespace mode.
The name parameter contains the raw XML 1.0 name of the
element type as a string and the attrs parameter holds an
instance of the Attributes class containing the attributes of
the element."""
def endElement(self, name):
"""Signals the end of an element in non-namespace mode.
The name parameter contains the name of the element type, just
as with the startElement event."""
def startElementNS(self, name, qname, attrs):
"""Signals the start of an element in namespace mode.
The name parameter contains the name of the element type as a
(uri, localname) tuple, the qname parameter the raw XML 1.0
name used in the source document, and the attrs parameter
holds an instance of the Attributes class containing the
attributes of the element.
The uri part of the name tuple is None for elements which have
no namespace."""
def endElementNS(self, name, qname):
"""Signals the end of an element in namespace mode.
The name parameter contains the name of the element type, just
as with the startElementNS event."""
def characters(self, content):
"""Receive notification of character data.
The Parser will call this method to report each chunk of
character data. SAX parsers may return all contiguous
character data in a single chunk, or they may split it into
several chunks; however, all of the characters in any single
event must come from the same external entity so that the
Locator provides useful information."""
def ignorableWhitespace(self, whitespace):
"""Receive notification of ignorable whitespace in element content.
Validating Parsers must use this method to report each chunk
of ignorable whitespace (see the W3C XML 1.0 recommendation,
section 2.10): non-validating parsers may also use this method
if they are capable of parsing and using content models.
SAX parsers may return all contiguous whitespace in a single
chunk, or they may split it into several chunks; however, all
of the characters in any single event must come from the same
external entity, so that the Locator provides useful
information."""
def processingInstruction(self, target, data):
"""Receive notification of a processing instruction.
The Parser will invoke this method once for each processing
instruction found: note that processing instructions may occur
before or after the main document element.
A SAX parser should never report an XML declaration (XML 1.0,
section 2.8) or a text declaration (XML 1.0, section 4.3.1)
using this method."""
def skippedEntity(self, name):
"""Receive notification of a skipped entity.
The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the
entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
http://xml.org/sax/features/external-general-entities and the
http://xml.org/sax/features/external-parameter-entities
properties."""
# ===== DTDHandler =====
class DTDHandler:
"""Handle DTD events.
This interface specifies only those DTD events required for basic
parsing (unparsed entities and attributes)."""
def notationDecl(self, name, publicId, systemId):
"Handle a notation declaration event."
def unparsedEntityDecl(self, name, publicId, systemId, ndata):
"Handle an unparsed entity declaration event."
# ===== ENTITYRESOLVER =====
class EntityResolver:
"""Basic interface for resolving entities. If you create an object
implementing this interface, then register the object with your
Parser, the parser will call the method in your object to
resolve all external entities. Note that DefaultHandler implements
this interface with the default behaviour."""
def resolveEntity(self, publicId, systemId):
"""Resolve the system identifier of an entity and return either
the system identifier to read from as a string, or an InputSource
to read from."""
return systemId
#============================================================================
#
# CORE FEATURES
#
#============================================================================
feature_namespaces = "http://xml.org/sax/features/namespaces"
# true: Perform Namespace processing (default).
# false: Optionally do not perform Namespace processing
# (implies namespace-prefixes).
# access: (parsing) read-only; (not parsing) read/write
feature_namespace_prefixes = "http://xml.org/sax/features/namespace-prefixes"
# true: Report the original prefixed names and attributes used for Namespace
# declarations.
# false: Do not report attributes used for Namespace declarations, and
# optionally do not report original prefixed names (default).
# access: (parsing) read-only; (not parsing) read/write
feature_string_interning = "http://xml.org/sax/features/string-interning"
# true: All element names, prefixes, attribute names, Namespace URIs, and
# local names are interned using the built-in intern function.
# false: Names are not necessarily interned, although they may be (default).
# access: (parsing) read-only; (not parsing) read/write
feature_validation = "http://xml.org/sax/features/validation"
# true: Report all validation errors (implies external-general-entities and
# external-parameter-entities).
# false: Do not report validation errors.
# access: (parsing) read-only; (not parsing) read/write
feature_external_ges = "http://xml.org/sax/features/external-general-entities"
# true: Include all external general (text) entities.
# false: Do not include external general entities.
# access: (parsing) read-only; (not parsing) read/write
feature_external_pes = "http://xml.org/sax/features/external-parameter-entities"
# true: Include all external parameter entities, including the external
# DTD subset.
# false: Do not include any external parameter entities, even the external
# DTD subset.
# access: (parsing) read-only; (not parsing) read/write
all_features = [feature_namespaces,
feature_namespace_prefixes,
feature_string_interning,
feature_validation,
feature_external_ges,
feature_external_pes]
#============================================================================
#
# CORE PROPERTIES
#
#============================================================================
property_lexical_handler = "http://xml.org/sax/properties/lexical-handler"
# data type: xml.sax.sax2lib.LexicalHandler
# description: An optional extension handler for lexical events like comments.
# access: read/write
property_declaration_handler = "http://xml.org/sax/properties/declaration-handler"
# data type: xml.sax.sax2lib.DeclHandler
# description: An optional extension handler for DTD-related events other
# than notations and unparsed entities.
# access: read/write
property_dom_node = "http://xml.org/sax/properties/dom-node"
# data type: org.w3c.dom.Node
# description: When parsing, the current DOM node being visited if this is
# a DOM iterator; when not parsing, the root DOM node for
# iteration.
# access: (parsing) read-only; (not parsing) read/write
property_xml_string = "http://xml.org/sax/properties/xml-string"
# data type: String
# description: The literal string of characters that was the source for
# the current event.
# access: read-only
property_encoding = "http://www.python.org/sax/properties/encoding"
# data type: String
# description: The name of the encoding to assume for input data.
# access: write: set the encoding, e.g. established by a higher-level
# protocol. May change during parsing (e.g. after
# processing a META tag)
# read: return the current encoding (possibly established through
# auto-detection.
# initial value: UTF-8
#
property_interning_dict = "http://www.python.org/sax/properties/interning-dict"
# data type: Dictionary
# description: The dictionary used to intern common strings in the document
# access: write: Request that the parser uses a specific dictionary, to
# allow interning across different documents
# read: return the current interning dictionary, or None
#
all_properties = [property_lexical_handler,
property_dom_node,
property_declaration_handler,
property_xml_string,
property_encoding,
property_interning_dict]
| Python |
"""\
A library of useful helper classes to the SAX classes, for the
convenience of application and driver writers.
"""
import os, urlparse, urllib, types
import handler
import xmlreader
try:
_StringTypes = [types.StringType, types.UnicodeType]
except AttributeError:
_StringTypes = [types.StringType]
# See whether the xmlcharrefreplace error handler is
# supported
try:
from codecs import xmlcharrefreplace_errors
_error_handling = "xmlcharrefreplace"
del xmlcharrefreplace_errors
except ImportError:
_error_handling = "strict"
def __dict_replace(s, d):
"""Replace substrings of a string using a dictionary."""
for key, value in d.items():
s = s.replace(key, value)
return s
def escape(data, entities={}):
"""Escape &, <, and > in a string of data.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
# must do ampersand first
data = data.replace("&", "&")
data = data.replace(">", ">")
data = data.replace("<", "<")
if entities:
data = __dict_replace(data, entities)
return data
def unescape(data, entities={}):
"""Unescape &, <, and > in a string of data.
You can unescape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
data = data.replace("<", "<")
data = data.replace(">", ">")
if entities:
data = __dict_replace(data, entities)
# must do ampersand last
return data.replace("&", "&")
def quoteattr(data, entities={}):
"""Escape and quote an attribute value.
Escape &, <, and > in a string of data, then quote it for use as
an attribute value. The \" character will be escaped as well, if
necessary.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
data = escape(data, entities)
if '"' in data:
if "'" in data:
data = '"%s"' % data.replace('"', """)
else:
data = "'%s'" % data
else:
data = '"%s"' % data
return data
class XMLGenerator(handler.ContentHandler):
def __init__(self, out=None, encoding="iso-8859-1"):
if out is None:
import sys
out = sys.stdout
handler.ContentHandler.__init__(self)
self._out = out
self._ns_contexts = [{}] # contains uri -> prefix dicts
self._current_context = self._ns_contexts[-1]
self._undeclared_ns_maps = []
self._encoding = encoding
def _write(self, text):
if isinstance(text, str):
self._out.write(text)
else:
self._out.write(text.encode(self._encoding, _error_handling))
# ContentHandler methods
def startDocument(self):
self._write('<?xml version="1.0" encoding="%s"?>\n' %
self._encoding)
def startPrefixMapping(self, prefix, uri):
self._ns_contexts.append(self._current_context.copy())
self._current_context[uri] = prefix
self._undeclared_ns_maps.append((prefix, uri))
def endPrefixMapping(self, prefix):
self._current_context = self._ns_contexts[-1]
del self._ns_contexts[-1]
def startElement(self, name, attrs):
self._write('<' + name)
for (name, value) in attrs.items():
self._write(' %s=%s' % (name, quoteattr(value)))
self._write('>')
def endElement(self, name):
self._write('</%s>' % name)
def startElementNS(self, name, qname, attrs):
if name[0] is None:
# if the name was not namespace-scoped, use the unqualified part
name = name[1]
else:
# else try to restore the original prefix from the namespace
name = self._current_context[name[0]] + ":" + name[1]
self._write('<' + name)
for pair in self._undeclared_ns_maps:
self._write(' xmlns:%s="%s"' % pair)
self._undeclared_ns_maps = []
for (name, value) in attrs.items():
name = self._current_context[name[0]] + ":" + name[1]
self._write(' %s=%s' % (name, quoteattr(value)))
self._write('>')
def endElementNS(self, name, qname):
if name[0] is None:
name = name[1]
else:
name = self._current_context[name[0]] + ":" + name[1]
self._write('</%s>' % name)
def characters(self, content):
self._write(escape(content))
def ignorableWhitespace(self, content):
self._write(content)
def processingInstruction(self, target, data):
self._write('<?%s %s?>' % (target, data))
class XMLFilterBase(xmlreader.XMLReader):
"""This class is designed to sit between an XMLReader and the
client application's event handlers. By default, it does nothing
but pass requests up to the reader and events on to the handlers
unmodified, but subclasses can override specific methods to modify
the event stream or the configuration requests as they pass
through."""
def __init__(self, parent = None):
xmlreader.XMLReader.__init__(self)
self._parent = parent
# ErrorHandler methods
def error(self, exception):
self._err_handler.error(exception)
def fatalError(self, exception):
self._err_handler.fatalError(exception)
def warning(self, exception):
self._err_handler.warning(exception)
# ContentHandler methods
def setDocumentLocator(self, locator):
self._cont_handler.setDocumentLocator(locator)
def startDocument(self):
self._cont_handler.startDocument()
def endDocument(self):
self._cont_handler.endDocument()
def startPrefixMapping(self, prefix, uri):
self._cont_handler.startPrefixMapping(prefix, uri)
def endPrefixMapping(self, prefix):
self._cont_handler.endPrefixMapping(prefix)
def startElement(self, name, attrs):
self._cont_handler.startElement(name, attrs)
def endElement(self, name):
self._cont_handler.endElement(name)
def startElementNS(self, name, qname, attrs):
self._cont_handler.startElementNS(name, qname, attrs)
def endElementNS(self, name, qname):
self._cont_handler.endElementNS(name, qname)
def characters(self, content):
self._cont_handler.characters(content)
def ignorableWhitespace(self, chars):
self._cont_handler.ignorableWhitespace(chars)
def processingInstruction(self, target, data):
self._cont_handler.processingInstruction(target, data)
def skippedEntity(self, name):
self._cont_handler.skippedEntity(name)
# DTDHandler methods
def notationDecl(self, name, publicId, systemId):
self._dtd_handler.notationDecl(name, publicId, systemId)
def unparsedEntityDecl(self, name, publicId, systemId, ndata):
self._dtd_handler.unparsedEntityDecl(name, publicId, systemId, ndata)
# EntityResolver methods
def resolveEntity(self, publicId, systemId):
return self._ent_handler.resolveEntity(publicId, systemId)
# XMLReader methods
def parse(self, source):
self._parent.setContentHandler(self)
self._parent.setErrorHandler(self)
self._parent.setEntityResolver(self)
self._parent.setDTDHandler(self)
self._parent.parse(source)
def setLocale(self, locale):
self._parent.setLocale(locale)
def getFeature(self, name):
return self._parent.getFeature(name)
def setFeature(self, name, state):
self._parent.setFeature(name, state)
def getProperty(self, name):
return self._parent.getProperty(name)
def setProperty(self, name, value):
self._parent.setProperty(name, value)
# XMLFilter methods
def getParent(self):
return self._parent
def setParent(self, parent):
self._parent = parent
# --- Utility functions
def prepare_input_source(source, base = ""):
"""This function takes an InputSource and an optional base URL and
returns a fully resolved InputSource object ready for reading."""
if type(source) in _StringTypes:
source = xmlreader.InputSource(source)
elif hasattr(source, "read"):
f = source
source = xmlreader.InputSource()
source.setByteStream(f)
if hasattr(f, "name"):
source.setSystemId(f.name)
if source.getByteStream() is None:
sysid = source.getSystemId()
basehead = os.path.dirname(os.path.normpath(base))
sysidfilename = os.path.join(basehead, sysid)
if os.path.isfile(sysidfilename):
source.setSystemId(sysidfilename)
f = open(sysidfilename, "rb")
else:
source.setSystemId(urlparse.urljoin(base, sysid))
f = urllib.urlopen(source.getSystemId())
source.setByteStream(f)
return source
| Python |
"""Different kinds of SAX Exceptions"""
import sys
if sys.platform[:4] == "java":
from java.lang import Exception
del sys
# ===== SAXEXCEPTION =====
class SAXException(Exception):
"""Encapsulate an XML error or warning. This class can contain
basic error or warning information from either the XML parser or
the application: you can subclass it to provide additional
functionality, or to add localization. Note that although you will
receive a SAXException as the argument to the handlers in the
ErrorHandler interface, you are not actually required to throw
the exception; instead, you can simply read the information in
it."""
def __init__(self, msg, exception=None):
"""Creates an exception. The message is required, but the exception
is optional."""
self._msg = msg
self._exception = exception
Exception.__init__(self, msg)
def getMessage(self):
"Return a message for this exception."
return self._msg
def getException(self):
"Return the embedded exception, or None if there was none."
return self._exception
def __str__(self):
"Create a string representation of the exception."
return self._msg
def __getitem__(self, ix):
"""Avoids weird error messages if someone does exception[ix] by
mistake, since Exception has __getitem__ defined."""
raise AttributeError("__getitem__")
# ===== SAXPARSEEXCEPTION =====
class SAXParseException(SAXException):
"""Encapsulate an XML parse error or warning.
This exception will include information for locating the error in
the original XML document. Note that although the application will
receive a SAXParseException as the argument to the handlers in the
ErrorHandler interface, the application is not actually required
to throw the exception; instead, it can simply read the
information in it and take a different action.
Since this exception is a subclass of SAXException, it inherits
the ability to wrap another exception."""
def __init__(self, msg, exception, locator):
"Creates the exception. The exception parameter is allowed to be None."
SAXException.__init__(self, msg, exception)
self._locator = locator
# We need to cache this stuff at construction time.
# If this exception is thrown, the objects through which we must
# traverse to get this information may be deleted by the time
# it gets caught.
self._systemId = self._locator.getSystemId()
self._colnum = self._locator.getColumnNumber()
self._linenum = self._locator.getLineNumber()
def getColumnNumber(self):
"""The column number of the end of the text where the exception
occurred."""
return self._colnum
def getLineNumber(self):
"The line number of the end of the text where the exception occurred."
return self._linenum
def getPublicId(self):
"Get the public identifier of the entity where the exception occurred."
return self._locator.getPublicId()
def getSystemId(self):
"Get the system identifier of the entity where the exception occurred."
return self._systemId
def __str__(self):
"Create a string representation of the exception."
sysid = self.getSystemId()
if sysid is None:
sysid = "<unknown>"
linenum = self.getLineNumber()
if linenum is None:
linenum = "?"
colnum = self.getColumnNumber()
if colnum is None:
colnum = "?"
return "%s:%s:%s: %s" % (sysid, linenum, colnum, self._msg)
# ===== SAXNOTRECOGNIZEDEXCEPTION =====
class SAXNotRecognizedException(SAXException):
"""Exception class for an unrecognized identifier.
An XMLReader will raise this exception when it is confronted with an
unrecognized feature or property. SAX applications and extensions may
use this class for similar purposes."""
# ===== SAXNOTSUPPORTEDEXCEPTION =====
class SAXNotSupportedException(SAXException):
"""Exception class for an unsupported operation.
An XMLReader will raise this exception when a service it cannot
perform is requested (specifically setting a state or value). SAX
applications and extensions may use this class for similar
purposes."""
# ===== SAXNOTSUPPORTEDEXCEPTION =====
class SAXReaderNotAvailable(SAXNotSupportedException):
"""Exception class for a missing driver.
An XMLReader module (driver) should raise this exception when it
is first imported, e.g. when a support module cannot be imported.
It also may be raised during parsing, e.g. if executing an external
program is not permitted."""
| Python |
"""
SAX driver for the pyexpat C module. This driver works with
pyexpat.__version__ == '2.22'.
"""
version = "0.20"
from xml.sax._exceptions import *
from xml.sax.handler import feature_validation, feature_namespaces
from xml.sax.handler import feature_namespace_prefixes
from xml.sax.handler import feature_external_ges, feature_external_pes
from xml.sax.handler import feature_string_interning
from xml.sax.handler import property_xml_string, property_interning_dict
# xml.parsers.expat does not raise ImportError in Jython
import sys
if sys.platform[:4] == "java":
raise SAXReaderNotAvailable("expat not available in Java", None)
del sys
try:
from xml.parsers import expat
except ImportError:
raise SAXReaderNotAvailable("expat not supported", None)
else:
if not hasattr(expat, "ParserCreate"):
raise SAXReaderNotAvailable("expat not supported", None)
from xml.sax import xmlreader, saxutils, handler
AttributesImpl = xmlreader.AttributesImpl
AttributesNSImpl = xmlreader.AttributesNSImpl
# If we're using a sufficiently recent version of Python, we can use
# weak references to avoid cycles between the parser and content
# handler, otherwise we'll just have to pretend.
try:
import _weakref
except ImportError:
def _mkproxy(o):
return o
else:
import weakref
_mkproxy = weakref.proxy
del weakref, _weakref
# --- ExpatLocator
class ExpatLocator(xmlreader.Locator):
"""Locator for use with the ExpatParser class.
This uses a weak reference to the parser object to avoid creating
a circular reference between the parser and the content handler.
"""
def __init__(self, parser):
self._ref = _mkproxy(parser)
def getColumnNumber(self):
parser = self._ref
if parser._parser is None:
return None
return parser._parser.ErrorColumnNumber
def getLineNumber(self):
parser = self._ref
if parser._parser is None:
return 1
return parser._parser.ErrorLineNumber
def getPublicId(self):
parser = self._ref
if parser is None:
return None
return parser._source.getPublicId()
def getSystemId(self):
parser = self._ref
if parser is None:
return None
return parser._source.getSystemId()
# --- ExpatParser
class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
"""SAX driver for the pyexpat C module."""
def __init__(self, namespaceHandling=0, bufsize=2**16-20):
xmlreader.IncrementalParser.__init__(self, bufsize)
self._source = xmlreader.InputSource()
self._parser = None
self._namespaces = namespaceHandling
self._lex_handler_prop = None
self._parsing = 0
self._entity_stack = []
self._external_ges = 1
self._interning = None
# XMLReader methods
def parse(self, source):
"Parse an XML document from a URL or an InputSource."
source = saxutils.prepare_input_source(source)
self._source = source
self.reset()
self._cont_handler.setDocumentLocator(ExpatLocator(self))
xmlreader.IncrementalParser.parse(self, source)
def prepareParser(self, source):
if source.getSystemId() != None:
self._parser.SetBase(source.getSystemId())
# Redefined setContentHandler to allow changing handlers during parsing
def setContentHandler(self, handler):
xmlreader.IncrementalParser.setContentHandler(self, handler)
if self._parsing:
self._reset_cont_handler()
def getFeature(self, name):
if name == feature_namespaces:
return self._namespaces
elif name == feature_string_interning:
return self._interning is not None
elif name in (feature_validation, feature_external_pes,
feature_namespace_prefixes):
return 0
elif name == feature_external_ges:
return self._external_ges
raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
def setFeature(self, name, state):
if self._parsing:
raise SAXNotSupportedException("Cannot set features while parsing")
if name == feature_namespaces:
self._namespaces = state
elif name == feature_external_ges:
self._external_ges = state
elif name == feature_string_interning:
if state:
if self._interning is None:
self._interning = {}
else:
self._interning = None
elif name == feature_validation:
if state:
raise SAXNotSupportedException(
"expat does not support validation")
elif name == feature_external_pes:
if state:
raise SAXNotSupportedException(
"expat does not read external parameter entities")
elif name == feature_namespace_prefixes:
if state:
raise SAXNotSupportedException(
"expat does not report namespace prefixes")
else:
raise SAXNotRecognizedException(
"Feature '%s' not recognized" % name)
def getProperty(self, name):
if name == handler.property_lexical_handler:
return self._lex_handler_prop
elif name == property_interning_dict:
return self._interning
elif name == property_xml_string:
if self._parser:
if hasattr(self._parser, "GetInputContext"):
return self._parser.GetInputContext()
else:
raise SAXNotRecognizedException(
"This version of expat does not support getting"
" the XML string")
else:
raise SAXNotSupportedException(
"XML string cannot be returned when not parsing")
raise SAXNotRecognizedException("Property '%s' not recognized" % name)
def setProperty(self, name, value):
if name == handler.property_lexical_handler:
self._lex_handler_prop = value
if self._parsing:
self._reset_lex_handler_prop()
elif name == property_interning_dict:
self._interning = value
elif name == property_xml_string:
raise SAXNotSupportedException("Property '%s' cannot be set" %
name)
else:
raise SAXNotRecognizedException("Property '%s' not recognized" %
name)
# IncrementalParser methods
def feed(self, data, isFinal = 0):
if not self._parsing:
self.reset()
self._parsing = 1
self._cont_handler.startDocument()
try:
# The isFinal parameter is internal to the expat reader.
# If it is set to true, expat will check validity of the entire
# document. When feeding chunks, they are not normally final -
# except when invoked from close.
self._parser.Parse(data, isFinal)
except expat.error, e:
exc = SAXParseException(expat.ErrorString(e.code), e, self)
# FIXME: when to invoke error()?
self._err_handler.fatalError(exc)
def close(self):
if self._entity_stack:
# If we are completing an external entity, do nothing here
return
self.feed("", isFinal = 1)
self._cont_handler.endDocument()
self._parsing = 0
# break cycle created by expat handlers pointing to our methods
self._parser = None
def _reset_cont_handler(self):
self._parser.ProcessingInstructionHandler = \
self._cont_handler.processingInstruction
self._parser.CharacterDataHandler = self._cont_handler.characters
def _reset_lex_handler_prop(self):
lex = self._lex_handler_prop
parser = self._parser
if lex is None:
parser.CommentHandler = None
parser.StartCdataSectionHandler = None
parser.EndCdataSectionHandler = None
parser.StartDoctypeDeclHandler = None
parser.EndDoctypeDeclHandler = None
else:
parser.CommentHandler = lex.comment
parser.StartCdataSectionHandler = lex.startCDATA
parser.EndCdataSectionHandler = lex.endCDATA
parser.StartDoctypeDeclHandler = self.start_doctype_decl
parser.EndDoctypeDeclHandler = lex.endDTD
def reset(self):
if self._namespaces:
self._parser = expat.ParserCreate(None, " ",
intern=self._interning)
self._parser.namespace_prefixes = 1
self._parser.StartElementHandler = self.start_element_ns
self._parser.EndElementHandler = self.end_element_ns
else:
self._parser = expat.ParserCreate(intern = self._interning)
self._parser.StartElementHandler = self.start_element
self._parser.EndElementHandler = self.end_element
self._reset_cont_handler()
self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl
self._parser.NotationDeclHandler = self.notation_decl
self._parser.StartNamespaceDeclHandler = self.start_namespace_decl
self._parser.EndNamespaceDeclHandler = self.end_namespace_decl
self._decl_handler_prop = None
if self._lex_handler_prop:
self._reset_lex_handler_prop()
# self._parser.DefaultHandler =
# self._parser.DefaultHandlerExpand =
# self._parser.NotStandaloneHandler =
self._parser.ExternalEntityRefHandler = self.external_entity_ref
try:
self._parser.SkippedEntityHandler = self.skipped_entity_handler
except AttributeError:
# This pyexpat does not support SkippedEntity
pass
self._parser.SetParamEntityParsing(
expat.XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
self._parsing = 0
self._entity_stack = []
# Locator methods
def getColumnNumber(self):
if self._parser is None:
return None
return self._parser.ErrorColumnNumber
def getLineNumber(self):
if self._parser is None:
return 1
return self._parser.ErrorLineNumber
def getPublicId(self):
return self._source.getPublicId()
def getSystemId(self):
return self._source.getSystemId()
# event handlers
def start_element(self, name, attrs):
self._cont_handler.startElement(name, AttributesImpl(attrs))
def end_element(self, name):
self._cont_handler.endElement(name)
def start_element_ns(self, name, attrs):
pair = name.split()
if len(pair) == 1:
# no namespace
pair = (None, name)
elif len(pair) == 3:
pair = pair[0], pair[1]
else:
# default namespace
pair = tuple(pair)
newattrs = {}
qnames = {}
for (aname, value) in attrs.items():
parts = aname.split()
length = len(parts)
if length == 1:
# no namespace
qname = aname
apair = (None, aname)
elif length == 3:
qname = "%s:%s" % (parts[2], parts[1])
apair = parts[0], parts[1]
else:
# default namespace
qname = parts[1]
apair = tuple(parts)
newattrs[apair] = value
qnames[apair] = qname
self._cont_handler.startElementNS(pair, None,
AttributesNSImpl(newattrs, qnames))
def end_element_ns(self, name):
pair = name.split()
if len(pair) == 1:
pair = (None, name)
elif len(pair) == 3:
pair = pair[0], pair[1]
else:
pair = tuple(pair)
self._cont_handler.endElementNS(pair, None)
# this is not used (call directly to ContentHandler)
def processing_instruction(self, target, data):
self._cont_handler.processingInstruction(target, data)
# this is not used (call directly to ContentHandler)
def character_data(self, data):
self._cont_handler.characters(data)
def start_namespace_decl(self, prefix, uri):
self._cont_handler.startPrefixMapping(prefix, uri)
def end_namespace_decl(self, prefix):
self._cont_handler.endPrefixMapping(prefix)
def start_doctype_decl(self, name, sysid, pubid, has_internal_subset):
self._lex_handler_prop.startDTD(name, pubid, sysid)
def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):
self._dtd_handler.unparsedEntityDecl(name, pubid, sysid, notation_name)
def notation_decl(self, name, base, sysid, pubid):
self._dtd_handler.notationDecl(name, pubid, sysid)
def external_entity_ref(self, context, base, sysid, pubid):
if not self._external_ges:
return 1
source = self._ent_handler.resolveEntity(pubid, sysid)
source = saxutils.prepare_input_source(source,
self._source.getSystemId() or
"")
self._entity_stack.append((self._parser, self._source))
self._parser = self._parser.ExternalEntityParserCreate(context)
self._source = source
try:
xmlreader.IncrementalParser.parse(self, source)
except:
return 0 # FIXME: save error info here?
(self._parser, self._source) = self._entity_stack[-1]
del self._entity_stack[-1]
return 1
def skipped_entity_handler(self, name, is_pe):
if is_pe:
# The SAX spec requires to report skipped PEs with a '%'
name = '%'+name
self._cont_handler.skippedEntity(name)
# ---
def create_parser(*args, **kwargs):
return ExpatParser(*args, **kwargs)
# ---
if __name__ == "__main__":
import xml.sax
p = create_parser()
p.setContentHandler(xml.sax.XMLGenerator())
p.setErrorHandler(xml.sax.ErrorHandler())
p.parse("../../../hamlet.xml")
| Python |
"""Simple API for XML (SAX) implementation for Python.
This module provides an implementation of the SAX 2 interface;
information about the Java version of the interface can be found at
http://www.megginson.com/SAX/. The Python version of the interface is
documented at <...>.
This package contains the following modules:
handler -- Base classes and constants which define the SAX 2 API for
the 'client-side' of SAX for Python.
saxutils -- Implementation of the convenience classes commonly used to
work with SAX.
xmlreader -- Base classes and constants which define the SAX 2 API for
the parsers used with SAX for Python.
expatreader -- Driver that allows use of the Expat parser with SAX.
"""
from xmlreader import InputSource
from handler import ContentHandler, ErrorHandler
from _exceptions import SAXException, SAXNotRecognizedException, \
SAXParseException, SAXNotSupportedException, \
SAXReaderNotAvailable
def parse(source, handler, errorHandler=ErrorHandler()):
parser = make_parser()
parser.setContentHandler(handler)
parser.setErrorHandler(errorHandler)
parser.parse(source)
def parseString(string, handler, errorHandler=ErrorHandler()):
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
if errorHandler is None:
errorHandler = ErrorHandler()
parser = make_parser()
parser.setContentHandler(handler)
parser.setErrorHandler(errorHandler)
inpsrc = InputSource()
inpsrc.setByteStream(StringIO(string))
parser.parse(inpsrc)
# this is the parser list used by the make_parser function if no
# alternatives are given as parameters to the function
default_parser_list = ["xml.sax.expatreader"]
# tell modulefinder that importing sax potentially imports expatreader
_false = 0
if _false:
import xml.sax.expatreader
import os, sys
if os.environ.has_key("PY_SAX_PARSER"):
default_parser_list = os.environ["PY_SAX_PARSER"].split(",")
del os
_key = "python.xml.sax.parser"
if sys.platform[:4] == "java" and sys.registry.containsKey(_key):
default_parser_list = sys.registry.getProperty(_key).split(",")
def make_parser(parser_list = []):
"""Creates and returns a SAX parser.
Creates the first parser it is able to instantiate of the ones
given in the list created by doing parser_list +
default_parser_list. The lists must contain the names of Python
modules containing both a SAX parser and a create_parser function."""
for parser_name in parser_list + default_parser_list:
try:
return _create_parser(parser_name)
except ImportError,e:
import sys
if sys.modules.has_key(parser_name):
# The parser module was found, but importing it
# failed unexpectedly, pass this exception through
raise
except SAXReaderNotAvailable:
# The parser module detected that it won't work properly,
# so try the next one
pass
raise SAXReaderNotAvailable("No parsers found", None)
# --- Internal utility methods used by make_parser
if sys.platform[ : 4] == "java":
def _create_parser(parser_name):
from org.python.core import imp
drv_module = imp.importName(parser_name, 0, globals())
return drv_module.create_parser()
else:
def _create_parser(parser_name):
drv_module = __import__(parser_name,{},{},['create_parser'])
return drv_module.create_parser()
del sys
| Python |
"""An XML Reader is the SAX 2 name for an XML parser. XML Parsers
should be based on this code. """
import handler
from _exceptions import SAXNotSupportedException, SAXNotRecognizedException
# ===== XMLREADER =====
class XMLReader:
"""Interface for reading an XML document using callbacks.
XMLReader is the interface that an XML parser's SAX2 driver must
implement. This interface allows an application to set and query
features and properties in the parser, to register event handlers
for document processing, and to initiate a document parse.
All SAX interfaces are assumed to be synchronous: the parse
methods must not return until parsing is complete, and readers
must wait for an event-handler callback to return before reporting
the next event."""
def __init__(self):
self._cont_handler = handler.ContentHandler()
self._dtd_handler = handler.DTDHandler()
self._ent_handler = handler.EntityResolver()
self._err_handler = handler.ErrorHandler()
def parse(self, source):
"Parse an XML document from a system identifier or an InputSource."
raise NotImplementedError("This method must be implemented!")
def getContentHandler(self):
"Returns the current ContentHandler."
return self._cont_handler
def setContentHandler(self, handler):
"Registers a new object to receive document content events."
self._cont_handler = handler
def getDTDHandler(self):
"Returns the current DTD handler."
return self._dtd_handler
def setDTDHandler(self, handler):
"Register an object to receive basic DTD-related events."
self._dtd_handler = handler
def getEntityResolver(self):
"Returns the current EntityResolver."
return self._ent_handler
def setEntityResolver(self, resolver):
"Register an object to resolve external entities."
self._ent_handler = resolver
def getErrorHandler(self):
"Returns the current ErrorHandler."
return self._err_handler
def setErrorHandler(self, handler):
"Register an object to receive error-message events."
self._err_handler = handler
def setLocale(self, locale):
"""Allow an application to set the locale for errors and warnings.
SAX parsers are not required to provide localization for errors
and warnings; if they cannot support the requested locale,
however, they must throw a SAX exception. Applications may
request a locale change in the middle of a parse."""
raise SAXNotSupportedException("Locale support not implemented")
def getFeature(self, name):
"Looks up and returns the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
def setFeature(self, name, state):
"Sets the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
def getProperty(self, name):
"Looks up and returns the value of a SAX2 property."
raise SAXNotRecognizedException("Property '%s' not recognized" % name)
def setProperty(self, name, value):
"Sets the value of a SAX2 property."
raise SAXNotRecognizedException("Property '%s' not recognized" % name)
class IncrementalParser(XMLReader):
"""This interface adds three extra methods to the XMLReader
interface that allow XML parsers to support incremental
parsing. Support for this interface is optional, since not all
underlying XML parsers support this functionality.
When the parser is instantiated it is ready to begin accepting
data from the feed method immediately. After parsing has been
finished with a call to close the reset method must be called to
make the parser ready to accept new data, either from feed or
using the parse method.
Note that these methods must _not_ be called during parsing, that
is, after parse has been called and before it returns.
By default, the class also implements the parse method of the XMLReader
interface using the feed, close and reset methods of the
IncrementalParser interface as a convenience to SAX 2.0 driver
writers."""
def __init__(self, bufsize=2**16):
self._bufsize = bufsize
XMLReader.__init__(self)
def parse(self, source):
import saxutils
source = saxutils.prepare_input_source(source)
self.prepareParser(source)
file = source.getByteStream()
buffer = file.read(self._bufsize)
while buffer != "":
self.feed(buffer)
buffer = file.read(self._bufsize)
self.close()
def feed(self, data):
"""This method gives the raw XML data in the data parameter to
the parser and makes it parse the data, emitting the
corresponding events. It is allowed for XML constructs to be
split across several calls to feed.
feed may raise SAXException."""
raise NotImplementedError("This method must be implemented!")
def prepareParser(self, source):
"""This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing."""
raise NotImplementedError("prepareParser must be overridden!")
def close(self):
"""This method is called when the entire XML document has been
passed to the parser through the feed method, to notify the
parser that there are no more data. This allows the parser to
do the final checks on the document and empty the internal
data buffer.
The parser will not be ready to parse another document until
the reset method has been called.
close may raise SAXException."""
raise NotImplementedError("This method must be implemented!")
def reset(self):
"""This method is called after close has been called to reset
the parser so that it is ready to parse new documents. The
results of calling parse or feed after close without calling
reset are undefined."""
raise NotImplementedError("This method must be implemented!")
# ===== LOCATOR =====
class Locator:
"""Interface for associating a SAX event with a document
location. A locator object will return valid results only during
calls to DocumentHandler methods; at any other time, the
results are unpredictable."""
def getColumnNumber(self):
"Return the column number where the current event ends."
return -1
def getLineNumber(self):
"Return the line number where the current event ends."
return -1
def getPublicId(self):
"Return the public identifier for the current event."
return None
def getSystemId(self):
"Return the system identifier for the current event."
return None
# ===== INPUTSOURCE =====
class InputSource:
"""Encapsulation of the information needed by the XMLReader to
read entities.
This class may include information about the public identifier,
system identifier, byte stream (possibly with character encoding
information) and/or the character stream of an entity.
Applications will create objects of this class for use in the
XMLReader.parse method and for returning from
EntityResolver.resolveEntity.
An InputSource belongs to the application, the XMLReader is not
allowed to modify InputSource objects passed to it from the
application, although it may make copies and modify those."""
def __init__(self, system_id = None):
self.__system_id = system_id
self.__public_id = None
self.__encoding = None
self.__bytefile = None
self.__charfile = None
def setPublicId(self, public_id):
"Sets the public identifier of this InputSource."
self.__public_id = public_id
def getPublicId(self):
"Returns the public identifier of this InputSource."
return self.__public_id
def setSystemId(self, system_id):
"Sets the system identifier of this InputSource."
self.__system_id = system_id
def getSystemId(self):
"Returns the system identifier of this InputSource."
return self.__system_id
def setEncoding(self, encoding):
"""Sets the character encoding of this InputSource.
The encoding must be a string acceptable for an XML encoding
declaration (see section 4.3.3 of the XML recommendation).
The encoding attribute of the InputSource is ignored if the
InputSource also contains a character stream."""
self.__encoding = encoding
def getEncoding(self):
"Get the character encoding of this InputSource."
return self.__encoding
def setByteStream(self, bytefile):
"""Set the byte stream (a Python file-like object which does
not perform byte-to-character conversion) for this input
source.
The SAX parser will ignore this if there is also a character
stream specified, but it will use a byte stream in preference
to opening a URI connection itself.
If the application knows the character encoding of the byte
stream, it should set it with the setEncoding method."""
self.__bytefile = bytefile
def getByteStream(self):
"""Get the byte stream for this input source.
The getEncoding method will return the character encoding for
this byte stream, or None if unknown."""
return self.__bytefile
def setCharacterStream(self, charfile):
"""Set the character stream for this input source. (The stream
must be a Python 2.0 Unicode-wrapped file-like that performs
conversion to Unicode strings.)
If there is a character stream specified, the SAX parser will
ignore any byte stream and will not attempt to open a URI
connection to the system identifier."""
self.__charfile = charfile
def getCharacterStream(self):
"Get the character stream for this input source."
return self.__charfile
# ===== ATTRIBUTESIMPL =====
class AttributesImpl:
def __init__(self, attrs):
"""Non-NS-aware implementation.
attrs should be of the form {name : value}."""
self._attrs = attrs
def getLength(self):
return len(self._attrs)
def getType(self, name):
return "CDATA"
def getValue(self, name):
return self._attrs[name]
def getValueByQName(self, name):
return self._attrs[name]
def getNameByQName(self, name):
if not self._attrs.has_key(name):
raise KeyError, name
return name
def getQNameByName(self, name):
if not self._attrs.has_key(name):
raise KeyError, name
return name
def getNames(self):
return self._attrs.keys()
def getQNames(self):
return self._attrs.keys()
def __len__(self):
return len(self._attrs)
def __getitem__(self, name):
return self._attrs[name]
def keys(self):
return self._attrs.keys()
def has_key(self, name):
return self._attrs.has_key(name)
def __contains__(self, name):
return self._attrs.has_key(name)
def get(self, name, alternative=None):
return self._attrs.get(name, alternative)
def copy(self):
return self.__class__(self._attrs)
def items(self):
return self._attrs.items()
def values(self):
return self._attrs.values()
# ===== ATTRIBUTESNSIMPL =====
class AttributesNSImpl(AttributesImpl):
def __init__(self, attrs, qnames):
"""NS-aware implementation.
attrs should be of the form {(ns_uri, lname): value, ...}.
qnames of the form {(ns_uri, lname): qname, ...}."""
self._attrs = attrs
self._qnames = qnames
def getValueByQName(self, name):
for (nsname, qname) in self._qnames.items():
if qname == name:
return self._attrs[nsname]
raise KeyError, name
def getNameByQName(self, name):
for (nsname, qname) in self._qnames.items():
if qname == name:
return nsname
raise KeyError, name
def getQNameByName(self, name):
return self._qnames[name]
def getQNames(self):
return self._qnames.values()
def copy(self):
return self.__class__(self._attrs, self._qnames)
def _test():
XMLReader()
IncrementalParser()
Locator()
if __name__ == "__main__":
_test()
| Python |
"""\
minidom.py -- a lightweight DOM implementation.
parse("foo.xml")
parseString("<foo><bar/></foo>")
Todo:
=====
* convenience methods for getting elements and text.
* more testing
* bring some of the writer and linearizer code into conformance with this
interface
* SAX 2 namespaces
"""
import xml.dom
from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
from xml.dom.minicompat import *
from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS
_TupleType = type(())
# This is used by the ID-cache invalidation checks; the list isn't
# actually complete, since the nodes being checked will never be the
# DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is
# the node being added or removed, not the node being modified.)
#
_nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE,
xml.dom.Node.ENTITY_REFERENCE_NODE)
class Node(xml.dom.Node, GetattrMagic):
namespaceURI = None # this is non-null only for elements and attributes
parentNode = None
ownerDocument = None
nextSibling = None
previousSibling = None
prefix = EMPTY_PREFIX # non-null only for NS elements and attributes
def __nonzero__(self):
return True
def toxml(self, encoding = None):
return self.toprettyxml("", "", encoding)
def toprettyxml(self, indent="\t", newl="\n", encoding = None):
# indent = the indentation string to prepend, per level
# newl = the newline string to append
writer = _get_StringIO()
if encoding is not None:
import codecs
# Can't use codecs.getwriter to preserve 2.0 compatibility
writer = codecs.lookup(encoding)[3](writer)
if self.nodeType == Node.DOCUMENT_NODE:
# Can pass encoding only to document, to put it into XML header
self.writexml(writer, "", indent, newl, encoding)
else:
self.writexml(writer, "", indent, newl)
return writer.getvalue()
def hasChildNodes(self):
if self.childNodes:
return True
else:
return False
def _get_childNodes(self):
return self.childNodes
def _get_firstChild(self):
if self.childNodes:
return self.childNodes[0]
def _get_lastChild(self):
if self.childNodes:
return self.childNodes[-1]
def insertBefore(self, newChild, refChild):
if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
for c in tuple(newChild.childNodes):
self.insertBefore(c, refChild)
### The DOM does not clearly specify what to return in this case
return newChild
if newChild.nodeType not in self._child_node_types:
raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(newChild), repr(self)))
if newChild.parentNode is not None:
newChild.parentNode.removeChild(newChild)
if refChild is None:
self.appendChild(newChild)
else:
try:
index = self.childNodes.index(refChild)
except ValueError:
raise xml.dom.NotFoundErr()
if newChild.nodeType in _nodeTypes_with_children:
_clear_id_cache(self)
self.childNodes.insert(index, newChild)
newChild.nextSibling = refChild
refChild.previousSibling = newChild
if index:
node = self.childNodes[index-1]
node.nextSibling = newChild
newChild.previousSibling = node
else:
newChild.previousSibling = None
newChild.parentNode = self
return newChild
def appendChild(self, node):
if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
for c in tuple(node.childNodes):
self.appendChild(c)
### The DOM does not clearly specify what to return in this case
return node
if node.nodeType not in self._child_node_types:
raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(node), repr(self)))
elif node.nodeType in _nodeTypes_with_children:
_clear_id_cache(self)
if node.parentNode is not None:
node.parentNode.removeChild(node)
_append_child(self, node)
node.nextSibling = None
return node
def replaceChild(self, newChild, oldChild):
if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
refChild = oldChild.nextSibling
self.removeChild(oldChild)
return self.insertBefore(newChild, refChild)
if newChild.nodeType not in self._child_node_types:
raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(newChild), repr(self)))
if newChild.parentNode is not None:
newChild.parentNode.removeChild(newChild)
if newChild is oldChild:
return
try:
index = self.childNodes.index(oldChild)
except ValueError:
raise xml.dom.NotFoundErr()
self.childNodes[index] = newChild
newChild.parentNode = self
oldChild.parentNode = None
if (newChild.nodeType in _nodeTypes_with_children
or oldChild.nodeType in _nodeTypes_with_children):
_clear_id_cache(self)
newChild.nextSibling = oldChild.nextSibling
newChild.previousSibling = oldChild.previousSibling
oldChild.nextSibling = None
oldChild.previousSibling = None
if newChild.previousSibling:
newChild.previousSibling.nextSibling = newChild
if newChild.nextSibling:
newChild.nextSibling.previousSibling = newChild
return oldChild
def removeChild(self, oldChild):
try:
self.childNodes.remove(oldChild)
except ValueError:
raise xml.dom.NotFoundErr()
if oldChild.nextSibling is not None:
oldChild.nextSibling.previousSibling = oldChild.previousSibling
if oldChild.previousSibling is not None:
oldChild.previousSibling.nextSibling = oldChild.nextSibling
oldChild.nextSibling = oldChild.previousSibling = None
if oldChild.nodeType in _nodeTypes_with_children:
_clear_id_cache(self)
oldChild.parentNode = None
return oldChild
def normalize(self):
L = []
for child in self.childNodes:
if child.nodeType == Node.TEXT_NODE:
data = child.data
if data and L and L[-1].nodeType == child.nodeType:
# collapse text node
node = L[-1]
node.data = node.data + child.data
node.nextSibling = child.nextSibling
child.unlink()
elif data:
if L:
L[-1].nextSibling = child
child.previousSibling = L[-1]
else:
child.previousSibling = None
L.append(child)
else:
# empty text node; discard
child.unlink()
else:
if L:
L[-1].nextSibling = child
child.previousSibling = L[-1]
else:
child.previousSibling = None
L.append(child)
if child.nodeType == Node.ELEMENT_NODE:
child.normalize()
self.childNodes[:] = L
def cloneNode(self, deep):
return _clone_node(self, deep, self.ownerDocument or self)
def isSupported(self, feature, version):
return self.ownerDocument.implementation.hasFeature(feature, version)
def _get_localName(self):
# Overridden in Element and Attr where localName can be Non-Null
return None
# Node interfaces from Level 3 (WD 9 April 2002)
def isSameNode(self, other):
return self is other
def getInterface(self, feature):
if self.isSupported(feature, None):
return self
else:
return None
# The "user data" functions use a dictionary that is only present
# if some user data has been set, so be careful not to assume it
# exists.
def getUserData(self, key):
try:
return self._user_data[key][0]
except (AttributeError, KeyError):
return None
def setUserData(self, key, data, handler):
old = None
try:
d = self._user_data
except AttributeError:
d = {}
self._user_data = d
if d.has_key(key):
old = d[key][0]
if data is None:
# ignore handlers passed for None
handler = None
if old is not None:
del d[key]
else:
d[key] = (data, handler)
return old
def _call_user_data_handler(self, operation, src, dst):
if hasattr(self, "_user_data"):
for key, (data, handler) in self._user_data.items():
if handler is not None:
handler.handle(operation, key, data, src, dst)
# minidom-specific API:
def unlink(self):
self.parentNode = self.ownerDocument = None
if self.childNodes:
for child in self.childNodes:
child.unlink()
self.childNodes = NodeList()
self.previousSibling = None
self.nextSibling = None
defproperty(Node, "firstChild", doc="First child node, or None.")
defproperty(Node, "lastChild", doc="Last child node, or None.")
defproperty(Node, "localName", doc="Namespace-local name of this node.")
def _append_child(self, node):
# fast path with less checks; usable by DOM builders if careful
childNodes = self.childNodes
if childNodes:
last = childNodes[-1]
node.__dict__["previousSibling"] = last
last.__dict__["nextSibling"] = node
childNodes.append(node)
node.__dict__["parentNode"] = self
def _in_document(node):
# return True iff node is part of a document tree
while node is not None:
if node.nodeType == Node.DOCUMENT_NODE:
return True
node = node.parentNode
return False
def _write_data(writer, data):
"Writes datachars to writer."
data = data.replace("&", "&").replace("<", "<")
data = data.replace("\"", """).replace(">", ">")
writer.write(data)
def _get_elements_by_tagName_helper(parent, name, rc):
for node in parent.childNodes:
if node.nodeType == Node.ELEMENT_NODE and \
(name == "*" or node.tagName == name):
rc.append(node)
_get_elements_by_tagName_helper(node, name, rc)
return rc
def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
for node in parent.childNodes:
if node.nodeType == Node.ELEMENT_NODE:
if ((localName == "*" or node.localName == localName) and
(nsURI == "*" or node.namespaceURI == nsURI)):
rc.append(node)
_get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
return rc
class DocumentFragment(Node):
nodeType = Node.DOCUMENT_FRAGMENT_NODE
nodeName = "#document-fragment"
nodeValue = None
attributes = None
parentNode = None
_child_node_types = (Node.ELEMENT_NODE,
Node.TEXT_NODE,
Node.CDATA_SECTION_NODE,
Node.ENTITY_REFERENCE_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE,
Node.NOTATION_NODE)
def __init__(self):
self.childNodes = NodeList()
class Attr(Node):
nodeType = Node.ATTRIBUTE_NODE
attributes = None
ownerElement = None
specified = False
_is_id = False
_child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
prefix=None):
# skip setattr for performance
d = self.__dict__
d["nodeName"] = d["name"] = qName
d["namespaceURI"] = namespaceURI
d["prefix"] = prefix
d['childNodes'] = NodeList()
# Add the single child node that represents the value of the attr
self.childNodes.append(Text())
# nodeValue and value are set elsewhere
def _get_localName(self):
return self.nodeName.split(":", 1)[-1]
def _get_name(self):
return self.name
def _get_specified(self):
return self.specified
def __setattr__(self, name, value):
d = self.__dict__
if name in ("value", "nodeValue"):
d["value"] = d["nodeValue"] = value
d2 = self.childNodes[0].__dict__
d2["data"] = d2["nodeValue"] = value
if self.ownerElement is not None:
_clear_id_cache(self.ownerElement)
elif name in ("name", "nodeName"):
d["name"] = d["nodeName"] = value
if self.ownerElement is not None:
_clear_id_cache(self.ownerElement)
else:
d[name] = value
def _set_prefix(self, prefix):
nsuri = self.namespaceURI
if prefix == "xmlns":
if nsuri and nsuri != XMLNS_NAMESPACE:
raise xml.dom.NamespaceErr(
"illegal use of 'xmlns' prefix for the wrong namespace")
d = self.__dict__
d['prefix'] = prefix
if prefix is None:
newName = self.localName
else:
newName = "%s:%s" % (prefix, self.localName)
if self.ownerElement:
_clear_id_cache(self.ownerElement)
d['nodeName'] = d['name'] = newName
def _set_value(self, value):
d = self.__dict__
d['value'] = d['nodeValue'] = value
if self.ownerElement:
_clear_id_cache(self.ownerElement)
self.childNodes[0].data = value
def unlink(self):
# This implementation does not call the base implementation
# since most of that is not needed, and the expense of the
# method call is not warranted. We duplicate the removal of
# children, but that's all we needed from the base class.
elem = self.ownerElement
if elem is not None:
del elem._attrs[self.nodeName]
del elem._attrsNS[(self.namespaceURI, self.localName)]
if self._is_id:
self._is_id = False
elem._magic_id_nodes -= 1
self.ownerDocument._magic_id_count -= 1
for child in self.childNodes:
child.unlink()
del self.childNodes[:]
def _get_isId(self):
if self._is_id:
return True
doc = self.ownerDocument
elem = self.ownerElement
if doc is None or elem is None:
return False
info = doc._get_elem_info(elem)
if info is None:
return False
if self.namespaceURI:
return info.isIdNS(self.namespaceURI, self.localName)
else:
return info.isId(self.nodeName)
def _get_schemaType(self):
doc = self.ownerDocument
elem = self.ownerElement
if doc is None or elem is None:
return _no_type
info = doc._get_elem_info(elem)
if info is None:
return _no_type
if self.namespaceURI:
return info.getAttributeTypeNS(self.namespaceURI, self.localName)
else:
return info.getAttributeType(self.nodeName)
defproperty(Attr, "isId", doc="True if this attribute is an ID.")
defproperty(Attr, "localName", doc="Namespace-local name of this attribute.")
defproperty(Attr, "schemaType", doc="Schema type for this attribute.")
class NamedNodeMap(NewStyle, GetattrMagic):
"""The attribute list is a transient interface to the underlying
dictionaries. Mutations here will change the underlying element's
dictionary.
Ordering is imposed artificially and does not reflect the order of
attributes as found in an input document.
"""
__slots__ = ('_attrs', '_attrsNS', '_ownerElement')
def __init__(self, attrs, attrsNS, ownerElement):
self._attrs = attrs
self._attrsNS = attrsNS
self._ownerElement = ownerElement
def _get_length(self):
return len(self._attrs)
def item(self, index):
try:
return self[self._attrs.keys()[index]]
except IndexError:
return None
def items(self):
L = []
for node in self._attrs.values():
L.append((node.nodeName, node.value))
return L
def itemsNS(self):
L = []
for node in self._attrs.values():
L.append(((node.namespaceURI, node.localName), node.value))
return L
def has_key(self, key):
if isinstance(key, StringTypes):
return self._attrs.has_key(key)
else:
return self._attrsNS.has_key(key)
def keys(self):
return self._attrs.keys()
def keysNS(self):
return self._attrsNS.keys()
def values(self):
return self._attrs.values()
def get(self, name, value=None):
return self._attrs.get(name, value)
__len__ = _get_length
def __cmp__(self, other):
if self._attrs is getattr(other, "_attrs", None):
return 0
else:
return cmp(id(self), id(other))
def __getitem__(self, attname_or_tuple):
if isinstance(attname_or_tuple, _TupleType):
return self._attrsNS[attname_or_tuple]
else:
return self._attrs[attname_or_tuple]
# same as set
def __setitem__(self, attname, value):
if isinstance(value, StringTypes):
try:
node = self._attrs[attname]
except KeyError:
node = Attr(attname)
node.ownerDocument = self._ownerElement.ownerDocument
self.setNamedItem(node)
node.value = value
else:
if not isinstance(value, Attr):
raise TypeError, "value must be a string or Attr object"
node = value
self.setNamedItem(node)
def getNamedItem(self, name):
try:
return self._attrs[name]
except KeyError:
return None
def getNamedItemNS(self, namespaceURI, localName):
try:
return self._attrsNS[(namespaceURI, localName)]
except KeyError:
return None
def removeNamedItem(self, name):
n = self.getNamedItem(name)
if n is not None:
_clear_id_cache(self._ownerElement)
del self._attrs[n.nodeName]
del self._attrsNS[(n.namespaceURI, n.localName)]
if n.__dict__.has_key('ownerElement'):
n.__dict__['ownerElement'] = None
return n
else:
raise xml.dom.NotFoundErr()
def removeNamedItemNS(self, namespaceURI, localName):
n = self.getNamedItemNS(namespaceURI, localName)
if n is not None:
_clear_id_cache(self._ownerElement)
del self._attrsNS[(n.namespaceURI, n.localName)]
del self._attrs[n.nodeName]
if n.__dict__.has_key('ownerElement'):
n.__dict__['ownerElement'] = None
return n
else:
raise xml.dom.NotFoundErr()
def setNamedItem(self, node):
if not isinstance(node, Attr):
raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(node), repr(self)))
old = self._attrs.get(node.name)
if old:
old.unlink()
self._attrs[node.name] = node
self._attrsNS[(node.namespaceURI, node.localName)] = node
node.ownerElement = self._ownerElement
_clear_id_cache(node.ownerElement)
return old
def setNamedItemNS(self, node):
return self.setNamedItem(node)
def __delitem__(self, attname_or_tuple):
node = self[attname_or_tuple]
_clear_id_cache(node.ownerElement)
node.unlink()
def __getstate__(self):
return self._attrs, self._attrsNS, self._ownerElement
def __setstate__(self, state):
self._attrs, self._attrsNS, self._ownerElement = state
defproperty(NamedNodeMap, "length",
doc="Number of nodes in the NamedNodeMap.")
AttributeList = NamedNodeMap
class TypeInfo(NewStyle):
__slots__ = 'namespace', 'name'
def __init__(self, namespace, name):
self.namespace = namespace
self.name = name
def __repr__(self):
if self.namespace:
return "<TypeInfo %r (from %r)>" % (self.name, self.namespace)
else:
return "<TypeInfo %r>" % self.name
def _get_name(self):
return self.name
def _get_namespace(self):
return self.namespace
_no_type = TypeInfo(None, None)
class Element(Node):
nodeType = Node.ELEMENT_NODE
nodeValue = None
schemaType = _no_type
_magic_id_nodes = 0
_child_node_types = (Node.ELEMENT_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE,
Node.TEXT_NODE,
Node.CDATA_SECTION_NODE,
Node.ENTITY_REFERENCE_NODE)
def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
localName=None):
self.tagName = self.nodeName = tagName
self.prefix = prefix
self.namespaceURI = namespaceURI
self.childNodes = NodeList()
self._attrs = {} # attributes are double-indexed:
self._attrsNS = {} # tagName -> Attribute
# URI,localName -> Attribute
# in the future: consider lazy generation
# of attribute objects this is too tricky
# for now because of headaches with
# namespaces.
def _get_localName(self):
return self.tagName.split(":", 1)[-1]
def _get_tagName(self):
return self.tagName
def unlink(self):
for attr in self._attrs.values():
attr.unlink()
self._attrs = None
self._attrsNS = None
Node.unlink(self)
def getAttribute(self, attname):
try:
return self._attrs[attname].value
except KeyError:
return ""
def getAttributeNS(self, namespaceURI, localName):
try:
return self._attrsNS[(namespaceURI, localName)].value
except KeyError:
return ""
def setAttribute(self, attname, value):
attr = self.getAttributeNode(attname)
if attr is None:
attr = Attr(attname)
# for performance
d = attr.__dict__
d["value"] = d["nodeValue"] = value
d["ownerDocument"] = self.ownerDocument
self.setAttributeNode(attr)
elif value != attr.value:
d = attr.__dict__
d["value"] = d["nodeValue"] = value
if attr.isId:
_clear_id_cache(self)
def setAttributeNS(self, namespaceURI, qualifiedName, value):
prefix, localname = _nssplit(qualifiedName)
attr = self.getAttributeNodeNS(namespaceURI, localname)
if attr is None:
# for performance
attr = Attr(qualifiedName, namespaceURI, localname, prefix)
d = attr.__dict__
d["prefix"] = prefix
d["nodeName"] = qualifiedName
d["value"] = d["nodeValue"] = value
d["ownerDocument"] = self.ownerDocument
self.setAttributeNode(attr)
else:
d = attr.__dict__
if value != attr.value:
d["value"] = d["nodeValue"] = value
if attr.isId:
_clear_id_cache(self)
if attr.prefix != prefix:
d["prefix"] = prefix
d["nodeName"] = qualifiedName
def getAttributeNode(self, attrname):
return self._attrs.get(attrname)
def getAttributeNodeNS(self, namespaceURI, localName):
return self._attrsNS.get((namespaceURI, localName))
def setAttributeNode(self, attr):
if attr.ownerElement not in (None, self):
raise xml.dom.InuseAttributeErr("attribute node already owned")
old1 = self._attrs.get(attr.name, None)
if old1 is not None:
self.removeAttributeNode(old1)
old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
if old2 is not None and old2 is not old1:
self.removeAttributeNode(old2)
_set_attribute_node(self, attr)
if old1 is not attr:
# It might have already been part of this node, in which case
# it doesn't represent a change, and should not be returned.
return old1
if old2 is not attr:
return old2
setAttributeNodeNS = setAttributeNode
def removeAttribute(self, name):
try:
attr = self._attrs[name]
except KeyError:
raise xml.dom.NotFoundErr()
self.removeAttributeNode(attr)
def removeAttributeNS(self, namespaceURI, localName):
try:
attr = self._attrsNS[(namespaceURI, localName)]
except KeyError:
raise xml.dom.NotFoundErr()
self.removeAttributeNode(attr)
def removeAttributeNode(self, node):
if node is None:
raise xml.dom.NotFoundErr()
try:
self._attrs[node.name]
except KeyError:
raise xml.dom.NotFoundErr()
_clear_id_cache(self)
node.unlink()
# Restore this since the node is still useful and otherwise
# unlinked
node.ownerDocument = self.ownerDocument
removeAttributeNodeNS = removeAttributeNode
def hasAttribute(self, name):
return self._attrs.has_key(name)
def hasAttributeNS(self, namespaceURI, localName):
return self._attrsNS.has_key((namespaceURI, localName))
def getElementsByTagName(self, name):
return _get_elements_by_tagName_helper(self, name, NodeList())
def getElementsByTagNameNS(self, namespaceURI, localName):
return _get_elements_by_tagName_ns_helper(
self, namespaceURI, localName, NodeList())
def __repr__(self):
return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
def writexml(self, writer, indent="", addindent="", newl=""):
# indent = current indentation
# addindent = indentation to add to higher levels
# newl = newline string
writer.write(indent+"<" + self.tagName)
attrs = self._get_attributes()
a_names = attrs.keys()
a_names.sort()
for a_name in a_names:
writer.write(" %s=\"" % a_name)
_write_data(writer, attrs[a_name].value)
writer.write("\"")
if self.childNodes:
writer.write(">%s"%(newl))
for node in self.childNodes:
node.writexml(writer,indent+addindent,addindent,newl)
writer.write("%s</%s>%s" % (indent,self.tagName,newl))
else:
writer.write("/>%s"%(newl))
def _get_attributes(self):
return NamedNodeMap(self._attrs, self._attrsNS, self)
def hasAttributes(self):
if self._attrs:
return True
else:
return False
# DOM Level 3 attributes, based on the 22 Oct 2002 draft
def setIdAttribute(self, name):
idAttr = self.getAttributeNode(name)
self.setIdAttributeNode(idAttr)
def setIdAttributeNS(self, namespaceURI, localName):
idAttr = self.getAttributeNodeNS(namespaceURI, localName)
self.setIdAttributeNode(idAttr)
def setIdAttributeNode(self, idAttr):
if idAttr is None or not self.isSameNode(idAttr.ownerElement):
raise xml.dom.NotFoundErr()
if _get_containing_entref(self) is not None:
raise xml.dom.NoModificationAllowedErr()
if not idAttr._is_id:
idAttr.__dict__['_is_id'] = True
self._magic_id_nodes += 1
self.ownerDocument._magic_id_count += 1
_clear_id_cache(self)
defproperty(Element, "attributes",
doc="NamedNodeMap of attributes on the element.")
defproperty(Element, "localName",
doc="Namespace-local name of this element.")
def _set_attribute_node(element, attr):
_clear_id_cache(element)
element._attrs[attr.name] = attr
element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
# This creates a circular reference, but Element.unlink()
# breaks the cycle since the references to the attribute
# dictionaries are tossed.
attr.__dict__['ownerElement'] = element
class Childless:
"""Mixin that makes childless-ness easy to implement and avoids
the complexity of the Node methods that deal with children.
"""
attributes = None
childNodes = EmptyNodeList()
firstChild = None
lastChild = None
def _get_firstChild(self):
return None
def _get_lastChild(self):
return None
def appendChild(self, node):
raise xml.dom.HierarchyRequestErr(
self.nodeName + " nodes cannot have children")
def hasChildNodes(self):
return False
def insertBefore(self, newChild, refChild):
raise xml.dom.HierarchyRequestErr(
self.nodeName + " nodes do not have children")
def removeChild(self, oldChild):
raise xml.dom.NotFoundErr(
self.nodeName + " nodes do not have children")
def replaceChild(self, newChild, oldChild):
raise xml.dom.HierarchyRequestErr(
self.nodeName + " nodes do not have children")
class ProcessingInstruction(Childless, Node):
nodeType = Node.PROCESSING_INSTRUCTION_NODE
def __init__(self, target, data):
self.target = self.nodeName = target
self.data = self.nodeValue = data
def _get_data(self):
return self.data
def _set_data(self, value):
d = self.__dict__
d['data'] = d['nodeValue'] = value
def _get_target(self):
return self.target
def _set_target(self, value):
d = self.__dict__
d['target'] = d['nodeName'] = value
def __setattr__(self, name, value):
if name == "data" or name == "nodeValue":
self.__dict__['data'] = self.__dict__['nodeValue'] = value
elif name == "target" or name == "nodeName":
self.__dict__['target'] = self.__dict__['nodeName'] = value
else:
self.__dict__[name] = value
def writexml(self, writer, indent="", addindent="", newl=""):
writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
class CharacterData(Childless, Node):
def _get_length(self):
return len(self.data)
__len__ = _get_length
def _get_data(self):
return self.__dict__['data']
def _set_data(self, data):
d = self.__dict__
d['data'] = d['nodeValue'] = data
_get_nodeValue = _get_data
_set_nodeValue = _set_data
def __setattr__(self, name, value):
if name == "data" or name == "nodeValue":
self.__dict__['data'] = self.__dict__['nodeValue'] = value
else:
self.__dict__[name] = value
def __repr__(self):
data = self.data
if len(data) > 10:
dotdotdot = "..."
else:
dotdotdot = ""
return "<DOM %s node \"%s%s\">" % (
self.__class__.__name__, data[0:10], dotdotdot)
def substringData(self, offset, count):
if offset < 0:
raise xml.dom.IndexSizeErr("offset cannot be negative")
if offset >= len(self.data):
raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
if count < 0:
raise xml.dom.IndexSizeErr("count cannot be negative")
return self.data[offset:offset+count]
def appendData(self, arg):
self.data = self.data + arg
def insertData(self, offset, arg):
if offset < 0:
raise xml.dom.IndexSizeErr("offset cannot be negative")
if offset >= len(self.data):
raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
if arg:
self.data = "%s%s%s" % (
self.data[:offset], arg, self.data[offset:])
def deleteData(self, offset, count):
if offset < 0:
raise xml.dom.IndexSizeErr("offset cannot be negative")
if offset >= len(self.data):
raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
if count < 0:
raise xml.dom.IndexSizeErr("count cannot be negative")
if count:
self.data = self.data[:offset] + self.data[offset+count:]
def replaceData(self, offset, count, arg):
if offset < 0:
raise xml.dom.IndexSizeErr("offset cannot be negative")
if offset >= len(self.data):
raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
if count < 0:
raise xml.dom.IndexSizeErr("count cannot be negative")
if count:
self.data = "%s%s%s" % (
self.data[:offset], arg, self.data[offset+count:])
defproperty(CharacterData, "length", doc="Length of the string data.")
class Text(CharacterData):
# Make sure we don't add an instance __dict__ if we don't already
# have one, at least when that's possible:
# XXX this does not work, CharacterData is an old-style class
# __slots__ = ()
nodeType = Node.TEXT_NODE
nodeName = "#text"
attributes = None
def splitText(self, offset):
if offset < 0 or offset > len(self.data):
raise xml.dom.IndexSizeErr("illegal offset value")
newText = self.__class__()
newText.data = self.data[offset:]
newText.ownerDocument = self.ownerDocument
next = self.nextSibling
if self.parentNode and self in self.parentNode.childNodes:
if next is None:
self.parentNode.appendChild(newText)
else:
self.parentNode.insertBefore(newText, next)
self.data = self.data[:offset]
return newText
def writexml(self, writer, indent="", addindent="", newl=""):
_write_data(writer, "%s%s%s"%(indent, self.data, newl))
# DOM Level 3 (WD 9 April 2002)
def _get_wholeText(self):
L = [self.data]
n = self.previousSibling
while n is not None:
if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
L.insert(0, n.data)
n = n.previousSibling
else:
break
n = self.nextSibling
while n is not None:
if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
L.append(n.data)
n = n.nextSibling
else:
break
return ''.join(L)
def replaceWholeText(self, content):
# XXX This needs to be seriously changed if minidom ever
# supports EntityReference nodes.
parent = self.parentNode
n = self.previousSibling
while n is not None:
if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
next = n.previousSibling
parent.removeChild(n)
n = next
else:
break
n = self.nextSibling
if not content:
parent.removeChild(self)
while n is not None:
if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
next = n.nextSibling
parent.removeChild(n)
n = next
else:
break
if content:
d = self.__dict__
d['data'] = content
d['nodeValue'] = content
return self
else:
return None
def _get_isWhitespaceInElementContent(self):
if self.data.strip():
return False
elem = _get_containing_element(self)
if elem is None:
return False
info = self.ownerDocument._get_elem_info(elem)
if info is None:
return False
else:
return info.isElementContent()
defproperty(Text, "isWhitespaceInElementContent",
doc="True iff this text node contains only whitespace"
" and is in element content.")
defproperty(Text, "wholeText",
doc="The text of all logically-adjacent text nodes.")
def _get_containing_element(node):
c = node.parentNode
while c is not None:
if c.nodeType == Node.ELEMENT_NODE:
return c
c = c.parentNode
return None
def _get_containing_entref(node):
c = node.parentNode
while c is not None:
if c.nodeType == Node.ENTITY_REFERENCE_NODE:
return c
c = c.parentNode
return None
class Comment(Childless, CharacterData):
nodeType = Node.COMMENT_NODE
nodeName = "#comment"
def __init__(self, data):
self.data = self.nodeValue = data
def writexml(self, writer, indent="", addindent="", newl=""):
writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
class CDATASection(Text):
# Make sure we don't add an instance __dict__ if we don't already
# have one, at least when that's possible:
# XXX this does not work, Text is an old-style class
# __slots__ = ()
nodeType = Node.CDATA_SECTION_NODE
nodeName = "#cdata-section"
def writexml(self, writer, indent="", addindent="", newl=""):
if self.data.find("]]>") >= 0:
raise ValueError("']]>' not allowed in a CDATA section")
writer.write("<![CDATA[%s]]>" % self.data)
class ReadOnlySequentialNamedNodeMap(NewStyle, GetattrMagic):
__slots__ = '_seq',
def __init__(self, seq=()):
# seq should be a list or tuple
self._seq = seq
def __len__(self):
return len(self._seq)
def _get_length(self):
return len(self._seq)
def getNamedItem(self, name):
for n in self._seq:
if n.nodeName == name:
return n
def getNamedItemNS(self, namespaceURI, localName):
for n in self._seq:
if n.namespaceURI == namespaceURI and n.localName == localName:
return n
def __getitem__(self, name_or_tuple):
if isinstance(name_or_tuple, _TupleType):
node = self.getNamedItemNS(*name_or_tuple)
else:
node = self.getNamedItem(name_or_tuple)
if node is None:
raise KeyError, name_or_tuple
return node
def item(self, index):
if index < 0:
return None
try:
return self._seq[index]
except IndexError:
return None
def removeNamedItem(self, name):
raise xml.dom.NoModificationAllowedErr(
"NamedNodeMap instance is read-only")
def removeNamedItemNS(self, namespaceURI, localName):
raise xml.dom.NoModificationAllowedErr(
"NamedNodeMap instance is read-only")
def setNamedItem(self, node):
raise xml.dom.NoModificationAllowedErr(
"NamedNodeMap instance is read-only")
def setNamedItemNS(self, node):
raise xml.dom.NoModificationAllowedErr(
"NamedNodeMap instance is read-only")
def __getstate__(self):
return [self._seq]
def __setstate__(self, state):
self._seq = state[0]
defproperty(ReadOnlySequentialNamedNodeMap, "length",
doc="Number of entries in the NamedNodeMap.")
class Identified:
"""Mix-in class that supports the publicId and systemId attributes."""
# XXX this does not work, this is an old-style class
# __slots__ = 'publicId', 'systemId'
def _identified_mixin_init(self, publicId, systemId):
self.publicId = publicId
self.systemId = systemId
def _get_publicId(self):
return self.publicId
def _get_systemId(self):
return self.systemId
class DocumentType(Identified, Childless, Node):
nodeType = Node.DOCUMENT_TYPE_NODE
nodeValue = None
name = None
publicId = None
systemId = None
internalSubset = None
def __init__(self, qualifiedName):
self.entities = ReadOnlySequentialNamedNodeMap()
self.notations = ReadOnlySequentialNamedNodeMap()
if qualifiedName:
prefix, localname = _nssplit(qualifiedName)
self.name = localname
self.nodeName = self.name
def _get_internalSubset(self):
return self.internalSubset
def cloneNode(self, deep):
if self.ownerDocument is None:
# it's ok
clone = DocumentType(None)
clone.name = self.name
clone.nodeName = self.name
operation = xml.dom.UserDataHandler.NODE_CLONED
if deep:
clone.entities._seq = []
clone.notations._seq = []
for n in self.notations._seq:
notation = Notation(n.nodeName, n.publicId, n.systemId)
clone.notations._seq.append(notation)
n._call_user_data_handler(operation, n, notation)
for e in self.entities._seq:
entity = Entity(e.nodeName, e.publicId, e.systemId,
e.notationName)
entity.actualEncoding = e.actualEncoding
entity.encoding = e.encoding
entity.version = e.version
clone.entities._seq.append(entity)
e._call_user_data_handler(operation, n, entity)
self._call_user_data_handler(operation, self, clone)
return clone
else:
return None
def writexml(self, writer, indent="", addindent="", newl=""):
writer.write("<!DOCTYPE ")
writer.write(self.name)
if self.publicId:
writer.write("\n PUBLIC '%s'\n '%s'"
% (self.publicId, self.systemId))
elif self.systemId:
writer.write("\n SYSTEM '%s'" % self.systemId)
if self.internalSubset is not None:
writer.write(" [")
writer.write(self.internalSubset)
writer.write("]")
writer.write(">\n")
class Entity(Identified, Node):
attributes = None
nodeType = Node.ENTITY_NODE
nodeValue = None
actualEncoding = None
encoding = None
version = None
def __init__(self, name, publicId, systemId, notation):
self.nodeName = name
self.notationName = notation
self.childNodes = NodeList()
self._identified_mixin_init(publicId, systemId)
def _get_actualEncoding(self):
return self.actualEncoding
def _get_encoding(self):
return self.encoding
def _get_version(self):
return self.version
def appendChild(self, newChild):
raise xml.dom.HierarchyRequestErr(
"cannot append children to an entity node")
def insertBefore(self, newChild, refChild):
raise xml.dom.HierarchyRequestErr(
"cannot insert children below an entity node")
def removeChild(self, oldChild):
raise xml.dom.HierarchyRequestErr(
"cannot remove children from an entity node")
def replaceChild(self, newChild, oldChild):
raise xml.dom.HierarchyRequestErr(
"cannot replace children of an entity node")
class Notation(Identified, Childless, Node):
nodeType = Node.NOTATION_NODE
nodeValue = None
def __init__(self, name, publicId, systemId):
self.nodeName = name
self._identified_mixin_init(publicId, systemId)
class DOMImplementation(DOMImplementationLS):
_features = [("core", "1.0"),
("core", "2.0"),
("core", "3.0"),
("core", None),
("xml", "1.0"),
("xml", "2.0"),
("xml", "3.0"),
("xml", None),
("ls-load", "3.0"),
("ls-load", None),
]
def hasFeature(self, feature, version):
if version == "":
version = None
return (feature.lower(), version) in self._features
def createDocument(self, namespaceURI, qualifiedName, doctype):
if doctype and doctype.parentNode is not None:
raise xml.dom.WrongDocumentErr(
"doctype object owned by another DOM tree")
doc = self._create_document()
add_root_element = not (namespaceURI is None
and qualifiedName is None
and doctype is None)
if not qualifiedName and add_root_element:
# The spec is unclear what to raise here; SyntaxErr
# would be the other obvious candidate. Since Xerces raises
# InvalidCharacterErr, and since SyntaxErr is not listed
# for createDocument, that seems to be the better choice.
# XXX: need to check for illegal characters here and in
# createElement.
# DOM Level III clears this up when talking about the return value
# of this function. If namespaceURI, qName and DocType are
# Null the document is returned without a document element
# Otherwise if doctype or namespaceURI are not None
# Then we go back to the above problem
raise xml.dom.InvalidCharacterErr("Element with no name")
if add_root_element:
prefix, localname = _nssplit(qualifiedName)
if prefix == "xml" \
and namespaceURI != "http://www.w3.org/XML/1998/namespace":
raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
if prefix and not namespaceURI:
raise xml.dom.NamespaceErr(
"illegal use of prefix without namespaces")
element = doc.createElementNS(namespaceURI, qualifiedName)
if doctype:
doc.appendChild(doctype)
doc.appendChild(element)
if doctype:
doctype.parentNode = doctype.ownerDocument = doc
doc.doctype = doctype
doc.implementation = self
return doc
def createDocumentType(self, qualifiedName, publicId, systemId):
doctype = DocumentType(qualifiedName)
doctype.publicId = publicId
doctype.systemId = systemId
return doctype
# DOM Level 3 (WD 9 April 2002)
def getInterface(self, feature):
if self.hasFeature(feature, None):
return self
else:
return None
# internal
def _create_document(self):
return Document()
class ElementInfo(NewStyle):
"""Object that represents content-model information for an element.
This implementation is not expected to be used in practice; DOM
builders should provide implementations which do the right thing
using information available to it.
"""
__slots__ = 'tagName',
def __init__(self, name):
self.tagName = name
def getAttributeType(self, aname):
return _no_type
def getAttributeTypeNS(self, namespaceURI, localName):
return _no_type
def isElementContent(self):
return False
def isEmpty(self):
"""Returns true iff this element is declared to have an EMPTY
content model."""
return False
def isId(self, aname):
"""Returns true iff the named attribte is a DTD-style ID."""
return False
def isIdNS(self, namespaceURI, localName):
"""Returns true iff the identified attribute is a DTD-style ID."""
return False
def __getstate__(self):
return self.tagName
def __setstate__(self, state):
self.tagName = state
def _clear_id_cache(node):
if node.nodeType == Node.DOCUMENT_NODE:
node._id_cache.clear()
node._id_search_stack = None
elif _in_document(node):
node.ownerDocument._id_cache.clear()
node.ownerDocument._id_search_stack= None
class Document(Node, DocumentLS):
_child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
nodeType = Node.DOCUMENT_NODE
nodeName = "#document"
nodeValue = None
attributes = None
doctype = None
parentNode = None
previousSibling = nextSibling = None
implementation = DOMImplementation()
# Document attributes from Level 3 (WD 9 April 2002)
actualEncoding = None
encoding = None
standalone = None
version = None
strictErrorChecking = False
errorHandler = None
documentURI = None
_magic_id_count = 0
def __init__(self):
self.childNodes = NodeList()
# mapping of (namespaceURI, localName) -> ElementInfo
# and tagName -> ElementInfo
self._elem_info = {}
self._id_cache = {}
self._id_search_stack = None
def _get_elem_info(self, element):
if element.namespaceURI:
key = element.namespaceURI, element.localName
else:
key = element.tagName
return self._elem_info.get(key)
def _get_actualEncoding(self):
return self.actualEncoding
def _get_doctype(self):
return self.doctype
def _get_documentURI(self):
return self.documentURI
def _get_encoding(self):
return self.encoding
def _get_errorHandler(self):
return self.errorHandler
def _get_standalone(self):
return self.standalone
def _get_strictErrorChecking(self):
return self.strictErrorChecking
def _get_version(self):
return self.version
def appendChild(self, node):
if node.nodeType not in self._child_node_types:
raise xml.dom.HierarchyRequestErr(
"%s cannot be child of %s" % (repr(node), repr(self)))
if node.parentNode is not None:
# This needs to be done before the next test since this
# may *be* the document element, in which case it should
# end up re-ordered to the end.
node.parentNode.removeChild(node)
if node.nodeType == Node.ELEMENT_NODE \
and self._get_documentElement():
raise xml.dom.HierarchyRequestErr(
"two document elements disallowed")
return Node.appendChild(self, node)
def removeChild(self, oldChild):
try:
self.childNodes.remove(oldChild)
except ValueError:
raise xml.dom.NotFoundErr()
oldChild.nextSibling = oldChild.previousSibling = None
oldChild.parentNode = None
if self.documentElement is oldChild:
self.documentElement = None
return oldChild
def _get_documentElement(self):
for node in self.childNodes:
if node.nodeType == Node.ELEMENT_NODE:
return node
def unlink(self):
if self.doctype is not None:
self.doctype.unlink()
self.doctype = None
Node.unlink(self)
def cloneNode(self, deep):
if not deep:
return None
clone = self.implementation.createDocument(None, None, None)
clone.encoding = self.encoding
clone.standalone = self.standalone
clone.version = self.version
for n in self.childNodes:
childclone = _clone_node(n, deep, clone)
assert childclone.ownerDocument.isSameNode(clone)
clone.childNodes.append(childclone)
if childclone.nodeType == Node.DOCUMENT_NODE:
assert clone.documentElement is None
elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
assert clone.doctype is None
clone.doctype = childclone
childclone.parentNode = clone
self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
self, clone)
return clone
def createDocumentFragment(self):
d = DocumentFragment()
d.ownerDocument = self
return d
def createElement(self, tagName):
e = Element(tagName)
e.ownerDocument = self
return e
def createTextNode(self, data):
if not isinstance(data, StringTypes):
raise TypeError, "node contents must be a string"
t = Text()
t.data = data
t.ownerDocument = self
return t
def createCDATASection(self, data):
if not isinstance(data, StringTypes):
raise TypeError, "node contents must be a string"
c = CDATASection()
c.data = data
c.ownerDocument = self
return c
def createComment(self, data):
c = Comment(data)
c.ownerDocument = self
return c
def createProcessingInstruction(self, target, data):
p = ProcessingInstruction(target, data)
p.ownerDocument = self
return p
def createAttribute(self, qName):
a = Attr(qName)
a.ownerDocument = self
a.value = ""
return a
def createElementNS(self, namespaceURI, qualifiedName):
prefix, localName = _nssplit(qualifiedName)
e = Element(qualifiedName, namespaceURI, prefix)
e.ownerDocument = self
return e
def createAttributeNS(self, namespaceURI, qualifiedName):
prefix, localName = _nssplit(qualifiedName)
a = Attr(qualifiedName, namespaceURI, localName, prefix)
a.ownerDocument = self
a.value = ""
return a
# A couple of implementation-specific helpers to create node types
# not supported by the W3C DOM specs:
def _create_entity(self, name, publicId, systemId, notationName):
e = Entity(name, publicId, systemId, notationName)
e.ownerDocument = self
return e
def _create_notation(self, name, publicId, systemId):
n = Notation(name, publicId, systemId)
n.ownerDocument = self
return n
def getElementById(self, id):
if self._id_cache.has_key(id):
return self._id_cache[id]
if not (self._elem_info or self._magic_id_count):
return None
stack = self._id_search_stack
if stack is None:
# we never searched before, or the cache has been cleared
stack = [self.documentElement]
self._id_search_stack = stack
elif not stack:
# Previous search was completed and cache is still valid;
# no matching node.
return None
result = None
while stack:
node = stack.pop()
# add child elements to stack for continued searching
stack.extend([child for child in node.childNodes
if child.nodeType in _nodeTypes_with_children])
# check this node
info = self._get_elem_info(node)
if info:
# We have to process all ID attributes before
# returning in order to get all the attributes set to
# be IDs using Element.setIdAttribute*().
for attr in node.attributes.values():
if attr.namespaceURI:
if info.isIdNS(attr.namespaceURI, attr.localName):
self._id_cache[attr.value] = node
if attr.value == id:
result = node
elif not node._magic_id_nodes:
break
elif info.isId(attr.name):
self._id_cache[attr.value] = node
if attr.value == id:
result = node
elif not node._magic_id_nodes:
break
elif attr._is_id:
self._id_cache[attr.value] = node
if attr.value == id:
result = node
elif node._magic_id_nodes == 1:
break
elif node._magic_id_nodes:
for attr in node.attributes.values():
if attr._is_id:
self._id_cache[attr.value] = node
if attr.value == id:
result = node
if result is not None:
break
return result
def getElementsByTagName(self, name):
return _get_elements_by_tagName_helper(self, name, NodeList())
def getElementsByTagNameNS(self, namespaceURI, localName):
return _get_elements_by_tagName_ns_helper(
self, namespaceURI, localName, NodeList())
def isSupported(self, feature, version):
return self.implementation.hasFeature(feature, version)
def importNode(self, node, deep):
if node.nodeType == Node.DOCUMENT_NODE:
raise xml.dom.NotSupportedErr("cannot import document nodes")
elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
raise xml.dom.NotSupportedErr("cannot import document type nodes")
return _clone_node(node, deep, self)
def writexml(self, writer, indent="", addindent="", newl="",
encoding = None):
if encoding is None:
writer.write('<?xml version="1.0" ?>\n')
else:
writer.write('<?xml version="1.0" encoding="%s"?>\n' % encoding)
for node in self.childNodes:
node.writexml(writer, indent, addindent, newl)
# DOM Level 3 (WD 9 April 2002)
def renameNode(self, n, namespaceURI, name):
if n.ownerDocument is not self:
raise xml.dom.WrongDocumentErr(
"cannot rename nodes from other documents;\n"
"expected %s,\nfound %s" % (self, n.ownerDocument))
if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
raise xml.dom.NotSupportedErr(
"renameNode() only applies to element and attribute nodes")
if namespaceURI != EMPTY_NAMESPACE:
if ':' in name:
prefix, localName = name.split(':', 1)
if ( prefix == "xmlns"
and namespaceURI != xml.dom.XMLNS_NAMESPACE):
raise xml.dom.NamespaceErr(
"illegal use of 'xmlns' prefix")
else:
if ( name == "xmlns"
and namespaceURI != xml.dom.XMLNS_NAMESPACE
and n.nodeType == Node.ATTRIBUTE_NODE):
raise xml.dom.NamespaceErr(
"illegal use of the 'xmlns' attribute")
prefix = None
localName = name
else:
prefix = None
localName = None
if n.nodeType == Node.ATTRIBUTE_NODE:
element = n.ownerElement
if element is not None:
is_id = n._is_id
element.removeAttributeNode(n)
else:
element = None
# avoid __setattr__
d = n.__dict__
d['prefix'] = prefix
d['localName'] = localName
d['namespaceURI'] = namespaceURI
d['nodeName'] = name
if n.nodeType == Node.ELEMENT_NODE:
d['tagName'] = name
else:
# attribute node
d['name'] = name
if element is not None:
element.setAttributeNode(n)
if is_id:
element.setIdAttributeNode(n)
# It's not clear from a semantic perspective whether we should
# call the user data handlers for the NODE_RENAMED event since
# we're re-using the existing node. The draft spec has been
# interpreted as meaning "no, don't call the handler unless a
# new node is created."
return n
defproperty(Document, "documentElement",
doc="Top-level element of this document.")
def _clone_node(node, deep, newOwnerDocument):
"""
Clone a node and give it the new owner document.
Called by Node.cloneNode and Document.importNode
"""
if node.ownerDocument.isSameNode(newOwnerDocument):
operation = xml.dom.UserDataHandler.NODE_CLONED
else:
operation = xml.dom.UserDataHandler.NODE_IMPORTED
if node.nodeType == Node.ELEMENT_NODE:
clone = newOwnerDocument.createElementNS(node.namespaceURI,
node.nodeName)
for attr in node.attributes.values():
clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
a.specified = attr.specified
if deep:
for child in node.childNodes:
c = _clone_node(child, deep, newOwnerDocument)
clone.appendChild(c)
elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
clone = newOwnerDocument.createDocumentFragment()
if deep:
for child in node.childNodes:
c = _clone_node(child, deep, newOwnerDocument)
clone.appendChild(c)
elif node.nodeType == Node.TEXT_NODE:
clone = newOwnerDocument.createTextNode(node.data)
elif node.nodeType == Node.CDATA_SECTION_NODE:
clone = newOwnerDocument.createCDATASection(node.data)
elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
clone = newOwnerDocument.createProcessingInstruction(node.target,
node.data)
elif node.nodeType == Node.COMMENT_NODE:
clone = newOwnerDocument.createComment(node.data)
elif node.nodeType == Node.ATTRIBUTE_NODE:
clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
node.nodeName)
clone.specified = True
clone.value = node.value
elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
assert node.ownerDocument is not newOwnerDocument
operation = xml.dom.UserDataHandler.NODE_IMPORTED
clone = newOwnerDocument.implementation.createDocumentType(
node.name, node.publicId, node.systemId)
clone.ownerDocument = newOwnerDocument
if deep:
clone.entities._seq = []
clone.notations._seq = []
for n in node.notations._seq:
notation = Notation(n.nodeName, n.publicId, n.systemId)
notation.ownerDocument = newOwnerDocument
clone.notations._seq.append(notation)
if hasattr(n, '_call_user_data_handler'):
n._call_user_data_handler(operation, n, notation)
for e in node.entities._seq:
entity = Entity(e.nodeName, e.publicId, e.systemId,
e.notationName)
entity.actualEncoding = e.actualEncoding
entity.encoding = e.encoding
entity.version = e.version
entity.ownerDocument = newOwnerDocument
clone.entities._seq.append(entity)
if hasattr(e, '_call_user_data_handler'):
e._call_user_data_handler(operation, n, entity)
else:
# Note the cloning of Document and DocumentType nodes is
# implemenetation specific. minidom handles those cases
# directly in the cloneNode() methods.
raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
# Check for _call_user_data_handler() since this could conceivably
# used with other DOM implementations (one of the FourThought
# DOMs, perhaps?).
if hasattr(node, '_call_user_data_handler'):
node._call_user_data_handler(operation, node, clone)
return clone
def _nssplit(qualifiedName):
fields = qualifiedName.split(':', 1)
if len(fields) == 2:
return fields
else:
return (None, fields[0])
def _get_StringIO():
# we can't use cStringIO since it doesn't support Unicode strings
from StringIO import StringIO
return StringIO()
def _do_pulldom_parse(func, args, kwargs):
events = func(*args, **kwargs)
toktype, rootNode = events.getEvent()
events.expandNode(rootNode)
events.clear()
return rootNode
def parse(file, parser=None, bufsize=None):
"""Parse a file into a DOM by filename or file object."""
if parser is None and not bufsize:
from xml.dom import expatbuilder
return expatbuilder.parse(file)
else:
from xml.dom import pulldom
return _do_pulldom_parse(pulldom.parse, (file,),
{'parser': parser, 'bufsize': bufsize})
def parseString(string, parser=None):
"""Parse a file into a DOM from a string."""
if parser is None:
from xml.dom import expatbuilder
return expatbuilder.parseString(string)
else:
from xml.dom import pulldom
return _do_pulldom_parse(pulldom.parseString, (string,),
{'parser': parser})
def getDOMImplementation(features=None):
if features:
if isinstance(features, StringTypes):
features = domreg._parse_feature_string(features)
for f, v in features:
if not Document.implementation.hasFeature(f, v):
return None
return Document.implementation
| Python |
# This is the Python mapping for interface NodeFilter from
# DOM2-Traversal-Range. It contains only constants.
class NodeFilter:
"""
This is the DOM2 NodeFilter interface. It contains only constants.
"""
FILTER_ACCEPT = 1
FILTER_REJECT = 2
FILTER_SKIP = 3
SHOW_ALL = 0xFFFFFFFFL
SHOW_ELEMENT = 0x00000001
SHOW_ATTRIBUTE = 0x00000002
SHOW_TEXT = 0x00000004
SHOW_CDATA_SECTION = 0x00000008
SHOW_ENTITY_REFERENCE = 0x00000010
SHOW_ENTITY = 0x00000020
SHOW_PROCESSING_INSTRUCTION = 0x00000040
SHOW_COMMENT = 0x00000080
SHOW_DOCUMENT = 0x00000100
SHOW_DOCUMENT_TYPE = 0x00000200
SHOW_DOCUMENT_FRAGMENT = 0x00000400
SHOW_NOTATION = 0x00000800
def acceptNode(self, node):
raise NotImplementedError
| Python |
"""Registration facilities for DOM. This module should not be used
directly. Instead, the functions getDOMImplementation and
registerDOMImplementation should be imported from xml.dom."""
from xml.dom.minicompat import * # isinstance, StringTypes
# This is a list of well-known implementations. Well-known names
# should be published by posting to xml-sig@python.org, and are
# subsequently recorded in this file.
well_known_implementations = {
'minidom':'xml.dom.minidom',
'4DOM': 'xml.dom.DOMImplementation',
}
# DOM implementations not officially registered should register
# themselves with their
registered = {}
def registerDOMImplementation(name, factory):
"""registerDOMImplementation(name, factory)
Register the factory function with the name. The factory function
should return an object which implements the DOMImplementation
interface. The factory function can either return the same object,
or a new one (e.g. if that implementation supports some
customization)."""
registered[name] = factory
def _good_enough(dom, features):
"_good_enough(dom, features) -> Return 1 if the dom offers the features"
for f,v in features:
if not dom.hasFeature(f,v):
return 0
return 1
def getDOMImplementation(name = None, features = ()):
"""getDOMImplementation(name = None, features = ()) -> DOM implementation.
Return a suitable DOM implementation. The name is either
well-known, the module name of a DOM implementation, or None. If
it is not None, imports the corresponding module and returns
DOMImplementation object if the import succeeds.
If name is not given, consider the available implementations to
find one with the required feature set. If no implementation can
be found, raise an ImportError. The features list must be a sequence
of (feature, version) pairs which are passed to hasFeature."""
import os
creator = None
mod = well_known_implementations.get(name)
if mod:
mod = __import__(mod, {}, {}, ['getDOMImplementation'])
return mod.getDOMImplementation()
elif name:
return registered[name]()
elif os.environ.has_key("PYTHON_DOM"):
return getDOMImplementation(name = os.environ["PYTHON_DOM"])
# User did not specify a name, try implementations in arbitrary
# order, returning the one that has the required features
if isinstance(features, StringTypes):
features = _parse_feature_string(features)
for creator in registered.values():
dom = creator()
if _good_enough(dom, features):
return dom
for creator in well_known_implementations.keys():
try:
dom = getDOMImplementation(name = creator)
except StandardError: # typically ImportError, or AttributeError
continue
if _good_enough(dom, features):
return dom
raise ImportError,"no suitable DOM implementation found"
def _parse_feature_string(s):
features = []
parts = s.split()
i = 0
length = len(parts)
while i < length:
feature = parts[i]
if feature[0] in "0123456789":
raise ValueError, "bad feature name: %r" % (feature,)
i = i + 1
version = None
if i < length:
v = parts[i]
if v[0] in "0123456789":
i = i + 1
version = v
features.append((feature, version))
return tuple(features)
| Python |
import xml.sax
import xml.sax.handler
import types
try:
_StringTypes = [types.StringType, types.UnicodeType]
except AttributeError:
_StringTypes = [types.StringType]
START_ELEMENT = "START_ELEMENT"
END_ELEMENT = "END_ELEMENT"
COMMENT = "COMMENT"
START_DOCUMENT = "START_DOCUMENT"
END_DOCUMENT = "END_DOCUMENT"
PROCESSING_INSTRUCTION = "PROCESSING_INSTRUCTION"
IGNORABLE_WHITESPACE = "IGNORABLE_WHITESPACE"
CHARACTERS = "CHARACTERS"
class PullDOM(xml.sax.ContentHandler):
_locator = None
document = None
def __init__(self, documentFactory=None):
from xml.dom import XML_NAMESPACE
self.documentFactory = documentFactory
self.firstEvent = [None, None]
self.lastEvent = self.firstEvent
self.elementStack = []
self.push = self.elementStack.append
try:
self.pop = self.elementStack.pop
except AttributeError:
# use class' pop instead
pass
self._ns_contexts = [{XML_NAMESPACE:'xml'}] # contains uri -> prefix dicts
self._current_context = self._ns_contexts[-1]
self.pending_events = []
def pop(self):
result = self.elementStack[-1]
del self.elementStack[-1]
return result
def setDocumentLocator(self, locator):
self._locator = locator
def startPrefixMapping(self, prefix, uri):
if not hasattr(self, '_xmlns_attrs'):
self._xmlns_attrs = []
self._xmlns_attrs.append((prefix or 'xmlns', uri))
self._ns_contexts.append(self._current_context.copy())
self._current_context[uri] = prefix or None
def endPrefixMapping(self, prefix):
self._current_context = self._ns_contexts.pop()
def startElementNS(self, name, tagName , attrs):
# Retrieve xml namespace declaration attributes.
xmlns_uri = 'http://www.w3.org/2000/xmlns/'
xmlns_attrs = getattr(self, '_xmlns_attrs', None)
if xmlns_attrs is not None:
for aname, value in xmlns_attrs:
attrs._attrs[(xmlns_uri, aname)] = value
self._xmlns_attrs = []
uri, localname = name
if uri:
# When using namespaces, the reader may or may not
# provide us with the original name. If not, create
# *a* valid tagName from the current context.
if tagName is None:
prefix = self._current_context[uri]
if prefix:
tagName = prefix + ":" + localname
else:
tagName = localname
if self.document:
node = self.document.createElementNS(uri, tagName)
else:
node = self.buildDocument(uri, tagName)
else:
# When the tagname is not prefixed, it just appears as
# localname
if self.document:
node = self.document.createElement(localname)
else:
node = self.buildDocument(None, localname)
for aname,value in attrs.items():
a_uri, a_localname = aname
if a_uri == xmlns_uri:
if a_localname == 'xmlns':
qname = a_localname
else:
qname = 'xmlns:' + a_localname
attr = self.document.createAttributeNS(a_uri, qname)
node.setAttributeNodeNS(attr)
elif a_uri:
prefix = self._current_context[a_uri]
if prefix:
qname = prefix + ":" + a_localname
else:
qname = a_localname
attr = self.document.createAttributeNS(a_uri, qname)
node.setAttributeNodeNS(attr)
else:
attr = self.document.createAttribute(a_localname)
node.setAttributeNode(attr)
attr.value = value
self.lastEvent[1] = [(START_ELEMENT, node), None]
self.lastEvent = self.lastEvent[1]
self.push(node)
def endElementNS(self, name, tagName):
self.lastEvent[1] = [(END_ELEMENT, self.pop()), None]
self.lastEvent = self.lastEvent[1]
def startElement(self, name, attrs):
if self.document:
node = self.document.createElement(name)
else:
node = self.buildDocument(None, name)
for aname,value in attrs.items():
attr = self.document.createAttribute(aname)
attr.value = value
node.setAttributeNode(attr)
self.lastEvent[1] = [(START_ELEMENT, node), None]
self.lastEvent = self.lastEvent[1]
self.push(node)
def endElement(self, name):
self.lastEvent[1] = [(END_ELEMENT, self.pop()), None]
self.lastEvent = self.lastEvent[1]
def comment(self, s):
if self.document:
node = self.document.createComment(s)
self.lastEvent[1] = [(COMMENT, node), None]
self.lastEvent = self.lastEvent[1]
else:
event = [(COMMENT, s), None]
self.pending_events.append(event)
def processingInstruction(self, target, data):
if self.document:
node = self.document.createProcessingInstruction(target, data)
self.lastEvent[1] = [(PROCESSING_INSTRUCTION, node), None]
self.lastEvent = self.lastEvent[1]
else:
event = [(PROCESSING_INSTRUCTION, target, data), None]
self.pending_events.append(event)
def ignorableWhitespace(self, chars):
node = self.document.createTextNode(chars)
self.lastEvent[1] = [(IGNORABLE_WHITESPACE, node), None]
self.lastEvent = self.lastEvent[1]
def characters(self, chars):
node = self.document.createTextNode(chars)
self.lastEvent[1] = [(CHARACTERS, node), None]
self.lastEvent = self.lastEvent[1]
def startDocument(self):
if self.documentFactory is None:
import xml.dom.minidom
self.documentFactory = xml.dom.minidom.Document.implementation
def buildDocument(self, uri, tagname):
# Can't do that in startDocument, since we need the tagname
# XXX: obtain DocumentType
node = self.documentFactory.createDocument(uri, tagname, None)
self.document = node
self.lastEvent[1] = [(START_DOCUMENT, node), None]
self.lastEvent = self.lastEvent[1]
self.push(node)
# Put everything we have seen so far into the document
for e in self.pending_events:
if e[0][0] == PROCESSING_INSTRUCTION:
_,target,data = e[0]
n = self.document.createProcessingInstruction(target, data)
e[0] = (PROCESSING_INSTRUCTION, n)
elif e[0][0] == COMMENT:
n = self.document.createComment(e[0][1])
e[0] = (COMMENT, n)
else:
raise AssertionError("Unknown pending event ",e[0][0])
self.lastEvent[1] = e
self.lastEvent = e
self.pending_events = None
return node.firstChild
def endDocument(self):
self.lastEvent[1] = [(END_DOCUMENT, self.document), None]
self.pop()
def clear(self):
"clear(): Explicitly release parsing structures"
self.document = None
class ErrorHandler:
def warning(self, exception):
print exception
def error(self, exception):
raise exception
def fatalError(self, exception):
raise exception
class DOMEventStream:
def __init__(self, stream, parser, bufsize):
self.stream = stream
self.parser = parser
self.bufsize = bufsize
if not hasattr(self.parser, 'feed'):
self.getEvent = self._slurp
self.reset()
def reset(self):
self.pulldom = PullDOM()
# This content handler relies on namespace support
self.parser.setFeature(xml.sax.handler.feature_namespaces, 1)
self.parser.setContentHandler(self.pulldom)
def __getitem__(self, pos):
rc = self.getEvent()
if rc:
return rc
raise IndexError
def next(self):
rc = self.getEvent()
if rc:
return rc
raise StopIteration
def __iter__(self):
return self
def expandNode(self, node):
event = self.getEvent()
parents = [node]
while event:
token, cur_node = event
if cur_node is node:
return
if token != END_ELEMENT:
parents[-1].appendChild(cur_node)
if token == START_ELEMENT:
parents.append(cur_node)
elif token == END_ELEMENT:
del parents[-1]
event = self.getEvent()
def getEvent(self):
# use IncrementalParser interface, so we get the desired
# pull effect
if not self.pulldom.firstEvent[1]:
self.pulldom.lastEvent = self.pulldom.firstEvent
while not self.pulldom.firstEvent[1]:
buf = self.stream.read(self.bufsize)
if not buf:
self.parser.close()
return None
self.parser.feed(buf)
rc = self.pulldom.firstEvent[1][0]
self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1]
return rc
def _slurp(self):
""" Fallback replacement for getEvent() using the
standard SAX2 interface, which means we slurp the
SAX events into memory (no performance gain, but
we are compatible to all SAX parsers).
"""
self.parser.parse(self.stream)
self.getEvent = self._emit
return self._emit()
def _emit(self):
""" Fallback replacement for getEvent() that emits
the events that _slurp() read previously.
"""
rc = self.pulldom.firstEvent[1][0]
self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1]
return rc
def clear(self):
"""clear(): Explicitly release parsing objects"""
self.pulldom.clear()
del self.pulldom
self.parser = None
self.stream = None
class SAX2DOM(PullDOM):
def startElementNS(self, name, tagName , attrs):
PullDOM.startElementNS(self, name, tagName, attrs)
curNode = self.elementStack[-1]
parentNode = self.elementStack[-2]
parentNode.appendChild(curNode)
def startElement(self, name, attrs):
PullDOM.startElement(self, name, attrs)
curNode = self.elementStack[-1]
parentNode = self.elementStack[-2]
parentNode.appendChild(curNode)
def processingInstruction(self, target, data):
PullDOM.processingInstruction(self, target, data)
node = self.lastEvent[0][1]
parentNode = self.elementStack[-1]
parentNode.appendChild(node)
def ignorableWhitespace(self, chars):
PullDOM.ignorableWhitespace(self, chars)
node = self.lastEvent[0][1]
parentNode = self.elementStack[-1]
parentNode.appendChild(node)
def characters(self, chars):
PullDOM.characters(self, chars)
node = self.lastEvent[0][1]
parentNode = self.elementStack[-1]
parentNode.appendChild(node)
default_bufsize = (2 ** 14) - 20
def parse(stream_or_string, parser=None, bufsize=None):
if bufsize is None:
bufsize = default_bufsize
if type(stream_or_string) in _StringTypes:
stream = open(stream_or_string)
else:
stream = stream_or_string
if not parser:
parser = xml.sax.make_parser()
return DOMEventStream(stream, parser, bufsize)
def parseString(string, parser=None):
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
bufsize = len(string)
buf = StringIO(string)
if not parser:
parser = xml.sax.make_parser()
return DOMEventStream(buf, parser, bufsize)
| Python |
"""Implementation of the DOM Level 3 'LS-Load' feature."""
import copy
import xml.dom
from xml.dom.minicompat import *
from xml.dom.NodeFilter import NodeFilter
__all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"]
class Options:
"""Features object that has variables set for each DOMBuilder feature.
The DOMBuilder class uses an instance of this class to pass settings to
the ExpatBuilder class.
"""
# Note that the DOMBuilder class in LoadSave constrains which of these
# values can be set using the DOM Level 3 LoadSave feature.
namespaces = 1
namespace_declarations = True
validation = False
external_parameter_entities = True
external_general_entities = True
external_dtd_subset = True
validate_if_schema = False
validate = False
datatype_normalization = False
create_entity_ref_nodes = True
entities = True
whitespace_in_element_content = True
cdata_sections = True
comments = True
charset_overrides_xml_encoding = True
infoset = False
supported_mediatypes_only = False
errorHandler = None
filter = None
class DOMBuilder:
entityResolver = None
errorHandler = None
filter = None
ACTION_REPLACE = 1
ACTION_APPEND_AS_CHILDREN = 2
ACTION_INSERT_AFTER = 3
ACTION_INSERT_BEFORE = 4
_legal_actions = (ACTION_REPLACE, ACTION_APPEND_AS_CHILDREN,
ACTION_INSERT_AFTER, ACTION_INSERT_BEFORE)
def __init__(self):
self._options = Options()
def _get_entityResolver(self):
return self.entityResolver
def _set_entityResolver(self, entityResolver):
self.entityResolver = entityResolver
def _get_errorHandler(self):
return self.errorHandler
def _set_errorHandler(self, errorHandler):
self.errorHandler = errorHandler
def _get_filter(self):
return self.filter
def _set_filter(self, filter):
self.filter = filter
def setFeature(self, name, state):
if self.supportsFeature(name):
state = state and 1 or 0
try:
settings = self._settings[(_name_xform(name), state)]
except KeyError:
raise xml.dom.NotSupportedErr(
"unsupported feature: %r" % (name,))
else:
for name, value in settings:
setattr(self._options, name, value)
else:
raise xml.dom.NotFoundErr("unknown feature: " + repr(name))
def supportsFeature(self, name):
return hasattr(self._options, _name_xform(name))
def canSetFeature(self, name, state):
key = (_name_xform(name), state and 1 or 0)
return self._settings.has_key(key)
# This dictionary maps from (feature,value) to a list of
# (option,value) pairs that should be set on the Options object.
# If a (feature,value) setting is not in this dictionary, it is
# not supported by the DOMBuilder.
#
_settings = {
("namespace_declarations", 0): [
("namespace_declarations", 0)],
("namespace_declarations", 1): [
("namespace_declarations", 1)],
("validation", 0): [
("validation", 0)],
("external_general_entities", 0): [
("external_general_entities", 0)],
("external_general_entities", 1): [
("external_general_entities", 1)],
("external_parameter_entities", 0): [
("external_parameter_entities", 0)],
("external_parameter_entities", 1): [
("external_parameter_entities", 1)],
("validate_if_schema", 0): [
("validate_if_schema", 0)],
("create_entity_ref_nodes", 0): [
("create_entity_ref_nodes", 0)],
("create_entity_ref_nodes", 1): [
("create_entity_ref_nodes", 1)],
("entities", 0): [
("create_entity_ref_nodes", 0),
("entities", 0)],
("entities", 1): [
("entities", 1)],
("whitespace_in_element_content", 0): [
("whitespace_in_element_content", 0)],
("whitespace_in_element_content", 1): [
("whitespace_in_element_content", 1)],
("cdata_sections", 0): [
("cdata_sections", 0)],
("cdata_sections", 1): [
("cdata_sections", 1)],
("comments", 0): [
("comments", 0)],
("comments", 1): [
("comments", 1)],
("charset_overrides_xml_encoding", 0): [
("charset_overrides_xml_encoding", 0)],
("charset_overrides_xml_encoding", 1): [
("charset_overrides_xml_encoding", 1)],
("infoset", 0): [],
("infoset", 1): [
("namespace_declarations", 0),
("validate_if_schema", 0),
("create_entity_ref_nodes", 0),
("entities", 0),
("cdata_sections", 0),
("datatype_normalization", 1),
("whitespace_in_element_content", 1),
("comments", 1),
("charset_overrides_xml_encoding", 1)],
("supported_mediatypes_only", 0): [
("supported_mediatypes_only", 0)],
("namespaces", 0): [
("namespaces", 0)],
("namespaces", 1): [
("namespaces", 1)],
}
def getFeature(self, name):
xname = _name_xform(name)
try:
return getattr(self._options, xname)
except AttributeError:
if name == "infoset":
options = self._options
return (options.datatype_normalization
and options.whitespace_in_element_content
and options.comments
and options.charset_overrides_xml_encoding
and not (options.namespace_declarations
or options.validate_if_schema
or options.create_entity_ref_nodes
or options.entities
or options.cdata_sections))
raise xml.dom.NotFoundErr("feature %s not known" % repr(name))
def parseURI(self, uri):
if self.entityResolver:
input = self.entityResolver.resolveEntity(None, uri)
else:
input = DOMEntityResolver().resolveEntity(None, uri)
return self.parse(input)
def parse(self, input):
options = copy.copy(self._options)
options.filter = self.filter
options.errorHandler = self.errorHandler
fp = input.byteStream
if fp is None and options.systemId:
import urllib2
fp = urllib2.urlopen(input.systemId)
return self._parse_bytestream(fp, options)
def parseWithContext(self, input, cnode, action):
if action not in self._legal_actions:
raise ValueError("not a legal action")
raise NotImplementedError("Haven't written this yet...")
def _parse_bytestream(self, stream, options):
import xml.dom.expatbuilder
builder = xml.dom.expatbuilder.makeBuilder(options)
return builder.parseFile(stream)
def _name_xform(name):
return name.lower().replace('-', '_')
class DOMEntityResolver(NewStyle):
__slots__ = '_opener',
def resolveEntity(self, publicId, systemId):
assert systemId is not None
source = DOMInputSource()
source.publicId = publicId
source.systemId = systemId
source.byteStream = self._get_opener().open(systemId)
# determine the encoding if the transport provided it
source.encoding = self._guess_media_encoding(source)
# determine the base URI is we can
import posixpath, urlparse
parts = urlparse.urlparse(systemId)
scheme, netloc, path, params, query, fragment = parts
# XXX should we check the scheme here as well?
if path and not path.endswith("/"):
path = posixpath.dirname(path) + "/"
parts = scheme, netloc, path, params, query, fragment
source.baseURI = urlparse.urlunparse(parts)
return source
def _get_opener(self):
try:
return self._opener
except AttributeError:
self._opener = self._create_opener()
return self._opener
def _create_opener(self):
import urllib2
return urllib2.build_opener()
def _guess_media_encoding(self, source):
info = source.byteStream.info()
if info.has_key("Content-Type"):
for param in info.getplist():
if param.startswith("charset="):
return param.split("=", 1)[1].lower()
class DOMInputSource(NewStyle):
__slots__ = ('byteStream', 'characterStream', 'stringData',
'encoding', 'publicId', 'systemId', 'baseURI')
def __init__(self):
self.byteStream = None
self.characterStream = None
self.stringData = None
self.encoding = None
self.publicId = None
self.systemId = None
self.baseURI = None
def _get_byteStream(self):
return self.byteStream
def _set_byteStream(self, byteStream):
self.byteStream = byteStream
def _get_characterStream(self):
return self.characterStream
def _set_characterStream(self, characterStream):
self.characterStream = characterStream
def _get_stringData(self):
return self.stringData
def _set_stringData(self, data):
self.stringData = data
def _get_encoding(self):
return self.encoding
def _set_encoding(self, encoding):
self.encoding = encoding
def _get_publicId(self):
return self.publicId
def _set_publicId(self, publicId):
self.publicId = publicId
def _get_systemId(self):
return self.systemId
def _set_systemId(self, systemId):
self.systemId = systemId
def _get_baseURI(self):
return self.baseURI
def _set_baseURI(self, uri):
self.baseURI = uri
class DOMBuilderFilter:
"""Element filter which can be used to tailor construction of
a DOM instance.
"""
# There's really no need for this class; concrete implementations
# should just implement the endElement() and startElement()
# methods as appropriate. Using this makes it easy to only
# implement one of them.
FILTER_ACCEPT = 1
FILTER_REJECT = 2
FILTER_SKIP = 3
FILTER_INTERRUPT = 4
whatToShow = NodeFilter.SHOW_ALL
def _get_whatToShow(self):
return self.whatToShow
def acceptNode(self, element):
return self.FILTER_ACCEPT
def startContainer(self, element):
return self.FILTER_ACCEPT
del NodeFilter
class DocumentLS:
"""Mixin to create documents that conform to the load/save spec."""
async = False
def _get_async(self):
return False
def _set_async(self, async):
if async:
raise xml.dom.NotSupportedErr(
"asynchronous document loading is not supported")
def abort(self):
# What does it mean to "clear" a document? Does the
# documentElement disappear?
raise NotImplementedError(
"haven't figured out what this means yet")
def load(self, uri):
raise NotImplementedError("haven't written this yet")
def loadXML(self, source):
raise NotImplementedError("haven't written this yet")
def saveXML(self, snode):
if snode is None:
snode = self
elif snode.ownerDocument is not self:
raise xml.dom.WrongDocumentErr()
return snode.toxml()
class DOMImplementationLS:
MODE_SYNCHRONOUS = 1
MODE_ASYNCHRONOUS = 2
def createDOMBuilder(self, mode, schemaType):
if schemaType is not None:
raise xml.dom.NotSupportedErr(
"schemaType not yet supported")
if mode == self.MODE_SYNCHRONOUS:
return DOMBuilder()
if mode == self.MODE_ASYNCHRONOUS:
raise xml.dom.NotSupportedErr(
"asynchronous builders are not supported")
raise ValueError("unknown value for mode")
def createDOMWriter(self):
raise NotImplementedError(
"the writer interface hasn't been written yet!")
def createDOMInputSource(self):
return DOMInputSource()
| Python |
"""W3C Document Object Model implementation for Python.
The Python mapping of the Document Object Model is documented in the
Python Library Reference in the section on the xml.dom package.
This package contains the following modules:
minidom -- A simple implementation of the Level 1 DOM with namespace
support added (based on the Level 2 specification) and other
minor Level 2 functionality.
pulldom -- DOM builder supporting on-demand tree-building for selected
subtrees of the document.
"""
class Node:
"""Class giving the NodeType constants."""
# DOM implementations may use this as a base class for their own
# Node implementations. If they don't, the constants defined here
# should still be used as the canonical definitions as they match
# the values given in the W3C recommendation. Client code can
# safely refer to these values in all tests of Node.nodeType
# values.
ELEMENT_NODE = 1
ATTRIBUTE_NODE = 2
TEXT_NODE = 3
CDATA_SECTION_NODE = 4
ENTITY_REFERENCE_NODE = 5
ENTITY_NODE = 6
PROCESSING_INSTRUCTION_NODE = 7
COMMENT_NODE = 8
DOCUMENT_NODE = 9
DOCUMENT_TYPE_NODE = 10
DOCUMENT_FRAGMENT_NODE = 11
NOTATION_NODE = 12
#ExceptionCode
INDEX_SIZE_ERR = 1
DOMSTRING_SIZE_ERR = 2
HIERARCHY_REQUEST_ERR = 3
WRONG_DOCUMENT_ERR = 4
INVALID_CHARACTER_ERR = 5
NO_DATA_ALLOWED_ERR = 6
NO_MODIFICATION_ALLOWED_ERR = 7
NOT_FOUND_ERR = 8
NOT_SUPPORTED_ERR = 9
INUSE_ATTRIBUTE_ERR = 10
INVALID_STATE_ERR = 11
SYNTAX_ERR = 12
INVALID_MODIFICATION_ERR = 13
NAMESPACE_ERR = 14
INVALID_ACCESS_ERR = 15
VALIDATION_ERR = 16
class DOMException(Exception):
"""Abstract base class for DOM exceptions.
Exceptions with specific codes are specializations of this class."""
def __init__(self, *args, **kw):
if self.__class__ is DOMException:
raise RuntimeError(
"DOMException should not be instantiated directly")
Exception.__init__(self, *args, **kw)
def _get_code(self):
return self.code
class IndexSizeErr(DOMException):
code = INDEX_SIZE_ERR
class DomstringSizeErr(DOMException):
code = DOMSTRING_SIZE_ERR
class HierarchyRequestErr(DOMException):
code = HIERARCHY_REQUEST_ERR
class WrongDocumentErr(DOMException):
code = WRONG_DOCUMENT_ERR
class InvalidCharacterErr(DOMException):
code = INVALID_CHARACTER_ERR
class NoDataAllowedErr(DOMException):
code = NO_DATA_ALLOWED_ERR
class NoModificationAllowedErr(DOMException):
code = NO_MODIFICATION_ALLOWED_ERR
class NotFoundErr(DOMException):
code = NOT_FOUND_ERR
class NotSupportedErr(DOMException):
code = NOT_SUPPORTED_ERR
class InuseAttributeErr(DOMException):
code = INUSE_ATTRIBUTE_ERR
class InvalidStateErr(DOMException):
code = INVALID_STATE_ERR
class SyntaxErr(DOMException):
code = SYNTAX_ERR
class InvalidModificationErr(DOMException):
code = INVALID_MODIFICATION_ERR
class NamespaceErr(DOMException):
code = NAMESPACE_ERR
class InvalidAccessErr(DOMException):
code = INVALID_ACCESS_ERR
class ValidationErr(DOMException):
code = VALIDATION_ERR
class UserDataHandler:
"""Class giving the operation constants for UserDataHandler.handle()."""
# Based on DOM Level 3 (WD 9 April 2002)
NODE_CLONED = 1
NODE_IMPORTED = 2
NODE_DELETED = 3
NODE_RENAMED = 4
XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"
XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"
XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"
EMPTY_NAMESPACE = None
EMPTY_PREFIX = None
from domreg import getDOMImplementation,registerDOMImplementation
| Python |
"""Facility to use the Expat parser to load a minidom instance
from a string or file.
This avoids all the overhead of SAX and pulldom to gain performance.
"""
# Warning!
#
# This module is tightly bound to the implementation details of the
# minidom DOM and can't be used with other DOM implementations. This
# is due, in part, to a lack of appropriate methods in the DOM (there is
# no way to create Entity and Notation nodes via the DOM Level 2
# interface), and for performance. The later is the cause of some fairly
# cryptic code.
#
# Performance hacks:
#
# - .character_data_handler() has an extra case in which continuing
# data is appended to an existing Text node; this can be a
# speedup since pyexpat can break up character data into multiple
# callbacks even though we set the buffer_text attribute on the
# parser. This also gives us the advantage that we don't need a
# separate normalization pass.
#
# - Determining that a node exists is done using an identity comparison
# with None rather than a truth test; this avoids searching for and
# calling any methods on the node object if it exists. (A rather
# nice speedup is achieved this way as well!)
from xml.dom import xmlbuilder, minidom, Node
from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE
from xml.parsers import expat
from xml.dom.minidom import _append_child, _set_attribute_node
from xml.dom.NodeFilter import NodeFilter
from xml.dom.minicompat import *
TEXT_NODE = Node.TEXT_NODE
CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE
DOCUMENT_NODE = Node.DOCUMENT_NODE
FILTER_ACCEPT = xmlbuilder.DOMBuilderFilter.FILTER_ACCEPT
FILTER_REJECT = xmlbuilder.DOMBuilderFilter.FILTER_REJECT
FILTER_SKIP = xmlbuilder.DOMBuilderFilter.FILTER_SKIP
FILTER_INTERRUPT = xmlbuilder.DOMBuilderFilter.FILTER_INTERRUPT
theDOMImplementation = minidom.getDOMImplementation()
# Expat typename -> TypeInfo
_typeinfo_map = {
"CDATA": minidom.TypeInfo(None, "cdata"),
"ENUM": minidom.TypeInfo(None, "enumeration"),
"ENTITY": minidom.TypeInfo(None, "entity"),
"ENTITIES": minidom.TypeInfo(None, "entities"),
"ID": minidom.TypeInfo(None, "id"),
"IDREF": minidom.TypeInfo(None, "idref"),
"IDREFS": minidom.TypeInfo(None, "idrefs"),
"NMTOKEN": minidom.TypeInfo(None, "nmtoken"),
"NMTOKENS": minidom.TypeInfo(None, "nmtokens"),
}
class ElementInfo(NewStyle):
__slots__ = '_attr_info', '_model', 'tagName'
def __init__(self, tagName, model=None):
self.tagName = tagName
self._attr_info = []
self._model = model
def __getstate__(self):
return self._attr_info, self._model, self.tagName
def __setstate__(self, state):
self._attr_info, self._model, self.tagName = state
def getAttributeType(self, aname):
for info in self._attr_info:
if info[1] == aname:
t = info[-2]
if t[0] == "(":
return _typeinfo_map["ENUM"]
else:
return _typeinfo_map[info[-2]]
return minidom._no_type
def getAttributeTypeNS(self, namespaceURI, localName):
return minidom._no_type
def isElementContent(self):
if self._model:
type = self._model[0]
return type not in (expat.model.XML_CTYPE_ANY,
expat.model.XML_CTYPE_MIXED)
else:
return False
def isEmpty(self):
if self._model:
return self._model[0] == expat.model.XML_CTYPE_EMPTY
else:
return False
def isId(self, aname):
for info in self._attr_info:
if info[1] == aname:
return info[-2] == "ID"
return False
def isIdNS(self, euri, ename, auri, aname):
# not sure this is meaningful
return self.isId((auri, aname))
def _intern(builder, s):
return builder._intern_setdefault(s, s)
def _parse_ns_name(builder, name):
assert ' ' in name
parts = name.split(' ')
intern = builder._intern_setdefault
if len(parts) == 3:
uri, localname, prefix = parts
prefix = intern(prefix, prefix)
qname = "%s:%s" % (prefix, localname)
qname = intern(qname, qname)
localname = intern(localname, localname)
else:
uri, localname = parts
prefix = EMPTY_PREFIX
qname = localname = intern(localname, localname)
return intern(uri, uri), localname, prefix, qname
class ExpatBuilder:
"""Document builder that uses Expat to build a ParsedXML.DOM document
instance."""
def __init__(self, options=None):
if options is None:
options = xmlbuilder.Options()
self._options = options
if self._options.filter is not None:
self._filter = FilterVisibilityController(self._options.filter)
else:
self._filter = None
# This *really* doesn't do anything in this case, so
# override it with something fast & minimal.
self._finish_start_element = id
self._parser = None
self.reset()
def createParser(self):
"""Create a new parser object."""
return expat.ParserCreate()
def getParser(self):
"""Return the parser object, creating a new one if needed."""
if not self._parser:
self._parser = self.createParser()
self._intern_setdefault = self._parser.intern.setdefault
self._parser.buffer_text = True
self._parser.ordered_attributes = True
self._parser.specified_attributes = True
self.install(self._parser)
return self._parser
def reset(self):
"""Free all data structures used during DOM construction."""
self.document = theDOMImplementation.createDocument(
EMPTY_NAMESPACE, None, None)
self.curNode = self.document
self._elem_info = self.document._elem_info
self._cdata = False
def install(self, parser):
"""Install the callbacks needed to build the DOM into the parser."""
# This creates circular references!
parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler
parser.StartElementHandler = self.first_element_handler
parser.EndElementHandler = self.end_element_handler
parser.ProcessingInstructionHandler = self.pi_handler
if self._options.entities:
parser.EntityDeclHandler = self.entity_decl_handler
parser.NotationDeclHandler = self.notation_decl_handler
if self._options.comments:
parser.CommentHandler = self.comment_handler
if self._options.cdata_sections:
parser.StartCdataSectionHandler = self.start_cdata_section_handler
parser.EndCdataSectionHandler = self.end_cdata_section_handler
parser.CharacterDataHandler = self.character_data_handler_cdata
else:
parser.CharacterDataHandler = self.character_data_handler
parser.ExternalEntityRefHandler = self.external_entity_ref_handler
parser.XmlDeclHandler = self.xml_decl_handler
parser.ElementDeclHandler = self.element_decl_handler
parser.AttlistDeclHandler = self.attlist_decl_handler
def parseFile(self, file):
"""Parse a document from a file object, returning the document
node."""
parser = self.getParser()
first_buffer = True
try:
while 1:
buffer = file.read(16*1024)
if not buffer:
break
parser.Parse(buffer, 0)
if first_buffer and self.document.documentElement:
self._setup_subset(buffer)
first_buffer = False
parser.Parse("", True)
except ParseEscape:
pass
doc = self.document
self.reset()
self._parser = None
return doc
def parseString(self, string):
"""Parse a document from a string, returning the document node."""
parser = self.getParser()
try:
parser.Parse(string, True)
self._setup_subset(string)
except ParseEscape:
pass
doc = self.document
self.reset()
self._parser = None
return doc
def _setup_subset(self, buffer):
"""Load the internal subset if there might be one."""
if self.document.doctype:
extractor = InternalSubsetExtractor()
extractor.parseString(buffer)
subset = extractor.getSubset()
self.document.doctype.internalSubset = subset
def start_doctype_decl_handler(self, doctypeName, systemId, publicId,
has_internal_subset):
doctype = self.document.implementation.createDocumentType(
doctypeName, publicId, systemId)
doctype.ownerDocument = self.document
self.document.childNodes.append(doctype)
self.document.doctype = doctype
if self._filter and self._filter.acceptNode(doctype) == FILTER_REJECT:
self.document.doctype = None
del self.document.childNodes[-1]
doctype = None
self._parser.EntityDeclHandler = None
self._parser.NotationDeclHandler = None
if has_internal_subset:
if doctype is not None:
doctype.entities._seq = []
doctype.notations._seq = []
self._parser.CommentHandler = None
self._parser.ProcessingInstructionHandler = None
self._parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler
def end_doctype_decl_handler(self):
if self._options.comments:
self._parser.CommentHandler = self.comment_handler
self._parser.ProcessingInstructionHandler = self.pi_handler
if not (self._elem_info or self._filter):
self._finish_end_element = id
def pi_handler(self, target, data):
node = self.document.createProcessingInstruction(target, data)
_append_child(self.curNode, node)
if self._filter and self._filter.acceptNode(node) == FILTER_REJECT:
self.curNode.removeChild(node)
def character_data_handler_cdata(self, data):
childNodes = self.curNode.childNodes
if self._cdata:
if ( self._cdata_continue
and childNodes[-1].nodeType == CDATA_SECTION_NODE):
childNodes[-1].appendData(data)
return
node = self.document.createCDATASection(data)
self._cdata_continue = True
elif childNodes and childNodes[-1].nodeType == TEXT_NODE:
node = childNodes[-1]
value = node.data + data
d = node.__dict__
d['data'] = d['nodeValue'] = value
return
else:
node = minidom.Text()
d = node.__dict__
d['data'] = d['nodeValue'] = data
d['ownerDocument'] = self.document
_append_child(self.curNode, node)
def character_data_handler(self, data):
childNodes = self.curNode.childNodes
if childNodes and childNodes[-1].nodeType == TEXT_NODE:
node = childNodes[-1]
d = node.__dict__
d['data'] = d['nodeValue'] = node.data + data
return
node = minidom.Text()
d = node.__dict__
d['data'] = d['nodeValue'] = node.data + data
d['ownerDocument'] = self.document
_append_child(self.curNode, node)
def entity_decl_handler(self, entityName, is_parameter_entity, value,
base, systemId, publicId, notationName):
if is_parameter_entity:
# we don't care about parameter entities for the DOM
return
if not self._options.entities:
return
node = self.document._create_entity(entityName, publicId,
systemId, notationName)
if value is not None:
# internal entity
# node *should* be readonly, but we'll cheat
child = self.document.createTextNode(value)
node.childNodes.append(child)
self.document.doctype.entities._seq.append(node)
if self._filter and self._filter.acceptNode(node) == FILTER_REJECT:
del self.document.doctype.entities._seq[-1]
def notation_decl_handler(self, notationName, base, systemId, publicId):
node = self.document._create_notation(notationName, publicId, systemId)
self.document.doctype.notations._seq.append(node)
if self._filter and self._filter.acceptNode(node) == FILTER_ACCEPT:
del self.document.doctype.notations._seq[-1]
def comment_handler(self, data):
node = self.document.createComment(data)
_append_child(self.curNode, node)
if self._filter and self._filter.acceptNode(node) == FILTER_REJECT:
self.curNode.removeChild(node)
def start_cdata_section_handler(self):
self._cdata = True
self._cdata_continue = False
def end_cdata_section_handler(self):
self._cdata = False
self._cdata_continue = False
def external_entity_ref_handler(self, context, base, systemId, publicId):
return 1
def first_element_handler(self, name, attributes):
if self._filter is None and not self._elem_info:
self._finish_end_element = id
self.getParser().StartElementHandler = self.start_element_handler
self.start_element_handler(name, attributes)
def start_element_handler(self, name, attributes):
node = self.document.createElement(name)
_append_child(self.curNode, node)
self.curNode = node
if attributes:
for i in range(0, len(attributes), 2):
a = minidom.Attr(attributes[i], EMPTY_NAMESPACE,
None, EMPTY_PREFIX)
value = attributes[i+1]
d = a.childNodes[0].__dict__
d['data'] = d['nodeValue'] = value
d = a.__dict__
d['value'] = d['nodeValue'] = value
d['ownerDocument'] = self.document
_set_attribute_node(node, a)
if node is not self.document.documentElement:
self._finish_start_element(node)
def _finish_start_element(self, node):
if self._filter:
# To be general, we'd have to call isSameNode(), but this
# is sufficient for minidom:
if node is self.document.documentElement:
return
filt = self._filter.startContainer(node)
if filt == FILTER_REJECT:
# ignore this node & all descendents
Rejecter(self)
elif filt == FILTER_SKIP:
# ignore this node, but make it's children become
# children of the parent node
Skipper(self)
else:
return
self.curNode = node.parentNode
node.parentNode.removeChild(node)
node.unlink()
# If this ever changes, Namespaces.end_element_handler() needs to
# be changed to match.
#
def end_element_handler(self, name):
curNode = self.curNode
self.curNode = curNode.parentNode
self._finish_end_element(curNode)
def _finish_end_element(self, curNode):
info = self._elem_info.get(curNode.tagName)
if info:
self._handle_white_text_nodes(curNode, info)
if self._filter:
if curNode is self.document.documentElement:
return
if self._filter.acceptNode(curNode) == FILTER_REJECT:
self.curNode.removeChild(curNode)
curNode.unlink()
def _handle_white_text_nodes(self, node, info):
if (self._options.whitespace_in_element_content
or not info.isElementContent()):
return
# We have element type information and should remove ignorable
# whitespace; identify for text nodes which contain only
# whitespace.
L = []
for child in node.childNodes:
if child.nodeType == TEXT_NODE and not child.data.strip():
L.append(child)
# Remove ignorable whitespace from the tree.
for child in L:
node.removeChild(child)
def element_decl_handler(self, name, model):
info = self._elem_info.get(name)
if info is None:
self._elem_info[name] = ElementInfo(name, model)
else:
assert info._model is None
info._model = model
def attlist_decl_handler(self, elem, name, type, default, required):
info = self._elem_info.get(elem)
if info is None:
info = ElementInfo(elem)
self._elem_info[elem] = info
info._attr_info.append(
[None, name, None, None, default, 0, type, required])
def xml_decl_handler(self, version, encoding, standalone):
self.document.version = version
self.document.encoding = encoding
# This is still a little ugly, thanks to the pyexpat API. ;-(
if standalone >= 0:
if standalone:
self.document.standalone = True
else:
self.document.standalone = False
# Don't include FILTER_INTERRUPT, since that's checked separately
# where allowed.
_ALLOWED_FILTER_RETURNS = (FILTER_ACCEPT, FILTER_REJECT, FILTER_SKIP)
class FilterVisibilityController(NewStyle):
"""Wrapper around a DOMBuilderFilter which implements the checks
to make the whatToShow filter attribute work."""
__slots__ = 'filter',
def __init__(self, filter):
self.filter = filter
def startContainer(self, node):
mask = self._nodetype_mask[node.nodeType]
if self.filter.whatToShow & mask:
val = self.filter.startContainer(node)
if val == FILTER_INTERRUPT:
raise ParseEscape
if val not in _ALLOWED_FILTER_RETURNS:
raise ValueError, \
"startContainer() returned illegal value: " + repr(val)
return val
else:
return FILTER_ACCEPT
def acceptNode(self, node):
mask = self._nodetype_mask[node.nodeType]
if self.filter.whatToShow & mask:
val = self.filter.acceptNode(node)
if val == FILTER_INTERRUPT:
raise ParseEscape
if val == FILTER_SKIP:
# move all child nodes to the parent, and remove this node
parent = node.parentNode
for child in node.childNodes[:]:
parent.appendChild(child)
# node is handled by the caller
return FILTER_REJECT
if val not in _ALLOWED_FILTER_RETURNS:
raise ValueError, \
"acceptNode() returned illegal value: " + repr(val)
return val
else:
return FILTER_ACCEPT
_nodetype_mask = {
Node.ELEMENT_NODE: NodeFilter.SHOW_ELEMENT,
Node.ATTRIBUTE_NODE: NodeFilter.SHOW_ATTRIBUTE,
Node.TEXT_NODE: NodeFilter.SHOW_TEXT,
Node.CDATA_SECTION_NODE: NodeFilter.SHOW_CDATA_SECTION,
Node.ENTITY_REFERENCE_NODE: NodeFilter.SHOW_ENTITY_REFERENCE,
Node.ENTITY_NODE: NodeFilter.SHOW_ENTITY,
Node.PROCESSING_INSTRUCTION_NODE: NodeFilter.SHOW_PROCESSING_INSTRUCTION,
Node.COMMENT_NODE: NodeFilter.SHOW_COMMENT,
Node.DOCUMENT_NODE: NodeFilter.SHOW_DOCUMENT,
Node.DOCUMENT_TYPE_NODE: NodeFilter.SHOW_DOCUMENT_TYPE,
Node.DOCUMENT_FRAGMENT_NODE: NodeFilter.SHOW_DOCUMENT_FRAGMENT,
Node.NOTATION_NODE: NodeFilter.SHOW_NOTATION,
}
class FilterCrutch(NewStyle):
__slots__ = '_builder', '_level', '_old_start', '_old_end'
def __init__(self, builder):
self._level = 0
self._builder = builder
parser = builder._parser
self._old_start = parser.StartElementHandler
self._old_end = parser.EndElementHandler
parser.StartElementHandler = self.start_element_handler
parser.EndElementHandler = self.end_element_handler
class Rejecter(FilterCrutch):
__slots__ = ()
def __init__(self, builder):
FilterCrutch.__init__(self, builder)
parser = builder._parser
for name in ("ProcessingInstructionHandler",
"CommentHandler",
"CharacterDataHandler",
"StartCdataSectionHandler",
"EndCdataSectionHandler",
"ExternalEntityRefHandler",
):
setattr(parser, name, None)
def start_element_handler(self, *args):
self._level = self._level + 1
def end_element_handler(self, *args):
if self._level == 0:
# restore the old handlers
parser = self._builder._parser
self._builder.install(parser)
parser.StartElementHandler = self._old_start
parser.EndElementHandler = self._old_end
else:
self._level = self._level - 1
class Skipper(FilterCrutch):
__slots__ = ()
def start_element_handler(self, *args):
node = self._builder.curNode
self._old_start(*args)
if self._builder.curNode is not node:
self._level = self._level + 1
def end_element_handler(self, *args):
if self._level == 0:
# We're popping back out of the node we're skipping, so we
# shouldn't need to do anything but reset the handlers.
self._builder._parser.StartElementHandler = self._old_start
self._builder._parser.EndElementHandler = self._old_end
self._builder = None
else:
self._level = self._level - 1
self._old_end(*args)
# framework document used by the fragment builder.
# Takes a string for the doctype, subset string, and namespace attrs string.
_FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID = \
"http://xml.python.org/entities/fragment-builder/internal"
_FRAGMENT_BUILDER_TEMPLATE = (
'''\
<!DOCTYPE wrapper
%%s [
<!ENTITY fragment-builder-internal
SYSTEM "%s">
%%s
]>
<wrapper %%s
>&fragment-builder-internal;</wrapper>'''
% _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID)
class FragmentBuilder(ExpatBuilder):
"""Builder which constructs document fragments given XML source
text and a context node.
The context node is expected to provide information about the
namespace declarations which are in scope at the start of the
fragment.
"""
def __init__(self, context, options=None):
if context.nodeType == DOCUMENT_NODE:
self.originalDocument = context
self.context = context
else:
self.originalDocument = context.ownerDocument
self.context = context
ExpatBuilder.__init__(self, options)
def reset(self):
ExpatBuilder.reset(self)
self.fragment = None
def parseFile(self, file):
"""Parse a document fragment from a file object, returning the
fragment node."""
return self.parseString(file.read())
def parseString(self, string):
"""Parse a document fragment from a string, returning the
fragment node."""
self._source = string
parser = self.getParser()
doctype = self.originalDocument.doctype
ident = ""
if doctype:
subset = doctype.internalSubset or self._getDeclarations()
if doctype.publicId:
ident = ('PUBLIC "%s" "%s"'
% (doctype.publicId, doctype.systemId))
elif doctype.systemId:
ident = 'SYSTEM "%s"' % doctype.systemId
else:
subset = ""
nsattrs = self._getNSattrs() # get ns decls from node's ancestors
document = _FRAGMENT_BUILDER_TEMPLATE % (ident, subset, nsattrs)
try:
parser.Parse(document, 1)
except:
self.reset()
raise
fragment = self.fragment
self.reset()
## self._parser = None
return fragment
def _getDeclarations(self):
"""Re-create the internal subset from the DocumentType node.
This is only needed if we don't already have the
internalSubset as a string.
"""
doctype = self.context.ownerDocument.doctype
s = ""
if doctype:
for i in range(doctype.notations.length):
notation = doctype.notations.item(i)
if s:
s = s + "\n "
s = "%s<!NOTATION %s" % (s, notation.nodeName)
if notation.publicId:
s = '%s PUBLIC "%s"\n "%s">' \
% (s, notation.publicId, notation.systemId)
else:
s = '%s SYSTEM "%s">' % (s, notation.systemId)
for i in range(doctype.entities.length):
entity = doctype.entities.item(i)
if s:
s = s + "\n "
s = "%s<!ENTITY %s" % (s, entity.nodeName)
if entity.publicId:
s = '%s PUBLIC "%s"\n "%s"' \
% (s, entity.publicId, entity.systemId)
elif entity.systemId:
s = '%s SYSTEM "%s"' % (s, entity.systemId)
else:
s = '%s "%s"' % (s, entity.firstChild.data)
if entity.notationName:
s = "%s NOTATION %s" % (s, entity.notationName)
s = s + ">"
return s
def _getNSattrs(self):
return ""
def external_entity_ref_handler(self, context, base, systemId, publicId):
if systemId == _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID:
# this entref is the one that we made to put the subtree
# in; all of our given input is parsed in here.
old_document = self.document
old_cur_node = self.curNode
parser = self._parser.ExternalEntityParserCreate(context)
# put the real document back, parse into the fragment to return
self.document = self.originalDocument
self.fragment = self.document.createDocumentFragment()
self.curNode = self.fragment
try:
parser.Parse(self._source, 1)
finally:
self.curNode = old_cur_node
self.document = old_document
self._source = None
return -1
else:
return ExpatBuilder.external_entity_ref_handler(
self, context, base, systemId, publicId)
class Namespaces:
"""Mix-in class for builders; adds support for namespaces."""
def _initNamespaces(self):
# list of (prefix, uri) ns declarations. Namespace attrs are
# constructed from this and added to the element's attrs.
self._ns_ordered_prefixes = []
def createParser(self):
"""Create a new namespace-handling parser."""
parser = expat.ParserCreate(namespace_separator=" ")
parser.namespace_prefixes = True
return parser
def install(self, parser):
"""Insert the namespace-handlers onto the parser."""
ExpatBuilder.install(self, parser)
if self._options.namespace_declarations:
parser.StartNamespaceDeclHandler = (
self.start_namespace_decl_handler)
def start_namespace_decl_handler(self, prefix, uri):
"""Push this namespace declaration on our storage."""
self._ns_ordered_prefixes.append((prefix, uri))
def start_element_handler(self, name, attributes):
if ' ' in name:
uri, localname, prefix, qname = _parse_ns_name(self, name)
else:
uri = EMPTY_NAMESPACE
qname = name
localname = None
prefix = EMPTY_PREFIX
node = minidom.Element(qname, uri, prefix, localname)
node.ownerDocument = self.document
_append_child(self.curNode, node)
self.curNode = node
if self._ns_ordered_prefixes:
for prefix, uri in self._ns_ordered_prefixes:
if prefix:
a = minidom.Attr(_intern(self, 'xmlns:' + prefix),
XMLNS_NAMESPACE, prefix, "xmlns")
else:
a = minidom.Attr("xmlns", XMLNS_NAMESPACE,
"xmlns", EMPTY_PREFIX)
d = a.childNodes[0].__dict__
d['data'] = d['nodeValue'] = uri
d = a.__dict__
d['value'] = d['nodeValue'] = uri
d['ownerDocument'] = self.document
_set_attribute_node(node, a)
del self._ns_ordered_prefixes[:]
if attributes:
_attrs = node._attrs
_attrsNS = node._attrsNS
for i in range(0, len(attributes), 2):
aname = attributes[i]
value = attributes[i+1]
if ' ' in aname:
uri, localname, prefix, qname = _parse_ns_name(self, aname)
a = minidom.Attr(qname, uri, localname, prefix)
_attrs[qname] = a
_attrsNS[(uri, localname)] = a
else:
a = minidom.Attr(aname, EMPTY_NAMESPACE,
aname, EMPTY_PREFIX)
_attrs[aname] = a
_attrsNS[(EMPTY_NAMESPACE, aname)] = a
d = a.childNodes[0].__dict__
d['data'] = d['nodeValue'] = value
d = a.__dict__
d['ownerDocument'] = self.document
d['value'] = d['nodeValue'] = value
d['ownerElement'] = node
if __debug__:
# This only adds some asserts to the original
# end_element_handler(), so we only define this when -O is not
# used. If changing one, be sure to check the other to see if
# it needs to be changed as well.
#
def end_element_handler(self, name):
curNode = self.curNode
if ' ' in name:
uri, localname, prefix, qname = _parse_ns_name(self, name)
assert (curNode.namespaceURI == uri
and curNode.localName == localname
and curNode.prefix == prefix), \
"element stack messed up! (namespace)"
else:
assert curNode.nodeName == name, \
"element stack messed up - bad nodeName"
assert curNode.namespaceURI == EMPTY_NAMESPACE, \
"element stack messed up - bad namespaceURI"
self.curNode = curNode.parentNode
self._finish_end_element(curNode)
class ExpatBuilderNS(Namespaces, ExpatBuilder):
"""Document builder that supports namespaces."""
def reset(self):
ExpatBuilder.reset(self)
self._initNamespaces()
class FragmentBuilderNS(Namespaces, FragmentBuilder):
"""Fragment builder that supports namespaces."""
def reset(self):
FragmentBuilder.reset(self)
self._initNamespaces()
def _getNSattrs(self):
"""Return string of namespace attributes from this element and
ancestors."""
# XXX This needs to be re-written to walk the ancestors of the
# context to build up the namespace information from
# declarations, elements, and attributes found in context.
# Otherwise we have to store a bunch more data on the DOM
# (though that *might* be more reliable -- not clear).
attrs = ""
context = self.context
L = []
while context:
if hasattr(context, '_ns_prefix_uri'):
for prefix, uri in context._ns_prefix_uri.items():
# add every new NS decl from context to L and attrs string
if prefix in L:
continue
L.append(prefix)
if prefix:
declname = "xmlns:" + prefix
else:
declname = "xmlns"
if attrs:
attrs = "%s\n %s='%s'" % (attrs, declname, uri)
else:
attrs = " %s='%s'" % (declname, uri)
context = context.parentNode
return attrs
class ParseEscape(Exception):
"""Exception raised to short-circuit parsing in InternalSubsetExtractor."""
pass
class InternalSubsetExtractor(ExpatBuilder):
"""XML processor which can rip out the internal document type subset."""
subset = None
def getSubset(self):
"""Return the internal subset as a string."""
return self.subset
def parseFile(self, file):
try:
ExpatBuilder.parseFile(self, file)
except ParseEscape:
pass
def parseString(self, string):
try:
ExpatBuilder.parseString(self, string)
except ParseEscape:
pass
def install(self, parser):
parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler
parser.StartElementHandler = self.start_element_handler
def start_doctype_decl_handler(self, name, publicId, systemId,
has_internal_subset):
if has_internal_subset:
parser = self.getParser()
self.subset = []
parser.DefaultHandler = self.subset.append
parser.EndDoctypeDeclHandler = self.end_doctype_decl_handler
else:
raise ParseEscape()
def end_doctype_decl_handler(self):
s = ''.join(self.subset).replace('\r\n', '\n').replace('\r', '\n')
self.subset = s
raise ParseEscape()
def start_element_handler(self, name, attrs):
raise ParseEscape()
def parse(file, namespaces=1):
"""Parse a document, returning the resulting Document node.
'file' may be either a file name or an open file object.
"""
if namespaces:
builder = ExpatBuilderNS()
else:
builder = ExpatBuilder()
if isinstance(file, StringTypes):
fp = open(file, 'rb')
try:
result = builder.parseFile(fp)
finally:
fp.close()
else:
result = builder.parseFile(file)
return result
def parseString(string, namespaces=1):
"""Parse a document from a string, returning the resulting
Document node.
"""
if namespaces:
builder = ExpatBuilderNS()
else:
builder = ExpatBuilder()
return builder.parseString(string)
def parseFragment(file, context, namespaces=1):
"""Parse a fragment of a document, given the context from which it
was originally extracted. context should be the parent of the
node(s) which are in the fragment.
'file' may be either a file name or an open file object.
"""
if namespaces:
builder = FragmentBuilderNS(context)
else:
builder = FragmentBuilder(context)
if isinstance(file, StringTypes):
fp = open(file, 'rb')
try:
result = builder.parseFile(fp)
finally:
fp.close()
else:
result = builder.parseFile(file)
return result
def parseFragmentString(string, context, namespaces=1):
"""Parse a fragment of a document from a string, given the context
from which it was originally extracted. context should be the
parent of the node(s) which are in the fragment.
"""
if namespaces:
builder = FragmentBuilderNS(context)
else:
builder = FragmentBuilder(context)
return builder.parseString(string)
def makeBuilder(options):
"""Create a builder based on an Options object."""
if options.namespaces:
return ExpatBuilderNS(options)
else:
return ExpatBuilder(options)
| Python |
"""Python version compatibility support for minidom."""
# This module should only be imported using "import *".
#
# The following names are defined:
#
# isinstance -- version of the isinstance() function that accepts
# tuples as the second parameter regardless of the
# Python version
#
# NodeList -- lightest possible NodeList implementation
#
# EmptyNodeList -- lightest possible NodeList that is guarateed to
# remain empty (immutable)
#
# StringTypes -- tuple of defined string types
#
# GetattrMagic -- base class used to make _get_<attr> be magically
# invoked when available
# defproperty -- function used in conjunction with GetattrMagic;
# using these together is needed to make them work
# as efficiently as possible in both Python 2.2+
# and older versions. For example:
#
# class MyClass(GetattrMagic):
# def _get_myattr(self):
# return something
#
# defproperty(MyClass, "myattr",
# "return some value")
#
# For Python 2.2 and newer, this will construct a
# property object on the class, which avoids
# needing to override __getattr__(). It will only
# work for read-only attributes.
#
# For older versions of Python, inheriting from
# GetattrMagic will use the traditional
# __getattr__() hackery to achieve the same effect,
# but less efficiently.
#
# defproperty() should be used for each version of
# the relevant _get_<property>() function.
#
# NewStyle -- base class to cause __slots__ to be honored in
# the new world
#
# True, False -- only for Python 2.2 and earlier
__all__ = ["NodeList", "EmptyNodeList", "NewStyle",
"StringTypes", "defproperty", "GetattrMagic"]
import xml.dom
try:
unicode
except NameError:
StringTypes = type(''),
else:
StringTypes = type(''), type(unicode(''))
# define True and False only if not defined as built-ins
try:
True
except NameError:
True = 1
False = 0
__all__.extend(["True", "False"])
try:
isinstance('', StringTypes)
except TypeError:
#
# Wrap isinstance() to make it compatible with the version in
# Python 2.2 and newer.
#
_isinstance = isinstance
def isinstance(obj, type_or_seq):
try:
return _isinstance(obj, type_or_seq)
except TypeError:
for t in type_or_seq:
if _isinstance(obj, t):
return 1
return 0
__all__.append("isinstance")
if list is type([]):
class NodeList(list):
__slots__ = ()
def item(self, index):
if 0 <= index < len(self):
return self[index]
def _get_length(self):
return len(self)
def _set_length(self, value):
raise xml.dom.NoModificationAllowedErr(
"attempt to modify read-only attribute 'length'")
length = property(_get_length, _set_length,
doc="The number of nodes in the NodeList.")
def __getstate__(self):
return list(self)
def __setstate__(self, state):
self[:] = state
class EmptyNodeList(tuple):
__slots__ = ()
def __add__(self, other):
NL = NodeList()
NL.extend(other)
return NL
def __radd__(self, other):
NL = NodeList()
NL.extend(other)
return NL
def item(self, index):
return None
def _get_length(self):
return 0
def _set_length(self, value):
raise xml.dom.NoModificationAllowedErr(
"attempt to modify read-only attribute 'length'")
length = property(_get_length, _set_length,
doc="The number of nodes in the NodeList.")
else:
def NodeList():
return []
def EmptyNodeList():
return []
try:
property
except NameError:
def defproperty(klass, name, doc):
# taken care of by the base __getattr__()
pass
class GetattrMagic:
def __getattr__(self, key):
if key.startswith("_"):
raise AttributeError, key
try:
get = getattr(self, "_get_" + key)
except AttributeError:
raise AttributeError, key
return get()
class NewStyle:
pass
else:
def defproperty(klass, name, doc):
get = getattr(klass, ("_get_" + name)).im_func
def set(self, value, name=name):
raise xml.dom.NoModificationAllowedErr(
"attempt to modify read-only attribute " + repr(name))
assert not hasattr(klass, "_set_" + name), \
"expected not to find _set_" + name
prop = property(get, set, doc=doc)
setattr(klass, name, prop)
class GetattrMagic:
pass
NewStyle = object
| Python |
"""Core XML support for Python.
This package contains three sub-packages:
dom -- The W3C Document Object Model. This supports DOM Level 1 +
Namespaces.
parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David
Megginson and ported to Python by Lars Marius Garshol. This
supports the SAX 2 API.
"""
__all__ = ["dom", "parsers", "sax"]
# When being checked-out without options, this has the form
# "<dollar>Revision: x.y </dollar>"
# When exported using -kv, it is "x.y".
__version__ = "$Revision: 1.15 $".split()[-2:][0]
_MINIMUM_XMLPLUS_VERSION = (0, 8, 4)
try:
import _xmlplus
except ImportError:
pass
else:
try:
v = _xmlplus.version_info
except AttributeError:
# _xmlplus is too old; ignore it
pass
else:
if v >= _MINIMUM_XMLPLUS_VERSION:
import sys
sys.modules[__name__] = _xmlplus
else:
del v
| Python |
"""Interface to the Expat non-validating XML parser."""
__version__ = '$Revision: 1.1 $'
from pyexpat import *
| Python |
"""Python interfaces to XML parsers.
This package contains one module:
expat -- Python wrapper for James Clark's Expat parser, with namespace
support.
"""
| Python |
"""IMAP4 client.
Based on RFC 2060.
Public class: IMAP4
Public variable: Debug
Public functions: Internaldate2tuple
Int2AP
ParseFlags
Time2Internaldate
"""
# Author: Piers Lauder <piers@cs.su.oz.au> December 1997.
#
# Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
# String method conversion by ESR, February 2001.
# GET/SETACL contributed by Anthony Baxter <anthony@interlink.com.au> April 2001.
# IMAP4_SSL contributed by Tino Lange <Tino.Lange@isg.de> March 2002.
# GET/SETQUOTA contributed by Andreas Zeidler <az@kreativkombinat.de> June 2002.
# PROXYAUTH contributed by Rick Holbert <holbert.13@osu.edu> November 2002.
__version__ = "2.55"
import binascii, os, random, re, socket, sys, time
__all__ = ["IMAP4", "IMAP4_SSL", "IMAP4_stream", "Internaldate2tuple",
"Int2AP", "ParseFlags", "Time2Internaldate"]
# Globals
CRLF = '\r\n'
Debug = 0
IMAP4_PORT = 143
IMAP4_SSL_PORT = 993
AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
# Commands
Commands = {
# name valid states
'APPEND': ('AUTH', 'SELECTED'),
'AUTHENTICATE': ('NONAUTH',),
'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
'CHECK': ('SELECTED',),
'CLOSE': ('SELECTED',),
'COPY': ('SELECTED',),
'CREATE': ('AUTH', 'SELECTED'),
'DELETE': ('AUTH', 'SELECTED'),
'DELETEACL': ('AUTH', 'SELECTED'),
'EXAMINE': ('AUTH', 'SELECTED'),
'EXPUNGE': ('SELECTED',),
'FETCH': ('SELECTED',),
'GETACL': ('AUTH', 'SELECTED'),
'GETQUOTA': ('AUTH', 'SELECTED'),
'GETQUOTAROOT': ('AUTH', 'SELECTED'),
'MYRIGHTS': ('AUTH', 'SELECTED'),
'LIST': ('AUTH', 'SELECTED'),
'LOGIN': ('NONAUTH',),
'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
'LSUB': ('AUTH', 'SELECTED'),
'NAMESPACE': ('AUTH', 'SELECTED'),
'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
'PARTIAL': ('SELECTED',), # NB: obsolete
'PROXYAUTH': ('AUTH',),
'RENAME': ('AUTH', 'SELECTED'),
'SEARCH': ('SELECTED',),
'SELECT': ('AUTH', 'SELECTED'),
'SETACL': ('AUTH', 'SELECTED'),
'SETQUOTA': ('AUTH', 'SELECTED'),
'SORT': ('SELECTED',),
'STATUS': ('AUTH', 'SELECTED'),
'STORE': ('SELECTED',),
'SUBSCRIBE': ('AUTH', 'SELECTED'),
'THREAD': ('SELECTED',),
'UID': ('SELECTED',),
'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
}
# Patterns to match server responses
Continuation = re.compile(r'\+( (?P<data>.*))?')
Flags = re.compile(r'.*FLAGS \((?P<flags>[^\)]*)\)')
InternalDate = re.compile(r'.*INTERNALDATE "'
r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
r'"')
Literal = re.compile(r'.*{(?P<size>\d+)}$')
MapCRLF = re.compile(r'\r\n|\r|\n')
Response_code = re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
Untagged_response = re.compile(r'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
Untagged_status = re.compile(r'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
class IMAP4:
"""IMAP4 client class.
Instantiate with: IMAP4([host[, port]])
host - host's name (default: localhost);
port - port number (default: standard IMAP4 port).
All IMAP4rev1 commands are supported by methods of the same
name (in lower-case).
All arguments to commands are converted to strings, except for
AUTHENTICATE, and the last argument to APPEND which is passed as
an IMAP4 literal. If necessary (the string contains any
non-printing characters or white-space and isn't enclosed with
either parentheses or double quotes) each string is quoted.
However, the 'password' argument to the LOGIN command is always
quoted. If you want to avoid having an argument string quoted
(eg: the 'flags' argument to STORE) then enclose the string in
parentheses (eg: "(\Deleted)").
Each command returns a tuple: (type, [data, ...]) where 'type'
is usually 'OK' or 'NO', and 'data' is either the text from the
tagged response, or untagged results from command. Each 'data'
is either a string, or a tuple. If a tuple, then the first part
is the header of the response, and the second part contains
the data (ie: 'literal' value).
Errors raise the exception class <instance>.error("<reason>").
IMAP4 server errors raise <instance>.abort("<reason>"),
which is a sub-class of 'error'. Mailbox status changes
from READ-WRITE to READ-ONLY raise the exception class
<instance>.readonly("<reason>"), which is a sub-class of 'abort'.
"error" exceptions imply a program error.
"abort" exceptions imply the connection should be reset, and
the command re-tried.
"readonly" exceptions imply the command should be re-tried.
Note: to use this module, you must read the RFCs pertaining
to the IMAP4 protocol, as the semantics of the arguments to
each IMAP4 command are left to the invoker, not to mention
the results.
"""
class error(Exception): pass # Logical errors - debug required
class abort(error): pass # Service errors - close and retry
class readonly(abort): pass # Mailbox status changed to READ-ONLY
mustquote = re.compile(r"[^\w!#$%&'*+,.:;<=>?^`|~-]")
def __init__(self, host = '', port = IMAP4_PORT):
self.debug = Debug
self.state = 'LOGOUT'
self.literal = None # A literal argument to a command
self.tagged_commands = {} # Tagged commands awaiting response
self.untagged_responses = {} # {typ: [data, ...], ...}
self.continuation_response = '' # Last continuation response
self.is_readonly = None # READ-ONLY desired state
self.tagnum = 0
# Open socket to server.
self.open(host, port)
# Create unique tag for this session,
# and compile tagged response matcher.
self.tagpre = Int2AP(random.randint(0, 31999))
self.tagre = re.compile(r'(?P<tag>'
+ self.tagpre
+ r'\d+) (?P<type>[A-Z]+) (?P<data>.*)')
# Get server welcome message,
# request and store CAPABILITY response.
if __debug__:
self._cmd_log_len = 10
self._cmd_log_idx = 0
self._cmd_log = {} # Last `_cmd_log_len' interactions
if self.debug >= 1:
self._mesg('imaplib version %s' % __version__)
self._mesg('new IMAP4 connection, tag=%s' % self.tagpre)
self.welcome = self._get_response()
if 'PREAUTH' in self.untagged_responses:
self.state = 'AUTH'
elif 'OK' in self.untagged_responses:
self.state = 'NONAUTH'
else:
raise self.error(self.welcome)
cap = 'CAPABILITY'
self._simple_command(cap)
if not cap in self.untagged_responses:
raise self.error('no CAPABILITY response from server')
self.capabilities = tuple(self.untagged_responses[cap][-1].upper().split())
if __debug__:
if self.debug >= 3:
self._mesg('CAPABILITIES: %r' % (self.capabilities,))
for version in AllowedVersions:
if not version in self.capabilities:
continue
self.PROTOCOL_VERSION = version
return
raise self.error('server not IMAP4 compliant')
def __getattr__(self, attr):
# Allow UPPERCASE variants of IMAP4 command methods.
if attr in Commands:
return getattr(self, attr.lower())
raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
# Overridable methods
def open(self, host = '', port = IMAP4_PORT):
"""Setup connection to remote server on "host:port"
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, readline, send, shutdown.
"""
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.file = self.sock.makefile('rb')
def read(self, size):
"""Read 'size' bytes from remote."""
return self.file.read(size)
def readline(self):
"""Read line from remote."""
return self.file.readline()
def send(self, data):
"""Send data to remote."""
self.sock.sendall(data)
def shutdown(self):
"""Close I/O established in "open"."""
self.file.close()
self.sock.close()
def socket(self):
"""Return socket instance used to connect to IMAP4 server.
socket = <instance>.socket()
"""
return self.sock
# Utility methods
def recent(self):
"""Return most recent 'RECENT' responses if any exist,
else prompt server for an update using the 'NOOP' command.
(typ, [data]) = <instance>.recent()
'data' is None if no new messages,
else list of RECENT responses, most recent last.
"""
name = 'RECENT'
typ, dat = self._untagged_response('OK', [None], name)
if dat[-1]:
return typ, dat
typ, dat = self.noop() # Prod server for response
return self._untagged_response(typ, dat, name)
def response(self, code):
"""Return data for response 'code' if received, or None.
Old value for response 'code' is cleared.
(code, [data]) = <instance>.response(code)
"""
return self._untagged_response(code, [None], code.upper())
# IMAP4 commands
def append(self, mailbox, flags, date_time, message):
"""Append message to named mailbox.
(typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
All args except `message' can be None.
"""
name = 'APPEND'
if not mailbox:
mailbox = 'INBOX'
if flags:
if (flags[0],flags[-1]) != ('(',')'):
flags = '(%s)' % flags
else:
flags = None
if date_time:
date_time = Time2Internaldate(date_time)
else:
date_time = None
self.literal = MapCRLF.sub(CRLF, message)
return self._simple_command(name, mailbox, flags, date_time)
def authenticate(self, mechanism, authobject):
"""Authenticate command - requires response processing.
'mechanism' specifies which authentication mechanism is to
be used - it must appear in <instance>.capabilities in the
form AUTH=<mechanism>.
'authobject' must be a callable object:
data = authobject(response)
It will be called to process server continuation responses.
It should return data that will be encoded and sent to server.
It should return None if the client abort response '*' should
be sent instead.
"""
mech = mechanism.upper()
# XXX: shouldn't this code be removed, not commented out?
#cap = 'AUTH=%s' % mech
#if not cap in self.capabilities: # Let the server decide!
# raise self.error("Server doesn't allow %s authentication." % mech)
self.literal = _Authenticator(authobject).process
typ, dat = self._simple_command('AUTHENTICATE', mech)
if typ != 'OK':
raise self.error(dat[-1])
self.state = 'AUTH'
return typ, dat
def check(self):
"""Checkpoint mailbox on server.
(typ, [data]) = <instance>.check()
"""
return self._simple_command('CHECK')
def close(self):
"""Close currently selected mailbox.
Deleted messages are removed from writable mailbox.
This is the recommended command before 'LOGOUT'.
(typ, [data]) = <instance>.close()
"""
try:
typ, dat = self._simple_command('CLOSE')
finally:
self.state = 'AUTH'
return typ, dat
def copy(self, message_set, new_mailbox):
"""Copy 'message_set' messages onto end of 'new_mailbox'.
(typ, [data]) = <instance>.copy(message_set, new_mailbox)
"""
return self._simple_command('COPY', message_set, new_mailbox)
def create(self, mailbox):
"""Create new mailbox.
(typ, [data]) = <instance>.create(mailbox)
"""
return self._simple_command('CREATE', mailbox)
def delete(self, mailbox):
"""Delete old mailbox.
(typ, [data]) = <instance>.delete(mailbox)
"""
return self._simple_command('DELETE', mailbox)
def deleteacl(self, mailbox, who):
"""Delete the ACLs (remove any rights) set for who on mailbox.
(typ, [data]) = <instance>.deleteacl(mailbox, who)
"""
return self._simple_command('DELETEACL', mailbox, who)
def expunge(self):
"""Permanently remove deleted items from selected mailbox.
Generates 'EXPUNGE' response for each deleted message.
(typ, [data]) = <instance>.expunge()
'data' is list of 'EXPUNGE'd message numbers in order received.
"""
name = 'EXPUNGE'
typ, dat = self._simple_command(name)
return self._untagged_response(typ, dat, name)
def fetch(self, message_set, message_parts):
"""Fetch (parts of) messages.
(typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
'message_parts' should be a string of selected parts
enclosed in parentheses, eg: "(UID BODY[TEXT])".
'data' are tuples of message part envelope and data.
"""
name = 'FETCH'
typ, dat = self._simple_command(name, message_set, message_parts)
return self._untagged_response(typ, dat, name)
def getacl(self, mailbox):
"""Get the ACLs for a mailbox.
(typ, [data]) = <instance>.getacl(mailbox)
"""
typ, dat = self._simple_command('GETACL', mailbox)
return self._untagged_response(typ, dat, 'ACL')
def getquota(self, root):
"""Get the quota root's resource usage and limits.
Part of the IMAP4 QUOTA extension defined in rfc2087.
(typ, [data]) = <instance>.getquota(root)
"""
typ, dat = self._simple_command('GETQUOTA', root)
return self._untagged_response(typ, dat, 'QUOTA')
def getquotaroot(self, mailbox):
"""Get the list of quota roots for the named mailbox.
(typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
"""
typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
typ, quota = self._untagged_response(typ, dat, 'QUOTA')
typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
return typ, [quotaroot, quota]
def list(self, directory='""', pattern='*'):
"""List mailbox names in directory matching pattern.
(typ, [data]) = <instance>.list(directory='""', pattern='*')
'data' is list of LIST responses.
"""
name = 'LIST'
typ, dat = self._simple_command(name, directory, pattern)
return self._untagged_response(typ, dat, name)
def login(self, user, password):
"""Identify client using plaintext password.
(typ, [data]) = <instance>.login(user, password)
NB: 'password' will be quoted.
"""
typ, dat = self._simple_command('LOGIN', user, self._quote(password))
if typ != 'OK':
raise self.error(dat[-1])
self.state = 'AUTH'
return typ, dat
def login_cram_md5(self, user, password):
""" Force use of CRAM-MD5 authentication.
(typ, [data]) = <instance>.login_cram_md5(user, password)
"""
self.user, self.password = user, password
return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
def _CRAM_MD5_AUTH(self, challenge):
""" Authobject to use with CRAM-MD5 authentication. """
import hmac
return self.user + " " + hmac.HMAC(self.password, challenge).hexdigest()
def logout(self):
"""Shutdown connection to server.
(typ, [data]) = <instance>.logout()
Returns server 'BYE' response.
"""
self.state = 'LOGOUT'
try: typ, dat = self._simple_command('LOGOUT')
except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
self.shutdown()
if 'BYE' in self.untagged_responses:
return 'BYE', self.untagged_responses['BYE']
return typ, dat
def lsub(self, directory='""', pattern='*'):
"""List 'subscribed' mailbox names in directory matching pattern.
(typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
'data' are tuples of message part envelope and data.
"""
name = 'LSUB'
typ, dat = self._simple_command(name, directory, pattern)
return self._untagged_response(typ, dat, name)
def myrights(self, mailbox):
"""Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
(typ, [data]) = <instance>.myrights(mailbox)
"""
typ,dat = self._simple_command('MYRIGHTS', mailbox)
return self._untagged_response(typ, dat, 'MYRIGHTS')
def namespace(self):
""" Returns IMAP namespaces ala rfc2342
(typ, [data, ...]) = <instance>.namespace()
"""
name = 'NAMESPACE'
typ, dat = self._simple_command(name)
return self._untagged_response(typ, dat, name)
def noop(self):
"""Send NOOP command.
(typ, [data]) = <instance>.noop()
"""
if __debug__:
if self.debug >= 3:
self._dump_ur(self.untagged_responses)
return self._simple_command('NOOP')
def partial(self, message_num, message_part, start, length):
"""Fetch truncated part of a message.
(typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
'data' is tuple of message part envelope and data.
"""
name = 'PARTIAL'
typ, dat = self._simple_command(name, message_num, message_part, start, length)
return self._untagged_response(typ, dat, 'FETCH')
def proxyauth(self, user):
"""Assume authentication as "user".
Allows an authorised administrator to proxy into any user's
mailbox.
(typ, [data]) = <instance>.proxyauth(user)
"""
name = 'PROXYAUTH'
return self._simple_command('PROXYAUTH', user)
def rename(self, oldmailbox, newmailbox):
"""Rename old mailbox name to new.
(typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
"""
return self._simple_command('RENAME', oldmailbox, newmailbox)
def search(self, charset, *criteria):
"""Search mailbox for matching messages.
(typ, [data]) = <instance>.search(charset, criterion, ...)
'data' is space separated list of matching message numbers.
"""
name = 'SEARCH'
if charset:
typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
else:
typ, dat = self._simple_command(name, *criteria)
return self._untagged_response(typ, dat, name)
def select(self, mailbox='INBOX', readonly=None):
"""Select a mailbox.
Flush all untagged responses.
(typ, [data]) = <instance>.select(mailbox='INBOX', readonly=None)
'data' is count of messages in mailbox ('EXISTS' response).
Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
other responses should be obtained via <instance>.response('FLAGS') etc.
"""
self.untagged_responses = {} # Flush old responses.
self.is_readonly = readonly
if readonly is not None:
name = 'EXAMINE'
else:
name = 'SELECT'
typ, dat = self._simple_command(name, mailbox)
if typ != 'OK':
self.state = 'AUTH' # Might have been 'SELECTED'
return typ, dat
self.state = 'SELECTED'
if 'READ-ONLY' in self.untagged_responses \
and not readonly:
if __debug__:
if self.debug >= 1:
self._dump_ur(self.untagged_responses)
raise self.readonly('%s is not writable' % mailbox)
return typ, self.untagged_responses.get('EXISTS', [None])
def setacl(self, mailbox, who, what):
"""Set a mailbox acl.
(typ, [data]) = <instance>.setacl(mailbox, who, what)
"""
return self._simple_command('SETACL', mailbox, who, what)
def setquota(self, root, limits):
"""Set the quota root's resource limits.
(typ, [data]) = <instance>.setquota(root, limits)
"""
typ, dat = self._simple_command('SETQUOTA', root, limits)
return self._untagged_response(typ, dat, 'QUOTA')
def sort(self, sort_criteria, charset, *search_criteria):
"""IMAP4rev1 extension SORT command.
(typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
"""
name = 'SORT'
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unimplemented extension command: %s' % name)
if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
sort_criteria = '(%s)' % sort_criteria
typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
return self._untagged_response(typ, dat, name)
def status(self, mailbox, names):
"""Request named status conditions for mailbox.
(typ, [data]) = <instance>.status(mailbox, names)
"""
name = 'STATUS'
#if self.PROTOCOL_VERSION == 'IMAP4': # Let the server decide!
# raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
typ, dat = self._simple_command(name, mailbox, names)
return self._untagged_response(typ, dat, name)
def store(self, message_set, command, flags):
"""Alters flag dispositions for messages in mailbox.
(typ, [data]) = <instance>.store(message_set, command, flags)
"""
if (flags[0],flags[-1]) != ('(',')'):
flags = '(%s)' % flags # Avoid quoting the flags
typ, dat = self._simple_command('STORE', message_set, command, flags)
return self._untagged_response(typ, dat, 'FETCH')
def subscribe(self, mailbox):
"""Subscribe to new mailbox.
(typ, [data]) = <instance>.subscribe(mailbox)
"""
return self._simple_command('SUBSCRIBE', mailbox)
def thread(self, threading_algorithm, charset, *search_criteria):
"""IMAPrev1 extension THREAD command.
(type, [data]) = <instance>.thread(threading_alogrithm, charset, search_criteria, ...)
"""
name = 'THREAD'
typ, dat = self._simple_command(name, threading_algorithm, charset, *search_criteria)
return self._untagged_response(typ, dat, name)
def uid(self, command, *args):
"""Execute "command arg ..." with messages identified by UID,
rather than message number.
(typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
Returns response appropriate to 'command'.
"""
command = command.upper()
if not command in Commands:
raise self.error("Unknown IMAP4 UID command: %s" % command)
if self.state not in Commands[command]:
raise self.error('command %s illegal in state %s'
% (command, self.state))
name = 'UID'
typ, dat = self._simple_command(name, command, *args)
if command in ('SEARCH', 'SORT'):
name = command
else:
name = 'FETCH'
return self._untagged_response(typ, dat, name)
def unsubscribe(self, mailbox):
"""Unsubscribe from old mailbox.
(typ, [data]) = <instance>.unsubscribe(mailbox)
"""
return self._simple_command('UNSUBSCRIBE', mailbox)
def xatom(self, name, *args):
"""Allow simple extension commands
notified by server in CAPABILITY response.
Assumes command is legal in current state.
(typ, [data]) = <instance>.xatom(name, arg, ...)
Returns response appropriate to extension command `name'.
"""
name = name.upper()
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unknown extension command: %s' % name)
if not name in Commands:
Commands[name] = (self.state,)
return self._simple_command(name, *args)
# Private methods
def _append_untagged(self, typ, dat):
if dat is None: dat = ''
ur = self.untagged_responses
if __debug__:
if self.debug >= 5:
self._mesg('untagged_responses[%s] %s += ["%s"]' %
(typ, len(ur.get(typ,'')), dat))
if typ in ur:
ur[typ].append(dat)
else:
ur[typ] = [dat]
def _check_bye(self):
bye = self.untagged_responses.get('BYE')
if bye:
raise self.abort(bye[-1])
def _command(self, name, *args):
if self.state not in Commands[name]:
self.literal = None
raise self.error(
'command %s illegal in state %s' % (name, self.state))
for typ in ('OK', 'NO', 'BAD'):
if typ in self.untagged_responses:
del self.untagged_responses[typ]
if 'READ-ONLY' in self.untagged_responses \
and not self.is_readonly:
raise self.readonly('mailbox status changed to READ-ONLY')
tag = self._new_tag()
data = '%s %s' % (tag, name)
for arg in args:
if arg is None: continue
data = '%s %s' % (data, self._checkquote(arg))
literal = self.literal
if literal is not None:
self.literal = None
if type(literal) is type(self._command):
literator = literal
else:
literator = None
data = '%s {%s}' % (data, len(literal))
if __debug__:
if self.debug >= 4:
self._mesg('> %s' % data)
else:
self._log('> %s' % data)
try:
self.send('%s%s' % (data, CRLF))
except (socket.error, OSError), val:
raise self.abort('socket error: %s' % val)
if literal is None:
return tag
while 1:
# Wait for continuation response
while self._get_response():
if self.tagged_commands[tag]: # BAD/NO?
return tag
# Send literal
if literator:
literal = literator(self.continuation_response)
if __debug__:
if self.debug >= 4:
self._mesg('write literal size %s' % len(literal))
try:
self.send(literal)
self.send(CRLF)
except (socket.error, OSError), val:
raise self.abort('socket error: %s' % val)
if not literator:
break
return tag
def _command_complete(self, name, tag):
self._check_bye()
try:
typ, data = self._get_tagged_response(tag)
except self.abort, val:
raise self.abort('command: %s => %s' % (name, val))
except self.error, val:
raise self.error('command: %s => %s' % (name, val))
self._check_bye()
if typ == 'BAD':
raise self.error('%s command error: %s %s' % (name, typ, data))
return typ, data
def _get_response(self):
# Read response and store.
#
# Returns None for continuation responses,
# otherwise first response line received.
resp = self._get_line()
# Command completion response?
if self._match(self.tagre, resp):
tag = self.mo.group('tag')
if not tag in self.tagged_commands:
raise self.abort('unexpected tagged response: %s' % resp)
typ = self.mo.group('type')
dat = self.mo.group('data')
self.tagged_commands[tag] = (typ, [dat])
else:
dat2 = None
# '*' (untagged) responses?
if not self._match(Untagged_response, resp):
if self._match(Untagged_status, resp):
dat2 = self.mo.group('data2')
if self.mo is None:
# Only other possibility is '+' (continuation) response...
if self._match(Continuation, resp):
self.continuation_response = self.mo.group('data')
return None # NB: indicates continuation
raise self.abort("unexpected response: '%s'" % resp)
typ = self.mo.group('type')
dat = self.mo.group('data')
if dat is None: dat = '' # Null untagged response
if dat2: dat = dat + ' ' + dat2
# Is there a literal to come?
while self._match(Literal, dat):
# Read literal direct from connection.
size = int(self.mo.group('size'))
if __debug__:
if self.debug >= 4:
self._mesg('read literal size %s' % size)
data = self.read(size)
# Store response with literal as tuple
self._append_untagged(typ, (dat, data))
# Read trailer - possibly containing another literal
dat = self._get_line()
self._append_untagged(typ, dat)
# Bracketed response information?
if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
self._append_untagged(self.mo.group('type'), self.mo.group('data'))
if __debug__:
if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
self._mesg('%s response: %s' % (typ, dat))
return resp
def _get_tagged_response(self, tag):
while 1:
result = self.tagged_commands[tag]
if result is not None:
del self.tagged_commands[tag]
return result
# Some have reported "unexpected response" exceptions.
# Note that ignoring them here causes loops.
# Instead, send me details of the unexpected response and
# I'll update the code in `_get_response()'.
try:
self._get_response()
except self.abort, val:
if __debug__:
if self.debug >= 1:
self.print_log()
raise
def _get_line(self):
line = self.readline()
if not line:
raise self.abort('socket error: EOF')
# Protocol mandates all lines terminated by CRLF
line = line[:-2]
if __debug__:
if self.debug >= 4:
self._mesg('< %s' % line)
else:
self._log('< %s' % line)
return line
def _match(self, cre, s):
# Run compiled regular expression match method on 's'.
# Save result, return success.
self.mo = cre.match(s)
if __debug__:
if self.mo is not None and self.debug >= 5:
self._mesg("\tmatched r'%s' => %r" % (cre.pattern, self.mo.groups()))
return self.mo is not None
def _new_tag(self):
tag = '%s%s' % (self.tagpre, self.tagnum)
self.tagnum = self.tagnum + 1
self.tagged_commands[tag] = None
return tag
def _checkquote(self, arg):
# Must quote command args if non-alphanumeric chars present,
# and not already quoted.
if type(arg) is not type(''):
return arg
if len(arg) >= 2 and (arg[0],arg[-1]) in (('(',')'),('"','"')):
return arg
if arg and self.mustquote.search(arg) is None:
return arg
return self._quote(arg)
def _quote(self, arg):
arg = arg.replace('\\', '\\\\')
arg = arg.replace('"', '\\"')
return '"%s"' % arg
def _simple_command(self, name, *args):
return self._command_complete(name, self._command(name, *args))
def _untagged_response(self, typ, dat, name):
if typ == 'NO':
return typ, dat
if not name in self.untagged_responses:
return typ, [None]
data = self.untagged_responses.pop(name)
if __debug__:
if self.debug >= 5:
self._mesg('untagged_responses[%s] => %s' % (name, data))
return typ, data
if __debug__:
def _mesg(self, s, secs=None):
if secs is None:
secs = time.time()
tm = time.strftime('%M:%S', time.localtime(secs))
sys.stderr.write(' %s.%02d %s\n' % (tm, (secs*100)%100, s))
sys.stderr.flush()
def _dump_ur(self, dict):
# Dump untagged responses (in `dict').
l = dict.items()
if not l: return
t = '\n\t\t'
l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l)
self._mesg('untagged responses dump:%s%s' % (t, t.join(l)))
def _log(self, line):
# Keep log of last `_cmd_log_len' interactions for debugging.
self._cmd_log[self._cmd_log_idx] = (line, time.time())
self._cmd_log_idx += 1
if self._cmd_log_idx >= self._cmd_log_len:
self._cmd_log_idx = 0
def print_log(self):
self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log))
i, n = self._cmd_log_idx, self._cmd_log_len
while n:
try:
self._mesg(*self._cmd_log[i])
except:
pass
i += 1
if i >= self._cmd_log_len:
i = 0
n -= 1
class IMAP4_SSL(IMAP4):
"""IMAP4 client class over SSL connection
Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
host - host's name (default: localhost);
port - port number (default: standard IMAP4 SSL port).
keyfile - PEM formatted file that contains your private key (default: None);
certfile - PEM formatted certificate chain file (default: None);
for more documentation see the docstring of the parent class IMAP4.
"""
def __init__(self, host = '', port = IMAP4_SSL_PORT, keyfile = None, certfile = None):
self.keyfile = keyfile
self.certfile = certfile
IMAP4.__init__(self, host, port)
def open(self, host = '', port = IMAP4_SSL_PORT):
"""Setup connection to remote server on "host:port".
(default: localhost:standard IMAP4 SSL port).
This connection will be used by the routines:
read, readline, send, shutdown.
"""
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((host, port))
self.sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
def read(self, size):
"""Read 'size' bytes from remote."""
# sslobj.read() sometimes returns < size bytes
chunks = []
read = 0
while read < size:
data = self.sslobj.read(size-read)
read += len(data)
chunks.append(data)
return ''.join(chunks)
def readline(self):
"""Read line from remote."""
# NB: socket.ssl needs a "readline" method, or perhaps a "makefile" method.
line = []
while 1:
char = self.sslobj.read(1)
line.append(char)
if char == "\n": return ''.join(line)
def send(self, data):
"""Send data to remote."""
# NB: socket.ssl needs a "sendall" method to match socket objects.
bytes = len(data)
while bytes > 0:
sent = self.sslobj.write(data)
if sent == bytes:
break # avoid copy
data = data[sent:]
bytes = bytes - sent
def shutdown(self):
"""Close I/O established in "open"."""
self.sock.close()
def socket(self):
"""Return socket instance used to connect to IMAP4 server.
socket = <instance>.socket()
"""
return self.sock
def ssl(self):
"""Return SSLObject instance used to communicate with the IMAP4 server.
ssl = <instance>.socket.ssl()
"""
return self.sslobj
class IMAP4_stream(IMAP4):
"""IMAP4 client class over a stream
Instantiate with: IMAP4_stream(command)
where "command" is a string that can be passed to os.popen2()
for more documentation see the docstring of the parent class IMAP4.
"""
def __init__(self, command):
self.command = command
IMAP4.__init__(self)
def open(self, host = None, port = None):
"""Setup a stream connection.
This connection will be used by the routines:
read, readline, send, shutdown.
"""
self.host = None # For compatibility with parent class
self.port = None
self.sock = None
self.file = None
self.writefile, self.readfile = os.popen2(self.command)
def read(self, size):
"""Read 'size' bytes from remote."""
return self.readfile.read(size)
def readline(self):
"""Read line from remote."""
return self.readfile.readline()
def send(self, data):
"""Send data to remote."""
self.writefile.write(data)
self.writefile.flush()
def shutdown(self):
"""Close I/O established in "open"."""
self.readfile.close()
self.writefile.close()
class _Authenticator:
"""Private class to provide en/decoding
for base64-based authentication conversation.
"""
def __init__(self, mechinst):
self.mech = mechinst # Callable object to provide/process data
def process(self, data):
ret = self.mech(self.decode(data))
if ret is None:
return '*' # Abort conversation
return self.encode(ret)
def encode(self, inp):
#
# Invoke binascii.b2a_base64 iteratively with
# short even length buffers, strip the trailing
# line feed from the result and append. "Even"
# means a number that factors to both 6 and 8,
# so when it gets to the end of the 8-bit input
# there's no partial 6-bit output.
#
oup = ''
while inp:
if len(inp) > 48:
t = inp[:48]
inp = inp[48:]
else:
t = inp
inp = ''
e = binascii.b2a_base64(t)
if e:
oup = oup + e[:-1]
return oup
def decode(self, inp):
if not inp:
return ''
return binascii.a2b_base64(inp)
Mon2num = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
def Internaldate2tuple(resp):
"""Convert IMAP4 INTERNALDATE to UT.
Returns Python time module tuple.
"""
mo = InternalDate.match(resp)
if not mo:
return None
mon = Mon2num[mo.group('mon')]
zonen = mo.group('zonen')
day = int(mo.group('day'))
year = int(mo.group('year'))
hour = int(mo.group('hour'))
min = int(mo.group('min'))
sec = int(mo.group('sec'))
zoneh = int(mo.group('zoneh'))
zonem = int(mo.group('zonem'))
# INTERNALDATE timezone must be subtracted to get UT
zone = (zoneh*60 + zonem)*60
if zonen == '-':
zone = -zone
tt = (year, mon, day, hour, min, sec, -1, -1, -1)
utc = time.mktime(tt)
# Following is necessary because the time module has no 'mkgmtime'.
# 'mktime' assumes arg in local timezone, so adds timezone/altzone.
lt = time.localtime(utc)
if time.daylight and lt[-1]:
zone = zone + time.altzone
else:
zone = zone + time.timezone
return time.localtime(utc - zone)
def Int2AP(num):
"""Convert integer to A-P string representation."""
val = ''; AP = 'ABCDEFGHIJKLMNOP'
num = int(abs(num))
while num:
num, mod = divmod(num, 16)
val = AP[mod] + val
return val
def ParseFlags(resp):
"""Convert IMAP4 flags response to python tuple."""
mo = Flags.match(resp)
if not mo:
return ()
return tuple(mo.group('flags').split())
def Time2Internaldate(date_time):
"""Convert 'date_time' to IMAP4 INTERNALDATE representation.
Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
"""
if isinstance(date_time, (int, float)):
tt = time.localtime(date_time)
elif isinstance(date_time, (tuple, time.struct_time)):
tt = date_time
elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
return date_time # Assume in correct format
else:
raise ValueError("date_time not of a known type")
dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
if dt[0] == '0':
dt = ' ' + dt[1:]
if time.daylight and tt[-1]:
zone = -time.altzone
else:
zone = -time.timezone
return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"'
if __name__ == '__main__':
# To test: invoke either as 'python imaplib.py [IMAP4_server_hostname]'
# or 'python imaplib.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
# to test the IMAP4_stream class
import getopt, getpass
try:
optlist, args = getopt.getopt(sys.argv[1:], 'd:s:')
except getopt.error, val:
optlist, args = (), ()
stream_command = None
for opt,val in optlist:
if opt == '-d':
Debug = int(val)
elif opt == '-s':
stream_command = val
if not args: args = (stream_command,)
if not args: args = ('',)
host = args[0]
USER = getpass.getuser()
PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost"))
test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {'user':USER, 'lf':'\n'}
test_seq1 = (
('login', (USER, PASSWD)),
('create', ('/tmp/xxx 1',)),
('rename', ('/tmp/xxx 1', '/tmp/yyy')),
('CREATE', ('/tmp/yyz 2',)),
('append', ('/tmp/yyz 2', None, None, test_mesg)),
('list', ('/tmp', 'yy*')),
('select', ('/tmp/yyz 2',)),
('search', (None, 'SUBJECT', 'test')),
('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')),
('store', ('1', 'FLAGS', '(\Deleted)')),
('namespace', ()),
('expunge', ()),
('recent', ()),
('close', ()),
)
test_seq2 = (
('select', ()),
('response',('UIDVALIDITY',)),
('uid', ('SEARCH', 'ALL')),
('response', ('EXISTS',)),
('append', (None, None, None, test_mesg)),
('recent', ()),
('logout', ()),
)
def run(cmd, args):
M._mesg('%s %s' % (cmd, args))
typ, dat = getattr(M, cmd)(*args)
M._mesg('%s => %s %s' % (cmd, typ, dat))
if typ == 'NO': raise dat[0]
return dat
try:
if stream_command:
M = IMAP4_stream(stream_command)
else:
M = IMAP4(host)
if M.state == 'AUTH':
test_seq1 = test_seq1[1:] # Login not needed
M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
M._mesg('CAPABILITIES = %r' % (M.capabilities,))
for cmd,args in test_seq1:
run(cmd, args)
for ml in run('list', ('/tmp/', 'yy%')):
mo = re.match(r'.*"([^"]+)"$', ml)
if mo: path = mo.group(1)
else: path = ml.split()[-1]
run('delete', (path,))
for cmd,args in test_seq2:
dat = run(cmd, args)
if (cmd,args) != ('uid', ('SEARCH', 'ALL')):
continue
uid = dat[-1].split()
if not uid: continue
run('uid', ('FETCH', '%s' % uid[-1],
'(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
print '\nAll tests OK.'
except:
print '\nTests failed.'
if not Debug:
print '''
If you would like to see debugging output,
try: %s -d5
''' % sys.argv[0]
raise
| Python |
""" robotparser.py
Copyright (C) 2000 Bastian Kleineidam
You can choose between two licenses when using this package:
1) GNU GPLv2
2) PSF license for Python 2.2
The robots.txt Exclusion Protocol is implemented as specified in
http://info.webcrawler.com/mak/projects/robots/norobots-rfc.html
"""
import urlparse,urllib
__all__ = ["RobotFileParser"]
debug = 0
def _debug(msg):
if debug: print msg
class RobotFileParser:
""" This class provides a set of methods to read, parse and answer
questions about a single robots.txt file.
"""
def __init__(self, url=''):
self.entries = []
self.default_entry = None
self.disallow_all = False
self.allow_all = False
self.set_url(url)
self.last_checked = 0
def mtime(self):
"""Returns the time the robots.txt file was last fetched.
This is useful for long-running web spiders that need to
check for new robots.txt files periodically.
"""
return self.last_checked
def modified(self):
"""Sets the time the robots.txt file was last fetched to the
current time.
"""
import time
self.last_checked = time.time()
def set_url(self, url):
"""Sets the URL referring to a robots.txt file."""
self.url = url
self.host, self.path = urlparse.urlparse(url)[1:3]
def read(self):
"""Reads the robots.txt URL and feeds it to the parser."""
opener = URLopener()
f = opener.open(self.url)
lines = []
line = f.readline()
while line:
lines.append(line.strip())
line = f.readline()
self.errcode = opener.errcode
if self.errcode == 401 or self.errcode == 403:
self.disallow_all = True
_debug("disallow all")
elif self.errcode >= 400:
self.allow_all = True
_debug("allow all")
elif self.errcode == 200 and lines:
_debug("parse lines")
self.parse(lines)
def _add_entry(self, entry):
if "*" in entry.useragents:
# the default entry is considered last
self.default_entry = entry
else:
self.entries.append(entry)
def parse(self, lines):
"""parse the input lines from a robots.txt file.
We allow that a user-agent: line is not preceded by
one or more blank lines."""
state = 0
linenumber = 0
entry = Entry()
for line in lines:
linenumber = linenumber + 1
if not line:
if state==1:
_debug("line %d: warning: you should insert"
" allow: or disallow: directives below any"
" user-agent: line" % linenumber)
entry = Entry()
state = 0
elif state==2:
self._add_entry(entry)
entry = Entry()
state = 0
# remove optional comment and strip line
i = line.find('#')
if i>=0:
line = line[:i]
line = line.strip()
if not line:
continue
line = line.split(':', 1)
if len(line) == 2:
line[0] = line[0].strip().lower()
line[1] = urllib.unquote(line[1].strip())
if line[0] == "user-agent":
if state==2:
_debug("line %d: warning: you should insert a blank"
" line before any user-agent"
" directive" % linenumber)
self._add_entry(entry)
entry = Entry()
entry.useragents.append(line[1])
state = 1
elif line[0] == "disallow":
if state==0:
_debug("line %d: error: you must insert a user-agent:"
" directive before this line" % linenumber)
else:
entry.rulelines.append(RuleLine(line[1], False))
state = 2
elif line[0] == "allow":
if state==0:
_debug("line %d: error: you must insert a user-agent:"
" directive before this line" % linenumber)
else:
entry.rulelines.append(RuleLine(line[1], True))
else:
_debug("line %d: warning: unknown key %s" % (linenumber,
line[0]))
else:
_debug("line %d: error: malformed line %s"%(linenumber, line))
if state==2:
self.entries.append(entry)
_debug("Parsed rules:\n%s" % str(self))
def can_fetch(self, useragent, url):
"""using the parsed robots.txt decide if useragent can fetch url"""
_debug("Checking robots.txt allowance for:\n user agent: %s\n url: %s" %
(useragent, url))
if self.disallow_all:
return False
if self.allow_all:
return True
# search for given user agent matches
# the first match counts
url = urllib.quote(urlparse.urlparse(urllib.unquote(url))[2]) or "/"
for entry in self.entries:
if entry.applies_to(useragent):
return entry.allowance(url)
# try the default entry last
if self.default_entry:
return self.default_entry.allowance(url)
# agent not found ==> access granted
return True
def __str__(self):
ret = ""
for entry in self.entries:
ret = ret + str(entry) + "\n"
return ret
class RuleLine:
"""A rule line is a single "Allow:" (allowance==True) or "Disallow:"
(allowance==False) followed by a path."""
def __init__(self, path, allowance):
if path == '' and not allowance:
# an empty value means allow all
allowance = True
self.path = urllib.quote(path)
self.allowance = allowance
def applies_to(self, filename):
return self.path=="*" or filename.startswith(self.path)
def __str__(self):
return (self.allowance and "Allow" or "Disallow")+": "+self.path
class Entry:
"""An entry has one or more user-agents and zero or more rulelines"""
def __init__(self):
self.useragents = []
self.rulelines = []
def __str__(self):
ret = ""
for agent in self.useragents:
ret = ret + "User-agent: "+agent+"\n"
for line in self.rulelines:
ret = ret + str(line) + "\n"
return ret
def applies_to(self, useragent):
"""check if this entry applies to the specified agent"""
# split the name token and make it lower case
useragent = useragent.split("/")[0].lower()
for agent in self.useragents:
if agent=='*':
# we have the catch-all agent
return True
agent = agent.lower()
if agent in useragent:
return True
return False
def allowance(self, filename):
"""Preconditions:
- our agent applies to this entry
- filename is URL decoded"""
for line in self.rulelines:
_debug((filename, str(line), line.allowance))
if line.applies_to(filename):
return line.allowance
return True
class URLopener(urllib.FancyURLopener):
def __init__(self, *args):
urllib.FancyURLopener.__init__(self, *args)
self.errcode = 200
def http_error_default(self, url, fp, errcode, errmsg, headers):
self.errcode = errcode
return urllib.FancyURLopener.http_error_default(self, url, fp, errcode,
errmsg, headers)
def _check(a,b):
if not b:
ac = "access denied"
else:
ac = "access allowed"
if a!=b:
print "failed"
else:
print "ok (%s)" % ac
print
def _test():
global debug
rp = RobotFileParser()
debug = 1
# robots.txt that exists, gotten to by redirection
rp.set_url('http://www.musi-cal.com/robots.txt')
rp.read()
# test for re.escape
_check(rp.can_fetch('*', 'http://www.musi-cal.com/'), 1)
# this should match the first rule, which is a disallow
_check(rp.can_fetch('', 'http://www.musi-cal.com/'), 0)
# various cherry pickers
_check(rp.can_fetch('CherryPickerSE',
'http://www.musi-cal.com/cgi-bin/event-search'
'?city=San+Francisco'), 0)
_check(rp.can_fetch('CherryPickerSE/1.0',
'http://www.musi-cal.com/cgi-bin/event-search'
'?city=San+Francisco'), 0)
_check(rp.can_fetch('CherryPickerSE/1.5',
'http://www.musi-cal.com/cgi-bin/event-search'
'?city=San+Francisco'), 0)
# case sensitivity
_check(rp.can_fetch('ExtractorPro', 'http://www.musi-cal.com/blubba'), 0)
_check(rp.can_fetch('extractorpro', 'http://www.musi-cal.com/blubba'), 0)
# substring test
_check(rp.can_fetch('toolpak/1.1', 'http://www.musi-cal.com/blubba'), 0)
# tests for catch-all * agent
_check(rp.can_fetch('spam', 'http://www.musi-cal.com/search'), 0)
_check(rp.can_fetch('spam', 'http://www.musi-cal.com/Musician/me'), 1)
_check(rp.can_fetch('spam', 'http://www.musi-cal.com/'), 1)
_check(rp.can_fetch('spam', 'http://www.musi-cal.com/'), 1)
# robots.txt that does not exist
rp.set_url('http://www.lycos.com/robots.txt')
rp.read()
_check(rp.can_fetch('Mozilla', 'http://www.lycos.com/search'), 1)
if __name__ == '__main__':
_test()
| Python |
# Author: Fred L. Drake, Jr.
# fdrake@acm.org
#
# This is a simple little module I wrote to make life easier. I didn't
# see anything quite like it in the library, though I may have overlooked
# something. I wrote this when I was trying to read some heavily nested
# tuples with fairly non-descriptive content. This is modeled very much
# after Lisp/Scheme - style pretty-printing of lists. If you find it
# useful, thank small children who sleep at night.
"""Support to pretty-print lists, tuples, & dictionaries recursively.
Very simple, but useful, especially in debugging data structures.
Classes
-------
PrettyPrinter()
Handle pretty-printing operations onto a stream using a configured
set of formatting parameters.
Functions
---------
pformat()
Format a Python object into a pretty-printed representation.
pprint()
Pretty-print a Python object to a stream [default is sys.stdout].
saferepr()
Generate a 'standard' repr()-like value, but protect against recursive
data structures.
"""
import sys as _sys
from cStringIO import StringIO as _StringIO
__all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
"PrettyPrinter"]
# cache these for faster access:
_commajoin = ", ".join
_id = id
_len = len
_type = type
def pprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
def pformat(object, indent=1, width=80, depth=None):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
def saferepr(object):
"""Version of repr() which can handle recursive data structures."""
return _safe_repr(object, {}, None, 0)[0]
def isreadable(object):
"""Determine if saferepr(object) is readable by eval()."""
return _safe_repr(object, {}, None, 0)[1]
def isrecursive(object):
"""Determine if object requires a recursive representation."""
return _safe_repr(object, {}, None, 0)[2]
class PrettyPrinter:
def __init__(self, indent=1, width=80, depth=None, stream=None):
"""Handle pretty printing operations onto a stream using a set of
configured parameters.
indent
Number of spaces to indent for each level of nesting.
width
Attempted maximum number of columns in the output.
depth
The maximum depth to print out nested structures.
stream
The desired output stream. If omitted (or false), the standard
output stream available at construction will be used.
"""
indent = int(indent)
width = int(width)
assert indent >= 0, "indent must be >= 0"
assert depth is None or depth > 0, "depth must be > 0"
assert width, "width must be != 0"
self._depth = depth
self._indent_per_level = indent
self._width = width
if stream is not None:
self._stream = stream
else:
self._stream = _sys.stdout
def pprint(self, object):
self._stream.write(self.pformat(object) + "\n")
def pformat(self, object):
sio = _StringIO()
self._format(object, sio, 0, 0, {}, 0)
return sio.getvalue()
def isrecursive(self, object):
return self.format(object, {}, 0, 0)[2]
def isreadable(self, object):
s, readable, recursive = self.format(object, {}, 0, 0)
return readable and not recursive
def _format(self, object, stream, indent, allowance, context, level):
level = level + 1
objid = _id(object)
if objid in context:
stream.write(_recursion(object))
self._recursive = True
self._readable = False
return
rep = self._repr(object, context, level - 1)
typ = _type(object)
sepLines = _len(rep) > (self._width - 1 - indent - allowance)
write = stream.write
if sepLines:
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__:
write('{')
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
length = _len(object)
if length:
context[objid] = 1
indent = indent + self._indent_per_level
items = object.items()
items.sort()
key, ent = items[0]
rep = self._repr(key, context, level)
write(rep)
write(': ')
self._format(ent, stream, indent + _len(rep) + 2,
allowance + 1, context, level)
if length > 1:
for key, ent in items[1:]:
rep = self._repr(key, context, level)
write(',\n%s%s: ' % (' '*indent, rep))
self._format(ent, stream, indent + _len(rep) + 2,
allowance + 1, context, level)
indent = indent - self._indent_per_level
del context[objid]
write('}')
return
if (issubclass(typ, list) and r is list.__repr__) or \
(issubclass(typ, tuple) and r is tuple.__repr__):
if issubclass(typ, list):
write('[')
endchar = ']'
else:
write('(')
endchar = ')'
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
length = _len(object)
if length:
context[objid] = 1
indent = indent + self._indent_per_level
self._format(object[0], stream, indent, allowance + 1,
context, level)
if length > 1:
for ent in object[1:]:
write(',\n' + ' '*indent)
self._format(ent, stream, indent,
allowance + 1, context, level)
indent = indent - self._indent_per_level
del context[objid]
if issubclass(typ, tuple) and length == 1:
write(',')
write(endchar)
return
write(rep)
def _repr(self, object, context, level):
repr, readable, recursive = self.format(object, context.copy(),
self._depth, level)
if not readable:
self._readable = False
if recursive:
self._recursive = True
return repr
def format(self, object, context, maxlevels, level):
"""Format object for a specific context, returning a string
and flags indicating whether the representation is 'readable'
and whether the object represents a recursive construct.
"""
return _safe_repr(object, context, maxlevels, level)
# Return triple (repr_string, isreadable, isrecursive).
def _safe_repr(object, context, maxlevels, level):
typ = _type(object)
if typ is str:
if 'locale' not in _sys.modules:
return repr(object), True, False
if "'" in object and '"' not in object:
closure = '"'
quotes = {'"': '\\"'}
else:
closure = "'"
quotes = {"'": "\\'"}
qget = quotes.get
sio = _StringIO()
write = sio.write
for char in object:
if char.isalpha():
write(char)
else:
write(qget(char, repr(char)[1:-1]))
return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__:
if not object:
return "{}", True, False
objid = _id(object)
if maxlevels and level > maxlevels:
return "{...}", False, objid in context
if objid in context:
return _recursion(object), False, True
context[objid] = 1
readable = True
recursive = False
components = []
append = components.append
level += 1
saferepr = _safe_repr
for k, v in object.iteritems():
krepr, kreadable, krecur = saferepr(k, context, maxlevels, level)
vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level)
append("%s: %s" % (krepr, vrepr))
readable = readable and kreadable and vreadable
if krecur or vrecur:
recursive = True
del context[objid]
return "{%s}" % _commajoin(components), readable, recursive
if (issubclass(typ, list) and r is list.__repr__) or \
(issubclass(typ, tuple) and r is tuple.__repr__):
if issubclass(typ, list):
if not object:
return "[]", True, False
format = "[%s]"
elif _len(object) == 1:
format = "(%s,)"
else:
if not object:
return "()", True, False
format = "(%s)"
objid = _id(object)
if maxlevels and level > maxlevels:
return format % "...", False, objid in context
if objid in context:
return _recursion(object), False, True
context[objid] = 1
readable = True
recursive = False
components = []
append = components.append
level += 1
for o in object:
orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level)
append(orepr)
if not oreadable:
readable = False
if orecur:
recursive = True
del context[objid]
return format % _commajoin(components), readable, recursive
rep = repr(object)
return rep, (rep and not rep.startswith('<')), False
def _recursion(object):
return ("<Recursion on %s with id=%s>"
% (_type(object).__name__, _id(object)))
def _perfcheck(object=None):
import time
if object is None:
object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
p = PrettyPrinter()
t1 = time.time()
_safe_repr(object, {}, None, 0)
t2 = time.time()
p.pformat(object)
t3 = time.time()
print "_safe_repr:", t2 - t1
print "pformat:", t3 - t2
if __name__ == "__main__":
_perfcheck()
| Python |
#
# Secret Labs' Regular Expression Engine
#
# re-compatible interface for the sre matching engine
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# This version of the SRE library can be redistributed under CNRI's
# Python 1.6 license. For any other use, please contact Secret Labs
# AB (info@pythonware.com).
#
# Portions of this engine have been developed in cooperation with
# CNRI. Hewlett-Packard provided funding for 1.6 integration and
# other compatibility work.
#
r"""Support for regular expressions (RE).
This module provides regular expression matching operations similar to
those found in Perl. It supports both 8-bit and Unicode strings; both
the pattern and the strings being processed can contain null bytes and
characters outside the US ASCII range.
Regular expressions can contain both special and ordinary characters.
Most ordinary characters, like "A", "a", or "0", are the simplest
regular expressions; they simply match themselves. You can
concatenate ordinary characters, so last matches the string 'last'.
The special characters are:
"." Matches any character except a newline.
"^" Matches the start of the string.
"$" Matches the end of the string.
"*" Matches 0 or more (greedy) repetitions of the preceding RE.
Greedy means that it will match as many repetitions as possible.
"+" Matches 1 or more (greedy) repetitions of the preceding RE.
"?" Matches 0 or 1 (greedy) of the preceding RE.
*?,+?,?? Non-greedy versions of the previous three special characters.
{m,n} Matches from m to n repetitions of the preceding RE.
{m,n}? Non-greedy version of the above.
"\\" Either escapes special characters or signals a special sequence.
[] Indicates a set of characters.
A "^" as the first character indicates a complementing set.
"|" A|B, creates an RE that will match either A or B.
(...) Matches the RE inside the parentheses.
The contents can be retrieved or matched later in the string.
(?iLmsux) Set the I, L, M, S, U, or X flag for the RE (see below).
(?:...) Non-grouping version of regular parentheses.
(?P<name>...) The substring matched by the group is accessible by name.
(?P=name) Matches the text matched earlier by the group named name.
(?#...) A comment; ignored.
(?=...) Matches if ... matches next, but doesn't consume the string.
(?!...) Matches if ... doesn't match next.
The special sequences consist of "\\" and a character from the list
below. If the ordinary character is not on the list, then the
resulting RE will match the second character.
\number Matches the contents of the group of the same number.
\A Matches only at the start of the string.
\Z Matches only at the end of the string.
\b Matches the empty string, but only at the start or end of a word.
\B Matches the empty string, but not at the start or end of a word.
\d Matches any decimal digit; equivalent to the set [0-9].
\D Matches any non-digit character; equivalent to the set [^0-9].
\s Matches any whitespace character; equivalent to [ \t\n\r\f\v].
\S Matches any non-whitespace character; equiv. to [^ \t\n\r\f\v].
\w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].
With LOCALE, it will match the set [0-9_] plus characters defined
as letters for the current locale.
\W Matches the complement of \w.
\\ Matches a literal backslash.
This module exports the following functions:
match Match a regular expression pattern to the beginning of a string.
search Search a string for the presence of a pattern.
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
compile Compile a pattern into a RegexObject.
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
Some of the functions in this module takes flags as optional parameters:
I IGNORECASE Perform case-insensitive matching.
L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
M MULTILINE "^" matches the beginning of lines as well as the string.
"$" matches the end of lines as well as the string.
S DOTALL "." matches any character at all, including the newline.
X VERBOSE Ignore whitespace and comments for nicer looking RE's.
U UNICODE Make \w, \W, \b, \B, dependent on the Unicode locale.
This module also defines an exception 'error'.
"""
import sys
import sre_compile
import sre_parse
# public symbols
__all__ = [ "match", "search", "sub", "subn", "split", "findall",
"compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
"U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
"UNICODE", "error" ]
__version__ = "2.2.1"
# flags
I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
# sre extensions (experimental, don't rely on these)
T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
# sre exception
error = sre_compile.error
# --------------------------------------------------------------------
# public interface
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).match(string)
def search(pattern, string, flags=0):
"""Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).search(string)
def sub(pattern, repl, string, count=0):
"""Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used."""
return _compile(pattern, 0).sub(repl, string, count)
def subn(pattern, repl, string, count=0):
"""Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a callable, it's passed the match object and must
return a replacement string to be used."""
return _compile(pattern, 0).subn(repl, string, count)
def split(pattern, string, maxsplit=0):
"""Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings."""
return _compile(pattern, 0).split(string, maxsplit)
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
return _compile(pattern, flags).findall(string)
if sys.hexversion >= 0x02020000:
__all__.append("finditer")
def finditer(pattern, string, flags=0):
"""Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a match object.
Empty matches are included in the result."""
return _compile(pattern, flags).finditer(string)
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
return _compile(pattern, flags)
def purge():
"Clear the regular expression cache"
_cache.clear()
_cache_repl.clear()
def template(pattern, flags=0):
"Compile a template pattern, returning a pattern object"
return _compile(pattern, flags|T)
def escape(pattern):
"Escape all non-alphanumeric characters in pattern."
s = list(pattern)
for i in range(len(pattern)):
c = pattern[i]
if not ("a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9"):
if c == "\000":
s[i] = "\\000"
else:
s[i] = "\\" + c
return pattern[:0].join(s)
# --------------------------------------------------------------------
# internals
_cache = {}
_cache_repl = {}
_pattern_type = type(sre_compile.compile("", 0))
_MAXCACHE = 100
def _compile(*key):
# internal: compile pattern
cachekey = (type(key[0]),) + key
p = _cache.get(cachekey)
if p is not None:
return p
pattern, flags = key
if isinstance(pattern, _pattern_type):
return pattern
if not sre_compile.isstring(pattern):
raise TypeError, "first argument must be string or compiled pattern"
try:
p = sre_compile.compile(pattern, flags)
except error, v:
raise error, v # invalid expression
if len(_cache) >= _MAXCACHE:
_cache.clear()
_cache[cachekey] = p
return p
def _compile_repl(*key):
# internal: compile replacement pattern
p = _cache_repl.get(key)
if p is not None:
return p
repl, pattern = key
try:
p = sre_parse.parse_template(repl, pattern)
except error, v:
raise error, v # invalid expression
if len(_cache_repl) >= _MAXCACHE:
_cache_repl.clear()
_cache_repl[key] = p
return p
def _expand(pattern, match, template):
# internal: match.expand implementation hook
template = sre_parse.parse_template(template, pattern)
return sre_parse.expand_template(template, match)
def _subx(pattern, template):
# internal: pattern.sub/subn implementation helper
template = _compile_repl(template, pattern)
if not template[0] and len(template[1]) == 1:
# literal replacement
return template[1][0]
def filter(match, template=template):
return sre_parse.expand_template(template, match)
return filter
# register myself for pickling
import copy_reg
def _pickle(p):
return _compile, (p.pattern, p.flags)
copy_reg.pickle(_pattern_type, _pickle, _compile)
# --------------------------------------------------------------------
# experimental stuff (see python-dev discussions for details)
class Scanner:
def __init__(self, lexicon, flags=0):
from sre_constants import BRANCH, SUBPATTERN
self.lexicon = lexicon
# combine phrases into a compound pattern
p = []
s = sre_parse.Pattern()
s.flags = flags
for phrase, action in lexicon:
p.append(sre_parse.SubPattern(s, [
(SUBPATTERN, (len(p)+1, sre_parse.parse(phrase, flags))),
]))
p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
s.groups = len(p)
self.scanner = sre_compile.compile(p)
def scan(self, string):
result = []
append = result.append
match = self.scanner.scanner(string).match
i = 0
while 1:
m = match()
if not m:
break
j = m.end()
if i == j:
break
action = self.lexicon[m.lastindex-1][1]
if callable(action):
self.match = m
action = action(self, m.group())
if action is not None:
append(action)
i = j
return result, string[i:]
| Python |
"""MH interface -- purely object-oriented (well, almost)
Executive summary:
import mhlib
mh = mhlib.MH() # use default mailbox directory and profile
mh = mhlib.MH(mailbox) # override mailbox location (default from profile)
mh = mhlib.MH(mailbox, profile) # override mailbox and profile
mh.error(format, ...) # print error message -- can be overridden
s = mh.getprofile(key) # profile entry (None if not set)
path = mh.getpath() # mailbox pathname
name = mh.getcontext() # name of current folder
mh.setcontext(name) # set name of current folder
list = mh.listfolders() # names of top-level folders
list = mh.listallfolders() # names of all folders, including subfolders
list = mh.listsubfolders(name) # direct subfolders of given folder
list = mh.listallsubfolders(name) # all subfolders of given folder
mh.makefolder(name) # create new folder
mh.deletefolder(name) # delete folder -- must have no subfolders
f = mh.openfolder(name) # new open folder object
f.error(format, ...) # same as mh.error(format, ...)
path = f.getfullname() # folder's full pathname
path = f.getsequencesfilename() # full pathname of folder's sequences file
path = f.getmessagefilename(n) # full pathname of message n in folder
list = f.listmessages() # list of messages in folder (as numbers)
n = f.getcurrent() # get current message
f.setcurrent(n) # set current message
list = f.parsesequence(seq) # parse msgs syntax into list of messages
n = f.getlast() # get last message (0 if no messagse)
f.setlast(n) # set last message (internal use only)
dict = f.getsequences() # dictionary of sequences in folder {name: list}
f.putsequences(dict) # write sequences back to folder
f.createmessage(n, fp) # add message from file f as number n
f.removemessages(list) # remove messages in list from folder
f.refilemessages(list, tofolder) # move messages in list to other folder
f.movemessage(n, tofolder, ton) # move one message to a given destination
f.copymessage(n, tofolder, ton) # copy one message to a given destination
m = f.openmessage(n) # new open message object (costs a file descriptor)
m is a derived class of mimetools.Message(rfc822.Message), with:
s = m.getheadertext() # text of message's headers
s = m.getheadertext(pred) # text of message's headers, filtered by pred
s = m.getbodytext() # text of message's body, decoded
s = m.getbodytext(0) # text of message's body, not decoded
"""
# XXX To do, functionality:
# - annotate messages
# - send messages
#
# XXX To do, organization:
# - move IntSet to separate file
# - move most Message functionality to module mimetools
# Customizable defaults
MH_PROFILE = '~/.mh_profile'
PATH = '~/Mail'
MH_SEQUENCES = '.mh_sequences'
FOLDER_PROTECT = 0700
# Imported modules
import os
import sys
import re
import mimetools
import multifile
import shutil
from bisect import bisect
__all__ = ["MH","Error","Folder","Message"]
# Exported constants
class Error(Exception):
pass
class MH:
"""Class representing a particular collection of folders.
Optional constructor arguments are the pathname for the directory
containing the collection, and the MH profile to use.
If either is omitted or empty a default is used; the default
directory is taken from the MH profile if it is specified there."""
def __init__(self, path = None, profile = None):
"""Constructor."""
if profile is None: profile = MH_PROFILE
self.profile = os.path.expanduser(profile)
if path is None: path = self.getprofile('Path')
if not path: path = PATH
if not os.path.isabs(path) and path[0] != '~':
path = os.path.join('~', path)
path = os.path.expanduser(path)
if not os.path.isdir(path): raise Error, 'MH() path not found'
self.path = path
def __repr__(self):
"""String representation."""
return 'MH(%r, %r)' % (self.path, self.profile)
def error(self, msg, *args):
"""Routine to print an error. May be overridden by a derived class."""
sys.stderr.write('MH error: %s\n' % (msg % args))
def getprofile(self, key):
"""Return a profile entry, None if not found."""
return pickline(self.profile, key)
def getpath(self):
"""Return the path (the name of the collection's directory)."""
return self.path
def getcontext(self):
"""Return the name of the current folder."""
context = pickline(os.path.join(self.getpath(), 'context'),
'Current-Folder')
if not context: context = 'inbox'
return context
def setcontext(self, context):
"""Set the name of the current folder."""
fn = os.path.join(self.getpath(), 'context')
f = open(fn, "w")
f.write("Current-Folder: %s\n" % context)
f.close()
def listfolders(self):
"""Return the names of the top-level folders."""
folders = []
path = self.getpath()
for name in os.listdir(path):
fullname = os.path.join(path, name)
if os.path.isdir(fullname):
folders.append(name)
folders.sort()
return folders
def listsubfolders(self, name):
"""Return the names of the subfolders in a given folder
(prefixed with the given folder name)."""
fullname = os.path.join(self.path, name)
# Get the link count so we can avoid listing folders
# that have no subfolders.
nlinks = os.stat(fullname).st_nlink
if nlinks <= 2:
return []
subfolders = []
subnames = os.listdir(fullname)
for subname in subnames:
fullsubname = os.path.join(fullname, subname)
if os.path.isdir(fullsubname):
name_subname = os.path.join(name, subname)
subfolders.append(name_subname)
# Stop looking for subfolders when
# we've seen them all
nlinks = nlinks - 1
if nlinks <= 2:
break
subfolders.sort()
return subfolders
def listallfolders(self):
"""Return the names of all folders and subfolders, recursively."""
return self.listallsubfolders('')
def listallsubfolders(self, name):
"""Return the names of subfolders in a given folder, recursively."""
fullname = os.path.join(self.path, name)
# Get the link count so we can avoid listing folders
# that have no subfolders.
nlinks = os.stat(fullname).st_nlink
if nlinks <= 2:
return []
subfolders = []
subnames = os.listdir(fullname)
for subname in subnames:
if subname[0] == ',' or isnumeric(subname): continue
fullsubname = os.path.join(fullname, subname)
if os.path.isdir(fullsubname):
name_subname = os.path.join(name, subname)
subfolders.append(name_subname)
if not os.path.islink(fullsubname):
subsubfolders = self.listallsubfolders(
name_subname)
subfolders = subfolders + subsubfolders
# Stop looking for subfolders when
# we've seen them all
nlinks = nlinks - 1
if nlinks <= 2:
break
subfolders.sort()
return subfolders
def openfolder(self, name):
"""Return a new Folder object for the named folder."""
return Folder(self, name)
def makefolder(self, name):
"""Create a new folder (or raise os.error if it cannot be created)."""
protect = pickline(self.profile, 'Folder-Protect')
if protect and isnumeric(protect):
mode = int(protect, 8)
else:
mode = FOLDER_PROTECT
os.mkdir(os.path.join(self.getpath(), name), mode)
def deletefolder(self, name):
"""Delete a folder. This removes files in the folder but not
subdirectories. Raise os.error if deleting the folder itself fails."""
fullname = os.path.join(self.getpath(), name)
for subname in os.listdir(fullname):
fullsubname = os.path.join(fullname, subname)
try:
os.unlink(fullsubname)
except os.error:
self.error('%s not deleted, continuing...' %
fullsubname)
os.rmdir(fullname)
numericprog = re.compile('^[1-9][0-9]*$')
def isnumeric(str):
return numericprog.match(str) is not None
class Folder:
"""Class representing a particular folder."""
def __init__(self, mh, name):
"""Constructor."""
self.mh = mh
self.name = name
if not os.path.isdir(self.getfullname()):
raise Error, 'no folder %s' % name
def __repr__(self):
"""String representation."""
return 'Folder(%r, %r)' % (self.mh, self.name)
def error(self, *args):
"""Error message handler."""
self.mh.error(*args)
def getfullname(self):
"""Return the full pathname of the folder."""
return os.path.join(self.mh.path, self.name)
def getsequencesfilename(self):
"""Return the full pathname of the folder's sequences file."""
return os.path.join(self.getfullname(), MH_SEQUENCES)
def getmessagefilename(self, n):
"""Return the full pathname of a message in the folder."""
return os.path.join(self.getfullname(), str(n))
def listsubfolders(self):
"""Return list of direct subfolders."""
return self.mh.listsubfolders(self.name)
def listallsubfolders(self):
"""Return list of all subfolders."""
return self.mh.listallsubfolders(self.name)
def listmessages(self):
"""Return the list of messages currently present in the folder.
As a side effect, set self.last to the last message (or 0)."""
messages = []
match = numericprog.match
append = messages.append
for name in os.listdir(self.getfullname()):
if match(name):
append(name)
messages = map(int, messages)
messages.sort()
if messages:
self.last = messages[-1]
else:
self.last = 0
return messages
def getsequences(self):
"""Return the set of sequences for the folder."""
sequences = {}
fullname = self.getsequencesfilename()
try:
f = open(fullname, 'r')
except IOError:
return sequences
while 1:
line = f.readline()
if not line: break
fields = line.split(':')
if len(fields) != 2:
self.error('bad sequence in %s: %s' %
(fullname, line.strip()))
key = fields[0].strip()
value = IntSet(fields[1].strip(), ' ').tolist()
sequences[key] = value
return sequences
def putsequences(self, sequences):
"""Write the set of sequences back to the folder."""
fullname = self.getsequencesfilename()
f = None
for key, seq in sequences.iteritems():
s = IntSet('', ' ')
s.fromlist(seq)
if not f: f = open(fullname, 'w')
f.write('%s: %s\n' % (key, s.tostring()))
if not f:
try:
os.unlink(fullname)
except os.error:
pass
else:
f.close()
def getcurrent(self):
"""Return the current message. Raise Error when there is none."""
seqs = self.getsequences()
try:
return max(seqs['cur'])
except (ValueError, KeyError):
raise Error, "no cur message"
def setcurrent(self, n):
"""Set the current message."""
updateline(self.getsequencesfilename(), 'cur', str(n), 0)
def parsesequence(self, seq):
"""Parse an MH sequence specification into a message list.
Attempt to mimic mh-sequence(5) as close as possible.
Also attempt to mimic observed behavior regarding which
conditions cause which error messages."""
# XXX Still not complete (see mh-format(5)).
# Missing are:
# - 'prev', 'next' as count
# - Sequence-Negation option
all = self.listmessages()
# Observed behavior: test for empty folder is done first
if not all:
raise Error, "no messages in %s" % self.name
# Common case first: all is frequently the default
if seq == 'all':
return all
# Test for X:Y before X-Y because 'seq:-n' matches both
i = seq.find(':')
if i >= 0:
head, dir, tail = seq[:i], '', seq[i+1:]
if tail[:1] in '-+':
dir, tail = tail[:1], tail[1:]
if not isnumeric(tail):
raise Error, "bad message list %s" % seq
try:
count = int(tail)
except (ValueError, OverflowError):
# Can't use sys.maxint because of i+count below
count = len(all)
try:
anchor = self._parseindex(head, all)
except Error, msg:
seqs = self.getsequences()
if not head in seqs:
if not msg:
msg = "bad message list %s" % seq
raise Error, msg, sys.exc_info()[2]
msgs = seqs[head]
if not msgs:
raise Error, "sequence %s empty" % head
if dir == '-':
return msgs[-count:]
else:
return msgs[:count]
else:
if not dir:
if head in ('prev', 'last'):
dir = '-'
if dir == '-':
i = bisect(all, anchor)
return all[max(0, i-count):i]
else:
i = bisect(all, anchor-1)
return all[i:i+count]
# Test for X-Y next
i = seq.find('-')
if i >= 0:
begin = self._parseindex(seq[:i], all)
end = self._parseindex(seq[i+1:], all)
i = bisect(all, begin-1)
j = bisect(all, end)
r = all[i:j]
if not r:
raise Error, "bad message list %s" % seq
return r
# Neither X:Y nor X-Y; must be a number or a (pseudo-)sequence
try:
n = self._parseindex(seq, all)
except Error, msg:
seqs = self.getsequences()
if not seq in seqs:
if not msg:
msg = "bad message list %s" % seq
raise Error, msg
return seqs[seq]
else:
if n not in all:
if isnumeric(seq):
raise Error, "message %d doesn't exist" % n
else:
raise Error, "no %s message" % seq
else:
return [n]
def _parseindex(self, seq, all):
"""Internal: parse a message number (or cur, first, etc.)."""
if isnumeric(seq):
try:
return int(seq)
except (OverflowError, ValueError):
return sys.maxint
if seq in ('cur', '.'):
return self.getcurrent()
if seq == 'first':
return all[0]
if seq == 'last':
return all[-1]
if seq == 'next':
n = self.getcurrent()
i = bisect(all, n)
try:
return all[i]
except IndexError:
raise Error, "no next message"
if seq == 'prev':
n = self.getcurrent()
i = bisect(all, n-1)
if i == 0:
raise Error, "no prev message"
try:
return all[i-1]
except IndexError:
raise Error, "no prev message"
raise Error, None
def openmessage(self, n):
"""Open a message -- returns a Message object."""
return Message(self, n)
def removemessages(self, list):
"""Remove one or more messages -- may raise os.error."""
errors = []
deleted = []
for n in list:
path = self.getmessagefilename(n)
commapath = self.getmessagefilename(',' + str(n))
try:
os.unlink(commapath)
except os.error:
pass
try:
os.rename(path, commapath)
except os.error, msg:
errors.append(msg)
else:
deleted.append(n)
if deleted:
self.removefromallsequences(deleted)
if errors:
if len(errors) == 1:
raise os.error, errors[0]
else:
raise os.error, ('multiple errors:', errors)
def refilemessages(self, list, tofolder, keepsequences=0):
"""Refile one or more messages -- may raise os.error.
'tofolder' is an open folder object."""
errors = []
refiled = {}
for n in list:
ton = tofolder.getlast() + 1
path = self.getmessagefilename(n)
topath = tofolder.getmessagefilename(ton)
try:
os.rename(path, topath)
except os.error:
# Try copying
try:
shutil.copy2(path, topath)
os.unlink(path)
except (IOError, os.error), msg:
errors.append(msg)
try:
os.unlink(topath)
except os.error:
pass
continue
tofolder.setlast(ton)
refiled[n] = ton
if refiled:
if keepsequences:
tofolder._copysequences(self, refiled.items())
self.removefromallsequences(refiled.keys())
if errors:
if len(errors) == 1:
raise os.error, errors[0]
else:
raise os.error, ('multiple errors:', errors)
def _copysequences(self, fromfolder, refileditems):
"""Helper for refilemessages() to copy sequences."""
fromsequences = fromfolder.getsequences()
tosequences = self.getsequences()
changed = 0
for name, seq in fromsequences.items():
try:
toseq = tosequences[name]
new = 0
except KeyError:
toseq = []
new = 1
for fromn, ton in refileditems:
if fromn in seq:
toseq.append(ton)
changed = 1
if new and toseq:
tosequences[name] = toseq
if changed:
self.putsequences(tosequences)
def movemessage(self, n, tofolder, ton):
"""Move one message over a specific destination message,
which may or may not already exist."""
path = self.getmessagefilename(n)
# Open it to check that it exists
f = open(path)
f.close()
del f
topath = tofolder.getmessagefilename(ton)
backuptopath = tofolder.getmessagefilename(',%d' % ton)
try:
os.rename(topath, backuptopath)
except os.error:
pass
try:
os.rename(path, topath)
except os.error:
# Try copying
ok = 0
try:
tofolder.setlast(None)
shutil.copy2(path, topath)
ok = 1
finally:
if not ok:
try:
os.unlink(topath)
except os.error:
pass
os.unlink(path)
self.removefromallsequences([n])
def copymessage(self, n, tofolder, ton):
"""Copy one message over a specific destination message,
which may or may not already exist."""
path = self.getmessagefilename(n)
# Open it to check that it exists
f = open(path)
f.close()
del f
topath = tofolder.getmessagefilename(ton)
backuptopath = tofolder.getmessagefilename(',%d' % ton)
try:
os.rename(topath, backuptopath)
except os.error:
pass
ok = 0
try:
tofolder.setlast(None)
shutil.copy2(path, topath)
ok = 1
finally:
if not ok:
try:
os.unlink(topath)
except os.error:
pass
def createmessage(self, n, txt):
"""Create a message, with text from the open file txt."""
path = self.getmessagefilename(n)
backuppath = self.getmessagefilename(',%d' % n)
try:
os.rename(path, backuppath)
except os.error:
pass
ok = 0
BUFSIZE = 16*1024
try:
f = open(path, "w")
while 1:
buf = txt.read(BUFSIZE)
if not buf:
break
f.write(buf)
f.close()
ok = 1
finally:
if not ok:
try:
os.unlink(path)
except os.error:
pass
def removefromallsequences(self, list):
"""Remove one or more messages from all sequences (including last)
-- but not from 'cur'!!!"""
if hasattr(self, 'last') and self.last in list:
del self.last
sequences = self.getsequences()
changed = 0
for name, seq in sequences.items():
if name == 'cur':
continue
for n in list:
if n in seq:
seq.remove(n)
changed = 1
if not seq:
del sequences[name]
if changed:
self.putsequences(sequences)
def getlast(self):
"""Return the last message number."""
if not hasattr(self, 'last'):
self.listmessages() # Set self.last
return self.last
def setlast(self, last):
"""Set the last message number."""
if last is None:
if hasattr(self, 'last'):
del self.last
else:
self.last = last
class Message(mimetools.Message):
def __init__(self, f, n, fp = None):
"""Constructor."""
self.folder = f
self.number = n
if fp is None:
path = f.getmessagefilename(n)
fp = open(path, 'r')
mimetools.Message.__init__(self, fp)
def __repr__(self):
"""String representation."""
return 'Message(%s, %s)' % (repr(self.folder), self.number)
def getheadertext(self, pred = None):
"""Return the message's header text as a string. If an
argument is specified, it is used as a filter predicate to
decide which headers to return (its argument is the header
name converted to lower case)."""
if pred is None:
return ''.join(self.headers)
headers = []
hit = 0
for line in self.headers:
if not line[0].isspace():
i = line.find(':')
if i > 0:
hit = pred(line[:i].lower())
if hit: headers.append(line)
return ''.join(headers)
def getbodytext(self, decode = 1):
"""Return the message's body text as string. This undoes a
Content-Transfer-Encoding, but does not interpret other MIME
features (e.g. multipart messages). To suppress decoding,
pass 0 as an argument."""
self.fp.seek(self.startofbody)
encoding = self.getencoding()
if not decode or encoding in ('', '7bit', '8bit', 'binary'):
return self.fp.read()
from StringIO import StringIO
output = StringIO()
mimetools.decode(self.fp, output, encoding)
return output.getvalue()
def getbodyparts(self):
"""Only for multipart messages: return the message's body as a
list of SubMessage objects. Each submessage object behaves
(almost) as a Message object."""
if self.getmaintype() != 'multipart':
raise Error, 'Content-Type is not multipart/*'
bdry = self.getparam('boundary')
if not bdry:
raise Error, 'multipart/* without boundary param'
self.fp.seek(self.startofbody)
mf = multifile.MultiFile(self.fp)
mf.push(bdry)
parts = []
while mf.next():
n = "%s.%r" % (self.number, 1 + len(parts))
part = SubMessage(self.folder, n, mf)
parts.append(part)
mf.pop()
return parts
def getbody(self):
"""Return body, either a string or a list of messages."""
if self.getmaintype() == 'multipart':
return self.getbodyparts()
else:
return self.getbodytext()
class SubMessage(Message):
def __init__(self, f, n, fp):
"""Constructor."""
Message.__init__(self, f, n, fp)
if self.getmaintype() == 'multipart':
self.body = Message.getbodyparts(self)
else:
self.body = Message.getbodytext(self)
self.bodyencoded = Message.getbodytext(self, decode=0)
# XXX If this is big, should remember file pointers
def __repr__(self):
"""String representation."""
f, n, fp = self.folder, self.number, self.fp
return 'SubMessage(%s, %s, %s)' % (f, n, fp)
def getbodytext(self, decode = 1):
if not decode:
return self.bodyencoded
if type(self.body) == type(''):
return self.body
def getbodyparts(self):
if type(self.body) == type([]):
return self.body
def getbody(self):
return self.body
class IntSet:
"""Class implementing sets of integers.
This is an efficient representation for sets consisting of several
continuous ranges, e.g. 1-100,200-400,402-1000 is represented
internally as a list of three pairs: [(1,100), (200,400),
(402,1000)]. The internal representation is always kept normalized.
The constructor has up to three arguments:
- the string used to initialize the set (default ''),
- the separator between ranges (default ',')
- the separator between begin and end of a range (default '-')
The separators must be strings (not regexprs) and should be different.
The tostring() function yields a string that can be passed to another
IntSet constructor; __repr__() is a valid IntSet constructor itself.
"""
# XXX The default begin/end separator means that negative numbers are
# not supported very well.
#
# XXX There are currently no operations to remove set elements.
def __init__(self, data = None, sep = ',', rng = '-'):
self.pairs = []
self.sep = sep
self.rng = rng
if data: self.fromstring(data)
def reset(self):
self.pairs = []
def __cmp__(self, other):
return cmp(self.pairs, other.pairs)
def __hash__(self):
return hash(self.pairs)
def __repr__(self):
return 'IntSet(%r, %r, %r)' % (self.tostring(), self.sep, self.rng)
def normalize(self):
self.pairs.sort()
i = 1
while i < len(self.pairs):
alo, ahi = self.pairs[i-1]
blo, bhi = self.pairs[i]
if ahi >= blo-1:
self.pairs[i-1:i+1] = [(alo, max(ahi, bhi))]
else:
i = i+1
def tostring(self):
s = ''
for lo, hi in self.pairs:
if lo == hi: t = repr(lo)
else: t = repr(lo) + self.rng + repr(hi)
if s: s = s + (self.sep + t)
else: s = t
return s
def tolist(self):
l = []
for lo, hi in self.pairs:
m = range(lo, hi+1)
l = l + m
return l
def fromlist(self, list):
for i in list:
self.append(i)
def clone(self):
new = IntSet()
new.pairs = self.pairs[:]
return new
def min(self):
return self.pairs[0][0]
def max(self):
return self.pairs[-1][-1]
def contains(self, x):
for lo, hi in self.pairs:
if lo <= x <= hi: return True
return False
def append(self, x):
for i in range(len(self.pairs)):
lo, hi = self.pairs[i]
if x < lo: # Need to insert before
if x+1 == lo:
self.pairs[i] = (x, hi)
else:
self.pairs.insert(i, (x, x))
if i > 0 and x-1 == self.pairs[i-1][1]:
# Merge with previous
self.pairs[i-1:i+1] = [
(self.pairs[i-1][0],
self.pairs[i][1])
]
return
if x <= hi: # Already in set
return
i = len(self.pairs) - 1
if i >= 0:
lo, hi = self.pairs[i]
if x-1 == hi:
self.pairs[i] = lo, x
return
self.pairs.append((x, x))
def addpair(self, xlo, xhi):
if xlo > xhi: return
self.pairs.append((xlo, xhi))
self.normalize()
def fromstring(self, data):
new = []
for part in data.split(self.sep):
list = []
for subp in part.split(self.rng):
s = subp.strip()
list.append(int(s))
if len(list) == 1:
new.append((list[0], list[0]))
elif len(list) == 2 and list[0] <= list[1]:
new.append((list[0], list[1]))
else:
raise ValueError, 'bad data passed to IntSet'
self.pairs = self.pairs + new
self.normalize()
# Subroutines to read/write entries in .mh_profile and .mh_sequences
def pickline(file, key, casefold = 1):
try:
f = open(file, 'r')
except IOError:
return None
pat = re.escape(key) + ':'
prog = re.compile(pat, casefold and re.IGNORECASE)
while 1:
line = f.readline()
if not line: break
if prog.match(line):
text = line[len(key)+1:]
while 1:
line = f.readline()
if not line or not line[0].isspace():
break
text = text + line
return text.strip()
return None
def updateline(file, key, value, casefold = 1):
try:
f = open(file, 'r')
lines = f.readlines()
f.close()
except IOError:
lines = []
pat = re.escape(key) + ':(.*)\n'
prog = re.compile(pat, casefold and re.IGNORECASE)
if value is None:
newline = None
else:
newline = '%s: %s\n' % (key, value)
for i in range(len(lines)):
line = lines[i]
if prog.match(line):
if newline is None:
del lines[i]
else:
lines[i] = newline
break
else:
if newline is not None:
lines.append(newline)
tempfile = file + "~"
f = open(tempfile, 'w')
for line in lines:
f.write(line)
f.close()
os.rename(tempfile, file)
# Test program
def test():
global mh, f
os.system('rm -rf $HOME/Mail/@test')
mh = MH()
def do(s): print s; print eval(s)
do('mh.listfolders()')
do('mh.listallfolders()')
testfolders = ['@test', '@test/test1', '@test/test2',
'@test/test1/test11', '@test/test1/test12',
'@test/test1/test11/test111']
for t in testfolders: do('mh.makefolder(%r)' % (t,))
do('mh.listsubfolders(\'@test\')')
do('mh.listallsubfolders(\'@test\')')
f = mh.openfolder('@test')
do('f.listsubfolders()')
do('f.listallsubfolders()')
do('f.getsequences()')
seqs = f.getsequences()
seqs['foo'] = IntSet('1-10 12-20', ' ').tolist()
print seqs
f.putsequences(seqs)
do('f.getsequences()')
for t in reversed(testfolders): do('mh.deletefolder(%r)' % (t,))
do('mh.getcontext()')
context = mh.getcontext()
f = mh.openfolder(context)
do('f.getcurrent()')
for seq in ['first', 'last', 'cur', '.', 'prev', 'next',
'first:3', 'last:3', 'cur:3', 'cur:-3',
'prev:3', 'next:3',
'1:3', '1:-3', '100:3', '100:-3', '10000:3', '10000:-3',
'all']:
try:
do('f.parsesequence(%r)' % (seq,))
except Error, msg:
print "Error:", msg
stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read()
list = map(int, stuff.split())
print list, "<-- pick"
do('f.listmessages()')
if __name__ == '__main__':
test()
| Python |
"""A parser for XML, using the derived class as static DTD."""
# Author: Sjoerd Mullender.
import re
import string
import warnings
warnings.warn("The xmllib module is obsolete. Use xml.sax instead.", DeprecationWarning)
del warnings
version = '0.3'
class Error(RuntimeError):
pass
# Regular expressions used for parsing
_S = '[ \t\r\n]+' # white space
_opS = '[ \t\r\n]*' # optional white space
_Name = '[a-zA-Z_:][-a-zA-Z0-9._:]*' # valid XML name
_QStr = "(?:'[^']*'|\"[^\"]*\")" # quoted XML string
illegal = re.compile('[^\t\r\n -\176\240-\377]') # illegal chars in content
interesting = re.compile('[]&<]')
amp = re.compile('&')
ref = re.compile('&(' + _Name + '|#[0-9]+|#x[0-9a-fA-F]+)[^-a-zA-Z0-9._:]')
entityref = re.compile('&(?P<name>' + _Name + ')[^-a-zA-Z0-9._:]')
charref = re.compile('&#(?P<char>[0-9]+[^0-9]|x[0-9a-fA-F]+[^0-9a-fA-F])')
space = re.compile(_S + '$')
newline = re.compile('\n')
attrfind = re.compile(
_S + '(?P<name>' + _Name + ')'
'(' + _opS + '=' + _opS +
'(?P<value>'+_QStr+'|[-a-zA-Z0-9.:+*%?!\(\)_#=~]+))?')
starttagopen = re.compile('<' + _Name)
starttagend = re.compile(_opS + '(?P<slash>/?)>')
starttagmatch = re.compile('<(?P<tagname>'+_Name+')'
'(?P<attrs>(?:'+attrfind.pattern+')*)'+
starttagend.pattern)
endtagopen = re.compile('</')
endbracket = re.compile(_opS + '>')
endbracketfind = re.compile('(?:[^>\'"]|'+_QStr+')*>')
tagfind = re.compile(_Name)
cdataopen = re.compile(r'<!\[CDATA\[')
cdataclose = re.compile(r'\]\]>')
# this matches one of the following:
# SYSTEM SystemLiteral
# PUBLIC PubidLiteral SystemLiteral
_SystemLiteral = '(?P<%s>'+_QStr+')'
_PublicLiteral = '(?P<%s>"[-\'\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*"|' \
"'[-\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*')"
_ExternalId = '(?:SYSTEM|' \
'PUBLIC'+_S+_PublicLiteral%'pubid'+ \
')'+_S+_SystemLiteral%'syslit'
doctype = re.compile('<!DOCTYPE'+_S+'(?P<name>'+_Name+')'
'(?:'+_S+_ExternalId+')?'+_opS)
xmldecl = re.compile('<\?xml'+_S+
'version'+_opS+'='+_opS+'(?P<version>'+_QStr+')'+
'(?:'+_S+'encoding'+_opS+'='+_opS+
"(?P<encoding>'[A-Za-z][-A-Za-z0-9._]*'|"
'"[A-Za-z][-A-Za-z0-9._]*"))?'
'(?:'+_S+'standalone'+_opS+'='+_opS+
'(?P<standalone>\'(?:yes|no)\'|"(?:yes|no)"))?'+
_opS+'\?>')
procopen = re.compile(r'<\?(?P<proc>' + _Name + ')' + _opS)
procclose = re.compile(_opS + r'\?>')
commentopen = re.compile('<!--')
commentclose = re.compile('-->')
doubledash = re.compile('--')
attrtrans = string.maketrans(' \r\n\t', ' ')
# definitions for XML namespaces
_NCName = '[a-zA-Z_][-a-zA-Z0-9._]*' # XML Name, minus the ":"
ncname = re.compile(_NCName + '$')
qname = re.compile('(?:(?P<prefix>' + _NCName + '):)?' # optional prefix
'(?P<local>' + _NCName + ')$')
xmlns = re.compile('xmlns(?::(?P<ncname>'+_NCName+'))?$')
# XML parser base class -- find tags and call handler functions.
# Usage: p = XMLParser(); p.feed(data); ...; p.close().
# The dtd is defined by deriving a class which defines methods with
# special names to handle tags: start_foo and end_foo to handle <foo>
# and </foo>, respectively. The data between tags is passed to the
# parser by calling self.handle_data() with some data as argument (the
# data may be split up in arbitrary chunks).
class XMLParser:
attributes = {} # default, to be overridden
elements = {} # default, to be overridden
# parsing options, settable using keyword args in __init__
__accept_unquoted_attributes = 0
__accept_missing_endtag_name = 0
__map_case = 0
__accept_utf8 = 0
__translate_attribute_references = 1
# Interface -- initialize and reset this instance
def __init__(self, **kw):
self.__fixed = 0
if 'accept_unquoted_attributes' in kw:
self.__accept_unquoted_attributes = kw['accept_unquoted_attributes']
if 'accept_missing_endtag_name' in kw:
self.__accept_missing_endtag_name = kw['accept_missing_endtag_name']
if 'map_case' in kw:
self.__map_case = kw['map_case']
if 'accept_utf8' in kw:
self.__accept_utf8 = kw['accept_utf8']
if 'translate_attribute_references' in kw:
self.__translate_attribute_references = kw['translate_attribute_references']
self.reset()
def __fixelements(self):
self.__fixed = 1
self.elements = {}
self.__fixdict(self.__dict__)
self.__fixclass(self.__class__)
def __fixclass(self, kl):
self.__fixdict(kl.__dict__)
for k in kl.__bases__:
self.__fixclass(k)
def __fixdict(self, dict):
for key in dict.keys():
if key[:6] == 'start_':
tag = key[6:]
start, end = self.elements.get(tag, (None, None))
if start is None:
self.elements[tag] = getattr(self, key), end
elif key[:4] == 'end_':
tag = key[4:]
start, end = self.elements.get(tag, (None, None))
if end is None:
self.elements[tag] = start, getattr(self, key)
# Interface -- reset this instance. Loses all unprocessed data
def reset(self):
self.rawdata = ''
self.stack = []
self.nomoretags = 0
self.literal = 0
self.lineno = 1
self.__at_start = 1
self.__seen_doctype = None
self.__seen_starttag = 0
self.__use_namespaces = 0
self.__namespaces = {'xml':None} # xml is implicitly declared
# backward compatibility hack: if elements not overridden,
# fill it in ourselves
if self.elements is XMLParser.elements:
self.__fixelements()
# For derived classes only -- enter literal mode (CDATA) till EOF
def setnomoretags(self):
self.nomoretags = self.literal = 1
# For derived classes only -- enter literal mode (CDATA)
def setliteral(self, *args):
self.literal = 1
# Interface -- feed some data to the parser. Call this as
# often as you want, with as little or as much text as you
# want (may include '\n'). (This just saves the text, all the
# processing is done by goahead().)
def feed(self, data):
self.rawdata = self.rawdata + data
self.goahead(0)
# Interface -- handle the remaining data
def close(self):
self.goahead(1)
if self.__fixed:
self.__fixed = 0
# remove self.elements so that we don't leak
del self.elements
# Interface -- translate references
def translate_references(self, data, all = 1):
if not self.__translate_attribute_references:
return data
i = 0
while 1:
res = amp.search(data, i)
if res is None:
return data
s = res.start(0)
res = ref.match(data, s)
if res is None:
self.syntax_error("bogus `&'")
i = s+1
continue
i = res.end(0)
str = res.group(1)
rescan = 0
if str[0] == '#':
if str[1] == 'x':
str = chr(int(str[2:], 16))
else:
str = chr(int(str[1:]))
if data[i - 1] != ';':
self.syntax_error("`;' missing after char reference")
i = i-1
elif all:
if str in self.entitydefs:
str = self.entitydefs[str]
rescan = 1
elif data[i - 1] != ';':
self.syntax_error("bogus `&'")
i = s + 1 # just past the &
continue
else:
self.syntax_error("reference to unknown entity `&%s;'" % str)
str = '&' + str + ';'
elif data[i - 1] != ';':
self.syntax_error("bogus `&'")
i = s + 1 # just past the &
continue
# when we get here, str contains the translated text and i points
# to the end of the string that is to be replaced
data = data[:s] + str + data[i:]
if rescan:
i = s
else:
i = s + len(str)
# Interface - return a dictionary of all namespaces currently valid
def getnamespace(self):
nsdict = {}
for t, d, nst in self.stack:
nsdict.update(d)
return nsdict
# Internal -- handle data as far as reasonable. May leave state
# and data to be processed by a subsequent call. If 'end' is
# true, force handling all data as if followed by EOF marker.
def goahead(self, end):
rawdata = self.rawdata
i = 0
n = len(rawdata)
while i < n:
if i > 0:
self.__at_start = 0
if self.nomoretags:
data = rawdata[i:n]
self.handle_data(data)
self.lineno = self.lineno + data.count('\n')
i = n
break
res = interesting.search(rawdata, i)
if res:
j = res.start(0)
else:
j = n
if i < j:
data = rawdata[i:j]
if self.__at_start and space.match(data) is None:
self.syntax_error('illegal data at start of file')
self.__at_start = 0
if not self.stack and space.match(data) is None:
self.syntax_error('data not in content')
if not self.__accept_utf8 and illegal.search(data):
self.syntax_error('illegal character in content')
self.handle_data(data)
self.lineno = self.lineno + data.count('\n')
i = j
if i == n: break
if rawdata[i] == '<':
if starttagopen.match(rawdata, i):
if self.literal:
data = rawdata[i]
self.handle_data(data)
self.lineno = self.lineno + data.count('\n')
i = i+1
continue
k = self.parse_starttag(i)
if k < 0: break
self.__seen_starttag = 1
self.lineno = self.lineno + rawdata[i:k].count('\n')
i = k
continue
if endtagopen.match(rawdata, i):
k = self.parse_endtag(i)
if k < 0: break
self.lineno = self.lineno + rawdata[i:k].count('\n')
i = k
continue
if commentopen.match(rawdata, i):
if self.literal:
data = rawdata[i]
self.handle_data(data)
self.lineno = self.lineno + data.count('\n')
i = i+1
continue
k = self.parse_comment(i)
if k < 0: break
self.lineno = self.lineno + rawdata[i:k].count('\n')
i = k
continue
if cdataopen.match(rawdata, i):
k = self.parse_cdata(i)
if k < 0: break
self.lineno = self.lineno + rawdata[i:k].count('\n')
i = k
continue
res = xmldecl.match(rawdata, i)
if res:
if not self.__at_start:
self.syntax_error("<?xml?> declaration not at start of document")
version, encoding, standalone = res.group('version',
'encoding',
'standalone')
if version[1:-1] != '1.0':
raise Error('only XML version 1.0 supported')
if encoding: encoding = encoding[1:-1]
if standalone: standalone = standalone[1:-1]
self.handle_xml(encoding, standalone)
i = res.end(0)
continue
res = procopen.match(rawdata, i)
if res:
k = self.parse_proc(i)
if k < 0: break
self.lineno = self.lineno + rawdata[i:k].count('\n')
i = k
continue
res = doctype.match(rawdata, i)
if res:
if self.literal:
data = rawdata[i]
self.handle_data(data)
self.lineno = self.lineno + data.count('\n')
i = i+1
continue
if self.__seen_doctype:
self.syntax_error('multiple DOCTYPE elements')
if self.__seen_starttag:
self.syntax_error('DOCTYPE not at beginning of document')
k = self.parse_doctype(res)
if k < 0: break
self.__seen_doctype = res.group('name')
if self.__map_case:
self.__seen_doctype = self.__seen_doctype.lower()
self.lineno = self.lineno + rawdata[i:k].count('\n')
i = k
continue
elif rawdata[i] == '&':
if self.literal:
data = rawdata[i]
self.handle_data(data)
i = i+1
continue
res = charref.match(rawdata, i)
if res is not None:
i = res.end(0)
if rawdata[i-1] != ';':
self.syntax_error("`;' missing in charref")
i = i-1
if not self.stack:
self.syntax_error('data not in content')
self.handle_charref(res.group('char')[:-1])
self.lineno = self.lineno + res.group(0).count('\n')
continue
res = entityref.match(rawdata, i)
if res is not None:
i = res.end(0)
if rawdata[i-1] != ';':
self.syntax_error("`;' missing in entityref")
i = i-1
name = res.group('name')
if self.__map_case:
name = name.lower()
if name in self.entitydefs:
self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:]
n = len(rawdata)
i = res.start(0)
else:
self.unknown_entityref(name)
self.lineno = self.lineno + res.group(0).count('\n')
continue
elif rawdata[i] == ']':
if self.literal:
data = rawdata[i]
self.handle_data(data)
i = i+1
continue
if n-i < 3:
break
if cdataclose.match(rawdata, i):
self.syntax_error("bogus `]]>'")
self.handle_data(rawdata[i])
i = i+1
continue
else:
raise Error('neither < nor & ??')
# We get here only if incomplete matches but
# nothing else
break
# end while
if i > 0:
self.__at_start = 0
if end and i < n:
data = rawdata[i]
self.syntax_error("bogus `%s'" % data)
if not self.__accept_utf8 and illegal.search(data):
self.syntax_error('illegal character in content')
self.handle_data(data)
self.lineno = self.lineno + data.count('\n')
self.rawdata = rawdata[i+1:]
return self.goahead(end)
self.rawdata = rawdata[i:]
if end:
if not self.__seen_starttag:
self.syntax_error('no elements in file')
if self.stack:
self.syntax_error('missing end tags')
while self.stack:
self.finish_endtag(self.stack[-1][0])
# Internal -- parse comment, return length or -1 if not terminated
def parse_comment(self, i):
rawdata = self.rawdata
if rawdata[i:i+4] != '<!--':
raise Error('unexpected call to handle_comment')
res = commentclose.search(rawdata, i+4)
if res is None:
return -1
if doubledash.search(rawdata, i+4, res.start(0)):
self.syntax_error("`--' inside comment")
if rawdata[res.start(0)-1] == '-':
self.syntax_error('comment cannot end in three dashes')
if not self.__accept_utf8 and \
illegal.search(rawdata, i+4, res.start(0)):
self.syntax_error('illegal character in comment')
self.handle_comment(rawdata[i+4: res.start(0)])
return res.end(0)
# Internal -- handle DOCTYPE tag, return length or -1 if not terminated
def parse_doctype(self, res):
rawdata = self.rawdata
n = len(rawdata)
name = res.group('name')
if self.__map_case:
name = name.lower()
pubid, syslit = res.group('pubid', 'syslit')
if pubid is not None:
pubid = pubid[1:-1] # remove quotes
pubid = ' '.join(pubid.split()) # normalize
if syslit is not None: syslit = syslit[1:-1] # remove quotes
j = k = res.end(0)
if k >= n:
return -1
if rawdata[k] == '[':
level = 0
k = k+1
dq = sq = 0
while k < n:
c = rawdata[k]
if not sq and c == '"':
dq = not dq
elif not dq and c == "'":
sq = not sq
elif sq or dq:
pass
elif level <= 0 and c == ']':
res = endbracket.match(rawdata, k+1)
if res is None:
return -1
self.handle_doctype(name, pubid, syslit, rawdata[j+1:k])
return res.end(0)
elif c == '<':
level = level + 1
elif c == '>':
level = level - 1
if level < 0:
self.syntax_error("bogus `>' in DOCTYPE")
k = k+1
res = endbracketfind.match(rawdata, k)
if res is None:
return -1
if endbracket.match(rawdata, k) is None:
self.syntax_error('garbage in DOCTYPE')
self.handle_doctype(name, pubid, syslit, None)
return res.end(0)
# Internal -- handle CDATA tag, return length or -1 if not terminated
def parse_cdata(self, i):
rawdata = self.rawdata
if rawdata[i:i+9] != '<![CDATA[':
raise Error('unexpected call to parse_cdata')
res = cdataclose.search(rawdata, i+9)
if res is None:
return -1
if not self.__accept_utf8 and \
illegal.search(rawdata, i+9, res.start(0)):
self.syntax_error('illegal character in CDATA')
if not self.stack:
self.syntax_error('CDATA not in content')
self.handle_cdata(rawdata[i+9:res.start(0)])
return res.end(0)
__xml_namespace_attributes = {'ns':None, 'src':None, 'prefix':None}
# Internal -- handle a processing instruction tag
def parse_proc(self, i):
rawdata = self.rawdata
end = procclose.search(rawdata, i)
if end is None:
return -1
j = end.start(0)
if not self.__accept_utf8 and illegal.search(rawdata, i+2, j):
self.syntax_error('illegal character in processing instruction')
res = tagfind.match(rawdata, i+2)
if res is None:
raise Error('unexpected call to parse_proc')
k = res.end(0)
name = res.group(0)
if self.__map_case:
name = name.lower()
if name == 'xml:namespace':
self.syntax_error('old-fashioned namespace declaration')
self.__use_namespaces = -1
# namespace declaration
# this must come after the <?xml?> declaration (if any)
# and before the <!DOCTYPE> (if any).
if self.__seen_doctype or self.__seen_starttag:
self.syntax_error('xml:namespace declaration too late in document')
attrdict, namespace, k = self.parse_attributes(name, k, j)
if namespace:
self.syntax_error('namespace declaration inside namespace declaration')
for attrname in attrdict.keys():
if not attrname in self.__xml_namespace_attributes:
self.syntax_error("unknown attribute `%s' in xml:namespace tag" % attrname)
if not 'ns' in attrdict or not 'prefix' in attrdict:
self.syntax_error('xml:namespace without required attributes')
prefix = attrdict.get('prefix')
if ncname.match(prefix) is None:
self.syntax_error('xml:namespace illegal prefix value')
return end.end(0)
if prefix in self.__namespaces:
self.syntax_error('xml:namespace prefix not unique')
self.__namespaces[prefix] = attrdict['ns']
else:
if name.lower() == 'xml':
self.syntax_error('illegal processing instruction target name')
self.handle_proc(name, rawdata[k:j])
return end.end(0)
# Internal -- parse attributes between i and j
def parse_attributes(self, tag, i, j):
rawdata = self.rawdata
attrdict = {}
namespace = {}
while i < j:
res = attrfind.match(rawdata, i)
if res is None:
break
attrname, attrvalue = res.group('name', 'value')
if self.__map_case:
attrname = attrname.lower()
i = res.end(0)
if attrvalue is None:
self.syntax_error("no value specified for attribute `%s'" % attrname)
attrvalue = attrname
elif attrvalue[:1] == "'" == attrvalue[-1:] or \
attrvalue[:1] == '"' == attrvalue[-1:]:
attrvalue = attrvalue[1:-1]
elif not self.__accept_unquoted_attributes:
self.syntax_error("attribute `%s' value not quoted" % attrname)
res = xmlns.match(attrname)
if res is not None:
# namespace declaration
ncname = res.group('ncname')
namespace[ncname or ''] = attrvalue or None
if not self.__use_namespaces:
self.__use_namespaces = len(self.stack)+1
continue
if '<' in attrvalue:
self.syntax_error("`<' illegal in attribute value")
if attrname in attrdict:
self.syntax_error("attribute `%s' specified twice" % attrname)
attrvalue = attrvalue.translate(attrtrans)
attrdict[attrname] = self.translate_references(attrvalue)
return attrdict, namespace, i
# Internal -- handle starttag, return length or -1 if not terminated
def parse_starttag(self, i):
rawdata = self.rawdata
# i points to start of tag
end = endbracketfind.match(rawdata, i+1)
if end is None:
return -1
tag = starttagmatch.match(rawdata, i)
if tag is None or tag.end(0) != end.end(0):
self.syntax_error('garbage in starttag')
return end.end(0)
nstag = tagname = tag.group('tagname')
if self.__map_case:
nstag = tagname = nstag.lower()
if not self.__seen_starttag and self.__seen_doctype and \
tagname != self.__seen_doctype:
self.syntax_error('starttag does not match DOCTYPE')
if self.__seen_starttag and not self.stack:
self.syntax_error('multiple elements on top level')
k, j = tag.span('attrs')
attrdict, nsdict, k = self.parse_attributes(tagname, k, j)
self.stack.append((tagname, nsdict, nstag))
if self.__use_namespaces:
res = qname.match(tagname)
else:
res = None
if res is not None:
prefix, nstag = res.group('prefix', 'local')
if prefix is None:
prefix = ''
ns = None
for t, d, nst in self.stack:
if prefix in d:
ns = d[prefix]
if ns is None and prefix != '':
ns = self.__namespaces.get(prefix)
if ns is not None:
nstag = ns + ' ' + nstag
elif prefix != '':
nstag = prefix + ':' + nstag # undo split
self.stack[-1] = tagname, nsdict, nstag
# translate namespace of attributes
attrnamemap = {} # map from new name to old name (used for error reporting)
for key in attrdict.keys():
attrnamemap[key] = key
if self.__use_namespaces:
nattrdict = {}
for key, val in attrdict.items():
okey = key
res = qname.match(key)
if res is not None:
aprefix, key = res.group('prefix', 'local')
if self.__map_case:
key = key.lower()
if aprefix is not None:
ans = None
for t, d, nst in self.stack:
if aprefix in d:
ans = d[aprefix]
if ans is None:
ans = self.__namespaces.get(aprefix)
if ans is not None:
key = ans + ' ' + key
else:
key = aprefix + ':' + key
nattrdict[key] = val
attrnamemap[key] = okey
attrdict = nattrdict
attributes = self.attributes.get(nstag)
if attributes is not None:
for key in attrdict.keys():
if not key in attributes:
self.syntax_error("unknown attribute `%s' in tag `%s'" % (attrnamemap[key], tagname))
for key, val in attributes.items():
if val is not None and not key in attrdict:
attrdict[key] = val
method = self.elements.get(nstag, (None, None))[0]
self.finish_starttag(nstag, attrdict, method)
if tag.group('slash') == '/':
self.finish_endtag(tagname)
return tag.end(0)
# Internal -- parse endtag
def parse_endtag(self, i):
rawdata = self.rawdata
end = endbracketfind.match(rawdata, i+1)
if end is None:
return -1
res = tagfind.match(rawdata, i+2)
if res is None:
if self.literal:
self.handle_data(rawdata[i])
return i+1
if not self.__accept_missing_endtag_name:
self.syntax_error('no name specified in end tag')
tag = self.stack[-1][0]
k = i+2
else:
tag = res.group(0)
if self.__map_case:
tag = tag.lower()
if self.literal:
if not self.stack or tag != self.stack[-1][0]:
self.handle_data(rawdata[i])
return i+1
k = res.end(0)
if endbracket.match(rawdata, k) is None:
self.syntax_error('garbage in end tag')
self.finish_endtag(tag)
return end.end(0)
# Internal -- finish processing of start tag
def finish_starttag(self, tagname, attrdict, method):
if method is not None:
self.handle_starttag(tagname, method, attrdict)
else:
self.unknown_starttag(tagname, attrdict)
# Internal -- finish processing of end tag
def finish_endtag(self, tag):
self.literal = 0
if not tag:
self.syntax_error('name-less end tag')
found = len(self.stack) - 1
if found < 0:
self.unknown_endtag(tag)
return
else:
found = -1
for i in range(len(self.stack)):
if tag == self.stack[i][0]:
found = i
if found == -1:
self.syntax_error('unopened end tag')
return
while len(self.stack) > found:
if found < len(self.stack) - 1:
self.syntax_error('missing close tag for %s' % self.stack[-1][2])
nstag = self.stack[-1][2]
method = self.elements.get(nstag, (None, None))[1]
if method is not None:
self.handle_endtag(nstag, method)
else:
self.unknown_endtag(nstag)
if self.__use_namespaces == len(self.stack):
self.__use_namespaces = 0
del self.stack[-1]
# Overridable -- handle xml processing instruction
def handle_xml(self, encoding, standalone):
pass
# Overridable -- handle DOCTYPE
def handle_doctype(self, tag, pubid, syslit, data):
pass
# Overridable -- handle start tag
def handle_starttag(self, tag, method, attrs):
method(attrs)
# Overridable -- handle end tag
def handle_endtag(self, tag, method):
method()
# Example -- handle character reference, no need to override
def handle_charref(self, name):
try:
if name[0] == 'x':
n = int(name[1:], 16)
else:
n = int(name)
except ValueError:
self.unknown_charref(name)
return
if not 0 <= n <= 255:
self.unknown_charref(name)
return
self.handle_data(chr(n))
# Definition of entities -- derived classes may override
entitydefs = {'lt': '<', # must use charref
'gt': '>',
'amp': '&', # must use charref
'quot': '"',
'apos': ''',
}
# Example -- handle data, should be overridden
def handle_data(self, data):
pass
# Example -- handle cdata, could be overridden
def handle_cdata(self, data):
pass
# Example -- handle comment, could be overridden
def handle_comment(self, data):
pass
# Example -- handle processing instructions, could be overridden
def handle_proc(self, name, data):
pass
# Example -- handle relatively harmless syntax errors, could be overridden
def syntax_error(self, message):
raise Error('Syntax error at line %d: %s' % (self.lineno, message))
# To be overridden -- handlers for unknown objects
def unknown_starttag(self, tag, attrs): pass
def unknown_endtag(self, tag): pass
def unknown_charref(self, ref): pass
def unknown_entityref(self, name):
self.syntax_error("reference to unknown entity `&%s;'" % name)
class TestXMLParser(XMLParser):
def __init__(self, **kw):
self.testdata = ""
XMLParser.__init__(self, **kw)
def handle_xml(self, encoding, standalone):
self.flush()
print 'xml: encoding =',encoding,'standalone =',standalone
def handle_doctype(self, tag, pubid, syslit, data):
self.flush()
print 'DOCTYPE:',tag, repr(data)
def handle_data(self, data):
self.testdata = self.testdata + data
if len(repr(self.testdata)) >= 70:
self.flush()
def flush(self):
data = self.testdata
if data:
self.testdata = ""
print 'data:', repr(data)
def handle_cdata(self, data):
self.flush()
print 'cdata:', repr(data)
def handle_proc(self, name, data):
self.flush()
print 'processing:',name,repr(data)
def handle_comment(self, data):
self.flush()
r = repr(data)
if len(r) > 68:
r = r[:32] + '...' + r[-32:]
print 'comment:', r
def syntax_error(self, message):
print 'error at line %d:' % self.lineno, message
def unknown_starttag(self, tag, attrs):
self.flush()
if not attrs:
print 'start tag: <' + tag + '>'
else:
print 'start tag: <' + tag,
for name, value in attrs.items():
print name + '=' + '"' + value + '"',
print '>'
def unknown_endtag(self, tag):
self.flush()
print 'end tag: </' + tag + '>'
def unknown_entityref(self, ref):
self.flush()
print '*** unknown entity ref: &' + ref + ';'
def unknown_charref(self, ref):
self.flush()
print '*** unknown char ref: &#' + ref + ';'
def close(self):
XMLParser.close(self)
self.flush()
def test(args = None):
import sys, getopt
from time import time
if not args:
args = sys.argv[1:]
opts, args = getopt.getopt(args, 'st')
klass = TestXMLParser
do_time = 0
for o, a in opts:
if o == '-s':
klass = XMLParser
elif o == '-t':
do_time = 1
if args:
file = args[0]
else:
file = 'test.xml'
if file == '-':
f = sys.stdin
else:
try:
f = open(file, 'r')
except IOError, msg:
print file, ":", msg
sys.exit(1)
data = f.read()
if f is not sys.stdin:
f.close()
x = klass()
t0 = time()
try:
if do_time:
x.feed(data)
x.close()
else:
for c in data:
x.feed(c)
x.close()
except Error, msg:
t1 = time()
print msg
if do_time:
print 'total time: %g' % (t1-t0)
sys.exit(1)
t1 = time()
if do_time:
print 'total time: %g' % (t1-t0)
if __name__ == '__main__':
test()
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.