diff --git a/Lib/plat-mac/Audio_mac.py b/Lib/plat-mac/Audio_mac.py index bf997874999..5350e5588c2 100644 --- a/Lib/plat-mac/Audio_mac.py +++ b/Lib/plat-mac/Audio_mac.py @@ -3,119 +3,119 @@ 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 __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 __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 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 stop(self, quietNow = 1): + ##chan = self._chan + self._chan = None + ##chan.SndDisposeChannel(1) + self._gc = [] - def setoutrate(self, outrate): - self._outrate = outrate + def setoutrate(self, outrate): + self._outrate = outrate - def setsampwidth(self, sampwidth): - self._sampwidth = sampwidth + def setsampwidth(self, sampwidth): + self._sampwidth = sampwidth - def setnchannels(self, nchannels): - self._nchannels = nchannels + 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 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 _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 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 getfillable(self): + return (self._qsize / self._nchannels / self._sampwidth) - self.getfilled() - def ulaw2lin(self, data): - import audioop - return audioop.ulaw2lin(data, 2) + 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() + 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() + test() diff --git a/Lib/plat-mac/Carbon/ControlAccessor.py b/Lib/plat-mac/Carbon/ControlAccessor.py index 20cf414dfbd..791544e7882 100644 --- a/Lib/plat-mac/Carbon/ControlAccessor.py +++ b/Lib/plat-mac/Carbon/ControlAccessor.py @@ -5,53 +5,53 @@ import struct # These needn't go through this module, but are here for completeness def SetControlData_Handle(control, part, selector, data): - control.SetControlData_Handle(part, selector, data) - + control.SetControlData_Handle(part, selector, data) + def GetControlData_Handle(control, part, selector): - return control.GetControlData_Handle(part, selector) - + return control.GetControlData_Handle(part, selector) + _accessdict = { - kControlPopupButtonMenuHandleTag: (SetControlData_Handle, GetControlData_Handle), + kControlPopupButtonMenuHandleTag: (SetControlData_Handle, GetControlData_Handle), } _codingdict = { - kControlPushButtonDefaultTag : ("b", None, None), - - kControlEditTextTextTag: (None, None, None), - kControlEditTextPasswordTag: (None, None, None), - - kControlPopupButtonMenuIDTag: ("h", None, None), - - kControlListBoxDoubleClickTag: ("b", None, None), + kControlPushButtonDefaultTag : ("b", None, None), + + kControlEditTextTextTag: (None, None, None), + kControlEditTextPasswordTag: (None, None, None), + + kControlPopupButtonMenuIDTag: ("h", None, None), + + kControlListBoxDoubleClickTag: ("b", None, None), } def SetControlData(control, part, selector, data): - if _accessdict.has_key(selector): - setfunc, getfunc = _accessdict[selector] - setfunc(control, part, selector, data) - return - if not _codingdict.has_key(selector): - raise KeyError, ('Unknown control selector', selector) - structfmt, coder, decoder = _codingdict[selector] - if coder: - data = coder(data) - if structfmt: - data = struct.pack(structfmt, data) - control.SetControlData(part, selector, data) - + if _accessdict.has_key(selector): + setfunc, getfunc = _accessdict[selector] + setfunc(control, part, selector, data) + return + if not _codingdict.has_key(selector): + raise KeyError, ('Unknown control selector', selector) + structfmt, coder, decoder = _codingdict[selector] + if coder: + data = coder(data) + if structfmt: + data = struct.pack(structfmt, data) + control.SetControlData(part, selector, data) + def GetControlData(control, part, selector): - if _accessdict.has_key(selector): - setfunc, getfunc = _accessdict[selector] - return getfunc(control, part, selector, data) - if not _codingdict.has_key(selector): - raise KeyError, ('Unknown control selector', selector) - structfmt, coder, decoder = _codingdict[selector] - data = control.GetControlData(part, selector) - if structfmt: - data = struct.unpack(structfmt, data) - if decoder: - data = decoder(data) - if type(data) == type(()) and len(data) == 1: - data = data[0] - return data - + if _accessdict.has_key(selector): + setfunc, getfunc = _accessdict[selector] + return getfunc(control, part, selector, data) + if not _codingdict.has_key(selector): + raise KeyError, ('Unknown control selector', selector) + structfmt, coder, decoder = _codingdict[selector] + data = control.GetControlData(part, selector) + if structfmt: + data = struct.unpack(structfmt, data) + if decoder: + data = decoder(data) + if type(data) == type(()) and len(data) == 1: + data = data[0] + return data + diff --git a/Lib/plat-mac/Carbon/Res.py b/Lib/plat-mac/Carbon/Res.py index 8465ab8856e..8f45d094648 100644 --- a/Lib/plat-mac/Carbon/Res.py +++ b/Lib/plat-mac/Carbon/Res.py @@ -1,4 +1,4 @@ try: - from OverrideFrom23._Res import * + from OverrideFrom23._Res import * except ImportError: - from _Res import * + from _Res import * diff --git a/Lib/plat-mac/PixMapWrapper.py b/Lib/plat-mac/PixMapWrapper.py index 01973e8f3a2..a2d13feecb1 100644 --- a/Lib/plat-mac/PixMapWrapper.py +++ b/Lib/plat-mac/PixMapWrapper.py @@ -14,202 +14,202 @@ 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 + '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 + '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.""" + """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 __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 __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 __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 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 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 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 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 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 + 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 diff --git a/Lib/plat-mac/aepack.py b/Lib/plat-mac/aepack.py index 5dd95b84506..22dfd21dd11 100644 --- a/Lib/plat-mac/aepack.py +++ b/Lib/plat-mac/aepack.py @@ -44,15 +44,15 @@ import os # 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, + typeComp : typeFloat, + typeColorTable : typeAEList, + typeDrawingArea : typeAERecord, + typeFixed : typeFloat, + typeExtended : typeFloat, + typePixelMap : typeAERecord, + typeRotation : typeAERecord, + typeStyledText : typeAERecord, + typeTextStyles : typeAERecord, }; # @@ -64,303 +64,303 @@ 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)) + 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 + """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) - + """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) + """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 + 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 + 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 + 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) + return aetypes.Unknown(type, data) def getpstr(s): - return s[1:1+ord(s[0])] + 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]) + 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) + return (ord(s[0])<<8) | (ord(s[1])<<0) def mkkeyword(keyword): - return aetypes.Keyword(keyword) + return aetypes.Keyword(keyword) def mkrange(dict): - return aetypes.Range(dict['star'], dict['stop']) + return aetypes.Range(dict['star'], dict['stop']) def mkcomparison(dict): - return aetypes.Comparison(dict['obj1'], dict['relo'].enum, dict['obj2']) + return aetypes.Comparison(dict['obj1'], dict['relo'].enum, dict['obj2']) def mklogical(dict): - return aetypes.Logical(dict['logc'], dict['term']) + return aetypes.Logical(dict['logc'], dict['term']) def mkstyledtext(dict): - return aetypes.StyledText(dict['ksty'], dict['ktxt']) - + return aetypes.StyledText(dict['ksty'], dict['ktxt']) + def mkaetext(dict): - return aetypes.AEText(dict[keyAEScriptTag], dict[keyAEStyles], dict[keyAEText]) - + return aetypes.AEText(dict[keyAEScriptTag], dict[keyAEStyles], dict[keyAEText]) + def mkinsertionloc(dict): - return aetypes.InsertionLoc(dict[keyAEObject], dict[keyAEPosition]) + 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) + 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 - + 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) + if modulename: + module = __import__(modulename) + codenamemapper = module._classdeclarations + classtype = codenamemapper.get(typecode, None) + if classtype: + return classtype + return aetypes.mktype(typecode) diff --git a/Lib/plat-mac/aetools.py b/Lib/plat-mac/aetools.py index ac264ee15d7..79b806964c0 100644 --- a/Lib/plat-mac/aetools.py +++ b/Lib/plat-mac/aetools.py @@ -9,11 +9,11 @@ unpackevent(event) returns the parameters and attributes from an AEAppleEvent re 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")) + x = Character(1, Document("foobar")) and pack(x) will create an AE object reference equivalent to AppleScript's - character 1 of document "foobar" + 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. @@ -41,306 +41,306 @@ LAUNCH_MAX_WAIT_TIME=10 # 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 + '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 + 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 + 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)) + 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 - + """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 - + """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) + """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 - - __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) + """An AE connection to an application""" + _signature = None # Can be overridden by subclasses + _moduleName = None # 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 __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' + 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) + _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) + _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', - } + 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' + 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 + 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 + _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 # 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' + 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 + 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['----'] + _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))) + """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 - 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(":") + 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) + test() + sys.exit(1) diff --git a/Lib/plat-mac/aetypes.py b/Lib/plat-mac/aetypes.py index e62e866fd73..538cf14e64b 100644 --- a/Lib/plat-mac/aetypes.py +++ b/Lib/plat-mac/aetypes.py @@ -10,549 +10,549 @@ import string # aetools_convert. # def pack(*args, **kwargs): - from aepack import pack - return pack( *args, **kwargs) - + from aepack import pack + return pack( *args, **kwargs) + def nice(s): - """'nice' representation of an object""" - if type(s) is StringType: return repr(s) - else: return str(s) + """'nice' representation of an object""" + if type(s) is StringType: return repr(s) + else: return str(s) class Unknown: - """An uninterpreted AE object""" - - def __init__(self, type, data): - self.type = type - self.data = data - - def __repr__(self): - return "Unknown(%s, %s)" % (`self.type`, `self.data`) - - def __aepack__(self): - return pack(self.data, self.type) + """An uninterpreted AE object""" + + def __init__(self, type, data): + self.type = type + self.data = data + + def __repr__(self): + return "Unknown(%s, %s)" % (`self.type`, `self.data`) + + def __aepack__(self): + return pack(self.data, self.type) class Enum: - """An AE enumeration value""" - - def __init__(self, enum): - self.enum = "%-4.4s" % str(enum) - - def __repr__(self): - return "Enum(%s)" % `self.enum` - - def __str__(self): - return string.strip(self.enum) - - def __aepack__(self): - return pack(self.enum, typeEnumeration) + """An AE enumeration value""" + + def __init__(self, enum): + self.enum = "%-4.4s" % str(enum) + + def __repr__(self): + return "Enum(%s)" % `self.enum` + + def __str__(self): + return string.strip(self.enum) + + def __aepack__(self): + return pack(self.enum, typeEnumeration) def IsEnum(x): - return isinstance(x, Enum) + return isinstance(x, Enum) def mkenum(enum): - if IsEnum(enum): return enum - return Enum(enum) + if IsEnum(enum): return enum + return Enum(enum) # Jack changed the way this is done class InsertionLoc: - def __init__(self, of, pos): - self.of = of - self.pos = pos - - def __repr__(self): - return "InsertionLoc(%s, %s)" % (`self.of`, `self.pos`) - - def __aepack__(self): - rec = {'kobj': self.of, 'kpos': self.pos} - return pack(rec, forcetype='insl') - + def __init__(self, of, pos): + self.of = of + self.pos = pos + + def __repr__(self): + return "InsertionLoc(%s, %s)" % (`self.of`, `self.pos`) + + def __aepack__(self): + rec = {'kobj': self.of, 'kpos': self.pos} + return pack(rec, forcetype='insl') + # Convenience functions for dsp: def beginning(of): - return InsertionLoc(of, Enum('bgng')) - + return InsertionLoc(of, Enum('bgng')) + def end(of): - return InsertionLoc(of, Enum('end ')) + return InsertionLoc(of, Enum('end ')) class Boolean: - """An AE boolean value""" - - def __init__(self, bool): - self.bool = (not not bool) - - def __repr__(self): - return "Boolean(%s)" % `self.bool` - - def __str__(self): - if self.bool: - return "True" - else: - return "False" - - def __aepack__(self): - return pack(struct.pack('b', self.bool), 'bool') + """An AE boolean value""" + + def __init__(self, bool): + self.bool = (not not bool) + + def __repr__(self): + return "Boolean(%s)" % `self.bool` + + def __str__(self): + if self.bool: + return "True" + else: + return "False" + + def __aepack__(self): + return pack(struct.pack('b', self.bool), 'bool') def IsBoolean(x): - return isinstance(x, Boolean) + return isinstance(x, Boolean) def mkboolean(bool): - if IsBoolean(bool): return bool - return Boolean(bool) + if IsBoolean(bool): return bool + return Boolean(bool) class Type: - """An AE 4-char typename object""" - - def __init__(self, type): - self.type = "%-4.4s" % str(type) - - def __repr__(self): - return "Type(%s)" % `self.type` - - def __str__(self): - return string.strip(self.type) - - def __aepack__(self): - return pack(self.type, typeType) + """An AE 4-char typename object""" + + def __init__(self, type): + self.type = "%-4.4s" % str(type) + + def __repr__(self): + return "Type(%s)" % `self.type` + + def __str__(self): + return string.strip(self.type) + + def __aepack__(self): + return pack(self.type, typeType) def IsType(x): - return isinstance(x, Type) + return isinstance(x, Type) def mktype(type): - if IsType(type): return type - return Type(type) + if IsType(type): return type + return Type(type) class Keyword: - """An AE 4-char keyword object""" - - def __init__(self, keyword): - self.keyword = "%-4.4s" % str(keyword) - - def __repr__(self): - return "Keyword(%s)" % `self.keyword` - - def __str__(self): - return string.strip(self.keyword) - - def __aepack__(self): - return pack(self.keyword, typeKeyword) + """An AE 4-char keyword object""" + + def __init__(self, keyword): + self.keyword = "%-4.4s" % str(keyword) + + def __repr__(self): + return "Keyword(%s)" % `self.keyword` + + def __str__(self): + return string.strip(self.keyword) + + def __aepack__(self): + return pack(self.keyword, typeKeyword) def IsKeyword(x): - return isinstance(x, Keyword) + return isinstance(x, Keyword) class Range: - """An AE range object""" - - def __init__(self, start, stop): - self.start = start - self.stop = stop - - def __repr__(self): - return "Range(%s, %s)" % (`self.start`, `self.stop`) - - def __str__(self): - return "%s thru %s" % (nice(self.start), nice(self.stop)) - - def __aepack__(self): - return pack({'star': self.start, 'stop': self.stop}, 'rang') + """An AE range object""" + + def __init__(self, start, stop): + self.start = start + self.stop = stop + + def __repr__(self): + return "Range(%s, %s)" % (`self.start`, `self.stop`) + + def __str__(self): + return "%s thru %s" % (nice(self.start), nice(self.stop)) + + def __aepack__(self): + return pack({'star': self.start, 'stop': self.stop}, 'rang') def IsRange(x): - return isinstance(x, Range) + return isinstance(x, Range) class Comparison: - """An AE Comparison""" - - def __init__(self, obj1, relo, obj2): - self.obj1 = obj1 - self.relo = "%-4.4s" % str(relo) - self.obj2 = obj2 - - def __repr__(self): - return "Comparison(%s, %s, %s)" % (`self.obj1`, `self.relo`, `self.obj2`) - - def __str__(self): - return "%s %s %s" % (nice(self.obj1), string.strip(self.relo), nice(self.obj2)) - - def __aepack__(self): - return pack({'obj1': self.obj1, - 'relo': mkenum(self.relo), - 'obj2': self.obj2}, - 'cmpd') + """An AE Comparison""" + + def __init__(self, obj1, relo, obj2): + self.obj1 = obj1 + self.relo = "%-4.4s" % str(relo) + self.obj2 = obj2 + + def __repr__(self): + return "Comparison(%s, %s, %s)" % (`self.obj1`, `self.relo`, `self.obj2`) + + def __str__(self): + return "%s %s %s" % (nice(self.obj1), string.strip(self.relo), nice(self.obj2)) + + def __aepack__(self): + return pack({'obj1': self.obj1, + 'relo': mkenum(self.relo), + 'obj2': self.obj2}, + 'cmpd') def IsComparison(x): - return isinstance(x, Comparison) - + return isinstance(x, Comparison) + class NComparison(Comparison): - # The class attribute 'relo' must be set in a subclass - - def __init__(self, obj1, obj2): - Comparison.__init__(obj1, self.relo, obj2) + # The class attribute 'relo' must be set in a subclass + + def __init__(self, obj1, obj2): + Comparison.__init__(obj1, self.relo, obj2) class Ordinal: - """An AE Ordinal""" - - def __init__(self, abso): -# self.obj1 = obj1 - self.abso = "%-4.4s" % str(abso) - - def __repr__(self): - return "Ordinal(%s)" % (`self.abso`) - - def __str__(self): - return "%s" % (string.strip(self.abso)) - - def __aepack__(self): - return pack(self.abso, 'abso') + """An AE Ordinal""" + + def __init__(self, abso): +# self.obj1 = obj1 + self.abso = "%-4.4s" % str(abso) + + def __repr__(self): + return "Ordinal(%s)" % (`self.abso`) + + def __str__(self): + return "%s" % (string.strip(self.abso)) + + def __aepack__(self): + return pack(self.abso, 'abso') def IsOrdinal(x): - return isinstance(x, Ordinal) - + return isinstance(x, Ordinal) + class NOrdinal(Ordinal): - # The class attribute 'abso' must be set in a subclass - - def __init__(self): - Ordinal.__init__(self, self.abso) + # The class attribute 'abso' must be set in a subclass + + def __init__(self): + Ordinal.__init__(self, self.abso) class Logical: - """An AE logical expression object""" - - def __init__(self, logc, term): - self.logc = "%-4.4s" % str(logc) - self.term = term - - def __repr__(self): - return "Logical(%s, %s)" % (`self.logc`, `self.term`) - - def __str__(self): - if type(self.term) == ListType and len(self.term) == 2: - return "%s %s %s" % (nice(self.term[0]), - string.strip(self.logc), - nice(self.term[1])) - else: - return "%s(%s)" % (string.strip(self.logc), nice(self.term)) - - def __aepack__(self): - return pack({'logc': mkenum(self.logc), 'term': self.term}, 'logi') + """An AE logical expression object""" + + def __init__(self, logc, term): + self.logc = "%-4.4s" % str(logc) + self.term = term + + def __repr__(self): + return "Logical(%s, %s)" % (`self.logc`, `self.term`) + + def __str__(self): + if type(self.term) == ListType and len(self.term) == 2: + return "%s %s %s" % (nice(self.term[0]), + string.strip(self.logc), + nice(self.term[1])) + else: + return "%s(%s)" % (string.strip(self.logc), nice(self.term)) + + def __aepack__(self): + return pack({'logc': mkenum(self.logc), 'term': self.term}, 'logi') def IsLogical(x): - return isinstance(x, Logical) + return isinstance(x, Logical) class StyledText: - """An AE object respresenting text in a certain style""" - - def __init__(self, style, text): - self.style = style - self.text = text - - def __repr__(self): - return "StyledText(%s, %s)" % (`self.style`, `self.text`) - - def __str__(self): - return self.text - - def __aepack__(self): - return pack({'ksty': self.style, 'ktxt': self.text}, 'STXT') + """An AE object respresenting text in a certain style""" + + def __init__(self, style, text): + self.style = style + self.text = text + + def __repr__(self): + return "StyledText(%s, %s)" % (`self.style`, `self.text`) + + def __str__(self): + return self.text + + def __aepack__(self): + return pack({'ksty': self.style, 'ktxt': self.text}, 'STXT') def IsStyledText(x): - return isinstance(x, StyledText) + return isinstance(x, StyledText) class AEText: - """An AE text object with style, script and language specified""" - - def __init__(self, script, style, text): - self.script = script - self.style = style - self.text = text - - def __repr__(self): - return "AEText(%s, %s, %s)" % (`self.script`, `self.style`, `self.text`) - - def __str__(self): - return self.text - - def __aepack__(self): - return pack({keyAEScriptTag: self.script, keyAEStyles: self.style, - keyAEText: self.text}, typeAEText) + """An AE text object with style, script and language specified""" + + def __init__(self, script, style, text): + self.script = script + self.style = style + self.text = text + + def __repr__(self): + return "AEText(%s, %s, %s)" % (`self.script`, `self.style`, `self.text`) + + def __str__(self): + return self.text + + def __aepack__(self): + return pack({keyAEScriptTag: self.script, keyAEStyles: self.style, + keyAEText: self.text}, typeAEText) def IsAEText(x): - return isinstance(x, AEText) + return isinstance(x, AEText) class IntlText: - """A text object with script and language specified""" - - def __init__(self, script, language, text): - self.script = script - self.language = language - self.text = text - - def __repr__(self): - return "IntlText(%s, %s, %s)" % (`self.script`, `self.language`, `self.text`) - - def __str__(self): - return self.text - - def __aepack__(self): - return pack(struct.pack('hh', self.script, self.language)+self.text, - typeIntlText) + """A text object with script and language specified""" + + def __init__(self, script, language, text): + self.script = script + self.language = language + self.text = text + + def __repr__(self): + return "IntlText(%s, %s, %s)" % (`self.script`, `self.language`, `self.text`) + + def __str__(self): + return self.text + + def __aepack__(self): + return pack(struct.pack('hh', self.script, self.language)+self.text, + typeIntlText) def IsIntlText(x): - return isinstance(x, IntlText) + return isinstance(x, IntlText) class IntlWritingCode: - """An object representing script and language""" - - def __init__(self, script, language): - self.script = script - self.language = language - - def __repr__(self): - return "IntlWritingCode(%s, %s)" % (`self.script`, `self.language`) - - def __str__(self): - return "script system %d, language %d"%(self.script, self.language) - - def __aepack__(self): - return pack(struct.pack('hh', self.script, self.language), - typeIntlWritingCode) + """An object representing script and language""" + + def __init__(self, script, language): + self.script = script + self.language = language + + def __repr__(self): + return "IntlWritingCode(%s, %s)" % (`self.script`, `self.language`) + + def __str__(self): + return "script system %d, language %d"%(self.script, self.language) + + def __aepack__(self): + return pack(struct.pack('hh', self.script, self.language), + typeIntlWritingCode) def IsIntlWritingCode(x): - return isinstance(x, IntlWritingCode) + return isinstance(x, IntlWritingCode) class QDPoint: - """A point""" - - def __init__(self, v, h): - self.v = v - self.h = h - - def __repr__(self): - return "QDPoint(%s, %s)" % (`self.v`, `self.h`) - - def __str__(self): - return "(%d, %d)"%(self.v, self.h) - - def __aepack__(self): - return pack(struct.pack('hh', self.v, self.h), - typeQDPoint) + """A point""" + + def __init__(self, v, h): + self.v = v + self.h = h + + def __repr__(self): + return "QDPoint(%s, %s)" % (`self.v`, `self.h`) + + def __str__(self): + return "(%d, %d)"%(self.v, self.h) + + def __aepack__(self): + return pack(struct.pack('hh', self.v, self.h), + typeQDPoint) def IsQDPoint(x): - return isinstance(x, QDPoint) + return isinstance(x, QDPoint) class QDRectangle: - """A rectangle""" - - def __init__(self, v0, h0, v1, h1): - self.v0 = v0 - self.h0 = h0 - self.v1 = v1 - self.h1 = h1 - - def __repr__(self): - return "QDRectangle(%s, %s, %s, %s)" % (`self.v0`, `self.h0`, - `self.v1`, `self.h1`) - - def __str__(self): - return "(%d, %d)-(%d, %d)"%(self.v0, self.h0, self.v1, self.h1) - - def __aepack__(self): - return pack(struct.pack('hhhh', self.v0, self.h0, self.v1, self.h1), - typeQDRectangle) + """A rectangle""" + + def __init__(self, v0, h0, v1, h1): + self.v0 = v0 + self.h0 = h0 + self.v1 = v1 + self.h1 = h1 + + def __repr__(self): + return "QDRectangle(%s, %s, %s, %s)" % (`self.v0`, `self.h0`, + `self.v1`, `self.h1`) + + def __str__(self): + return "(%d, %d)-(%d, %d)"%(self.v0, self.h0, self.v1, self.h1) + + def __aepack__(self): + return pack(struct.pack('hhhh', self.v0, self.h0, self.v1, self.h1), + typeQDRectangle) def IsQDRectangle(x): - return isinstance(x, QDRectangle) + return isinstance(x, QDRectangle) class RGBColor: - """An RGB color""" - - def __init__(self, r, g, b): - self.r = r - self.g = g - self.b = b - - def __repr__(self): - return "RGBColor(%s, %s, %s)" % (`self.r`, `self.g`, `self.b`) - - def __str__(self): - return "0x%x red, 0x%x green, 0x%x blue"% (self.r, self.g, self.b) - - def __aepack__(self): - return pack(struct.pack('hhh', self.r, self.g, self.b), - typeRGBColor) + """An RGB color""" + + def __init__(self, r, g, b): + self.r = r + self.g = g + self.b = b + + def __repr__(self): + return "RGBColor(%s, %s, %s)" % (`self.r`, `self.g`, `self.b`) + + def __str__(self): + return "0x%x red, 0x%x green, 0x%x blue"% (self.r, self.g, self.b) + + def __aepack__(self): + return pack(struct.pack('hhh', self.r, self.g, self.b), + typeRGBColor) def IsRGBColor(x): - return isinstance(x, RGBColor) + return isinstance(x, RGBColor) class ObjectSpecifier: - - """A class for constructing and manipulation AE object specifiers in python. - - An object specifier is actually a record with four fields: - - key type description - --- ---- ----------- - - 'want' type 4-char class code of thing we want, - e.g. word, paragraph or property - - 'form' enum how we specify which 'want' thing(s) we want, - e.g. by index, by range, by name, or by property specifier - - 'seld' any which thing(s) we want, - e.g. its index, its name, or its property specifier - - 'from' object the object in which it is contained, - or null, meaning look for it in the application - - Note that we don't call this class plain "Object", since that name - is likely to be used by the application. - """ - - def __init__(self, want, form, seld, fr = None): - self.want = want - self.form = form - self.seld = seld - self.fr = fr - - def __repr__(self): - s = "ObjectSpecifier(%s, %s, %s" % (`self.want`, `self.form`, `self.seld`) - if self.fr: - s = s + ", %s)" % `self.fr` - else: - s = s + ")" - return s - - def __aepack__(self): - return pack({'want': mktype(self.want), - 'form': mkenum(self.form), - 'seld': self.seld, - 'from': self.fr}, - 'obj ') + + """A class for constructing and manipulation AE object specifiers in python. + + An object specifier is actually a record with four fields: + + key type description + --- ---- ----------- + + 'want' type 4-char class code of thing we want, + e.g. word, paragraph or property + + 'form' enum how we specify which 'want' thing(s) we want, + e.g. by index, by range, by name, or by property specifier + + 'seld' any which thing(s) we want, + e.g. its index, its name, or its property specifier + + 'from' object the object in which it is contained, + or null, meaning look for it in the application + + Note that we don't call this class plain "Object", since that name + is likely to be used by the application. + """ + + def __init__(self, want, form, seld, fr = None): + self.want = want + self.form = form + self.seld = seld + self.fr = fr + + def __repr__(self): + s = "ObjectSpecifier(%s, %s, %s" % (`self.want`, `self.form`, `self.seld`) + if self.fr: + s = s + ", %s)" % `self.fr` + else: + s = s + ")" + return s + + def __aepack__(self): + return pack({'want': mktype(self.want), + 'form': mkenum(self.form), + 'seld': self.seld, + 'from': self.fr}, + 'obj ') def IsObjectSpecifier(x): - return isinstance(x, ObjectSpecifier) + return isinstance(x, ObjectSpecifier) # Backwards compatability, sigh... class Property(ObjectSpecifier): - def __init__(self, which, fr = None, want='prop'): - ObjectSpecifier.__init__(self, want, 'prop', mktype(which), fr) + def __init__(self, which, fr = None, want='prop'): + ObjectSpecifier.__init__(self, want, 'prop', mktype(which), fr) - def __repr__(self): - if self.fr: - return "Property(%s, %s)" % (`self.seld.type`, `self.fr`) - else: - return "Property(%s)" % `self.seld.type` - - def __str__(self): - if self.fr: - return "Property %s of %s" % (str(self.seld), str(self.fr)) - else: - return "Property %s" % str(self.seld) + def __repr__(self): + if self.fr: + return "Property(%s, %s)" % (`self.seld.type`, `self.fr`) + else: + return "Property(%s)" % `self.seld.type` + + def __str__(self): + if self.fr: + return "Property %s of %s" % (str(self.seld), str(self.fr)) + else: + return "Property %s" % str(self.seld) class NProperty(ObjectSpecifier): - # Subclasses *must* self baseclass attributes: - # want is the type of this property - # which is the property name of this property + # Subclasses *must* self baseclass attributes: + # want is the type of this property + # which is the property name of this property - def __init__(self, fr = None): - #try: - # dummy = self.want - #except: - # self.want = 'prop' - self.want = 'prop' - ObjectSpecifier.__init__(self, self.want, 'prop', - mktype(self.which), fr) + def __init__(self, fr = None): + #try: + # dummy = self.want + #except: + # self.want = 'prop' + self.want = 'prop' + ObjectSpecifier.__init__(self, self.want, 'prop', + mktype(self.which), fr) - def __repr__(self): - rv = "Property(%s"%`self.seld.type` - if self.fr: - rv = rv + ", fr=%s" % `self.fr` - if self.want != 'prop': - rv = rv + ", want=%s" % `self.want` - return rv + ")" - - def __str__(self): - if self.fr: - return "Property %s of %s" % (str(self.seld), str(self.fr)) - else: - return "Property %s" % str(self.seld) + def __repr__(self): + rv = "Property(%s"%`self.seld.type` + if self.fr: + rv = rv + ", fr=%s" % `self.fr` + if self.want != 'prop': + rv = rv + ", want=%s" % `self.want` + return rv + ")" + + def __str__(self): + if self.fr: + return "Property %s of %s" % (str(self.seld), str(self.fr)) + else: + return "Property %s" % str(self.seld) class SelectableItem(ObjectSpecifier): - - def __init__(self, want, seld, fr = None): - t = type(seld) - if t == StringType: - form = 'name' - elif IsRange(seld): - form = 'rang' - elif IsComparison(seld) or IsLogical(seld): - form = 'test' - elif t == TupleType: - # Breakout: specify both form and seld in a tuple - # (if you want ID or rele or somesuch) - form, seld = seld - else: - form = 'indx' - ObjectSpecifier.__init__(self, want, form, seld, fr) + + def __init__(self, want, seld, fr = None): + t = type(seld) + if t == StringType: + form = 'name' + elif IsRange(seld): + form = 'rang' + elif IsComparison(seld) or IsLogical(seld): + form = 'test' + elif t == TupleType: + # Breakout: specify both form and seld in a tuple + # (if you want ID or rele or somesuch) + form, seld = seld + else: + form = 'indx' + ObjectSpecifier.__init__(self, want, form, seld, fr) class ComponentItem(SelectableItem): - # Derived classes *must* set the *class attribute* 'want' to some constant - # Also, dictionaries _propdict and _elemdict must be set to map property - # and element names to the correct classes + # Derived classes *must* set the *class attribute* 'want' to some constant + # Also, dictionaries _propdict and _elemdict must be set to map property + # and element names to the correct classes - _propdict = {} - _elemdict = {} - def __init__(self, which, fr = None): - SelectableItem.__init__(self, self.want, which, fr) - - def __repr__(self): - if not self.fr: - return "%s(%s)" % (self.__class__.__name__, `self.seld`) - return "%s(%s, %s)" % (self.__class__.__name__, `self.seld`, `self.fr`) - - def __str__(self): - seld = self.seld - if type(seld) == StringType: - ss = repr(seld) - elif IsRange(seld): - start, stop = seld.start, seld.stop - if type(start) == InstanceType == type(stop) and \ - start.__class__ == self.__class__ == stop.__class__: - ss = str(start.seld) + " thru " + str(stop.seld) - else: - ss = str(seld) - else: - ss = str(seld) - s = "%s %s" % (self.__class__.__name__, ss) - if self.fr: s = s + " of %s" % str(self.fr) - return s - - def __getattr__(self, name): - if self._elemdict.has_key(name): - cls = self._elemdict[name] - return DelayedComponentItem(cls, self) - if self._propdict.has_key(name): - cls = self._propdict[name] - return cls(self) - raise AttributeError, name - - + _propdict = {} + _elemdict = {} + def __init__(self, which, fr = None): + SelectableItem.__init__(self, self.want, which, fr) + + def __repr__(self): + if not self.fr: + return "%s(%s)" % (self.__class__.__name__, `self.seld`) + return "%s(%s, %s)" % (self.__class__.__name__, `self.seld`, `self.fr`) + + def __str__(self): + seld = self.seld + if type(seld) == StringType: + ss = repr(seld) + elif IsRange(seld): + start, stop = seld.start, seld.stop + if type(start) == InstanceType == type(stop) and \ + start.__class__ == self.__class__ == stop.__class__: + ss = str(start.seld) + " thru " + str(stop.seld) + else: + ss = str(seld) + else: + ss = str(seld) + s = "%s %s" % (self.__class__.__name__, ss) + if self.fr: s = s + " of %s" % str(self.fr) + return s + + def __getattr__(self, name): + if self._elemdict.has_key(name): + cls = self._elemdict[name] + return DelayedComponentItem(cls, self) + if self._propdict.has_key(name): + cls = self._propdict[name] + return cls(self) + raise AttributeError, name + + class DelayedComponentItem: - def __init__(self, compclass, fr): - self.compclass = compclass - self.fr = fr - - def __call__(self, which): - return self.compclass(which, self.fr) - - def __repr__(self): - return "%s(???, %s)" % (self.__class__.__name__, `self.fr`) - - def __str__(self): - return "selector for element %s of %s"%(self.__class__.__name__, str(self.fr)) + def __init__(self, compclass, fr): + self.compclass = compclass + self.fr = fr + + def __call__(self, which): + return self.compclass(which, self.fr) + + def __repr__(self): + return "%s(???, %s)" % (self.__class__.__name__, `self.fr`) + + def __str__(self): + return "selector for element %s of %s"%(self.__class__.__name__, str(self.fr)) template = """ class %s(ComponentItem): want = '%s' diff --git a/Lib/plat-mac/applesingle.py b/Lib/plat-mac/applesingle.py index f8be3d28e1a..5b9c2dddd52 100644 --- a/Lib/plat-mac/applesingle.py +++ b/Lib/plat-mac/applesingle.py @@ -24,77 +24,77 @@ AS_RESOURCEFORK=2 AS_IGNORE=(3,4,5,6,8,9,10,11,12,13,14,15) def decode(input, output, resonly=0): - if type(input) == type(''): - input = open(input, 'rb') - # Should we also test for FSSpecs or FSRefs? - header = input.read(AS_HEADER_LENGTH) - try: - magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) - except ValueError, arg: - raise Error, "Unpack header error: %s"%arg - if verbose: - print 'Magic: 0x%8.8x'%magic - print 'Version: 0x%8.8x'%version - print 'Entries: %d'%nentry - if magic != AS_MAGIC: - raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic - if version != AS_VERSION: - raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version - if nentry <= 0: - raise Error, "AppleSingle file contains no forks" - headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] - didwork = 0 - for hdr in headers: - try: - id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) - except ValueError, arg: - raise Error, "Unpack entry error: %s"%arg - if verbose: - print 'Fork %d, offset %d, length %d'%(id, offset, length) - input.seek(offset) - if length == 0: - data = '' - else: - data = input.read(length) - if len(data) != length: - raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) - if id == AS_DATAFORK: - if verbose: - print ' (data fork)' - if not resonly: - didwork = 1 - fp = open(output, 'wb') - fp.write(data) - fp.close() - elif id == AS_RESOURCEFORK: - didwork = 1 - if verbose: - print ' (resource fork)' - if resonly: - fp = open(output, 'wb') - else: - fp = MacOS.openrf(output, 'wb') - fp.write(data) - fp.close() - elif id in AS_IGNORE: - if verbose: - print ' (ignored)' - else: - raise Error, 'Unknown fork type %d'%id - if not didwork: - raise Error, 'No useful forks found' + if type(input) == type(''): + input = open(input, 'rb') + # Should we also test for FSSpecs or FSRefs? + header = input.read(AS_HEADER_LENGTH) + try: + magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) + except ValueError, arg: + raise Error, "Unpack header error: %s"%arg + if verbose: + print 'Magic: 0x%8.8x'%magic + print 'Version: 0x%8.8x'%version + print 'Entries: %d'%nentry + if magic != AS_MAGIC: + raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic + if version != AS_VERSION: + raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version + if nentry <= 0: + raise Error, "AppleSingle file contains no forks" + headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] + didwork = 0 + for hdr in headers: + try: + id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) + except ValueError, arg: + raise Error, "Unpack entry error: %s"%arg + if verbose: + print 'Fork %d, offset %d, length %d'%(id, offset, length) + input.seek(offset) + if length == 0: + data = '' + else: + data = input.read(length) + if len(data) != length: + raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) + if id == AS_DATAFORK: + if verbose: + print ' (data fork)' + if not resonly: + didwork = 1 + fp = open(output, 'wb') + fp.write(data) + fp.close() + elif id == AS_RESOURCEFORK: + didwork = 1 + if verbose: + print ' (resource fork)' + if resonly: + fp = open(output, 'wb') + else: + fp = MacOS.openrf(output, 'wb') + fp.write(data) + fp.close() + elif id in AS_IGNORE: + if verbose: + print ' (ignored)' + else: + raise Error, 'Unknown fork type %d'%id + if not didwork: + raise Error, 'No useful forks found' def _test(): - if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4: - print 'Usage: applesingle.py [-r] applesinglefile decodedfile' - sys.exit(1) - if sys.argv[1] == '-r': - resonly = 1 - del sys.argv[1] - else: - resonly = 0 - decode(sys.argv[1], sys.argv[2], resonly=resonly) - + if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4: + print 'Usage: applesingle.py [-r] applesinglefile decodedfile' + sys.exit(1) + if sys.argv[1] == '-r': + resonly = 1 + del sys.argv[1] + else: + resonly = 0 + decode(sys.argv[1], sys.argv[2], resonly=resonly) + if __name__ == '__main__': - _test() - \ No newline at end of file + _test() + \ No newline at end of file diff --git a/Lib/plat-mac/appletrawmain.py b/Lib/plat-mac/appletrawmain.py index 4771f3cc14d..88259c1b3ae 100644 --- a/Lib/plat-mac/appletrawmain.py +++ b/Lib/plat-mac/appletrawmain.py @@ -14,13 +14,13 @@ import marshal # 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__') + # 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] + _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 @@ -36,28 +36,28 @@ argvemulator.ArgvCollector().mainloop() # __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__) + # + # 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) + __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) diff --git a/Lib/plat-mac/appletrunner.py b/Lib/plat-mac/appletrunner.py index adda7b19880..8d46c2ad276 100755 --- a/Lib/plat-mac/appletrunner.py +++ b/Lib/plat-mac/appletrunner.py @@ -6,12 +6,12 @@ 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 + 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.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) diff --git a/Lib/plat-mac/bgenlocations.py b/Lib/plat-mac/bgenlocations.py index 896861ebc70..418037dabed 100644 --- a/Lib/plat-mac/bgenlocations.py +++ b/Lib/plat-mac/bgenlocations.py @@ -12,12 +12,12 @@ Error = "bgenlocations.Error" # Where bgen is. For unix-Python bgen isn't installed, so you have to refer to # the source tree here. if sys.platform == 'mac': - # For MacPython we know where it is - def _pardir(p): return os.path.split(p)[0] - BGENDIR=os.path.join(sys.prefix, "Tools", "bgen", "bgen") + # For MacPython we know where it is + def _pardir(p): return os.path.split(p)[0] + BGENDIR=os.path.join(sys.prefix, "Tools", "bgen", "bgen") else: - # for unix-Python we don't know, please set it yourself. - BGENDIR="/Users/jack/src/python/Tools/bgen/bgen" + # for unix-Python we don't know, please set it yourself. + BGENDIR="/Users/jack/src/python/Tools/bgen/bgen" # # Where to find the Universal Header include files. If you have CodeWarrior @@ -26,9 +26,9 @@ else: # end of lines, so don't worry about that. # if sys.platform == 'mac': - _MWERKSDIR="Sap:Applications (Mac OS 9):Metrowerks CodeWarrior 7.0:Metrowerks CodeWarrior" + _MWERKSDIR="Sap:Applications (Mac OS 9):Metrowerks CodeWarrior 7.0:Metrowerks CodeWarrior" else: - _MWERKSDIR="/Volumes/Sap/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/" + _MWERKSDIR="/Volumes/Sap/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/" INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces", "CIncludes") # @@ -37,25 +37,25 @@ INCLUDEDIR=os.path.join(_MWERKSDIR, "MacOS Support", "Universal", "Interfaces", # your source directory, not your installed directory. # if sys.platform == 'mac': - TOOLBOXDIR=os.path.join(sys.prefix, "Lib", "plat-mac", "Carbon") + TOOLBOXDIR=os.path.join(sys.prefix, "Lib", "plat-mac", "Carbon") else: - TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon" + TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon" # Creator for C files: CREATOR="CWIE" if not os.path.exists(BGENDIR): - raise Error, "Please fix bgenlocations.py, BGENDIR does not exist: %s" % 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 + 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 - + 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 + BGENDIR = BGENDIR + os.sep if INCLUDEDIR[-1] != os.sep: - INCLUDEDIR = INCLUDEDIR + os.sep + INCLUDEDIR = INCLUDEDIR + os.sep if TOOLBOXDIR[-1] != os.sep: - TOOLBOXDIR = TOOLBOXDIR + os.sep - + TOOLBOXDIR = TOOLBOXDIR + os.sep + diff --git a/Lib/plat-mac/buildtools.py b/Lib/plat-mac/buildtools.py index 56f23a47d1e..6e6396d35c0 100644 --- a/Lib/plat-mac/buildtools.py +++ b/Lib/plat-mac/buildtools.py @@ -42,375 +42,375 @@ WRITE = 2 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 %s not found on sys.path" % `template` - file = file.as_pathname() - return file - + """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 %s 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"): - - 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) - + rsrcname=None, others=[], raw=0, progress="default"): + + 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) + 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) + 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): - if MacOS.runtimemodel == 'macho': - return process_common_macho(template, progress, code, rsrcname, destname, - is_update, raw, others, filename) - 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) + copy_codefragment, raw=0, others=[], filename=None): + if MacOS.runtimemodel == 'macho': + return process_common_macho(template, progress, code, rsrcname, destname, + is_update, raw, others, filename) + 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) + 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): - # 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 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 - 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) + raw=0, others=[], filename=None): + # 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 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 + 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) + 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 + 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) - + 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() + 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() diff --git a/Lib/plat-mac/bundlebuilder.py b/Lib/plat-mac/bundlebuilder.py index 28ccbd7924d..26c38865d64 100755 --- a/Lib/plat-mac/bundlebuilder.py +++ b/Lib/plat-mac/bundlebuilder.py @@ -42,173 +42,173 @@ 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. - """ + """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 __init__(self, **kwargs): + defaults = self._getDefaults() + defaults.update(kwargs) + self.__dict__.update(defaults) - def _getDefaults(cls): - defaults = {} - for name, value in cls.__dict__.items(): - if name[0] != "_" and not isinstance(value, - (function, classmethod)): - defaults[name] = deepcopy(value) - for base in cls.__bases__: - if hasattr(base, "_getDefaults"): - defaults.update(base._getDefaults()) - return defaults - _getDefaults = classmethod(_getDefaults) + def _getDefaults(cls): + defaults = {} + for name, value in cls.__dict__.items(): + if name[0] != "_" and not isinstance(value, + (function, classmethod)): + defaults[name] = deepcopy(value) + for base in cls.__bases__: + if hasattr(base, "_getDefaults"): + defaults.update(base._getDefaults()) + 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. - """ + """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.) + # (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 + # Name of the bundle, with or without extension. + name = None - # The property list ("plist") - plist = Plist(CFBundleDevelopmentRegion = "English", - CFBundleInfoDictionaryVersion = "6.0") + # 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 type of the bundle. + type = "BNDL" + # The creator code of the bundle. + creator = None - # List of files that have to be copied to /Contents/Resources. - resources = [] + # List of files that have to be copied to /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 (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 = [] + # 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" + # 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 + # Make symlinks instead copying files. This is handy during debugging, but + # makes the bundle non-distributable. + symlink = 0 - # Verbosity level. - verbosity = 1 + # Verbosity level. + verbosity = 1 - 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) + 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 not hasattr(plist, "CFBundleIdentifier"): - plist.CFBundleIdentifier = self.name + 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 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 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 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 _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 _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 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 + def report(self): + # XXX something decent + pass if __debug__: - PYC_EXT = ".pyc" + PYC_EXT = ".pyc" else: - PYC_EXT = ".pyo" + PYC_EXT = ".pyo" MAGIC = imp.get_magic() USE_ZIPIMPORT = "zipimport" in sys.builtin_module_names @@ -221,13 +221,13 @@ 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) + 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) SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec") @@ -237,22 +237,22 @@ SITE_CO = compile(SITE_PY, "<-bundlebuilder.py->", "exec") # 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) + 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' + 'win32api', 'ce', '_winreg', 'nturl2path', 'sitecustomize', + 'org.python.core', 'riscos', 'riscosenviron', 'riscospath' ] STRIP_EXEC = "/usr/bin/strip" @@ -281,7 +281,7 @@ mainprogram = os.path.join(resdir, "%(mainprogram)s") sys.argv.insert(1, mainprogram) os.environ["PYTHONPATH"] = resdir if %(standalone)s: - os.environ["PYTHONHOME"] = resdir + os.environ["PYTHONHOME"] = resdir os.environ["PYTHONEXECUTABLE"] = executable os.environ["DYLD_LIBRARY_PATH"] = libdir os.execve(executable, sys.argv, os.environ) @@ -301,312 +301,312 @@ execfile(os.path.join(os.path.split(__file__)[0], "%(realmainprogram)s")) class AppBuilder(BundleBuilder): - # Override type of the bundle. - type = "APPL" + # Override type of the bundle. + type = "APPL" - # platform, name of the subfolder of Contents that contains the executable. - platform = "MacOS" + # 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 + # 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 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 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 + # 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 + # Symlink the executable instead of copying it. + symlink_exec = 0 - # If True, build standalone app. - standalone = 0 - - # If True, add a real main program that emulates sys.argv before calling - # mainprogram - argv_emulation = 0 + # If True, build standalone app. + standalone = 0 + + # 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. + # The following attributes are only used when building a standalone app. - # Exclude these modules. - excludeModules = [] + # Exclude these modules. + excludeModules = [] - # Include these modules. - includeModules = [] + # Include these modules. + includeModules = [] - # Include these packages. - includePackages = [] + # Include these packages. + includePackages = [] - # Strip binaries. - strip = 0 + # Strip binaries. + strip = 0 - # Found Python modules: [(name, codeobject, ispkg), ...] - pymodules = [] + # Found Python modules: [(name, codeobject, ispkg), ...] + pymodules = [] - # Modules that modulefinder couldn't find: - missingModules = [] - maybeMissingModules = [] + # Modules that modulefinder couldn't find: + missingModules = [] + maybeMissingModules = [] - # List of all binaries (executables or shared libs), for stripping purposes - binaries = [] + # List of all binaries (executables or shared libs), for stripping purposes + binaries = [] - def setup(self): - if self.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'") + def setup(self): + if self.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) + 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.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: - self.symlink_exec = 1 - self.executable = sys.executable + if self.executable is None: + if not self.standalone: + self.symlink_exec = 1 + self.executable = sys.executable - if self.nibname: - self.plist.NSMainNibFile = self.nibname - if not hasattr(self.plist, "NSPrincipalClass"): - self.plist.NSPrincipalClass = "NSApplication" + if self.nibname: + self.plist.NSMainNibFile = self.nibname + if not hasattr(self.plist, "NSPrincipalClass"): + self.plist.NSPrincipalClass = "NSApplication" - BundleBuilder.setup(self) + BundleBuilder.setup(self) - self.plist.CFBundleExecutable = self.name + self.plist.CFBundleExecutable = self.name - if self.standalone: - self.findDependencies() + if self.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.executable, execpath)) - self.binaries.append(execpath) - self.execpath = execpath + 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.executable, execpath)) + self.binaries.append(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: - 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: - # XXX we're screwed when the end user has deleted - # /usr/bin/python - hashbang = "/usr/bin/python" - else: - hashbang = os.path.realpath(sys.executable) - standalone = self.standalone - open(bootstrappath, "w").write(BOOTSTRAP_SCRIPT % locals()) - os.chmod(bootstrappath, 0775) + 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: + 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: + # XXX we're screwed when the end user has deleted + # /usr/bin/python + hashbang = "/usr/bin/python" + else: + hashbang = os.path.realpath(sys.executable) + standalone = self.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))) + 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: - self.addPythonModules() - if self.strip and not self.symlink: - self.stripBinaries() + def postProcess(self): + if self.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.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() + if self.missingModules or self.maybeMissingModules: + self.reportMissing() - def addPythonModules(self): - self.message("Adding Python modules", 1) + 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(SITE_CO, 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 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(SITE_CO, 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) + 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) + 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: - self.message("Stripping binaries", 1) - for relpath in self.binaries: - self.message("Stripping %s" % relpath, 2) - abspath = pathjoin(self.bundlepath, relpath) - assert not os.path.islink(abspath) - rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, 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: + self.message("Stripping binaries", 1) + for relpath in self.binaries: + self.message("Stripping %s" % relpath, 2) + abspath = pathjoin(self.bundlepath, relpath) + assert not os.path.islink(abspath) + rv = os.system("%s -S \"%s\"" % (STRIP_EXEC, abspath)) - 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__ = SITE_CO - mf.scan_code(SITE_CO, site) + 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__ = SITE_CO + mf.scan_code(SITE_CO, site) - # warnings.py gets imported implicitly from C - mf.import_hook("warnings") + # 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) + 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: - if mod.__file__ and mod.__code__ is None: - # C extension - path = mod.__file__ - filename = os.path.basename(path) - if USE_ZIPIMPORT: - # Python modules are stored in a Zip archive, but put - # extensions in Contents/Resources/.a and add a tiny "loader" - # program in the Zip archive. Due to Thomas Heller. - dstpath = pathjoin("Contents", "Resources", filename) - source = EXT_LOADER % {"name": name, "filename": filename} - code = compile(source, "" % name, "exec") - mod.__code__ = code - else: - # just copy the file - dstpath = name.split(".")[:-1] + [filename] - dstpath = pathjoin("Contents", "Resources", *dstpath) - self.files.append((path, dstpath)) - self.binaries.append(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)) + mf.run_script(self.mainprogram) + modules = mf.modules.items() + modules.sort() + for name, mod in modules: + if mod.__file__ and mod.__code__ is None: + # C extension + path = mod.__file__ + filename = os.path.basename(path) + if USE_ZIPIMPORT: + # Python modules are stored in a Zip archive, but put + # extensions in Contents/Resources/.a and add a tiny "loader" + # program in the Zip archive. Due to Thomas Heller. + dstpath = pathjoin("Contents", "Resources", filename) + source = EXT_LOADER % {"name": name, "filename": filename} + code = compile(source, "" % name, "exec") + mod.__code__ = code + else: + # just copy the file + dstpath = name.split(".")[:-1] + [filename] + dstpath = pathjoin("Contents", "Resources", *dstpath) + self.files.append((path, dstpath)) + self.binaries.append(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) + 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 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: - self.reportMissing() + def report(self): + # XXX something decent + import pprint + pprint.pprint(self.__dict__) + if self.standalone: + self.reportMissing() # # Utilities. @@ -616,67 +616,67 @@ 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 + 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() + 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) - else: - shutil.copy2(src, dst) + """Copy a file or a directory.""" + if mkdirs: + makedirs(os.path.dirname(dst)) + if os.path.isdir(src): + shutil.copytree(src, dst) + 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) + """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 + """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) + """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) + """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 = """\ @@ -718,97 +718,97 @@ Options: """ def usage(msg=None): - if msg: - print msg - print cmdline_doc - sys.exit(1) + if msg: + print msg + print cmdline_doc + sys.exit(1) def main(builder=None): - if builder is None: - builder = AppBuilder(verbosity=1) + 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=") + 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=") - try: - options, args = getopt.getopt(sys.argv[1:], shortopts, longopts) - except getopt.error: - usage() + 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(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 == '--iconfile': - builder.iconfile = arg - elif opt == "--lib": - builder.libs.append(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 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 + 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(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 == '--iconfile': + builder.iconfile = arg + elif opt == "--lib": + builder.libs.append(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 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 - if len(args) != 1: - usage("Must specify one command ('build', 'report' or 'help')") - command = args[0] + 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) + 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) + builder = AppBuilder(**kwargs) + main(builder) if __name__ == "__main__": - main() + main() diff --git a/Lib/plat-mac/cfmfile.py b/Lib/plat-mac/cfmfile.py index a4eecf23be8..317046a89b3 100644 --- a/Lib/plat-mac/cfmfile.py +++ b/Lib/plat-mac/cfmfile.py @@ -18,167 +18,167 @@ 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) + """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) + + 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() + + 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() diff --git a/Lib/plat-mac/findertools.py b/Lib/plat-mac/findertools.py index 5add05f1f43..b3223bd6ab0 100644 --- a/Lib/plat-mac/findertools.py +++ b/Lib/plat-mac/findertools.py @@ -30,803 +30,803 @@ Error = 'findertools.Error' _finder_talker = None def _getfinder(): - """returns basic (recyclable) Finder AE interface object""" - global _finder_talker - if not _finder_talker: - _finder_talker = Finder.Finder() - _finder_talker.send_flags = ( _finder_talker.send_flags | - AppleEvents.kAECanInteract | AppleEvents.kAECanSwitchLayer) - return _finder_talker - + """returns basic (recyclable) Finder AE interface object""" + global _finder_talker + if not _finder_talker: + _finder_talker = Finder.Finder() + _finder_talker.send_flags = ( _finder_talker.send_flags | + AppleEvents.kAECanInteract | AppleEvents.kAECanSwitchLayer) + return _finder_talker + def launch(file): - """Open a file thru the finder. Specify file by name or fsspec""" - finder = _getfinder() - fss = Carbon.File.FSSpec(file) - return finder.open(fss) - + """Open a file thru the finder. Specify file by name or fsspec""" + finder = _getfinder() + fss = Carbon.File.FSSpec(file) + return finder.open(fss) + def Print(file): - """Print a file thru the finder. Specify file by name or fsspec""" - finder = _getfinder() - fss = Carbon.File.FSSpec(file) - return finder._print(fss) - + """Print a file thru the finder. Specify file by name or fsspec""" + finder = _getfinder() + fss = Carbon.File.FSSpec(file) + return finder._print(fss) + def copy(src, dstdir): - """Copy a file to a folder""" - finder = _getfinder() - if type(src) == type([]): - src_fss = [] - for s in src: - src_fss.append(Carbon.File.FSSpec(s)) - else: - src_fss = Carbon.File.FSSpec(src) - dst_fss = Carbon.File.FSSpec(dstdir) - return finder.duplicate(src_fss, to=dst_fss) + """Copy a file to a folder""" + finder = _getfinder() + if type(src) == type([]): + src_fss = [] + for s in src: + src_fss.append(Carbon.File.FSSpec(s)) + else: + src_fss = Carbon.File.FSSpec(src) + dst_fss = Carbon.File.FSSpec(dstdir) + return finder.duplicate(src_fss, to=dst_fss) def move(src, dstdir): - """Move a file to a folder""" - finder = _getfinder() - if type(src) == type([]): - src_fss = [] - for s in src: - src_fss.append(Carbon.File.FSSpec(s)) - else: - src_fss = Carbon.File.FSSpec(src) - dst_fss = Carbon.File.FSSpec(dstdir) - return finder.move(src_fss, to=dst_fss) - + """Move a file to a folder""" + finder = _getfinder() + if type(src) == type([]): + src_fss = [] + for s in src: + src_fss.append(Carbon.File.FSSpec(s)) + else: + src_fss = Carbon.File.FSSpec(src) + dst_fss = Carbon.File.FSSpec(dstdir) + return finder.move(src_fss, to=dst_fss) + def sleep(): - """Put the mac to sleep""" - finder = _getfinder() - finder.sleep() - + """Put the mac to sleep""" + finder = _getfinder() + finder.sleep() + def shutdown(): - """Shut the mac down""" - finder = _getfinder() - finder.shut_down() - + """Shut the mac down""" + finder = _getfinder() + finder.shut_down() + def restart(): - """Restart the mac""" - finder = _getfinder() - finder.restart() + """Restart the mac""" + finder = _getfinder() + finder.restart() #--------------------------------------------------- -# Additional findertools +# Additional findertools # def reveal(file): - """Reveal a file in the finder. Specify file by name, fsref or fsspec.""" - finder = _getfinder() - fsr = Carbon.File.FSRef(file) - file_alias = fsr.FSNewAliasMinimal() - return finder.reveal(file_alias) - + """Reveal a file in the finder. Specify file by name, fsref or fsspec.""" + finder = _getfinder() + fsr = Carbon.File.FSRef(file) + file_alias = fsr.FSNewAliasMinimal() + return finder.reveal(file_alias) + def select(file): - """select a file in the finder. Specify file by name, fsref or fsspec.""" - finder = _getfinder() - fsr = Carbon.File.FSRef(file) - file_alias = fsr.FSNewAliasMinimal() - return finder.select(file_alias) - + """select a file in the finder. Specify file by name, fsref or fsspec.""" + finder = _getfinder() + fsr = Carbon.File.FSRef(file) + file_alias = fsr.FSNewAliasMinimal() + return finder.select(file_alias) + def update(file): - """Update the display of the specified object(s) to match - their on-disk representation. Specify file by name, fsref or fsspec.""" - finder = _getfinder() - fsr = Carbon.File.FSRef(file) - file_alias = fsr.FSNewAliasMinimal() - return finder.update(file_alias) + """Update the display of the specified object(s) to match + their on-disk representation. Specify file by name, fsref or fsspec.""" + finder = _getfinder() + fsr = Carbon.File.FSRef(file) + file_alias = fsr.FSNewAliasMinimal() + return finder.update(file_alias) #--------------------------------------------------- -# More findertools +# More findertools # def comment(object, comment=None): - """comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window.""" - object = Carbon.File.FSRef(object) - object_alias = object.FSNewAliasMonimal() - if comment == None: - return _getcomment(object_alias) - else: - return _setcomment(object_alias, comment) - + """comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window.""" + object = Carbon.File.FSRef(object) + object_alias = object.FSNewAliasMonimal() + if comment == None: + return _getcomment(object_alias) + else: + return _setcomment(object_alias, comment) + def _setcomment(object_alias, comment): - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('comt'), fr=aeobj_00) - args['----'] = aeobj_01 - args["data"] = comment - _reply, args, attrs = finder.send("core", "setd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('comt'), fr=aeobj_00) + args['----'] = aeobj_01 + args["data"] = comment + _reply, args, attrs = finder.send("core", "setd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def _getcomment(object_alias): - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('comt'), fr=aeobj_00) - args['----'] = aeobj_01 - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('comt'), fr=aeobj_00) + args['----'] = aeobj_01 + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] #--------------------------------------------------- -# Get information about current processes in the Finder. +# Get information about current processes in the Finder. def processes(): - """processes returns a list of all active processes running on this computer and their creators.""" - finder = _getfinder() - args = {} - attrs = {} - processnames = [] - processnumbers = [] - creators = [] - partitions = [] - used = [] - ## get the processnames or else the processnumbers - args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None) - _reply, args, attrs = finder.send('core', 'getd', args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - p = [] - if args.has_key('----'): - p = args['----'] - for proc in p: - if hasattr(proc, 'seld'): - # it has a real name - processnames.append(proc.seld) - elif hasattr(proc, 'type'): - if proc.type == "psn ": - # it has a process number - processnumbers.append(proc.data) - ## get the creators - args = {} - attrs = {} - aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None) - args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fcrt'), fr=aeobj_0) - _reply, args, attrs = finder.send('core', 'getd', args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(_arg) - if args.has_key('----'): - p = args['----'] - creators = p[:] - ## concatenate in one dict - result = [] - if len(processnames) > len(processnumbers): - data = processnames - else: - data = processnumbers - for i in range(len(creators)): - result.append((data[i], creators[i])) - return result + """processes returns a list of all active processes running on this computer and their creators.""" + finder = _getfinder() + args = {} + attrs = {} + processnames = [] + processnumbers = [] + creators = [] + partitions = [] + used = [] + ## get the processnames or else the processnumbers + args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None) + _reply, args, attrs = finder.send('core', 'getd', args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + p = [] + if args.has_key('----'): + p = args['----'] + for proc in p: + if hasattr(proc, 'seld'): + # it has a real name + processnames.append(proc.seld) + elif hasattr(proc, 'type'): + if proc.type == "psn ": + # it has a process number + processnumbers.append(proc.data) + ## get the creators + args = {} + attrs = {} + aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None) + args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fcrt'), fr=aeobj_0) + _reply, args, attrs = finder.send('core', 'getd', args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(_arg) + if args.has_key('----'): + p = args['----'] + creators = p[:] + ## concatenate in one dict + result = [] + if len(processnames) > len(processnumbers): + data = processnames + else: + data = processnumbers + for i in range(len(creators)): + result.append((data[i], creators[i])) + return result class _process: - pass + pass def isactiveprocess(processname): - """Check of processname is active. MacOS9""" - all = processes() - ok = 0 - for n, c in all: - if n == processname: - return 1 - return 0 - + """Check of processname is active. MacOS9""" + all = processes() + ok = 0 + for n, c in all: + if n == processname: + return 1 + return 0 + def processinfo(processname): - """Return an object with all process properties as attributes for processname. MacOS9""" - p = _process() - - if processname == "Finder": - p.partition = None - p.used = None - else: - p.partition = _processproperty(processname, 'appt') - p.used = _processproperty(processname, 'pusd') - p.visible = _processproperty(processname, 'pvis') #Is the process' layer visible? - p.frontmost = _processproperty(processname, 'pisf') #Is the process the frontmost process? - p.file = _processproperty(processname, 'file') #the file from which the process was launched - p.filetype = _processproperty(processname, 'asty') #the OSType of the file type of the process - p.creatortype = _processproperty(processname, 'fcrt') #the OSType of the creator of the process (the signature) - p.accepthighlevel = _processproperty(processname, 'revt') #Is the process high-level event aware (accepts open application, open document, print document, and quit)? - p.hasscripting = _processproperty(processname, 'hscr') #Does the process have a scripting terminology, i.e., can it be scripted? - return p - + """Return an object with all process properties as attributes for processname. MacOS9""" + p = _process() + + if processname == "Finder": + p.partition = None + p.used = None + else: + p.partition = _processproperty(processname, 'appt') + p.used = _processproperty(processname, 'pusd') + p.visible = _processproperty(processname, 'pvis') #Is the process' layer visible? + p.frontmost = _processproperty(processname, 'pisf') #Is the process the frontmost process? + p.file = _processproperty(processname, 'file') #the file from which the process was launched + p.filetype = _processproperty(processname, 'asty') #the OSType of the file type of the process + p.creatortype = _processproperty(processname, 'fcrt') #the OSType of the creator of the process (the signature) + p.accepthighlevel = _processproperty(processname, 'revt') #Is the process high-level event aware (accepts open application, open document, print document, and quit)? + p.hasscripting = _processproperty(processname, 'hscr') #Does the process have a scripting terminology, i.e., can it be scripted? + return p + def _processproperty(processname, property): - """return the partition size and memory used for processname""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="name", seld=processname, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type(property), fr=aeobj_00) - args['----'] = aeobj_01 - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """return the partition size and memory used for processname""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="name", seld=processname, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type(property), fr=aeobj_00) + args['----'] = aeobj_01 + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] #--------------------------------------------------- -# Mess around with Finder windows. - +# Mess around with Finder windows. + def openwindow(object): - """Open a Finder window for object, Specify object by name or fsspec.""" - finder = _getfinder() - object = Carbon.File.FSRef(object) - object_alias = object.FSNewAliasMinimal() - args = {} - attrs = {} - _code = 'aevt' - _subcode = 'odoc' - aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) - args['----'] = aeobj_0 - _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - + """Open a Finder window for object, Specify object by name or fsspec.""" + finder = _getfinder() + object = Carbon.File.FSRef(object) + object_alias = object.FSNewAliasMinimal() + args = {} + attrs = {} + _code = 'aevt' + _subcode = 'odoc' + aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) + args['----'] = aeobj_0 + _reply, args, attrs = finder.send(_code, _subcode, args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + def closewindow(object): - """Close a Finder window for folder, Specify by path.""" - finder = _getfinder() - object = Carbon.File.FSRef(object) - object_alias = object.FSNewAliasMinimal() - args = {} - attrs = {} - _code = 'core' - _subcode = 'clos' - aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) - args['----'] = aeobj_0 - _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) + """Close a Finder window for folder, Specify by path.""" + finder = _getfinder() + object = Carbon.File.FSRef(object) + object_alias = object.FSNewAliasMinimal() + args = {} + attrs = {} + _code = 'core' + _subcode = 'clos' + aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) + args['----'] = aeobj_0 + _reply, args, attrs = finder.send(_code, _subcode, args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) def location(object, pos=None): - """Set the position of a Finder window for folder to pos=(w, h). Specify file by name or fsspec. - If pos=None, location will return the current position of the object.""" - object = Carbon.File.FSRef(object) - object_alias = object.FSNewAliasMinimal() - if not pos: - return _getlocation(object_alias) - return _setlocation(object_alias, pos) - + """Set the position of a Finder window for folder to pos=(w, h). Specify file by name or fsspec. + If pos=None, location will return the current position of the object.""" + object = Carbon.File.FSRef(object) + object_alias = object.FSNewAliasMinimal() + if not pos: + return _getlocation(object_alias) + return _setlocation(object_alias, pos) + def _setlocation(object_alias, (x, y)): - """_setlocation: Set the location of the icon for the object.""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('posn'), fr=aeobj_00) - args['----'] = aeobj_01 - args["data"] = [x, y] - _reply, args, attrs = finder.send("core", "setd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - return (x,y) - + """_setlocation: Set the location of the icon for the object.""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('posn'), fr=aeobj_00) + args['----'] = aeobj_01 + args["data"] = [x, y] + _reply, args, attrs = finder.send("core", "setd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + return (x,y) + def _getlocation(object_alias): - """_getlocation: get the location of the icon for the object.""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('posn'), fr=aeobj_00) - args['----'] = aeobj_01 - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - pos = args['----'] - return pos.h, pos.v + """_getlocation: get the location of the icon for the object.""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('posn'), fr=aeobj_00) + args['----'] = aeobj_01 + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + pos = args['----'] + return pos.h, pos.v def label(object, index=None): - """label: set or get the label of the item. Specify file by name or fsspec.""" - object = Carbon.File.FSRef(object) - object_alias = object.FSNewAliasMinimal() - if index == None: - return _getlabel(object_alias) - if index < 0 or index > 7: - index = 0 - return _setlabel(object_alias, index) - + """label: set or get the label of the item. Specify file by name or fsspec.""" + object = Carbon.File.FSRef(object) + object_alias = object.FSNewAliasMinimal() + if index == None: + return _getlabel(object_alias) + if index < 0 or index > 7: + index = 0 + return _setlabel(object_alias, index) + def _getlabel(object_alias): - """label: Get the label for the object.""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('labi'), fr=aeobj_00) - args['----'] = aeobj_01 - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """label: Get the label for the object.""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('labi'), fr=aeobj_00) + args['----'] = aeobj_01 + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def _setlabel(object_alias, index): - """label: Set the label for the object.""" - finder = _getfinder() - args = {} - attrs = {} - _code = 'core' - _subcode = 'setd' - aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="alis", seld=object_alias, fr=None) - aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('labi'), fr=aeobj_0) - args['----'] = aeobj_1 - args["data"] = index - _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - return index + """label: Set the label for the object.""" + finder = _getfinder() + args = {} + attrs = {} + _code = 'core' + _subcode = 'setd' + aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="alis", seld=object_alias, fr=None) + aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('labi'), fr=aeobj_0) + args['----'] = aeobj_1 + args["data"] = index + _reply, args, attrs = finder.send(_code, _subcode, args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + return index def windowview(folder, view=None): - """windowview: Set the view of the window for the folder. Specify file by name or fsspec. - 0 = by icon (default) - 1 = by name - 2 = by button - """ - fsr = Carbon.File.FSRef(folder) - folder_alias = fsr.FSNewAliasMinimal() - if view == None: - return _getwindowview(folder_alias) - return _setwindowview(folder_alias, view) - + """windowview: Set the view of the window for the folder. Specify file by name or fsspec. + 0 = by icon (default) + 1 = by name + 2 = by button + """ + fsr = Carbon.File.FSRef(folder) + folder_alias = fsr.FSNewAliasMinimal() + if view == None: + return _getwindowview(folder_alias) + return _setwindowview(folder_alias, view) + def _setwindowview(folder_alias, view=0): - """set the windowview""" - attrs = {} - args = {} - if view == 1: - _v = aetypes.Type('pnam') - elif view == 2: - _v = aetypes.Type('lgbu') - else: - _v = aetypes.Type('iimg') - finder = _getfinder() - aeobj_0 = aetypes.ObjectSpecifier(want = aetypes.Type('cfol'), - form = 'alis', seld = folder_alias, fr=None) - aeobj_1 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'), - form = 'prop', seld = aetypes.Type('cwnd'), fr=aeobj_0) - aeobj_2 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'), - form = 'prop', seld = aetypes.Type('pvew'), fr=aeobj_1) - aeobj_3 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'), - form = 'prop', seld = _v, fr=None) - _code = 'core' - _subcode = 'setd' - args['----'] = aeobj_2 - args['data'] = aeobj_3 - _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """set the windowview""" + attrs = {} + args = {} + if view == 1: + _v = aetypes.Type('pnam') + elif view == 2: + _v = aetypes.Type('lgbu') + else: + _v = aetypes.Type('iimg') + finder = _getfinder() + aeobj_0 = aetypes.ObjectSpecifier(want = aetypes.Type('cfol'), + form = 'alis', seld = folder_alias, fr=None) + aeobj_1 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'), + form = 'prop', seld = aetypes.Type('cwnd'), fr=aeobj_0) + aeobj_2 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'), + form = 'prop', seld = aetypes.Type('pvew'), fr=aeobj_1) + aeobj_3 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'), + form = 'prop', seld = _v, fr=None) + _code = 'core' + _subcode = 'setd' + args['----'] = aeobj_2 + args['data'] = aeobj_3 + _reply, args, attrs = finder.send(_code, _subcode, args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def _getwindowview(folder_alias): - """get the windowview""" - attrs = {} - args = {} - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=folder_alias, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_00) - aeobj_02 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('pvew'), fr=aeobj_01) - args['----'] = aeobj_02 - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - views = {'iimg':0, 'pnam':1, 'lgbu':2} - if args.has_key('----'): - return views[args['----'].enum] + """get the windowview""" + attrs = {} + args = {} + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=folder_alias, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_00) + aeobj_02 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('pvew'), fr=aeobj_01) + args['----'] = aeobj_02 + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + views = {'iimg':0, 'pnam':1, 'lgbu':2} + if args.has_key('----'): + return views[args['----'].enum] def windowsize(folder, size=None): - """Set the size of a Finder window for folder to size=(w, h), Specify by path. - If size=None, windowsize will return the current size of the window. - Specify file by name or fsspec. - """ - fsr = Carbon.File.FSRef(folder) - folder_alias = fsr.FSNewAliasMinimal() - openwindow(fsr) - if not size: - return _getwindowsize(folder_alias) - return _setwindowsize(folder_alias, size) - + """Set the size of a Finder window for folder to size=(w, h), Specify by path. + If size=None, windowsize will return the current size of the window. + Specify file by name or fsspec. + """ + fsr = Carbon.File.FSRef(folder) + folder_alias = fsr.FSNewAliasMinimal() + openwindow(fsr) + if not size: + return _getwindowsize(folder_alias) + return _setwindowsize(folder_alias, size) + def _setwindowsize(folder_alias, (w, h)): - """Set the size of a Finder window for folder to (w, h)""" - finder = _getfinder() - args = {} - attrs = {} - _code = 'core' - _subcode = 'setd' - aevar00 = [w, h] - aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), - form="alis", seld=folder_alias, fr=None) - aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0) - aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1) - args['----'] = aeobj_2 - args["data"] = aevar00 - _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - return (w, h) - + """Set the size of a Finder window for folder to (w, h)""" + finder = _getfinder() + args = {} + attrs = {} + _code = 'core' + _subcode = 'setd' + aevar00 = [w, h] + aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), + form="alis", seld=folder_alias, fr=None) + aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0) + aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1) + args['----'] = aeobj_2 + args["data"] = aevar00 + _reply, args, attrs = finder.send(_code, _subcode, args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + return (w, h) + def _getwindowsize(folder_alias): - """Set the size of a Finder window for folder to (w, h)""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), - form="alis", seld=folder_alias, fr=None) - aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0) - aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('posn'), fr=aeobj_1) - args['----'] = aeobj_2 - _reply, args, attrs = finder.send('core', 'getd', args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """Set the size of a Finder window for folder to (w, h)""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), + form="alis", seld=folder_alias, fr=None) + aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0) + aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('posn'), fr=aeobj_1) + args['----'] = aeobj_2 + _reply, args, attrs = finder.send('core', 'getd', args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def windowposition(folder, pos=None): - """Set the position of a Finder window for folder to pos=(w, h).""" - fsr = Carbon.File.FSRef(folder) - folder_alias = fsr.FSNewAliasMinimal() - openwindow(fsr) - if not pos: - return _getwindowposition(folder_alias) - if type(pos) == InstanceType: - # pos might be a QDPoint object as returned by _getwindowposition - pos = (pos.h, pos.v) - return _setwindowposition(folder_alias, pos) - + """Set the position of a Finder window for folder to pos=(w, h).""" + fsr = Carbon.File.FSRef(folder) + folder_alias = fsr.FSNewAliasMinimal() + openwindow(fsr) + if not pos: + return _getwindowposition(folder_alias) + if type(pos) == InstanceType: + # pos might be a QDPoint object as returned by _getwindowposition + pos = (pos.h, pos.v) + return _setwindowposition(folder_alias, pos) + def _setwindowposition(folder_alias, (x, y)): - """Set the size of a Finder window for folder to (w, h).""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), - form="alis", seld=folder_alias, fr=None) - aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0) - aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('posn'), fr=aeobj_1) - args['----'] = aeobj_2 - args["data"] = [x, y] - _reply, args, attrs = finder.send('core', 'setd', args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """Set the size of a Finder window for folder to (w, h).""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), + form="alis", seld=folder_alias, fr=None) + aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0) + aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('posn'), fr=aeobj_1) + args['----'] = aeobj_2 + args["data"] = [x, y] + _reply, args, attrs = finder.send('core', 'setd', args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def _getwindowposition(folder_alias): - """Get the size of a Finder window for folder, Specify by path.""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), - form="alis", seld=folder_alias, fr=None) - aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0) - aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1) - args['----'] = aeobj_2 - _reply, args, attrs = finder.send('core', 'getd', args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """Get the size of a Finder window for folder, Specify by path.""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), + form="alis", seld=folder_alias, fr=None) + aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0) + aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1) + args['----'] = aeobj_2 + _reply, args, attrs = finder.send('core', 'getd', args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def icon(object, icondata=None): - """icon sets the icon of object, if no icondata is given, - icon will return an AE object with binary data for the current icon. - If left untouched, this data can be used to paste the icon on another file. - Development opportunity: get and set the data as PICT.""" - fsr = Carbon.File.FSRef(object) - object_alias = fsr.FSNewAliasMinimal() - if icondata == None: - return _geticon(object_alias) - return _seticon(object_alias, icondata) - + """icon sets the icon of object, if no icondata is given, + icon will return an AE object with binary data for the current icon. + If left untouched, this data can be used to paste the icon on another file. + Development opportunity: get and set the data as PICT.""" + fsr = Carbon.File.FSRef(object) + object_alias = fsr.FSNewAliasMinimal() + if icondata == None: + return _geticon(object_alias) + return _seticon(object_alias, icondata) + def _geticon(object_alias): - """get the icondata for object. Binary data of some sort.""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), - form="alis", seld=object_alias, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00) - args['----'] = aeobj_01 - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """get the icondata for object. Binary data of some sort.""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), + form="alis", seld=object_alias, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00) + args['----'] = aeobj_01 + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def _seticon(object_alias, icondata): - """set the icondata for object, formatted as produced by _geticon()""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), - form="alis", seld=object_alias, fr=None) - aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), - form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00) - args['----'] = aeobj_01 - args["data"] = icondata - _reply, args, attrs = finder.send("core", "setd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'].data + """set the icondata for object, formatted as produced by _geticon()""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), + form="alis", seld=object_alias, fr=None) + aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), + form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00) + args['----'] = aeobj_01 + args["data"] = icondata + _reply, args, attrs = finder.send("core", "setd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'].data #--------------------------------------------------- -# Volumes and servers. - +# Volumes and servers. + def mountvolume(volume, server=None, username=None, password=None): - """mount a volume, local or on a server on AppleTalk. - Note: mounting a ASIP server requires a different operation. - server is the name of the server where the volume belongs - username, password belong to a registered user of the volume.""" - finder = _getfinder() - args = {} - attrs = {} - if password: - args["PASS"] = password - if username: - args["USER"] = username - if server: - args["SRVR"] = server - args['----'] = volume - _reply, args, attrs = finder.send("aevt", "mvol", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """mount a volume, local or on a server on AppleTalk. + Note: mounting a ASIP server requires a different operation. + server is the name of the server where the volume belongs + username, password belong to a registered user of the volume.""" + finder = _getfinder() + args = {} + attrs = {} + if password: + args["PASS"] = password + if username: + args["USER"] = username + if server: + args["SRVR"] = server + args['----'] = volume + _reply, args, attrs = finder.send("aevt", "mvol", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def unmountvolume(volume): - """unmount a volume that's on the desktop""" - putaway(volume) - + """unmount a volume that's on the desktop""" + putaway(volume) + def putaway(object): - """puth the object away, whereever it came from.""" - finder = _getfinder() - args = {} - attrs = {} - args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('cdis'), form="name", seld=object, fr=None) - _reply, args, attrs = talker.send("fndr", "ptwy", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """puth the object away, whereever it came from.""" + finder = _getfinder() + args = {} + attrs = {} + args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('cdis'), form="name", seld=object, fr=None) + _reply, args, attrs = talker.send("fndr", "ptwy", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] #--------------------------------------------------- -# Miscellaneous functions +# Miscellaneous functions # def volumelevel(level): - """set the audio output level, parameter between 0 (silent) and 7 (full blast)""" - finder = _getfinder() - args = {} - attrs = {} - if level < 0: - level = 0 - elif level > 7: - level = 7 - args['----'] = level - _reply, args, attrs = finder.send("aevt", "stvl", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """set the audio output level, parameter between 0 (silent) and 7 (full blast)""" + finder = _getfinder() + args = {} + attrs = {} + if level < 0: + level = 0 + elif level > 7: + level = 7 + args['----'] = level + _reply, args, attrs = finder.send("aevt", "stvl", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def OSversion(): - """return the version of the system software""" - finder = _getfinder() - args = {} - attrs = {} - aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('ver2'), fr=None) - args['----'] = aeobj_00 - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - return args['----'] + """return the version of the system software""" + finder = _getfinder() + args = {} + attrs = {} + aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('ver2'), fr=None) + args['----'] = aeobj_00 + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + return args['----'] def filesharing(): - """return the current status of filesharing and whether it is starting up or not: - -1 file sharing is off and not starting up - 0 file sharing is off and starting up - 1 file sharing is on""" - status = -1 - finder = _getfinder() - # see if it is on - args = {} - attrs = {} - args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fshr'), fr=None) - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - if args['----'] == 0: - status = -1 - else: - status = 1 - # is it starting up perchance? - args = {} - attrs = {} - args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fsup'), fr=None) - _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): - raise Error, aetools.decodeerror(args) - if args.has_key('----'): - if args['----'] == 1: - status = 0 - return status - + """return the current status of filesharing and whether it is starting up or not: + -1 file sharing is off and not starting up + 0 file sharing is off and starting up + 1 file sharing is on""" + status = -1 + finder = _getfinder() + # see if it is on + args = {} + attrs = {} + args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fshr'), fr=None) + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + if args['----'] == 0: + status = -1 + else: + status = 1 + # is it starting up perchance? + args = {} + attrs = {} + args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fsup'), fr=None) + _reply, args, attrs = finder.send("core", "getd", args, attrs) + if args.has_key('errn'): + raise Error, aetools.decodeerror(args) + if args.has_key('----'): + if args['----'] == 1: + status = 0 + return status + def movetotrash(path): - """move the object to the trash""" - fss = Carbon.File.FSSpec(path) - trashfolder = Carbon.Folder.FSFindFolder(fss.as_tuple()[0], 'trsh', 0) - move(path, trashfolder) + """move the object to the trash""" + fss = Carbon.File.FSSpec(path) + trashfolder = Carbon.Folder.FSFindFolder(fss.as_tuple()[0], 'trsh', 0) + move(path, trashfolder) def emptytrash(): - """empty the trash""" - finder = _getfinder() - args = {} - attrs = {} - args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('trsh'), fr=None) - _reply, args, attrs = finder.send("fndr", "empt", args, attrs) - if args.has_key('errn'): - raise aetools.Error, aetools.decodeerror(args) + """empty the trash""" + finder = _getfinder() + args = {} + attrs = {} + args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('trsh'), fr=None) + _reply, args, attrs = finder.send("fndr", "empt", args, attrs) + if args.has_key('errn'): + raise aetools.Error, aetools.decodeerror(args) def _test(): - import EasyDialogs - print 'Original findertools functionality test...' - print 'Testing launch...' - pathname = EasyDialogs.AskFileForOpen('File to launch:') - if pathname: - result = launch(pathname) - if result: - print 'Result: ', result - print 'Press return-', - sys.stdin.readline() - print 'Testing print...' - pathname = EasyDialogs.AskFileForOpen('File to print:') - if pathname: - result = Print(pathname) - if result: - print 'Result: ', result - print 'Press return-', - sys.stdin.readline() - print 'Testing copy...' - pathname = EasyDialogs.AskFileForOpen('File to copy:') - if pathname: - destdir = EasyDialogs.AskFolder('Destination:') - if destdir: - result = copy(pathname, destdir) - if result: - print 'Result:', result - print 'Press return-', - sys.stdin.readline() - print 'Testing move...' - pathname = EasyDialogs.AskFileForOpen('File to move:') - if pathname: - destdir = EasyDialogs.AskFolder('Destination:') - if destdir: - result = move(pathname, destdir) - if result: - print 'Result:', result - print 'Press return-', - sys.stdin.readline() - print 'Testing sleep...' - if EasyDialogs.AskYesNoCancel('Sleep?') > 0: - result = sleep() - if result: - print 'Result:', result - print 'Press return-', - sys.stdin.readline() - print 'Testing shutdown...' - if EasyDialogs.AskYesNoCancel('Shut down?') > 0: - result = shutdown() - if result: - print 'Result:', result - print 'Press return-', - sys.stdin.readline() - print 'Testing restart...' - if EasyDialogs.AskYesNoCancel('Restart?') > 0: - result = restart() - if result: - print 'Result:', result - print 'Press return-', - sys.stdin.readline() + import EasyDialogs + print 'Original findertools functionality test...' + print 'Testing launch...' + pathname = EasyDialogs.AskFileForOpen('File to launch:') + if pathname: + result = launch(pathname) + if result: + print 'Result: ', result + print 'Press return-', + sys.stdin.readline() + print 'Testing print...' + pathname = EasyDialogs.AskFileForOpen('File to print:') + if pathname: + result = Print(pathname) + if result: + print 'Result: ', result + print 'Press return-', + sys.stdin.readline() + print 'Testing copy...' + pathname = EasyDialogs.AskFileForOpen('File to copy:') + if pathname: + destdir = EasyDialogs.AskFolder('Destination:') + if destdir: + result = copy(pathname, destdir) + if result: + print 'Result:', result + print 'Press return-', + sys.stdin.readline() + print 'Testing move...' + pathname = EasyDialogs.AskFileForOpen('File to move:') + if pathname: + destdir = EasyDialogs.AskFolder('Destination:') + if destdir: + result = move(pathname, destdir) + if result: + print 'Result:', result + print 'Press return-', + sys.stdin.readline() + print 'Testing sleep...' + if EasyDialogs.AskYesNoCancel('Sleep?') > 0: + result = sleep() + if result: + print 'Result:', result + print 'Press return-', + sys.stdin.readline() + print 'Testing shutdown...' + if EasyDialogs.AskYesNoCancel('Shut down?') > 0: + result = shutdown() + if result: + print 'Result:', result + print 'Press return-', + sys.stdin.readline() + print 'Testing restart...' + if EasyDialogs.AskYesNoCancel('Restart?') > 0: + result = restart() + if result: + print 'Result:', result + print 'Press return-', + sys.stdin.readline() def _test2(): - print '\nmorefindertools version %s\nTests coming up...' %__version__ - import os - import random + print '\nmorefindertools version %s\nTests coming up...' %__version__ + import os + import random - # miscellaneous - print '\tfilesharing on?', filesharing() # is file sharing on, off, starting up? - print '\tOS version', OSversion() # the version of the system software + # miscellaneous + print '\tfilesharing on?', filesharing() # is file sharing on, off, starting up? + print '\tOS version', OSversion() # the version of the system software - # set the soundvolume in a simple way - print '\tSystem beep volume' - for i in range(0, 7): - volumelevel(i) - MacOS.SysBeep() + # set the soundvolume in a simple way + print '\tSystem beep volume' + for i in range(0, 7): + volumelevel(i) + MacOS.SysBeep() - # Finder's windows, file location, file attributes - open("@findertoolstest", "w") - f = "@findertoolstest" - reveal(f) # reveal this file in a Finder window - select(f) # select this file + # Finder's windows, file location, file attributes + open("@findertoolstest", "w") + f = "@findertoolstest" + reveal(f) # reveal this file in a Finder window + select(f) # select this file - base, file = os.path.split(f) - closewindow(base) # close the window this file is in (opened by reveal) - openwindow(base) # open it again - windowview(base, 1) # set the view by list + base, file = os.path.split(f) + closewindow(base) # close the window this file is in (opened by reveal) + openwindow(base) # open it again + windowview(base, 1) # set the view by list - label(f, 2) # set the label of this file to something orange - print '\tlabel', label(f) # get the label of this file + label(f, 2) # set the label of this file to something orange + print '\tlabel', label(f) # get the label of this file - # the file location only works in a window with icon view! - print 'Random locations for an icon' - windowview(base, 0) # set the view by icon - windowsize(base, (600, 600)) - for i in range(50): - location(f, (random.randint(10, 590), random.randint(10, 590))) + # the file location only works in a window with icon view! + print 'Random locations for an icon' + windowview(base, 0) # set the view by icon + windowsize(base, (600, 600)) + for i in range(50): + location(f, (random.randint(10, 590), random.randint(10, 590))) - windowsize(base, (200, 400)) - windowview(base, 1) # set the view by icon + windowsize(base, (200, 400)) + windowview(base, 1) # set the view by icon - orgpos = windowposition(base) - print 'Animated window location' - for i in range(10): - pos = (100+i*10, 100+i*10) - windowposition(base, pos) - print '\twindow position', pos - windowposition(base, orgpos) # park it where it was before + orgpos = windowposition(base) + print 'Animated window location' + for i in range(10): + pos = (100+i*10, 100+i*10) + windowposition(base, pos) + print '\twindow position', pos + windowposition(base, orgpos) # park it where it was before - print 'Put a comment in file', f, ':' - print '\t', comment(f) # print the Finder comment this file has - s = 'This is a comment no one reads!' - comment(f, s) # set the Finder comment - + print 'Put a comment in file', f, ':' + print '\t', comment(f) # print the Finder comment this file has + s = 'This is a comment no one reads!' + comment(f, s) # set the Finder comment + def _test3(): - print 'MacOS9 or better specific functions' - # processes - pr = processes() # return a list of tuples with (active_processname, creatorcode) - print 'Return a list of current active processes:' - for p in pr: - print '\t', p - - # get attributes of the first process in the list - print 'Attributes of the first process in the list:' - pinfo = processinfo(pr[0][0]) - print '\t', pr[0][0] - print '\t\tmemory partition', pinfo.partition # the memory allocated to this process - print '\t\tmemory used', pinfo.used # the memory actuall used by this process - print '\t\tis visible', pinfo.visible # is the process visible to the user - print '\t\tis frontmost', pinfo.frontmost # is the process the front most one? - print '\t\thas scripting', pinfo.hasscripting # is the process scriptable? - print '\t\taccepts high level events', pinfo.accepthighlevel # does the process accept high level appleevents? + print 'MacOS9 or better specific functions' + # processes + pr = processes() # return a list of tuples with (active_processname, creatorcode) + print 'Return a list of current active processes:' + for p in pr: + print '\t', p + + # get attributes of the first process in the list + print 'Attributes of the first process in the list:' + pinfo = processinfo(pr[0][0]) + print '\t', pr[0][0] + print '\t\tmemory partition', pinfo.partition # the memory allocated to this process + print '\t\tmemory used', pinfo.used # the memory actuall used by this process + print '\t\tis visible', pinfo.visible # is the process visible to the user + print '\t\tis frontmost', pinfo.frontmost # is the process the front most one? + print '\t\thas scripting', pinfo.hasscripting # is the process scriptable? + print '\t\taccepts high level events', pinfo.accepthighlevel # does the process accept high level appleevents? if __name__ == '__main__': - _test() - _test2() - _test3() - + _test() + _test2() + _test3() + diff --git a/Lib/plat-mac/gensuitemodule.py b/Lib/plat-mac/gensuitemodule.py index 0fcd1c410e6..622016e3eff 100644 --- a/Lib/plat-mac/gensuitemodule.py +++ b/Lib/plat-mac/gensuitemodule.py @@ -29,8 +29,8 @@ 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: + 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) @@ -39,252 +39,252 @@ def usage(): --dump Dump aete resource to stdout in stead of creating module (-d) --verbose Tell us what happens (-v) """) - sys.exit(1) + 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() - + 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) - + 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 + """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", `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) + 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", `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", `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) - + 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", `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 - + """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) + 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) - + 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 + """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 + """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. @@ -292,520 +292,520 @@ def simplify(item): # 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) + 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]) + 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]) + 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 + 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 + 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:', `c` + if f.tell() & 1: + c = f.read(1) + ##if c <> '\0': + ## print 'align:', `c` def getlist(f, description, getitem): - count = getword(f) - list = [] - for i in range(count): - list.append(generic(getitem, f)) - getalign(f) - return list + 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", `what`, args - res = vageneric(what, f, args) - print '->', `res` - return res + print "generic", `what`, args + res = vageneric(what, f, args) + print '->', `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: %s" % `what` + 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: %s" % `what` getdata = [ - (getostype, "type"), - (getpstr, "description"), - (getword, "flags") - ] + (getostype, "type"), + (getpstr, "description"), + (getword, "flags") + ] getargument = [ - (getpstr, "name"), - (getostype, "keyword"), - (getdata, "what") - ] + (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) - ] + (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") - ] + (getpstr, "name"), + (getostype, "code"), + (getdata, "what") + ] getelement = [ - (getostype, "type"), - (getlist, "keyform", getostype) - ] + (getostype, "type"), + (getlist, "keyform", getostype) + ] getclass = [ - (getpstr, "name"), - (getostype, "class code"), - (getpstr, "description"), - (getlist, "properties", getproperty), - (getlist, "elements", getelement) - ] + (getpstr, "name"), + (getostype, "class code"), + (getpstr, "description"), + (getlist, "properties", getproperty), + (getlist, "elements", getelement) + ] getcomparison = [ - (getpstr, "operator name"), - (getostype, "operator ID"), - (getpstr, "operator comment"), - ] + (getpstr, "operator name"), + (getostype, "operator ID"), + (getpstr, "operator comment"), + ] getenumerator = [ - (getpstr, "enumerator name"), - (getostype, "enumerator ID"), - (getpstr, "enumerator comment") - ] + (getpstr, "enumerator name"), + (getostype, "enumerator ID"), + (getpstr, "enumerator comment") + ] getenumeration = [ - (getostype, "enumeration ID"), - (getlist, "enumerator", getenumerator) - ] + (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) - ] + (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) - ] + (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("\t'%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("\t'%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("\tif not getattr(v, '_propdict', None):\n") - fp.write("\t\tv._propdict = {}\n") - fp.write("\t\tv._elemdict = {}\n") - fp.write("\t\tfor superclassname in getattr(v, '_superclassnames', []):\n") - fp.write("\t\t\tsuperclass = eval(superclassname)\n") - fp.write("\t\t\tgetbaseclasses(superclass)\n") - fp.write("\t\t\tv._propdict.update(getattr(superclass, '_propdict', {}))\n") - fp.write("\t\t\tv._elemdict.update(getattr(superclass, '_elemdict', {}))\n") - fp.write("\t\tv._propdict.update(getattr(v, '_privpropdict', {}))\n") - fp.write("\t\tv._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) + 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 - 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("\t%s : %s,\n" % (`k`, v)) - fp.write("}\n") + # Generate a code-to-name mapper for all of the types (classes) declared in this module + 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(" %s : %s,\n" % (`k`, 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\t\t%s_Events"%modname) - fp.write(",\n\t\taetools.TalkTo):\n") - fp.write("\t_signature = %s\n\n"%`creatorsignature`) - fp.write("\t_moduleName = '%s'\n\n"%packagename) - fp.close() + 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 = %s\n\n"%`creatorsignature`) + fp.write(" _moduleName = '%s'\n\n"%packagename) + 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, 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 = %s\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("\tpass\n\n") - - objc = ObjectCompiler(fp, 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("\t_argmap_%s = {\n"%funcname) - for a in arguments: - fp.write("\t\t%s : %s,\n"%(`identify(a[0])`, `a[1]`)) - fp.write("\t}\n\n") - - # - # Generate function header - # - has_arg = (not is_null(accepts)) - opt_arg = (has_arg and is_optional(accepts)) - - fp.write("\tdef %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('\t\t"""%s: %s\n'%(ascii(name), ascii(desc))) - if has_arg: - fp.write("\t\tRequired argument: %s\n"%getdatadoc(accepts)) - elif opt_arg: - fp.write("\t\tOptional argument: %s\n"%getdatadoc(accepts)) - for arg in arguments: - fp.write("\t\tKeyword argument %s: %s\n"%(identify(arg[0]), - getdatadoc(arg[2]))) - fp.write("\t\tKeyword argument _attributes: AppleEvent attribute dictionary\n") - if not is_null(returns): - fp.write("\t\tReturns: %s\n"%getdatadoc(returns)) - fp.write('\t\t"""\n') - # - # Fiddle the args so everything ends up in 'arguments' dictionary - # - fp.write("\t\t_code = %s\n"% `code`) - fp.write("\t\t_subcode = %s\n\n"% `subcode`) - # - # Do keyword name substitution - # - if arguments: - fp.write("\t\taetools.keysubst(_arguments, self._argmap_%s)\n"%funcname) - else: - fp.write("\t\tif _arguments: raise TypeError, 'No optional args expected'\n") - # - # Stuff required arg (if there is one) into arguments - # - if has_arg: - fp.write("\t\t_arguments['----'] = _object\n") - elif opt_arg: - fp.write("\t\tif _object:\n") - fp.write("\t\t\t_arguments['----'] = _object\n") - else: - fp.write("\t\tif _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("\t\taetools.enumsubst(_arguments, %s, _Enum_%s)\n" % - (`kname`, identify(ename))) - self.enumsneeded[ename] = 1 - fp.write("\n") - # - # Do the transaction - # - fp.write("\t\t_reply, _arguments, _attributes = self.send(_code, _subcode,\n") - fp.write("\t\t\t\t_arguments, _attributes)\n") - # - # Error handling - # - fp.write("\t\tif _arguments.get('errn', 0):\n") - fp.write("\t\t\traise aetools.Error, aetools.decodeerror(_arguments)\n") - fp.write("\t\t# XXXX Optionally decode result\n") - # - # Decode result - # - fp.write("\t\tif _arguments.has_key('----'):\n") - if is_enum(returns): - fp.write("\t\t\t# XXXX Should do enum remapping here...\n") - fp.write("\t\t\treturn _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 - + 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 = %s\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(" %s : %s,\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 = %s\n"% `code`) + fp.write(" _subcode = %s\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, %s, _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 @@ -814,378 +814,392 @@ class SuiteCompiler: # 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, type, name): - return self.name2code[type].has_key(name) - - 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 - + + 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, basesuite=None, othernamemappers=None, interact=1, - verbose=None): - self.fp = fp - self.verbose = verbose - self.basesuite = basesuite - self.can_interact = interact - 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 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('\t"""%s - %s """\n' % (ascii(name), ascii(desc))) - self.fp.write('\twant = %s\n' % `code`) - self.namemappers[0].addnamecode('class', pname, code) - properties.sort() - for prop in properties: - self.compileproperty(prop) - elements.sort() - for elem in elements: - self.compileelement(elem) - - def compileproperty(self, prop): - [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('\t"""%s - %s """\n' % (ascii(name), ascii(what[1]))) - self.fp.write("\twhich = %s\n" % `code`) - self.fp.write("\twant = %s\n" % `what[0]`) - self.namemappers[0].addnamecode('property', pname, code) - - def compileelement(self, elem): - [code, keyform] = elem - if self.fp: - self.fp.write("# element %s as %s\n" % (`code`, keyform)) + 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 = %s\n' % `code`) + self.namemappers[0].addnamecode('class', pname, code) + properties.sort() + for prop in properties: + self.compileproperty(prop) + elements.sort() + for elem in elements: + self.compileelement(elem) + + def compileproperty(self, prop): + [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.hasname(pname): + pass + 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 = %s\n" % `code`) + self.fp.write(" want = %s\n" % `what[0]`) + self.namemappers[0].addnamecode('property', pname, code) + + def compileelement(self, elem): + [code, keyform] = elem + if self.fp: + self.fp.write("# element %s 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 %s)' % (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) + 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 %s)' % (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) + 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 = %s\n"%(cname, `superclassnames`)) + if self.fp: + self.fp.write("%s._superclassnames = %s\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 %s 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("\t'%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("\t'%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('\t"""%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("\t%s : %s,\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("\t%s : %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("\t%s : _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("\t%s : %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("\t%s : %s,\n" % (`k`, v)) -## self.fp.write("}\n") + 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 %s 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(" %s : %s,\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(" %s : %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(" %s : _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(" %s : %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(" %s : %s,\n" % (`k`, v)) +## self.fp.write("}\n") def compiledata(data): - [type, description, flags] = data - return "%s -- %s %s" % (`type`, `description`, compiledataflags(flags)) - + [type, description, flags] = data + return "%s -- %s %s" % (`type`, `description`, compiledataflags(flags)) + def is_null(data): - return data[0] == 'null' - + return data[0] == 'null' + def is_optional(data): - return (data[2] & 0x8000) - + return (data[2] & 0x8000) + def is_enum(data): - return (data[2] & 0x2000) - + 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 %s"%`type` + [type, descr, flags] = data + if descr: + return ascii(descr) + if type == '****': + return 'anything' + if type == 'obj ': + return 'an AE object reference' + return "undocumented, typecode %s"%`type` dataflagdict = {15: "optional", 14: "list", 13: "enum", 12: "mutable"} def compiledataflags(flags): - bits = [] - for i in range(16): - if flags & (1<>8) & 0xff) + chr(numstr & 0xff) - for i in data: - rv = rv + _code_default(i) - return rv - + 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) - + 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:', `data` - return chr(data) - + print 'XXXX boolean:', `data` + return chr(data) + def _code_text(data, key): - return data - + return data + def _code_charset(data, key): - return data[0] + data[1] - + return data[0] + data[1] + def _code_appspec(data, key): - return data[0] + _code_default(data[1]) - + 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), + "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) + 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) - + 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) - + 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) - + 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) - + 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) - + 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) - + 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) - + 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) - + 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() - + _test() + diff --git a/Lib/plat-mac/macerrors.py b/Lib/plat-mac/macerrors.py index 32f00a192e7..ce2a1182878 100644 --- a/Lib/plat-mac/macerrors.py +++ b/Lib/plat-mac/macerrors.py @@ -1,1852 +1,1852 @@ -svTempDisable = -32768 #svTempDisable -svDisabled = -32640 #Reserve range -32640 to -32768 for Apple temp disables. -fontNotOutlineErr = -32615 #bitmap font passed to routine that does outlines only -kURL68kNotSupportedError = -30788 #kURL68kNotSupportedError -kURLAccessNotAvailableError = -30787 #kURLAccessNotAvailableError -kURLInvalidConfigurationError = -30786 #kURLInvalidConfigurationError -kURLExtensionFailureError = -30785 #kURLExtensionFailureError -kURLFileEmptyError = -30783 #kURLFileEmptyError -kURLInvalidCallError = -30781 #kURLInvalidCallError -kURLUnsettablePropertyError = -30780 #kURLUnsettablePropertyError -kURLPropertyBufferTooSmallError = -30779 #kURLPropertyBufferTooSmallError -kURLUnknownPropertyError = -30778 #kURLUnknownPropertyError -kURLPropertyNotYetKnownError = -30777 #kURLPropertyNotYetKnownError -kURLAuthenticationError = -30776 #kURLAuthenticationError -kURLServerBusyError = -30775 #kURLServerBusyError -kURLUnsupportedSchemeError = -30774 #kURLUnsupportedSchemeError -kURLInvalidURLError = -30773 #kURLInvalidURLError -kURLDestinationExistsError = -30772 #kURLDestinationExistsError -kURLProgressAlreadyDisplayedError = -30771 #kURLProgressAlreadyDisplayedError -kURLInvalidURLReferenceError = -30770 #kURLInvalidURLReferenceError -controlHandleInvalidErr = -30599 #controlHandleInvalidErr -controlInvalidDataVersionErr = -30597 #controlInvalidDataVersionErr -errItemNotControl = -30596 #errItemNotControl -errCantEmbedRoot = -30595 #errCantEmbedRoot -errCantEmbedIntoSelf = -30594 #errCantEmbedIntoSelf -errWindowRegionCodeInvalid = -30593 #errWindowRegionCodeInvalid -errControlHiddenOrDisabled = -30592 #errControlHiddenOrDisabled -errDataSizeMismatch = -30591 #errDataSizeMismatch -errControlIsNotEmbedder = -30590 #errControlIsNotEmbedder -errControlsAlreadyExist = -30589 #errControlsAlreadyExist -errInvalidPartCode = -30588 #errInvalidPartCode -errRootAlreadyExists = -30587 #errRootAlreadyExists -errNoRootControl = -30586 #errNoRootControl -errCouldntSetFocus = -30585 #errCouldntSetFocus -errUnknownControl = -30584 #errUnknownControl -errWindowDoesntSupportFocus = -30583 #errWindowDoesntSupportFocus -errControlDoesntSupportFocus = -30582 #errControlDoesntSupportFocus -errDataNotSupported = -30581 #errDataNotSupported -errMessageNotSupported = -30580 #errMessageNotSupported -themeMonitorDepthNotSupportedErr = -30567 #theme not supported at monitor depth -themeScriptFontNotFoundErr = -30566 #theme font requested for uninstalled script system -themeBadCursorIndexErr = -30565 #themeBadCursorIndexErr -themeHasNoAccentsErr = -30564 #themeHasNoAccentsErr -themeBadTextColorErr = -30563 #themeBadTextColorErr -themeProcessNotRegisteredErr = -30562 #themeProcessNotRegisteredErr -themeProcessRegisteredErr = -30561 #themeProcessRegisteredErr -themeInvalidBrushErr = -30560 #pattern index invalid -qtvrUninitialized = -30555 #qtvrUninitialized -qtvrLibraryLoadErr = -30554 #qtvrLibraryLoadErr -streamingNodeNotReadyErr = -30553 #streamingNodeNotReadyErr -noMemoryNodeFailedInitialize = -30552 #noMemoryNodeFailedInitialize -invalidHotSpotIDErr = -30551 #invalidHotSpotIDErr -invalidNodeFormatErr = -30550 #invalidNodeFormatErr -limitReachedErr = -30549 #limitReachedErr -settingNotSupportedByNodeErr = -30548 #settingNotSupportedByNodeErr -propertyNotSupportedByNodeErr = -30547 #propertyNotSupportedByNodeErr -timeNotInViewErr = -30546 #timeNotInViewErr -invalidViewStateErr = -30545 #invalidViewStateErr -invalidNodeIDErr = -30544 #invalidNodeIDErr -selectorNotSupportedByNodeErr = -30543 #selectorNotSupportedByNodeErr -callNotSupportedByNodeErr = -30542 #callNotSupportedByNodeErr -constraintReachedErr = -30541 #constraintReachedErr -notAQTVRMovieErr = -30540 #notAQTVRMovieErr -kFBCnoSuchHit = -30532 #kFBCnoSuchHit -kFBCbadSearchSession = -30531 #kFBCbadSearchSession -kFBCindexDiskIOFailed = -30530 #kFBCindexDiskIOFailed -kFBCsummarizationCanceled = -30529 #kFBCsummarizationCanceled -kFBCbadIndexFileVersion = -30528 #kFBCbadIndexFileVersion -kFBCanalysisNotAvailable = -30527 #kFBCanalysisNotAvailable -kFBCillegalSessionChange = -30526 #tried to add/remove vols to a session -kFBCsomeFilesNotIndexed = -30525 #kFBCsomeFilesNotIndexed -kFBCsearchFailed = -30524 #kFBCsearchFailed -kFBCindexNotAvailable = -30523 #kFBCindexNotAvailable -kFBCindexFileDestroyed = -30522 #kFBCindexFileDestroyed -kFBCaccessCanceled = -30521 #kFBCaccessCanceled -kFBCindexingCanceled = -30520 #kFBCindexingCanceled -kFBCnoSearchSession = -30519 #kFBCnoSearchSession -kFBCindexNotFound = -30518 #kFBCindexNotFound -kFBCflushFailed = -30517 #kFBCflushFailed -kFBCaddDocFailed = -30516 #kFBCaddDocFailed -kFBCaccessorStoreFailed = -30515 #kFBCaccessorStoreFailed -kFBCindexCreationFailed = -30514 #couldn't create index -kFBCmergingFailed = -30513 #couldn't merge index files -kFBCtokenizationFailed = -30512 #couldn't read from document or query -kFBCmoveFailed = -30511 #V-Twin exception caught -kFBCdeletionFailed = -30510 #V-Twin exception caught -kFBCcommitFailed = -30509 #V-Twin exception caught -kFBCindexingFailed = -30508 #V-Twin exception caught -kFBCvalidationFailed = -30507 #V-Twin exception caught -kFBCcompactionFailed = -30506 #V-Twin exception caught -kFBCbadIndexFile = -30505 #bad FSSpec, or bad data in file -kFBCfileNotIndexed = -30504 #kFBCfileNotIndexed -kFBCbadParam = -30503 #kFBCbadParam -kFBCallocFailed = -30502 #probably low memory -kFBCnoIndexesFound = -30501 #kFBCnoIndexesFound -kFBCvTwinExceptionErr = -30500 #no telling what it was -kDSpStereoContextErr = -30450 #kDSpStereoContextErr -kDSpInternalErr = -30449 #kDSpInternalErr -kDSpConfirmSwitchWarning = -30448 #kDSpConfirmSwitchWarning -kDSpFrameRateNotReadyErr = -30447 #kDSpFrameRateNotReadyErr -kDSpContextNotFoundErr = -30446 #kDSpContextNotFoundErr -kDSpContextNotReservedErr = -30445 #kDSpContextNotReservedErr -kDSpContextAlreadyReservedErr = -30444 #kDSpContextAlreadyReservedErr -kDSpInvalidAttributesErr = -30443 #kDSpInvalidAttributesErr -kDSpInvalidContextErr = -30442 #kDSpInvalidContextErr -kDSpSystemSWTooOldErr = -30441 #kDSpSystemSWTooOldErr -kDSpNotInitializedErr = -30440 #kDSpNotInitializedErr -kISpListBusyErr = -30429 #kISpListBusyErr -kISpDeviceActiveErr = -30428 #kISpDeviceActiveErr -kISpSystemActiveErr = -30427 #kISpSystemActiveErr -kISpDeviceInactiveErr = -30426 #kISpDeviceInactiveErr -kISpSystemInactiveErr = -30425 #kISpSystemInactiveErr -kISpElementNotInListErr = -30424 #kISpElementNotInListErr -kISpElementInListErr = -30423 #kISpElementInListErr -kISpBufferToSmallErr = -30422 #kISpBufferToSmallErr -kISpSystemListErr = -30421 #kISpSystemListErr -kISpInternalErr = -30420 #kISpInternalErr -kNSpJoinFailedErr = -30399 #kNSpJoinFailedErr -kNSpCantBlockErr = -30398 #kNSpCantBlockErr -kNSpMessageTooBigErr = -30397 #kNSpMessageTooBigErr -kNSpSendFailedErr = -30396 #kNSpSendFailedErr -kNSpConnectFailedErr = -30395 #kNSpConnectFailedErr -kNSpGameTerminatedErr = -30394 #kNSpGameTerminatedErr -kNSpTimeoutErr = -30393 #kNSpTimeoutErr -kNSpInvalidProtocolListErr = -30392 #kNSpInvalidProtocolListErr -kNSpInvalidProtocolRefErr = -30391 #kNSpInvalidProtocolRefErr -kNSpInvalidDefinitionErr = -30390 #kNSpInvalidDefinitionErr -kNSpAddPlayerFailedErr = -30389 #kNSpAddPlayerFailedErr -kNSpCreateGroupFailedErr = -30388 #kNSpCreateGroupFailedErr -kNSpNoHostVolunteersErr = -30387 #kNSpNoHostVolunteersErr -kNSpNoGroupsErr = -30386 #kNSpNoGroupsErr -kNSpNoPlayersErr = -30385 #kNSpNoPlayersErr -kNSpInvalidGroupIDErr = -30384 #kNSpInvalidGroupIDErr -kNSpInvalidPlayerIDErr = -30383 #kNSpInvalidPlayerIDErr -kNSpNameRequiredErr = -30382 #kNSpNameRequiredErr -kNSpFeatureNotImplementedErr = -30381 #kNSpFeatureNotImplementedErr -kNSpAddressInUseErr = -30380 #kNSpAddressInUseErr -kNSpRemovePlayerFailedErr = -30379 #kNSpRemovePlayerFailedErr -kNSpFreeQExhaustedErr = -30378 #kNSpFreeQExhaustedErr -kNSpInvalidAddressErr = -30377 #kNSpInvalidAddressErr -kNSpNotAdvertisingErr = -30376 #kNSpNotAdvertisingErr -kNSpAlreadyAdvertisingErr = -30374 #kNSpAlreadyAdvertisingErr -kNSpMemAllocationErr = -30373 #kNSpMemAllocationErr -kNSpOTVersionTooOldErr = -30371 #kNSpOTVersionTooOldErr -kNSpOTNotPresentErr = -30370 #kNSpOTNotPresentErr -kNSpInvalidParameterErr = -30369 #kNSpInvalidParameterErr -kNSpInvalidGameRefErr = -30367 #kNSpInvalidGameRefErr -kNSpProtocolNotAvailableErr = -30366 #kNSpProtocolNotAvailableErr -kNSpHostFailedErr = -30365 #kNSpHostFailedErr -kNSpPipeFullErr = -30364 #kNSpPipeFullErr -kNSpTopologyNotSupportedErr = -30362 #kNSpTopologyNotSupportedErr -kNSpAlreadyInitializedErr = -30361 #kNSpAlreadyInitializedErr -kNSpInitializationFailedErr = -30360 #kNSpInitializationFailedErr -kSSpScaleToZeroErr = -30344 #kSSpScaleToZeroErr -kSSpParallelUpVectorErr = -30343 #kSSpParallelUpVectorErr -kSSpCantInstallErr = -30342 #kSSpCantInstallErr -kSSpVersionErr = -30341 #kSSpVersionErr -kSSpInternalErr = -30340 #kSSpInternalErr -kALMInternalErr = -30049 #kALMInternalErr -kALMGroupNotFoundErr = -30048 #kALMGroupNotFoundErr -kALMNoSuchModuleErr = -30047 #kALMNoSuchModuleErr -kALMModuleCommunicationErr = -30046 #kALMModuleCommunicationErr -kALMDuplicateModuleErr = -30045 #kALMDuplicateModuleErr -kALMInstallationErr = -30044 #kALMInstallationErr -kALMDeferSwitchErr = -30043 #kALMDeferSwitchErr -kALMRebootFlagsLevelErr = -30042 #kALMRebootFlagsLevelErr -kLocalesDefaultDisplayStatus = -30029 #Requested display locale unavailable, used default -kLocalesTableFormatErr = -30002 #kLocalesTableFormatErr -kLocalesBufferTooSmallErr = -30001 #kLocalesBufferTooSmallErr -kFNSNameNotFoundErr = -29589 #The name with the requested paramters was not found -kFNSBadFlattenedSizeErr = -29587 #flattened size didn't match input or was too small -kFNSInsufficientDataErr = -29586 #insufficient data for the operation -kFNSMismatchErr = -29585 #reference didn't match or wasn't found in profile -kFNSDuplicateReferenceErr = -29584 #the ref. being added is already in the profile -kFNSBadProfileVersionErr = -29583 #profile version is out of known range -kFNSInvalidProfileErr = -29582 #profile is NULL or otherwise bad -kFNSBadReferenceVersionErr = -29581 #ref. version is out of known range -kFNSInvalidReferenceErr = -29580 #ref. was NULL or otherwise bad -kCollateInvalidCollationRef = -29507 #kCollateInvalidCollationRef -kCollateBufferTooSmall = -29506 #kCollateBufferTooSmall -kCollateInvalidChar = -29505 #kCollateInvalidChar -kCollatePatternNotFoundErr = -29504 #kCollatePatternNotFoundErr -kCollateUnicodeConvertFailedErr = -29503 #kCollateUnicodeConvertFailedErr -kCollateMissingUnicodeTableErr = -29502 #kCollateMissingUnicodeTableErr -kCollateInvalidOptions = -29501 #kCollateInvalidOptions -kCollateAttributesNotFoundErr = -29500 #kCollateAttributesNotFoundErr -kMPInvalidIDErr = -29299 #kMPInvalidIDErr -kMPInsufficientResourcesErr = -29298 #kMPInsufficientResourcesErr -kMPTaskAbortedErr = -29297 #kMPTaskAbortedErr -kMPTimeoutErr = -29296 #kMPTimeoutErr -kMPDeletedErr = -29295 #kMPDeletedErr -kMPBlueBlockingErr = -29293 #kMPBlueBlockingErr -kMPTaskStoppedErr = -29292 #A convention used with MPThrowException. -kMPTaskBlockedErr = -29291 #kMPTaskBlockedErr -kMPTaskCreatedErr = -29290 #kMPTaskCreatedErr -kMPProcessTerminatedErr = -29289 #kMPProcessTerminatedErr -kMPProcessCreatedErr = -29288 #kMPProcessCreatedErr -kMPPrivilegedErr = -29276 #kMPPrivilegedErr -kMPIterationEndErr = -29275 #kMPIterationEndErr -kUCTextBreakLocatorMissingType = -25341 #Unicode text break error -kUCOutputBufferTooSmall = -25340 #Output buffer too small for Unicode string result -errKCCreateChainFailed = -25318 #errKCCreateChainFailed -errKCDataNotModifiable = -25317 #errKCDataNotModifiable -errKCDataNotAvailable = -25316 #errKCDataNotAvailable -errKCInteractionRequired = -25315 #errKCInteractionRequired -errKCNoPolicyModule = -25314 #errKCNoPolicyModule -errKCNoCertificateModule = -25313 #errKCNoCertificateModule -errKCNoStorageModule = -25312 #errKCNoStorageModule -errKCKeySizeNotAllowed = -25311 #errKCKeySizeNotAllowed -errKCWrongKCVersion = -25310 #errKCWrongKCVersion -errKCReadOnlyAttr = -25309 #errKCReadOnlyAttr -errKCInteractionNotAllowed = -25308 #errKCInteractionNotAllowed -errKCNoDefaultKeychain = -25307 #errKCNoDefaultKeychain -errKCNoSuchClass = -25306 #errKCNoSuchClass -errKCInvalidSearchRef = -25305 #errKCInvalidSearchRef -errKCInvalidItemRef = -25304 #errKCInvalidItemRef -errKCNoSuchAttr = -25303 #errKCNoSuchAttr -errKCDataTooLarge = -25302 #errKCDataTooLarge -errKCBufferTooSmall = -25301 #errKCBufferTooSmall -errKCItemNotFound = -25300 #errKCItemNotFound -errKCDuplicateItem = -25299 #errKCDuplicateItem -errKCInvalidCallback = -25298 #errKCInvalidCallback -errKCDuplicateCallback = -25297 #errKCDuplicateCallback -errKCDuplicateKeychain = -25296 #errKCDuplicateKeychain -errKCInvalidKeychain = -25295 #errKCInvalidKeychain -errKCNoSuchKeychain = -25294 #errKCNoSuchKeychain -errKCAuthFailed = -25293 #errKCAuthFailed -errKCReadOnly = -25292 #errKCReadOnly -errKCNotAvailable = -25291 #errKCNotAvailable -printerStatusOpCodeNotSupportedErr = -25280 #printerStatusOpCodeNotSupportedErr -kTXNOutsideOfFrameErr = -22018 #kTXNOutsideOfFrameErr -kTXNOutsideOfLineErr = -22017 #kTXNOutsideOfLineErr -kTXNATSUIIsNotInstalledErr = -22016 #kTXNATSUIIsNotInstalledErr -kTXNDataTypeNotAllowedErr = -22015 #kTXNDataTypeNotAllowedErr -kTXNCopyNotAllowedInEchoModeErr = -22014 #kTXNCopyNotAllowedInEchoModeErr -kTXNCannotTurnTSMOffWhenUsingUnicodeErr = -22013 #kTXNCannotTurnTSMOffWhenUsingUnicodeErr -kTXNAlreadyInitializedErr = -22012 #kTXNAlreadyInitializedErr -kTXNInvalidRunIndex = -22011 #kTXNInvalidRunIndex -kTXNSomeOrAllTagsInvalidForRunErr = -22010 #kTXNSomeOrAllTagsInvalidForRunErr -kTXNAttributeTagInvalidForRunErr = -22009 #dataValue is set to this per invalid tag -kTXNNoMatchErr = -22008 #kTXNNoMatchErr -kTXNRunIndexOutofBoundsErr = -22007 #kTXNRunIndexOutofBoundsErr -kTXNCannotSetAutoIndentErr = -22006 #kTXNCannotSetAutoIndentErr -kTXNBadDefaultFileTypeWarning = -22005 #kTXNBadDefaultFileTypeWarning -kTXNUserCanceledOperationErr = -22004 #kTXNUserCanceledOperationErr -kTXNIllegalToCrossDataBoundariesErr = -22003 #kTXNIllegalToCrossDataBoundariesErr -kTXNInvalidFrameIDErr = -22002 #kTXNInvalidFrameIDErr -kTXNCannotAddFrameErr = -22001 #kTXNCannotAddFrameErr -kTXNEndIterationErr = -22000 #kTXNEndIterationErr -invalidIndexErr = -20002 #The recordIndex parameter is not valid. -recordDataTooBigErr = -20001 #The record data is bigger than buffer size (1024 bytes). -unknownInsertModeErr = -20000 #There is no such an insert mode. -kModemScriptMissing = -14002 #kModemScriptMissing -kModemPreferencesMissing = -14001 #kModemPreferencesMissing -kModemOutOfMemory = -14000 #kModemOutOfMemory -kHIDBaseError = -13950 #kHIDBaseError -kHIDNullStateErr = -13949 #kHIDNullStateErr -kHIDBufferTooSmallErr = -13948 #kHIDBufferTooSmallErr -kHIDValueOutOfRangeErr = -13947 #kHIDValueOutOfRangeErr -kHIDUsageNotFoundErr = -13946 #kHIDUsageNotFoundErr -kHIDNotValueArrayErr = -13945 #kHIDNotValueArrayErr -kHIDInvalidPreparsedDataErr = -13944 #kHIDInvalidPreparsedDataErr -kHIDIncompatibleReportErr = -13943 #kHIDIncompatibleReportErr -kHIDBadLogPhysValuesErr = -13942 #kHIDBadLogPhysValuesErr -kHIDInvalidReportTypeErr = -13941 #kHIDInvalidReportTypeErr -kHIDInvalidReportLengthErr = -13940 #kHIDInvalidReportLengthErr -kHIDNullPointerErr = -13939 #kHIDNullPointerErr -kHIDBadParameterErr = -13938 #kHIDBadParameterErr -kHIDNotEnoughMemoryErr = -13937 #kHIDNotEnoughMemoryErr -kHIDEndOfDescriptorErr = -13936 #kHIDEndOfDescriptorErr -kHIDUsagePageZeroErr = -13935 #kHIDUsagePageZeroErr -kHIDBadLogicalMinimumErr = -13934 #kHIDBadLogicalMinimumErr -kHIDBadLogicalMaximumErr = -13933 #kHIDBadLogicalMaximumErr -kHIDInvertedLogicalRangeErr = -13932 #kHIDInvertedLogicalRangeErr -kHIDInvertedPhysicalRangeErr = -13931 #kHIDInvertedPhysicalRangeErr -kHIDUnmatchedUsageRangeErr = -13930 #kHIDUnmatchedUsageRangeErr -kHIDInvertedUsageRangeErr = -13929 #kHIDInvertedUsageRangeErr -kHIDUnmatchedStringRangeErr = -13928 #kHIDUnmatchedStringRangeErr -kHIDUnmatchedDesignatorRangeErr = -13927 #kHIDUnmatchedDesignatorRangeErr -kHIDReportSizeZeroErr = -13926 #kHIDReportSizeZeroErr -kHIDReportCountZeroErr = -13925 #kHIDReportCountZeroErr -kHIDReportIDZeroErr = -13924 #kHIDReportIDZeroErr -kHIDInvalidRangePageErr = -13923 #kHIDInvalidRangePageErr -kHIDDeviceNotReady = -13910 #The device is still initializing, try again later -kHIDVersionIncompatibleErr = -13909 #kHIDVersionIncompatibleErr -debuggingNoMatchErr = -13887 #debugging component or option not found at this index -debuggingNoCallbackErr = -13886 #debugging component has no callback -debuggingInvalidNameErr = -13885 #componentName or optionName is invalid (NULL) -debuggingInvalidOptionErr = -13884 #optionSelectorNum is not registered -debuggingInvalidSignatureErr = -13883 #componentSignature not registered -debuggingDuplicateOptionErr = -13882 #optionSelectorNum already registered -debuggingDuplicateSignatureErr = -13881 #componentSignature already registered -debuggingExecutionContextErr = -13880 #routine cannot be called at this time -kBridgeSoftwareRunningCantSleep = -13038 #kBridgeSoftwareRunningCantSleep -kNoSuchPowerSource = -13020 #kNoSuchPowerSource -kProcessorTempRoutineRequiresMPLib2 = -13014 #kProcessorTempRoutineRequiresMPLib2 -kCantReportProcessorTemperatureErr = -13013 #kCantReportProcessorTemperatureErr -kPowerMgtRequestDenied = -13010 #kPowerMgtRequestDenied -kPowerMgtMessageNotHandled = -13009 #kPowerMgtMessageNotHandled -kPowerHandlerNotFoundForProcErr = -13008 #kPowerHandlerNotFoundForProcErr -kPowerHandlerNotFoundForDeviceErr = -13007 #kPowerHandlerNotFoundForDeviceErr -kPowerHandlerExistsForDeviceErr = -13006 #kPowerHandlerExistsForDeviceErr -pmRecvEndErr = -13005 #during receive, pmgr did not finish hs configured for this connection -pmRecvStartErr = -13004 #during receive, pmgr did not start hs -pmSendEndErr = -13003 #during send, pmgr did not finish hs -pmSendStartErr = -13002 #during send, pmgr did not start hs -pmReplyTOErr = -13001 #Timed out waiting for reply -pmBusyErr = -13000 #Power Mgr never ready to start handshake -pictureDataErr = -11005 #the picture data was invalid -colorsRequestedErr = -11004 #the number of colors requested was illegal -cantLoadPickMethodErr = -11003 #unable to load the custom pick proc -pictInfoVerbErr = -11002 #the passed verb was invalid -pictInfoIDErr = -11001 #the internal consistancy check for the PictInfoID is wrong -pictInfoVersionErr = -11000 #wrong version of the PictInfo structure -errTaskNotFound = -10780 #no task with that task id exists -telNotEnoughdspBW = -10116 #not enough real-time for allocation -telBadSampleRate = -10115 #incompatible sample rate -telBadSWErr = -10114 #Software not installed properly -telDetAlreadyOn = -10113 #detection is already turned on -telAutoAnsNotOn = -10112 #autoAnswer in not turned on -telValidateFailed = -10111 #telValidate failed -telBadProcID = -10110 #invalid procID -telDeviceNotFound = -10109 #device not found -telBadCodeResource = -10108 #code resource not found -telInitFailed = -10107 #initialization failed -telNoCommFolder = -10106 #Communications/Extensions € not found -telUnknownErr = -10103 #unable to set config -telNoSuchTool = -10102 #unable to find tool with name specified -telBadFunction = -10091 #bad msgCode specified -telPBErr = -10090 #parameter block error, bad format -telCANotDeflectable = -10082 #CA not "deflectable" -telCANotRejectable = -10081 #CA not "rejectable" -telCANotAcceptable = -10080 #CA not "acceptable" -telTermNotOpen = -10072 #terminal not opened via TELOpenTerm -telStillNeeded = -10071 #terminal driver still needed by someone else -telAlreadyOpen = -10070 #terminal already open -telNoCallbackRef = -10064 #no call back reference was specified, but is required -telDisplayModeNotSupp = -10063 #display mode not supported by tool -telBadDisplayMode = -10062 #bad display mode specified -telFwdTypeNotSupp = -10061 #forward type not supported by tool -telDNTypeNotSupp = -10060 #DN type not supported by tool -telBadRate = -10059 #bad rate specified -telBadBearerType = -10058 #bad bearerType specified -telBadSelect = -10057 #unable to select or deselect DN -telBadParkID = -10056 #bad park id specified -telBadPickupGroupID = -10055 #bad pickup group ID specified -telBadFwdType = -10054 #bad fwdType specified -telBadFeatureID = -10053 #bad feature ID specified -telBadIntercomID = -10052 #bad intercom ID specified -telBadPageID = -10051 #bad page ID specified -telBadDNType = -10050 #DN type invalid -telConfLimitExceeded = -10047 #attempt to exceed switch conference limits -telCBErr = -10046 #call back feature not set previously -telTransferRej = -10045 #transfer request rejected -telTransferErr = -10044 #transfer not prepared -telConfRej = -10043 #conference request was rejected -telConfErr = -10042 #conference was not prepared -telConfNoLimit = -10041 #no limit was specified but required -telConfLimitErr = -10040 #limit specified is too high for this configuration -telFeatNotSupp = -10033 #feature program call not supported by this tool -telFeatActive = -10032 #feature already active -telFeatNotAvail = -10031 #feature subscribed but not available -telFeatNotSub = -10030 #feature not subscribed -errAEPropertiesClash = -10025 #illegal combination of properties settings for Set Data, make new, or duplicate -errAECantPutThatThere = -10024 #in make new, duplicate, etc. class can't be an element of container -errAENotAnEnumMember = -10023 #enumerated value in SetData is not allowed for this property -telIntExtNotSupp = -10022 #internal external type not supported by this tool -telBadIntExt = -10021 #bad internal external error -telStateNotSupp = -10020 #device state not supported by tool -telBadStateErr = -10019 #bad device state specified -telIndexNotSupp = -10018 #index not supported by this tool -telBadIndex = -10017 #bad index specified -telAPattNotSupp = -10016 #alerting pattern not supported by tool -telBadAPattErr = -10015 #bad alerting pattern specified -telVTypeNotSupp = -10014 #volume type not supported by this tool -telBadVTypeErr = -10013 #bad volume type error -telBadLevelErr = -10012 #bad volume level setting -telHTypeNotSupp = -10011 #hook type not supported by this tool -telBadHTypeErr = -10010 #bad hook type specified -errAECantSupplyType = -10009 #errAECantSupplyType -telNoOpenErr = -10008 #unable to open terminal -telNoMemErr = -10007 #no memory to allocate handle -errOSACantAssign = -10006 #Signaled when an object cannot be set in a container. -telBadProcErr = -10005 #bad msgProc specified -telBadHandErr = -10004 #bad handle specified -OSAIllegalAssign = -10003 #Signaled when an object can never be set in a container -telBadDNErr = -10002 #TELDNHandle not found or invalid -telBadTermErr = -10001 #invalid TELHandle or handle not found -errAEEventFailed = -10000 #errAEEventFailed -cannotMoveAttachedController = -9999 #cannotMoveAttachedController -controllerHasFixedHeight = -9998 #controllerHasFixedHeight -cannotSetWidthOfAttachedController = -9997 #cannotSetWidthOfAttachedController -controllerBoundsNotExact = -9996 #controllerBoundsNotExact -editingNotAllowed = -9995 #editingNotAllowed -badControllerHeight = -9994 #badControllerHeight -deviceCantMeetRequest = -9408 #deviceCantMeetRequest -seqGrabInfoNotAvailable = -9407 #seqGrabInfoNotAvailable -badSGChannel = -9406 #badSGChannel -couldntGetRequiredComponent = -9405 #couldntGetRequiredComponent -notEnoughDiskSpaceToGrab = -9404 #notEnoughDiskSpaceToGrab -notEnoughMemoryToGrab = -9403 #notEnoughMemoryToGrab -cantDoThatInCurrentMode = -9402 #cantDoThatInCurrentMode -grabTimeComplete = -9401 #grabTimeComplete -noDeviceForChannel = -9400 #noDeviceForChannel -kNoCardBusCISErr = -9109 #No valid CIS exists for this CardBus card -kNotZVCapableErr = -9108 #This socket does not support Zoomed Video -kCardPowerOffErr = -9107 #Power to the card has been turned off -kAttemptDupCardEntryErr = -9106 #The Enabler was asked to create a duplicate card entry -kAlreadySavedStateErr = -9105 #The state has been saved on previous call -kTooManyIOWindowsErr = -9104 #device requested more than one I/O window -kNotReadyErr = -9103 #PC Card failed to go ready -kClientRequestDenied = -9102 #CS Clients should return this code inorder to -kNoCompatibleNameErr = -9101 #There is no compatible driver name for this device -kNoEnablerForCardErr = -9100 #No Enablers were found that can support the card -kNoCardEnablersFoundErr = -9099 #No Enablers were found -kUnsupportedCardErr = -9098 #Card not supported by generic enabler -kNoClientTableErr = -9097 #The client table has not be initialized yet -kNoMoreInterruptSlotsErr = -9096 #All internal Interrupt slots are in use -kNoMoreTimerClientsErr = -9095 #All timer callbacks are in use -kNoIOWindowRequestedErr = -9094 #Request I/O window before calling configuration -kBadCustomIFIDErr = -9093 #Custom interface ID is invalid -kBadTupleDataErr = -9092 #Data in tuple is invalid -kInvalidCSClientErr = -9091 #Card Services ClientID is not registered -kUnsupportedVsErr = -9090 #Unsupported Voltage Sense -kInvalidDeviceNumber = -9089 #kInvalidDeviceNumber -kPostCardEventErr = -9088 #_PCCSLPostCardEvent failed and dropped an event -kCantConfigureCardErr = -9087 #kCantConfigureCardErr -kPassCallToChainErr = -9086 #kPassCallToChainErr -kCardBusCardErr = -9085 #kCardBusCardErr -k16BitCardErr = -9084 #k16BitCardErr -kBadDeviceErr = -9083 #kBadDeviceErr -kBadLinkErr = -9082 #kBadLinkErr -kInvalidRegEntryErr = -9081 #kInvalidRegEntryErr -kNoCardSevicesSocketsErr = -9080 #kNoCardSevicesSocketsErr -kOutOfResourceErr = -9079 #Card Services has exhausted the resource -kNoMoreItemsErr = -9078 #there are no more of the requested item -kInUseErr = -9077 #requested resource is being used by a client -kConfigurationLockedErr = -9076 #a configuration has already been locked -kWriteProtectedErr = -9075 #media is write-protected -kBusyErr = -9074 #unable to process request at this time - try later -kUnsupportedModeErr = -9073 #mode is not supported -kUnsupportedFunctionErr = -9072 #function is not supported by this implementation -kNoCardErr = -9071 #no PC card in the socket -kGeneralFailureErr = -9070 #an undefined error has occurred -kWriteFailureErr = -9069 #unable to complete write request -kReadFailureErr = -9068 #unable to complete read request -kBadSpeedErr = -9067 #specified speed is unavailable -kBadCISErr = -9066 #CIS on card is invalid -kBadHandleErr = -9065 #clientHandle is invalid -kBadArgsErr = -9064 #values in argument packet are invalid -kBadArgLengthErr = -9063 #ArgLength argument is invalid -kBadWindowErr = -9062 #specified window is invalid -kBadVppErr = -9061 #specified Vpp1 or Vpp2 power level index is invalid -kBadVccErr = -9060 #specified Vcc power level index is invalid -kBadTypeErr = -9059 #specified window or interface type is invalid -kBadSocketErr = -9058 #specified logical or physical socket number is invalid -kBadSizeErr = -9057 #specified size is invalid -kBadPageErr = -9056 #specified page is invalid -kBadOffsetErr = -9055 #specified PC card memory array offset is invalid -kBadIRQErr = -9054 #specified IRQ level is invalid -kBadEDCErr = -9053 #specified EDC generator specified is invalid -kBadBaseErr = -9052 #specified base system memory address is invalid -kBadAttributeErr = -9051 #specified attributes field value is invalid -kBadAdapterErr = -9050 #invalid adapter number -codecOffscreenFailedPleaseRetryErr = -8992 #codecOffscreenFailedPleaseRetryErr -lockPortBitsWrongGDeviceErr = -8991 #lockPortBitsWrongGDeviceErr -directXObjectAlreadyExists = -8990 #directXObjectAlreadyExists -codecDroppedFrameErr = -8989 #returned from ImageCodecDrawBand -codecOffscreenFailedErr = -8988 #codecOffscreenFailedErr -codecNeedAccessKeyErr = -8987 #codec needs password in order to decompress -codecParameterDialogConfirm = -8986 #codecParameterDialogConfirm -lockPortBitsSurfaceLostErr = -8985 #lockPortBitsSurfaceLostErr -lockPortBitsBadPortErr = -8984 #lockPortBitsBadPortErr -lockPortBitsWindowClippedErr = -8983 #lockPortBitsWindowClippedErr -lockPortBitsWindowResizedErr = -8982 #lockPortBitsWindowResizedErr -lockPortBitsWindowMovedErr = -8981 #lockPortBitsWindowMovedErr -lockPortBitsBadSurfaceErr = -8980 #lockPortBitsBadSurfaceErr -codecNeedToFlushChainErr = -8979 #codecNeedToFlushChainErr -codecDisabledErr = -8978 #codec disabled itself -- pass codecFlagReenable to reset -codecNoMemoryPleaseWaitErr = -8977 #codecNoMemoryPleaseWaitErr -codecNothingToBlitErr = -8976 #codecNothingToBlitErr -codecCantQueueErr = -8975 #codecCantQueueErr -codecCantWhenErr = -8974 #codecCantWhenErr -codecOpenErr = -8973 #codecOpenErr -codecConditionErr = -8972 #codecConditionErr -codecExtensionNotFoundErr = -8971 #codecExtensionNotFoundErr -codecDataVersErr = -8970 #codecDataVersErr -codecBadDataErr = -8969 #codecBadDataErr -codecWouldOffscreenErr = -8968 #codecWouldOffscreenErr -codecAbortErr = -8967 #codecAbortErr -codecSpoolErr = -8966 #codecSpoolErr -codecImageBufErr = -8965 #codecImageBufErr -codecScreenBufErr = -8964 #codecScreenBufErr -codecSizeErr = -8963 #codecSizeErr -codecUnimpErr = -8962 #codecUnimpErr -noCodecErr = -8961 #noCodecErr -codecErr = -8960 #codecErr -kIllegalClockValueErr = -8852 #kIllegalClockValueErr -kUTCOverflowErr = -8851 #kUTCOverflowErr -kUTCUnderflowErr = -8850 #kUTCUnderflowErr -kATSULastErr = -8809 #The last ATSUI error code. -kATSULineBreakInWord = -8808 #This is not an error code but is returned by ATSUBreakLine to -kATSUCoordinateOverflowErr = -8807 #Used to indicate the coordinates provided to an ATSUI routine caused -kATSUNoFontScalerAvailableErr = -8806 #Used when no font scaler is available for the font passed -kATSUNoFontCmapAvailableErr = -8805 #Used when no CMAP table can be accessed or synthesized for the -kATSULowLevelErr = -8804 #Used when an error was encountered within the low level ATS -kATSUQuickDrawTextErr = -8803 #Used when QuickDraw Text encounters an error rendering or measuring -kATSUNoStyleRunsAssignedErr = -8802 #Used when an attempt was made to measure, highlight or draw -kATSUNotSetErr = -8801 #Used when the client attempts to retrieve an attribute, -kATSUInvalidCacheErr = -8800 #Used when an attempt was made to read in style data -kATSUInvalidAttributeTagErr = -8799 #Used when an attempt was made to use a tag value that -kATSUInvalidAttributeSizeErr = -8798 #Used when an attempt was made to use an attribute with a -kATSUInvalidAttributeValueErr = -8797 #Used when an attempt was made to use an attribute with -kATSUInvalidFontErr = -8796 #Used when an attempt was made to use an invalid font ID. -kATSUNoCorrespondingFontErr = -8795 #This value is retrned by font ID conversion -kATSUFontsNotMatched = -8794 #This value is returned by ATSUMatchFontsToText() -kATSUFontsMatched = -8793 #This is not an error code but is returned by -kATSUInvalidTextRangeErr = -8792 #An attempt was made to extract information -kATSUInvalidStyleErr = -8791 #An attempt was made to use a ATSUStyle which -kATSUInvalidTextLayoutErr = -8790 #An attempt was made to use a ATSUTextLayout -kTECOutputBufferFullStatus = -8785 #output buffer has no room for conversion of next input text element (partial conversion) -kTECNeedFlushStatus = -8784 #kTECNeedFlushStatus -kTECUsedFallbacksStatus = -8783 #kTECUsedFallbacksStatus -kTECItemUnavailableErr = -8771 #item (e.g. name) not available for specified region (& encoding if relevant) -kTECGlobalsUnavailableErr = -8770 #globals have already been deallocated (premature TERM) -unicodeChecksumErr = -8769 #unicodeChecksumErr -unicodeNoTableErr = -8768 #unicodeNoTableErr -unicodeVariantErr = -8767 #unicodeVariantErr -unicodeFallbacksErr = -8766 #unicodeFallbacksErr -unicodePartConvertErr = -8765 #unicodePartConvertErr -unicodeBufErr = -8764 #unicodeBufErr -unicodeCharErr = -8763 #unicodeCharErr -unicodeElementErr = -8762 #unicodeElementErr -unicodeNotFoundErr = -8761 #unicodeNotFoundErr -unicodeTableFormatErr = -8760 #unicodeTableFormatErr -unicodeDirectionErr = -8759 #unicodeDirectionErr -unicodeContextualErr = -8758 #unicodeContextualErr -unicodeTextEncodingDataErr = -8757 #unicodeTextEncodingDataErr -kTECDirectionErr = -8756 #direction stack overflow, etc. -kTECIncompleteElementErr = -8755 #text element may be incomplete or is too long for internal buffers -kTECUnmappableElementErr = -8754 #kTECUnmappableElementErr -kTECPartialCharErr = -8753 #input buffer ends in the middle of a multibyte character, conversion stopped -kTECBadTextRunErr = -8752 #kTECBadTextRunErr -kTECArrayFullErr = -8751 #supplied name buffer or TextRun, TextEncoding, or UnicodeMapping array is too small -kTECBufferBelowMinimumSizeErr = -8750 #output buffer too small to allow processing of first input text element -kTECNoConversionPathErr = -8749 #kTECNoConversionPathErr -kTECCorruptConverterErr = -8748 #invalid converter object reference -kTECTableFormatErr = -8747 #kTECTableFormatErr -kTECTableChecksumErr = -8746 #kTECTableChecksumErr -kTECMissingTableErr = -8745 #kTECMissingTableErr -kTextUndefinedElementErr = -8740 #text conversion errors -kTextMalformedInputErr = -8739 #in DBCS, for example, high byte followed by invalid low byte -kTextUnsupportedEncodingErr = -8738 #specified encoding not supported for this operation -kRANotEnabled = -7139 #kRANotEnabled -kRACallBackFailed = -7138 #kRACallBackFailed -kRADuplicateIPAddr = -7137 #kRADuplicateIPAddr -kRANCPRejectedbyPeer = -7136 #kRANCPRejectedbyPeer -kRAExtAuthenticationFailed = -7135 #kRAExtAuthenticationFailed -kRAATalkInactive = -7134 #kRAATalkInactive -kRAPeerNotResponding = -7133 #kRAPeerNotResponding -kRAPPPPeerDisconnected = -7132 #kRAPPPPeerDisconnected -kRAPPPUserDisconnected = -7131 #kRAPPPUserDisconnected -kRAPPPNegotiationFailed = -7130 #kRAPPPNegotiationFailed -kRAPPPAuthenticationFailed = -7129 #kRAPPPAuthenticationFailed -kRAPPPProtocolRejected = -7128 #kRAPPPProtocolRejected -dcmBufferOverflowErr = -7127 #data is larger than buffer size -kRANotPrimaryInterface = -7126 #when IPCP is not primary TCP/IP intf. -kRATCPIPNotConfigured = -7125 #TCP/IP not configured, could be loaded -kRATCPIPInactive = -7124 #TCP/IP inactive, cannot be loaded -kRARemoteAccessNotReady = -7123 #kRARemoteAccessNotReady -kRAInitOpenTransportFailed = -7122 #kRAInitOpenTransportFailed -dcmProtectedErr = -7121 #need keyword to use dictionary -kRAUserPwdEntryRequired = -7120 #kRAUserPwdEntryRequired -kRAUserPwdChangeRequired = -7119 #kRAUserPwdChangeRequired -dcmBadFindMethodErr = -7118 #no such find method supported -kRAInvalidSerialProtocol = -7117 #kRAInvalidSerialProtocol -kRAInvalidPortState = -7116 #kRAInvalidPortState -dcmBadKeyErr = -7115 #bad key information -kRAPortBusy = -7114 #kRAPortBusy -kRAInstallationDamaged = -7113 #kRAInstallationDamaged -dcmBadFieldTypeErr = -7112 #no such field type supported -dcmBadFieldInfoErr = -7111 #incomplete information -dcmNecessaryFieldErr = -7110 #lack required/identify field -dcmDupRecordErr = -7109 #same record already exist -kRANotConnected = -7108 #kRANotConnected -dcmBlockFullErr = -7107 #dictionary block full -kRAMissingResources = -7106 #kRAMissingResources -dcmDictionaryBusyErr = -7105 #dictionary is busy -dcmDictionaryNotOpenErr = -7104 #dictionary not opened -dcmPermissionErr = -7103 #invalid permission -dcmBadDictionaryErr = -7102 #invalid dictionary -dcmNotDictionaryErr = -7101 #not dictionary -kRAInvalidParameter = -7100 #kRAInvalidParameter -laEngineNotFoundErr = -7000 #can't find the engine -laPropertyErr = -6999 #Error in properties -kUSBUnknownDeviceErr = -6998 #device ref not recognised -laPropertyIsReadOnlyErr = -6997 #the property is read only -laPropertyUnknownErr = -6996 #the property is unknown to this environment -laPropertyValueErr = -6995 #Invalid property value -laDictionaryTooManyErr = -6994 #too many dictionaries -laDictionaryUnknownErr = -6993 #can't use this dictionary with this environment -laDictionaryNotOpenedErr = -6992 #the dictionary is not opened -laTextOverFlowErr = -6991 #text is too long -laFailAnalysisErr = -6990 #analysis failed -laNoMoreMorphemeErr = -6989 #nothing to read -laInvalidPathErr = -6988 #path is not correct -kUSBNotHandled = -6987 #Notification was not handled (same as NotFound) -laEnvironmentNotFoundErr = -6986 #can't fint the specified environment -laEnvironmentBusyErr = -6985 #specified environment is used -laTooSmallBufferErr = -6984 #output buffer is too small to store any result -kUSBFlagsError = -6983 #Unused flags not zeroed -kUSBAbortedError = -6982 #Pipe aborted -kUSBNoBandwidthError = -6981 #Not enough bandwidth available -kUSBPipeIdleError = -6980 #Pipe is Idle, it will not accept transactions -kUSBPipeStalledError = -6979 #Pipe has stalled, error needs to be cleared -kUSBUnknownInterfaceErr = -6978 #Interface ref not recognised -kUSBDeviceBusy = -6977 #Device is already being configured -kUSBDevicePowerProblem = -6976 #Device has a power problem -kUSBInvalidBuffer = -6975 #bad buffer, usually nil -kUSBDeviceSuspended = -6974 #Device is suspended -kUSBDeviceNotSuspended = -6973 #device is not suspended for resume -kUSBDeviceDisconnected = -6972 #Disconnected during suspend or reset -kUSBTimedOut = -6971 #Transaction timed out. -kUSBQueueAborted = -6970 #Pipe zero stall cleared. -kUSBPortDisabled = -6969 #The port you are attached to is disabled, use USBDeviceReset. -kUSBBadDispatchTable = -6950 #Improper driver dispatch table -kUSBUnknownNotification = -6949 #Notification type not defined -kUSBQueueFull = -6948 #Internal queue maxxed -kUSBLinkErr = -6916 #kUSBLinkErr -kUSBCRCErr = -6915 #Pipe stall, bad CRC -kUSBBitstufErr = -6914 #Pipe stall, bitstuffing -kUSBDataToggleErr = -6913 #Pipe stall, Bad data toggle -kUSBEndpointStallErr = -6912 #Device didn't understand -kUSBNotRespondingErr = -6911 #Pipe stall, No device, device hung -kUSBPIDCheckErr = -6910 #Pipe stall, PID CRC error -kUSBWrongPIDErr = -6909 #Pipe stall, Bad or wrong PID -kUSBOverRunErr = -6908 #Packet too large or more data than buffer -kUSBUnderRunErr = -6907 #Less data than buffer -kUSBRes1Err = -6906 #kUSBRes1Err -kUSBRes2Err = -6905 #kUSBRes2Err -kUSBBufOvrRunErr = -6904 #Host hardware failure on data in, PCI busy? -kUSBBufUnderRunErr = -6903 #Host hardware failure on data out, PCI busy? -kUSBNotSent1Err = -6902 #Transaction not sent -kUSBNotSent2Err = -6901 #Transaction not sent -kDMFoundErr = -6232 #Did not proceed because we found an item -kDMMainDisplayCannotMoveErr = -6231 #Trying to move main display (or a display mirrored to it) -kDMDisplayAlreadyInstalledErr = -6230 #Attempt to add an already installed display. -kDMDisplayNotFoundErr = -6229 #Could not find item (will someday remove). -kDMDriverNotDisplayMgrAwareErr = -6228 #Video Driver does not support display manager. -kDMSWNotInitializedErr = -6227 #Required software not initialized (eg windowmanager or display mgr). -kSysSWTooOld = -6226 #Missing critical pieces of System Software. -kDMMirroringNotOn = -6225 #Returned by all calls that need mirroring to be on to do their thing. -kDMCantBlock = -6224 #Mirroring is already on, canÕt Block now (call DMUnMirror() first). -kDMMirroringBlocked = -6223 #DMBlockMirroring() has been called. -kDMWrongNumberOfDisplays = -6222 #Can only handle 2 displays for now. -kDMMirroringOnAlready = -6221 #Returned by all calls that need mirroring to be off to do their thing. -kDMGenErr = -6220 #Unexpected Error -kQTSSUnknownErr = -6150 #kQTSSUnknownErr -collectionVersionErr = -5753 #collectionVersionErr -collectionIndexRangeErr = -5752 #collectionIndexRangeErr -collectionItemNotFoundErr = -5751 #collectionItemNotFoundErr -collectionItemLockedErr = -5750 #collectionItemLockedErr -kNavMissingKindStringErr = -5699 #kNavMissingKindStringErr -kNavInvalidCustomControlMessageErr = -5698 #kNavInvalidCustomControlMessageErr -kNavCustomControlMessageFailedErr = -5697 #kNavCustomControlMessageFailedErr -kNavInvalidSystemConfigErr = -5696 #kNavInvalidSystemConfigErr -kNavWrongDialogClassErr = -5695 #kNavWrongDialogClassErr -kNavWrongDialogStateErr = -5694 #kNavWrongDialogStateErr -dialogNoTimeoutErr = -5640 #dialogNoTimeoutErr -menuInvalidErr = -5623 #menu is invalid -menuItemNotFoundErr = -5622 #specified menu item wasn't found -menuUsesSystemDefErr = -5621 #GetMenuDefinition failed because the menu uses the system MDEF -menuNotFoundErr = -5620 #specified menu or menu ID wasn't found -windowWrongStateErr = -5615 #window is not in a state that is valid for the current action -windowManagerInternalErr = -5614 #something really weird happened inside the window manager -windowAttributesConflictErr = -5613 #passed some attributes that are mutually exclusive -windowAttributeImmutableErr = -5612 #tried to change attributes which can't be changed -errWindowDoesNotFitOnscreen = -5611 #ConstrainWindowToScreen could not make the window fit onscreen -errWindowNotFound = -5610 #returned from FindWindowOfClass -errFloatingWindowsNotInitialized = -5609 #called HideFloatingWindows or ShowFloatingWindows without calling InitFloatingWindows -errWindowsAlreadyInitialized = -5608 #tried to call InitFloatingWindows twice, or called InitWindows and then floating windows -errUserWantsToDragWindow = -5607 #if returned from TrackWindowProxyDrag, you should call DragWindow on the window -errCorruptWindowDescription = -5606 #tried to load a corrupt window description (size or version fields incorrect) -errUnrecognizedWindowClass = -5605 #tried to create a window with a bad WindowClass -errWindowPropertyNotFound = -5604 #tried to get a nonexistent property -errInvalidWindowProperty = -5603 #tried to access a property tag with private creator -errWindowDoesNotHaveProxy = -5602 #tried to do something requiring a proxy to a window which doesnÕt have a proxy -errUnsupportedWindowAttributesForClass = -5601 #tried to create a window with WindowAttributes not supported by the WindowClass -errInvalidWindowPtr = -5600 #tried to pass a bad WindowRef argument -gestaltLocationErr = -5553 #gestalt function ptr wasn't in sysheap -gestaltDupSelectorErr = -5552 #tried to add an entry that already existed -gestaltUndefSelectorErr = -5551 #undefined selector was passed to Gestalt -gestaltUnknownErr = -5550 #value returned if Gestalt doesn't know the answer -envVersTooBig = -5502 #Version bigger than call can handle -envBadVers = -5501 #Version non-positive -envNotPresent = -5500 #returned by glue. -qtsAddressBusyErr = -5421 #qtsAddressBusyErr -qtsConnectionFailedErr = -5420 #qtsConnectionFailedErr -qtsTimeoutErr = -5408 #qtsTimeoutErr -qtsUnknownValueErr = -5407 #qtsUnknownValueErr -qtsTooMuchDataErr = -5406 #qtsTooMuchDataErr -qtsUnsupportedFeatureErr = -5405 #qtsUnsupportedFeatureErr -qtsUnsupportedRateErr = -5404 #qtsUnsupportedRateErr -qtsUnsupportedDataTypeErr = -5403 #qtsUnsupportedDataTypeErr -qtsBadDataErr = -5402 #something is wrong with the data -qtsBadStateErr = -5401 #qtsBadStateErr -qtsBadSelectorErr = -5400 #qtsBadSelectorErr -errIAEndOfTextRun = -5388 #errIAEndOfTextRun -errIATextExtractionErr = -5387 #errIATextExtractionErr -errIAInvalidDocument = -5386 #errIAInvalidDocument -errIACanceled = -5385 #errIACanceled -errIABufferTooSmall = -5384 #errIABufferTooSmall -errIANoMoreItems = -5383 #errIANoMoreItems -errIAParamErr = -5382 #errIAParamErr -errIAAllocationErr = -5381 #errIAAllocationErr -errIAUnknownErr = -5380 #errIAUnknownErr -hrURLNotHandledErr = -5363 #hrURLNotHandledErr -hrUnableToResizeHandleErr = -5362 #hrUnableToResizeHandleErr -hrMiscellaneousExceptionErr = -5361 #hrMiscellaneousExceptionErr -hrHTMLRenderingLibNotInstalledErr = -5360 #hrHTMLRenderingLibNotInstalledErr -errCannotUndo = -5253 #errCannotUndo -errNonContiuousAttribute = -5252 #errNonContiuousAttribute -errUnknownElement = -5251 #errUnknownElement -errReadOnlyText = -5250 #errReadOnlyText -errEmptyScrap = -5249 #errEmptyScrap -errNoHiliteText = -5248 #errNoHiliteText -errOffsetNotOnElementBounday = -5247 #errOffsetNotOnElementBounday -errInvalidRange = -5246 #errInvalidRange -errIteratorReachedEnd = -5245 #errIteratorReachedEnd -errEngineNotFound = -5244 #errEngineNotFound -errAlreadyInImagingMode = -5243 #errAlreadyInImagingMode -errNotInImagingMode = -5242 #errNotInImagingMode -errMarginWilllNotFit = -5241 #errMarginWilllNotFit -errUnknownAttributeTag = -5240 #errUnknownAttributeTag -afpSameNodeErr = -5063 #An Attempt was made to connect to a file server running on the same machine -afpAlreadyMounted = -5062 #The volume is already mounted -afpCantMountMoreSrvre = -5061 #The Maximum number of server connections has been reached -afpBadDirIDType = -5060 #afpBadDirIDType -afpCallNotAllowed = -5048 #The server knows what you wanted to do, but won't let you do it just now -afpAlreadyLoggedInErr = -5047 #User has been authenticated but is already logged in from another machine (and that's not allowed on this server) -afpPwdPolicyErr = -5046 #Password does not conform to servers password policy -afpPwdNeedsChangeErr = -5045 #The password needs to be changed -afpInsideTrashErr = -5044 #The folder being shared is inside the trash folder OR the shared folder is being moved into the trash folder -afpInsideSharedErr = -5043 #The folder being shared is inside a shared folder OR the folder contains a shared folder and is being moved into a shared folder -afpPwdExpiredErr = -5042 #The password being used is too old: this requires the user to change the password before log-in can continue -afpPwdTooShortErr = -5041 #The password being set is too short: there is a minimum length that must be met or exceeded -afpPwdSameErr = -5040 #Someone tried to change their password to the same password on a mantadory password change -afpBadIDErr = -5039 #afpBadIDErr -afpSameObjectErr = -5038 #afpSameObjectErr -afpCatalogChanged = -5037 #afpCatalogChanged -afpDiffVolErr = -5036 #afpDiffVolErr -afpIDExists = -5035 #afpIDExists -afpIDNotFound = -5034 #afpIDNotFound -afpContainsSharedErr = -5033 #the folder being shared contains a shared folder -afpObjectLocked = -5032 #Object is M/R/D/W inhibited -afpVolLocked = -5031 #Volume is Read-Only -afpIconTypeError = -5030 #Icon size specified different from existing icon size -afpDirNotFound = -5029 #Unknown directory specified -afpCantRename = -5028 #AFPRename cannot rename volume -afpServerGoingDown = -5027 #Server is shutting down -afpTooManyFilesOpen = -5026 #Maximum open file count reached -afpObjectTypeErr = -5025 #File/Directory specified where Directory/File expected -afpCallNotSupported = -5024 #Unsupported AFP call was made -afpUserNotAuth = -5023 #No AFPLogin call has successfully been made for this session -afpSessClosed = -5022 #Session closed -afpRangeOverlap = -5021 #Some or all of range already locked by same user -afpRangeNotLocked = -5020 #Tried to unlock range that was not locked by user -afpParmErr = -5019 #A specified parameter was out of allowable range -afpObjectNotFound = -5018 #Specified file or directory does not exist -afpObjectExists = -5017 #Specified destination file or directory already exists -afpNoServer = -5016 #Server not responding -afpNoMoreLocks = -5015 #Maximum lock limit reached -afpMiscErr = -5014 #Unexpected error encountered during execution -afpLockErr = -5013 #Some or all of requested range is locked by another user -afpItemNotFound = -5012 #Unknown UserName/UserID or missing comment/APPL entry -afpFlatVol = -5011 #Cannot create directory on specified volume -afpFileBusy = -5010 #Cannot delete an open file -afpEofError = -5009 #Read beyond logical end-of-file -afpDiskFull = -5008 #Insufficient free space on volume for operation -afpDirNotEmpty = -5007 #Cannot delete non-empty directory -afpDenyConflict = -5006 #Specified open/deny modes conflict with current open modes -afpCantMove = -5005 #Move destination is offspring of source, or root was specified -afpBitmapErr = -5004 #Bitmap contained bits undefined for call -afpBadVersNum = -5003 #Unknown AFP protocol version number specified -afpBadUAM = -5002 #Unknown user authentication method specified -afpAuthContinue = -5001 #Further information required to complete AFPLogin call -afpAccessDenied = -5000 #Insufficient access privileges for operation -illegalScrapFlavorSizeErr = -4999 #illegalScrapFlavorSizeErr -illegalScrapFlavorTypeErr = -4998 #illegalScrapFlavorTypeErr -illegalScrapFlavorFlagsErr = -4997 #illegalScrapFlavorFlagsErr -scrapFlavorSizeMismatchErr = -4996 #scrapFlavorSizeMismatchErr -scrapFlavorFlagsMismatchErr = -4995 #scrapFlavorFlagsMismatchErr -nilScrapFlavorDataErr = -4994 #nilScrapFlavorDataErr -noScrapPromiseKeeperErr = -4993 #noScrapPromiseKeeperErr -scrapPromiseNotKeptErr = -4992 #scrapPromiseNotKeptErr -processStateIncorrectErr = -4991 #processStateIncorrectErr -badScrapRefErr = -4990 #badScrapRefErr -duplicateScrapFlavorErr = -4989 #duplicateScrapFlavorErr -internalScrapErr = -4988 #internalScrapErr -coreFoundationUnknownErr = -4960 #coreFoundationUnknownErr -badRoutingSizeErr = -4276 #badRoutingSizeErr -routingNotFoundErr = -4275 #routingNotFoundErr -duplicateRoutingErr = -4274 #duplicateRoutingErr -invalidFolderTypeErr = -4273 #invalidFolderTypeErr -noMoreFolderDescErr = -4272 #noMoreFolderDescErr -duplicateFolderDescErr = -4271 #duplicateFolderDescErr -badFolderDescErr = -4270 #badFolderDescErr -cmCantGamutCheckError = -4217 #Gammut checking not supported by this ColorWorld -cmNamedColorNotFound = -4216 #NamedColor not found -cmCantCopyModifiedV1Profile = -4215 #Illegal to copy version 1 profiles that have been modified -cmRangeOverFlow = -4214 #Color conversion warning that some output color values over/underflowed and were clipped -cmInvalidProfileComment = -4213 #Bad Profile comment during drawpicture -cmNoGDevicesError = -4212 #Begin/End Matching -- no gdevices available -cmInvalidDstMap = -4211 #Destination pix/bit map was invalid -cmInvalidSrcMap = -4210 #Source pix/bit map was invalid -cmInvalidColorSpace = -4209 #Profile colorspace does not match bitmap type -cmErrIncompatibleProfile = -4208 #Other ColorSync Errors -cmSearchError = -4207 #cmSearchError -cmInvalidSearch = -4206 #Bad Search Handle -cmInvalidProfileLocation = -4205 #Operation not supported for this profile location -cmInvalidProfile = -4204 #A Profile must contain a 'cs1 ' tag to be valid -cmFatalProfileErr = -4203 #cmFatalProfileErr -cmCantDeleteElement = -4202 #cmCantDeleteElement -cmIndexRangeErr = -4201 #Tag index out of range -kNSLInitializationFailed = -4200 #UNABLE TO INITIALIZE THE MANAGER!!!!! DO NOT CONTINUE!!!! -kNSLNotInitialized = -4199 #kNSLNotInitialized -kNSLInsufficientSysVer = -4198 #kNSLInsufficientSysVer -kNSLInsufficientOTVer = -4197 #kNSLInsufficientOTVer -kNSLNoElementsInList = -4196 #kNSLNoElementsInList -kNSLBadReferenceErr = -4195 #kNSLBadReferenceErr -kNSLBadServiceTypeErr = -4194 #kNSLBadServiceTypeErr -kNSLBadDataTypeErr = -4193 #kNSLBadDataTypeErr -kNSLBadNetConnection = -4192 #kNSLBadNetConnection -kNSLNoSupportForService = -4191 #kNSLNoSupportForService -kNSLInvalidPluginSpec = -4190 #kNSLInvalidPluginSpec -kNSLRequestBufferAlreadyInList = -4189 #kNSLRequestBufferAlreadyInList -kNSLNoContextAvailable = -4188 #(ContinueLookup function ptr invalid) -kNSLBufferTooSmallForData = -4187 #(Client buffer too small for data from plugin) -kNSLCannotContinueLookup = -4186 #(Can't continue lookup; error or bad state) -kNSLBadClientInfoPtr = -4185 #(nil ClientAsyncInfoPtr; no reference available) -kNSLNullListPtr = -4184 #(client is trying to add items to a nil list) -kNSLBadProtocolTypeErr = -4183 #(client is trying to add a null protocol type) -kNSLPluginLoadFailed = -4182 #(manager unable to load one of the plugins) -kNSLNoPluginsFound = -4181 #(manager didn't find any valid plugins to load) -kNSLSearchAlreadyInProgress = -4180 #(you can only have one ongoing search per clientRef) -kNSLNoPluginsForSearch = -4179 #(no plugins will respond to search request; bad protocol(s)?) -kNSLNullNeighborhoodPtr = -4178 #(client passed a null neighborhood ptr) -kNSLSomePluginsFailedToLoad = -4177 #(one or more plugins failed to load, but at least one did load; this error isn't fatal) -kNSLErrNullPtrError = -4176 #kNSLErrNullPtrError -kNSLNotImplementedYet = -4175 #kNSLNotImplementedYet -kNSLUILibraryNotAvailable = -4174 #The NSL UI Library needs to be in the Extensions Folder -kNSLNoCarbonLib = -4173 #kNSLNoCarbonLib -kNSLBadURLSyntax = -4172 #URL contains illegal characters -kNSLSchedulerError = -4171 #A custom thread routine encountered an error -kNSL68kContextNotSupported = -4170 #no 68k allowed -noHelpForItem = -4009 #noHelpForItem -badProfileError = -4008 #badProfileError -colorSyncNotInstalled = -4007 #colorSyncNotInstalled -pickerCantLive = -4006 #pickerCantLive -cantLoadPackage = -4005 #cantLoadPackage -cantCreatePickerWindow = -4004 #cantCreatePickerWindow -cantLoadPicker = -4003 #cantLoadPicker -pickerResourceError = -4002 #pickerResourceError -requiredFlagsDontMatch = -4001 #requiredFlagsDontMatch -firstPickerError = -4000 #firstPickerError -kOTPortLostConnection = -3285 # -kOTUserRequestedErr = -3284 # -kOTConfigurationChangedErr = -3283 # -kOTBadConfigurationErr = -3282 # -kOTPortWasEjectedErr = -3281 # -kOTPortHasDiedErr = -3280 # -kOTClientNotInittedErr = -3279 # -kENOMSGErr = -3278 # -kESRCHErr = -3277 # -kEINPROGRESSErr = -3276 # -kENODATAErr = -3275 # -kENOSTRErr = -3274 # -kECANCELErr = -3273 # -kEBADMSGErr = -3272 # -kENOSRErr = -3271 # -kETIMEErr = -3270 # -kEPROTOErr = -3269 #‚‚‚ fill out missing codes ‚‚‚ -kEHOSTUNREACHErr = -3264 #No route to host -kEHOSTDOWNErr = -3263 #Host is down -kECONNREFUSEDErr = -3260 #Connection refused -kETIMEDOUTErr = -3259 #Connection timed out -kETOOMANYREFSErr = -3258 #Too many references: can't splice -kESHUTDOWNErr = -3257 #Can't send after socket shutdown -kENOTCONNErr = -3256 #Socket is not connected -kEISCONNErr = -3255 #Socket is already connected -kENOBUFSErr = -3254 #No buffer space available -kECONNRESETErr = -3253 #Connection reset by peer -kECONNABORTEDErr = -3252 #Software caused connection abort -kENETRESETErr = -3251 #Network dropped connection on reset -kENETUNREACHErr = -3250 #Network is unreachable -kENETDOWNErr = -3249 #Network is down -kEADDRNOTAVAILErr = -3248 #Can't assign requested address -kEADDRINUSEErr = -3247 #Address already in use -kEOPNOTSUPPErr = -3244 #Operation not supported on socket -kESOCKTNOSUPPORTErr = -3243 #Socket type not supported -kEPROTONOSUPPORTErr = -3242 #Protocol not supported -kENOPROTOOPTErr = -3241 #Protocol not available -kEPROTOTYPEErr = -3240 #Protocol wrong type for socket -kEMSGSIZEErr = -3239 #Message too long -kEDESTADDRREQErr = -3238 #Destination address required -kENOTSOCKErr = -3237 #Socket operation on non-socket -kEALREADYErr = -3236 # -kEWOULDBLOCKErr = -3234 #Call would block, so was aborted -kERANGEErr = -3233 #Message size too large for STREAM -kEPIPEErr = -3231 #Broken pipe -kENOTTYErr = -3224 #Not a character device -kEINVALErr = -3221 #Invalid argument -kENODEVErr = -3218 #No such device -kOTDuplicateFoundErr = -3216 #OT generic duplicate found error -kEBUSYErr = -3215 #Device or resource busy -kEFAULTErr = -3213 #Bad address -kEACCESErr = -3212 #Permission denied -kOTOutOfMemoryErr = -3211 #OT ran out of memory, may be a temporary -kEAGAINErr = -3210 #Try operation again later -kEBADFErr = -3208 #Bad file number -kENXIOErr = -3205 #No such device or address -kEIOErr = -3204 #I/O error -kEINTRErr = -3203 #Interrupted system service -kENORSRCErr = -3202 #No such resource -kOTNotFoundErr = -3201 #OT generic not found error -kEPERMErr = -3200 #Permission denied -kOTCanceledErr = -3180 #XTI2OSStatus(TCANCELED) The command was cancelled -kOTBadSyncErr = -3179 #XTI2OSStatus(TBADSYNC) A synchronous call at interrupt time -kOTProtocolErr = -3178 #XTI2OSStatus(TPROTO) An unspecified provider error occurred -kOTQFullErr = -3177 #XTI2OSStatus(TQFULL) -kOTResAddressErr = -3176 #XTI2OSStatus(TRESADDR) -kOTResQLenErr = -3175 #XTI2OSStatus(TRESQLEN) -kOTProviderMismatchErr = -3174 #XTI2OSStatus(TPROVMISMATCH) Tried to accept on incompatible endpoint -kOTIndOutErr = -3173 #XTI2OSStatus(TINDOUT) Accept failed because of pending listen -kOTAddressBusyErr = -3172 #XTI2OSStatus(TADDRBUSY) Address requested is already in use -kOTBadQLenErr = -3171 #XTI2OSStatus(TBADQLEN) A Bind to an in-use addr with qlen > 0 -kOTBadNameErr = -3170 #XTI2OSStatus(TBADNAME) A bad endpoint name was supplied -kOTNoStructureTypeErr = -3169 #XTI2OSStatus(TNOSTRUCTYPE) Bad structure type requested for OTAlloc -kOTStateChangeErr = -3168 #XTI2OSStatus(TSTATECHNG) State is changing - try again later -kOTNotSupportedErr = -3167 #XTI2OSStatus(TNOTSUPPORT) Command is not supported -kOTNoReleaseErr = -3166 #XTI2OSStatus(TNOREL) No orderly release indication available -kOTBadFlagErr = -3165 #XTI2OSStatus(TBADFLAG) A Bad flag value was supplied -kOTNoUDErrErr = -3164 #XTI2OSStatus(TNOUDERR) No Unit Data Error indication available -kOTNoDisconnectErr = -3163 #XTI2OSStatus(TNODIS) No disconnect indication available -kOTNoDataErr = -3162 #XTI2OSStatus(TNODATA) No data available for reading -kOTFlowErr = -3161 #XTI2OSStatus(TFLOW) Provider is flow-controlled -kOTBufferOverflowErr = -3160 #XTI2OSStatus(TBUFOVFLW) Passed buffer not big enough -kOTBadDataErr = -3159 #XTI2OSStatus(TBADDATA) An illegal amount of data was specified -kOTLookErr = -3158 #XTI2OSStatus(TLOOK) An event occurred - call Look() -kOTSysErrorErr = -3157 #XTI2OSStatus(TSYSERR) A system error occurred -kOTBadSequenceErr = -3156 #XTI2OSStatus(TBADSEQ) Sequence specified does not exist -kOTOutStateErr = -3155 #XTI2OSStatus(TOUTSTATE) Call issued in wrong state -kOTNoAddressErr = -3154 #XTI2OSStatus(TNOADDR) No address was specified -kOTBadReferenceErr = -3153 #XTI2OSStatus(TBADF) Bad provider reference -kOTAccessErr = -3152 #XTI2OSStatus(TACCES) Missing access permission -kOTBadOptionErr = -3151 #XTI2OSStatus(TBADOPT) A Bad option was specified -kOTBadAddressErr = -3150 #XTI2OSStatus(TBADADDR) A Bad address was specified -sktClosedErr = -3109 #sktClosedErr -recNotFnd = -3108 #recNotFnd -atpBadRsp = -3107 #atpBadRsp -atpLenErr = -3106 #atpLenErr -readQErr = -3105 #readQErr -extractErr = -3104 #extractErr -ckSumErr = -3103 #ckSumErr -noMPPErr = -3102 #noMPPErr -buf2SmallErr = -3101 #buf2SmallErr -noPrefAppErr = -3032 #noPrefAppErr -badTranslationSpecErr = -3031 #badTranslationSpecErr -noTranslationPathErr = -3030 #noTranslationPathErr -couldNotParseSourceFileErr = -3026 #Source document does not contain source type -invalidTranslationPathErr = -3025 #Source type to destination type not a valid path -retryComponentRegistrationErr = -3005 #retryComponentRegistrationErr -unresolvedComponentDLLErr = -3004 #unresolvedComponentDLLErr -componentDontRegister = -3003 #componentDontRegister -componentNotCaptured = -3002 #componentNotCaptured -validInstancesExist = -3001 #validInstancesExist -invalidComponentID = -3000 #invalidComponentID -cfragLastErrCode = -2899 #The last value in the range of CFM errors. -cfragOutputLengthErr = -2831 #An output parameter is too small to hold the value. -cfragAbortClosureErr = -2830 #Used by notification handlers to abort a closure. -cfragClosureIDErr = -2829 #The closure ID was not valid. -cfragContainerIDErr = -2828 #The fragment container ID was not valid. -cfragNoRegistrationErr = -2827 #The registration name was not found. -cfragNotClosureErr = -2826 #The closure ID was actually a connection ID. -cfragFileSizeErr = -2825 #A file was too large to be mapped. -cfragFragmentUsageErr = -2824 #A semantic error in usage of the fragment. -cfragArchitectureErr = -2823 #A fragment has an unacceptable architecture. -cfragNoApplicationErr = -2822 #No application member found in the cfrg resource. -cfragInitFunctionErr = -2821 #A fragment's initialization routine returned an error. -cfragFragmentCorruptErr = -2820 #A fragment's container was corrupt (known format). -cfragCFMInternalErr = -2819 #An internal inconstistancy has been detected. -cfragCFMStartupErr = -2818 #Internal error during CFM initialization. -cfragLibConnErr = -2817 # -cfragInitAtBootErr = -2816 #A boot library has an initialization function. (System 7 only) -cfragInitLoopErr = -2815 #Circularity in required initialization order. -cfragImportTooNewErr = -2814 #An import library was too new for a client. -cfragImportTooOldErr = -2813 #An import library was too old for a client. -cfragInitOrderErr = -2812 # -cfragNoIDsErr = -2811 #No more CFM IDs for contexts, connections, etc. -cfragNoClientMemErr = -2810 #Out of memory for fragment mapping or section instances. -cfragNoPrivateMemErr = -2809 #Out of memory for internal bookkeeping. -cfragNoPositionErr = -2808 #The registration insertion point was not found. -cfragUnresolvedErr = -2807 #A fragment had "hard" unresolved imports. -cfragFragmentFormatErr = -2806 #A fragment's container format is unknown. -cfragDupRegistrationErr = -2805 #The registration name was already in use. -cfragNoLibraryErr = -2804 #The named library was not found. -cfragNoSectionErr = -2803 #The specified section was not found. -cfragNoSymbolErr = -2802 #The specified symbol was not found. -cfragConnectionIDErr = -2801 #The connection ID was not valid. -cfragFirstErrCode = -2800 #The first value in the range of CFM errors. -errASInconsistentNames = -2780 #English errors: -errASNoResultReturned = -2763 #The range -2780 thru -2799 is reserved for dialect specific error codes. (Error codes from different dialects may overlap.) -errASParameterNotForEvent = -2762 #errASParameterNotForEvent -errASIllegalFormalParameter = -2761 #errASIllegalFormalParameter -errASTerminologyNestingTooDeep = -2760 #errASTerminologyNestingTooDeep -OSAControlFlowError = -2755 #Signaled when illegal control flow occurs in an application (no catcher for throw, non-lexical loop exit, etc.) -OSAInconsistentDeclarations = -2754 #Signaled when a variable is declared inconsistently in the same scope, such as both local and global -OSAUndefinedVariable = -2753 #Signaled when a variable is accessed that has no value -OSADuplicateHandler = -2752 #Signaled when more than one handler is defined with the same name in a scope where the language doesn't allow it -OSADuplicateProperty = -2751 #Signaled when a formal parameter, local variable, or instance variable is specified more than once. -OSADuplicateParameter = -2750 #Signaled when a formal parameter, local variable, or instance variable is specified more than once -OSATokenTooLong = -2742 #Signaled when a name or number is too long to be parsed -OSASyntaxTypeError = -2741 #Signaled when another form of syntax was expected. (e.g. "expected a but found ") -OSASyntaxError = -2740 #Signaled when a syntax error occurs. (e.g. "Syntax error" or " can't go after ") -errASCantCompareMoreThan32k = -2721 #Parser/Compiler errors: -errASCantConsiderAndIgnore = -2720 #errASCantConsiderAndIgnore -errOSACantCreate = -2710 #errOSACantCreate -errOSACantGetTerminology = -2709 #errOSACantGetTerminology -errOSADataBlockTooLarge = -2708 #Signaled when an intrinsic limitation is exceeded for the size of a value or data structure. -errOSAInternalTableOverflow = -2707 #Signaled when a runtime internal data structure overflows -errOSAStackOverflow = -2706 #Signaled when the runtime stack overflows -errOSACorruptTerminology = -2705 #Signaled when an application's terminology resource is not readable -errOSAAppNotHighLevelEventAware = -2704 #Signaled when an application can't respond to AppleEvents -errOSACantLaunch = -2703 #Signaled when application can't be launched or when it is remote and program linking is not enabled -errOSANumericOverflow = -2702 #Signaled when integer or real value is too large to be represented -errOSADivideByZero = -2701 #Signaled when there is an attempt to divide by zero -errOSAGeneralError = -2700 #Signaled by user scripts or applications when no actual error code is to be returned. -noIconDataAvailableErr = -2582 #The necessary icon data is not available -noSuchIconErr = -2581 #The requested icon could not be found -invalidIconRefErr = -2580 #The icon ref is not valid -nrCallNotSupported = -2557 #This call is not available or supported on this machine -nrTransactionAborted = -2556 #transaction was aborted -nrExitedIteratorScope = -2555 #outer scope of iterator was exited -nrIterationDone = -2554 #iteration operation is done -nrPropertyAlreadyExists = -2553 #property already exists -nrInvalidEntryIterationOp = -2552 #invalid entry iteration operation -nrPathBufferTooSmall = -2551 #buffer for path is too small -nrPathNotFound = -2550 #a path component lookup failed -nrResultCodeBase = -2549 #nrResultCodeBase -nrOverrunErr = -2548 #nrOverrunErr -nrNotModifiedErr = -2547 #nrNotModifiedErr -nrTypeMismatchErr = -2546 #nrTypeMismatchErr -nrPowerSwitchAbortErr = -2545 #nrPowerSwitchAbortErr -nrPowerErr = -2544 #nrPowerErr -nrDataTruncatedErr = -2543 #nrDataTruncatedErr -nrNotSlotDeviceErr = -2542 #nrNotSlotDeviceErr -nrNameErr = -2541 #nrNameErr -nrNotCreatedErr = -2540 #nrNotCreatedErr -nrNotFoundErr = -2539 #nrNotFoundErr -nrInvalidNodeErr = -2538 #nrInvalidNodeErr -nrNotEnoughMemoryErr = -2537 #nrNotEnoughMemoryErr -nrLockedErr = -2536 #nrLockedErr -mmInternalError = -2526 #mmInternalError -tsmDefaultIsNotInputMethodErr = -2524 #Current Input source is KCHR or uchr, not Input Method (GetDefaultInputMethod) -tsmNoStem = -2523 #No stem exists for the token -tsmNoMoreTokens = -2522 #No more tokens are available for the source text -tsmNoHandler = -2521 #No Callback Handler exists for callback -tsmInvalidContext = -2520 #Invalid TSMContext specified in call -tsmUnknownErr = -2519 #any other errors -tsmUnsupportedTypeErr = -2518 #unSupported interface type error -tsmScriptHasNoIMErr = -2517 #script has no imput method or is using old IM -tsmInputMethodIsOldErr = -2516 #returned by GetDefaultInputMethod -tsmComponentAlreadyOpenErr = -2515 #text service already opened for the document -tsmTSNotOpenErr = -2514 #text service is not open -tsmTSHasNoMenuErr = -2513 #the text service has no menu -tsmUseInputWindowErr = -2512 #not TSM aware because we are using input window -tsmDocumentOpenErr = -2511 #there are open documents -tsmTextServiceNotFoundErr = -2510 #no text service found -tsmCantOpenComponentErr = -2509 #canÕt open the component -tsmNoOpenTSErr = -2508 #no open text service -tsmDocNotActiveErr = -2507 #document is NOT active -tsmTSMDocBusyErr = -2506 #document is still active -tsmInvalidDocIDErr = -2505 #invalid TSM documentation id -tsmNeverRegisteredErr = -2504 #app never registered error (not TSM aware) -tsmAlreadyRegisteredErr = -2503 #want to register again error -tsmNotAnAppErr = -2502 #not an application error -tsmInputMethodNotFoundErr = -2501 #tsmInputMethodNotFoundErr -tsmUnsupScriptLanguageErr = -2500 #tsmUnsupScriptLanguageErr -kernelUnrecoverableErr = -2499 #kernelUnrecoverableErr -kernelReturnValueErr = -2422 #kernelReturnValueErr -kernelAlreadyFreeErr = -2421 #kernelAlreadyFreeErr -kernelIDErr = -2419 #kernelIDErr -kernelExceptionErr = -2418 #kernelExceptionErr -kernelTerminatedErr = -2417 #kernelTerminatedErr -kernelInUseErr = -2416 #kernelInUseErr -kernelTimeoutErr = -2415 #kernelTimeoutErr -kernelAsyncReceiveLimitErr = -2414 #kernelAsyncReceiveLimitErr -kernelAsyncSendLimitErr = -2413 #kernelAsyncSendLimitErr -kernelAttributeErr = -2412 #kernelAttributeErr -kernelExecutionLevelErr = -2411 #kernelExecutionLevelErr -kernelDeletePermissionErr = -2410 #kernelDeletePermissionErr -kernelExecutePermissionErr = -2409 #kernelExecutePermissionErr -kernelReadPermissionErr = -2408 #kernelReadPermissionErr -kernelWritePermissionErr = -2407 #kernelWritePermissionErr -kernelObjectExistsErr = -2406 #kernelObjectExistsErr -kernelUnsupportedErr = -2405 #kernelUnsupportedErr -kernelPrivilegeErr = -2404 #kernelPrivilegeErr -kernelOptionsErr = -2403 #kernelOptionsErr -kernelCanceledErr = -2402 #kernelCanceledErr -kernelIncompleteErr = -2401 #kernelIncompleteErr -badCallOrderErr = -2209 #Usually due to a status call being called prior to being setup first -noDMAErr = -2208 #CanÕt do DMA digitizing (i.e. can't go to requested dest -badDepthErr = -2207 #CanÕt digitize into this depth -notExactSizeErr = -2206 #CanÕt do exact size requested -noMoreKeyColorsErr = -2205 #all key indexes in use -notExactMatrixErr = -2204 #warning of bad matrix, digitizer did its best -matrixErr = -2203 #bad matrix, digitizer did nothing -qtParamErr = -2202 #bad input parameter (out of range, etc) -digiUnimpErr = -2201 #feature unimplemented -qtXMLApplicationErr = -2159 #qtXMLApplicationErr -qtXMLParseErr = -2158 #qtXMLParseErr -qtActionNotHandledErr = -2157 #qtActionNotHandledErr -notEnoughDataErr = -2149 #notEnoughDataErr -urlDataHFTPURLErr = -2148 #urlDataHFTPURLErr -urlDataHFTPServerDisconnectedErr = -2147 #urlDataHFTPServerDisconnectedErr -urlDataHFTPNoPasswordErr = -2146 #urlDataHFTPNoPasswordErr -urlDataHFTPNeedPasswordErr = -2145 #urlDataHFTPNeedPasswordErr -urlDataHFTPBadNameListErr = -2144 #urlDataHFTPBadNameListErr -urlDataHFTPNoNetDriverErr = -2143 #urlDataHFTPNoNetDriverErr -urlDataHFTPFilenameErr = -2142 #urlDataHFTPFilenameErr -urlDataHFTPPermissionsErr = -2141 #urlDataHFTPPermissionsErr -urlDataHFTPQuotaErr = -2140 #urlDataHFTPQuotaErr -urlDataHFTPNoDirectoryErr = -2139 #urlDataHFTPNoDirectoryErr -urlDataHFTPDataConnectionErr = -2138 #urlDataHFTPDataConnectionErr -urlDataHFTPServerErr = -2137 #urlDataHFTPServerErr -urlDataHFTPBadPasswordErr = -2136 #urlDataHFTPBadPasswordErr -urlDataHFTPBadUserErr = -2135 #urlDataHFTPBadUserErr -urlDataHFTPShutdownErr = -2134 #urlDataHFTPShutdownErr -urlDataHFTPProtocolErr = -2133 #urlDataHFTPProtocolErr -urlDataHHTTPRedirectErr = -2132 #urlDataHHTTPRedirectErr -urlDataHHTTPURLErr = -2131 #urlDataHHTTPURLErr -urlDataHHTTPNoNetDriverErr = -2130 #urlDataHHTTPNoNetDriverErr -urlDataHHTTPProtocolErr = -2129 #urlDataHHTTPProtocolErr -qtNetworkAlreadyAllocatedErr = -2127 #qtNetworkAlreadyAllocatedErr -notAllowedToSaveMovieErr = -2126 #notAllowedToSaveMovieErr -fileOffsetTooBigErr = -2125 #fileOffsetTooBigErr -ASDEntryNotFoundErr = -2124 #ASDEntryNotFoundErr -ASDBadForkErr = -2123 #ASDBadForkErr -ASDBadHeaderErr = -2122 #ASDBadHeaderErr -AAPNotFoundErr = -2121 #AAPNotFoundErr -AAPNotCreatedErr = -2120 #AAPNotCreatedErr -qfcbNotCreatedErr = -2119 #qfcbNotCreatedErr -qfcbNotFoundErr = -2118 #qfcbNotFoundErr -wackBadMetaDataErr = -2117 #wackBadMetaDataErr -wackForkNotFoundErr = -2116 #wackForkNotFoundErr -wackBadFileErr = -2115 #wackBadFileErr -unknownFormatErr = -2114 #unknownFormatErr -pathNotVerifiedErr = -2113 #pathNotVerifiedErr -noPathMappingErr = -2112 #noPathMappingErr -emptyPathErr = -2111 #emptyPathErr -pathTooLongErr = -2110 #pathTooLongErr -cannotBeLeafAtomErr = -2109 #cannotBeLeafAtomErr -invalidAtomTypeErr = -2108 #invalidAtomTypeErr -invalidAtomContainerErr = -2107 #invalidAtomContainerErr -invalidAtomErr = -2106 #invalidAtomErr -duplicateAtomTypeAndIDErr = -2105 #duplicateAtomTypeAndIDErr -atomIndexInvalidErr = -2104 #atomIndexInvalidErr -atomsNotOfSameTypeErr = -2103 #atomsNotOfSameTypeErr -notLeafAtomErr = -2102 #notLeafAtomErr -cannotFindAtomErr = -2101 #cannotFindAtomErr -unsupportedProcessorErr = -2097 #unsupportedProcessorErr -unsupportedOSErr = -2096 #unsupportedOSErr -qtmlUninitialized = -2095 #qtmlUninitialized -qtmlDllEntryNotFoundErr = -2094 #Windows specific errors (when qtml is loading) -qtmlDllLoadErr = -2093 #Windows specific errors (when qtml is loading) -componentDllEntryNotFoundErr = -2092 #Windows specific errors (when component is loading) -componentDllLoadErr = -2091 #Windows specific errors (when component is loading) -videoOutputInUseErr = -2090 #videoOutputInUseErr -noExportProcAvailableErr = -2089 #noExportProcAvailableErr -tuneParseOSErr = -2087 #tuneParseOSErr -tunePlayerFullOSErr = -2086 #tunePlayerFullOSErr -noteChannelNotAllocatedOSErr = -2085 #noteChannelNotAllocatedOSErr -illegalNoteChannelOSErr = -2084 #illegalNoteChannelOSErr -synthesizerOSErr = -2083 #synthesizerOSErr -synthesizerNotRespondingOSErr = -2082 #synthesizerNotRespondingOSErr -midiManagerAbsentOSErr = -2081 #midiManagerAbsentOSErr -illegalControllerOSErr = -2080 #illegalControllerOSErr -illegalInstrumentOSErr = -2079 #illegalInstrumentOSErr -illegalKnobValueOSErr = -2078 #illegalKnobValueOSErr -illegalKnobOSErr = -2077 #illegalKnobOSErr -illegalChannelOSErr = -2076 #illegalChannelOSErr -illegalPartOSErr = -2075 #illegalPartOSErr -illegalVoiceAllocationOSErr = -2074 #illegalVoiceAllocationOSErr -cantReceiveFromSynthesizerOSErr = -2073 #cantReceiveFromSynthesizerOSErr -cantSendToSynthesizerOSErr = -2072 #cantSendToSynthesizerOSErr -notImplementedMusicOSErr = -2071 #notImplementedMusicOSErr -internalComponentErr = -2070 #internalComponentErr -invalidSpriteIDErr = -2069 #invalidSpriteIDErr -invalidImageIndexErr = -2068 #invalidImageIndexErr -invalidSpriteIndexErr = -2067 #invalidSpriteIndexErr -gWorldsNotSameDepthAndSizeErr = -2066 #gWorldsNotSameDepthAndSizeErr -invalidSpritePropertyErr = -2065 #invalidSpritePropertyErr -invalidSpriteWorldPropertyErr = -2064 #invalidSpriteWorldPropertyErr -missingRequiredParameterErr = -2063 #missingRequiredParameterErr -movieTextNotFoundErr = -2062 #movieTextNotFoundErr -sourceNotFoundErr = -2061 #sourceNotFoundErr -noSourceTreeFoundErr = -2060 #noSourceTreeFoundErr -samplesAlreadyInMediaErr = -2059 #samplesAlreadyInMediaErr -auxiliaryExportDataUnavailable = -2058 #auxiliaryExportDataUnavailable -unsupportedAuxiliaryImportData = -2057 #unsupportedAuxiliaryImportData -soundSupportNotAvailableErr = -2056 #QT for Windows error -noSoundTrackInMovieErr = -2055 #QT for Windows error -noVideoTrackInMovieErr = -2054 #QT for Windows error -featureUnsupported = -2053 #featureUnsupported -couldNotUseAnExistingSample = -2052 #couldNotUseAnExistingSample -noDefaultDataRef = -2051 #noDefaultDataRef -badDataRefIndex = -2050 #badDataRefIndex -invalidDataRefContainer = -2049 #invalidDataRefContainer -noMovieFound = -2048 #noMovieFound -dataNoDataRef = -2047 #dataNoDataRef -endOfDataReached = -2046 #endOfDataReached -dataAlreadyClosed = -2045 #dataAlreadyClosed -dataAlreadyOpenForWrite = -2044 #dataAlreadyOpenForWrite -dataNotOpenForWrite = -2043 #dataNotOpenForWrite -dataNotOpenForRead = -2042 #dataNotOpenForRead -invalidSampleDescription = -2041 #invalidSampleDescription -invalidChunkCache = -2040 #invalidChunkCache -invalidSampleDescIndex = -2039 #invalidSampleDescIndex -invalidChunkNum = -2038 #invalidChunkNum -invalidSampleNum = -2037 #invalidSampleNum -invalidRect = -2036 #invalidRect -cantEnableTrack = -2035 #cantEnableTrack -internalQuickTimeError = -2034 #internalQuickTimeError -badEditIndex = -2033 #badEditIndex -timeNotInMedia = -2032 #timeNotInMedia -timeNotInTrack = -2031 #timeNotInTrack -trackNotInMovie = -2030 #trackNotInMovie -trackIDNotFound = -2029 #trackIDNotFound -badTrackIndex = -2028 #badTrackIndex -maxSizeToGrowTooSmall = -2027 #maxSizeToGrowTooSmall -userDataItemNotFound = -2026 #userDataItemNotFound -staleEditState = -2025 #staleEditState -nonMatchingEditState = -2024 #nonMatchingEditState -invalidEditState = -2023 #invalidEditState -cantCreateSingleForkFile = -2022 #happens when file already exists -wfFileNotFound = -2021 #wfFileNotFound -movieToolboxUninitialized = -2020 #movieToolboxUninitialized -progressProcAborted = -2019 #progressProcAborted -mediaTypesDontMatch = -2018 #mediaTypesDontMatch -badEditList = -2017 #badEditList -cantPutPublicMovieAtom = -2016 #cantPutPublicMovieAtom -invalidTime = -2015 #invalidTime -invalidDuration = -2014 #invalidDuration -invalidHandler = -2013 #invalidHandler -invalidDataRef = -2012 #invalidDataRef -invalidSampleTable = -2011 #invalidSampleTable -invalidMovie = -2010 #invalidMovie -invalidTrack = -2009 #invalidTrack -invalidMedia = -2008 #invalidMedia -noDataHandler = -2007 #noDataHandler -noMediaHandler = -2006 #noMediaHandler -badComponentType = -2005 #badComponentType -cantOpenHandler = -2004 #cantOpenHandler -cantFindHandler = -2003 #cantFindHandler -badPublicMovieAtom = -2002 #badPublicMovieAtom -badImageDescription = -2001 #badImageDescription -couldNotResolveDataRef = -2000 #couldNotResolveDataRef -nonDragOriginatorErr = -1862 #illegal attempt at originator only data -badImageErr = -1861 #bad translucent image PixMap -badImageRgnErr = -1860 #bad translucent image region -noSuitableDisplaysErr = -1859 #no displays support translucency -unsupportedForPlatformErr = -1858 #call is for PowerPC only -dragNotAcceptedErr = -1857 #drag was not accepted by receiver -handlerNotFoundErr = -1856 #handler not found -duplicateHandlerErr = -1855 #handler already exists -cantGetFlavorErr = -1854 #error while trying to get flavor data -duplicateFlavorErr = -1853 #flavor type already exists -badDragFlavorErr = -1852 #unknown flavor type -badDragItemErr = -1851 #unknown drag item reference -badDragRefErr = -1850 #unknown drag reference -errEndOfBody = -1813 #errEndOfBody -errEndOfDocument = -1812 #errEndOfDocument -errTopOfBody = -1811 #errTopOfBody -errTopOfDocument = -1810 #errTopOfDocument -errOffsetIsOutsideOfView = -1801 #errOffsetIsOutsideOfView -errOffsetInvalid = -1800 #errOffsetInvalid -errOSACantOpenComponent = -1762 #Can't connect to scripting system with that ID -errOSAComponentMismatch = -1761 #Parameters are from 2 different components -errOSADataFormatTooNew = -1759 #errOSADataFormatTooNew -errOSADataFormatObsolete = -1758 #errOSADataFormatObsolete -errOSANoSuchDialect = -1757 #errOSANoSuchDialect -errOSASourceNotAvailable = -1756 #errOSASourceNotAvailable -errOSABadSelector = -1754 #errOSABadSelector -errOSAScriptError = -1753 #errOSAScriptError -errOSABadStorageType = -1752 #errOSABadStorageType -errOSAInvalidID = -1751 #errOSAInvalidID -errOSASystemError = -1750 #errOSASystemError -errAEBufferTooSmall = -1741 #buffer for AEFlattenDesc too small -errAEBuildSyntaxError = -1740 #AEBuildDesc and friends detected a syntax error -errAEDescIsNull = -1739 #attempting to perform an invalid operation on a null descriptor -errAEStreamAlreadyConverted = -1738 #attempt to convert a stream that has already been converted -errAEStreamBadNesting = -1737 #nesting violation while streaming -errAEDuplicateHandler = -1736 #attempt to install handler in table for identical class and id (1.1 or greater) -errAEEventFiltered = -1735 #event has been filtered, and should not be propogated (1.1 or greater) -errAEReceiveEscapeCurrent = -1734 #break out of only lowest level of AEReceive (1.1 or greater) -errAEReceiveTerminate = -1733 #break out of all levels of AEReceive to the topmost (1.1 or greater) -errAERecordingIsAlreadyOn = -1732 #available only in version 1.0.1 or greater -errAEUnknownObjectType = -1731 #available only in version 1.0.1 or greater -errAEEmptyListContainer = -1730 #Attempt to pass empty list as container to accessor -errAENegativeCount = -1729 #CountProc returned negative value -errAENoSuchObject = -1728 #e.g.,: specifier asked for the 3rd, but there are only 2. Basically, this indicates a run-time resolution error. -errAENotAnObjSpec = -1727 #Param to AEResolve not of type 'obj ' -errAEBadTestKey = -1726 #Test is neither typeLogicalDescriptor nor typeCompDescriptor -errAENoSuchLogical = -1725 #Something other than AND, OR, or NOT -errAEAccessorNotFound = -1723 #Accessor proc matching wantClass and containerType or wildcards not found -errAEWrongNumberArgs = -1721 #Logical op kAENOT used with other than 1 term -errAEImpossibleRange = -1720 #A range like 3rd to 2nd, or 1st to all. -errAEIllegalIndex = -1719 #index is out of range in a put operation -errAEReplyNotArrived = -1718 #the contents of the reply you are accessing have not arrived yet -errAEHandlerNotFound = -1717 #no handler in the dispatch tables fits the parameters to AEGetEventHandler or AEGetCoercionHandler -errAEUnknownAddressType = -1716 #the target address type is not known -errAEParamMissed = -1715 #a required parameter was not accessed -errAENotASpecialFunction = -1714 #there is no special function for/with this keyword -errAENoUserInteraction = -1713 #no user interaction is allowed -errAETimeout = -1712 #the AppleEvent timed out -errAEWaitCanceled = -1711 #in AESend, the user cancelled out of wait loop for reply or receipt -errAEUnknownSendMode = -1710 #mode wasn't NoReply, WaitReply, or QueueReply or Interaction level is unknown -errAEReplyNotValid = -1709 #AEResetTimer was passed an invalid reply parameter -errAEEventNotHandled = -1708 #the AppleEvent was not handled by any handler -errAENotAppleEvent = -1707 #the event is not in AppleEvent format -errAENewerVersion = -1706 #need newer version of the AppleEvent manager -errAEBadListItem = -1705 #the specified list item does not exist -errAENotAEDesc = -1704 #errAENotAEDesc -errAEWrongDataType = -1703 #errAEWrongDataType -errAECorruptData = -1702 #errAECorruptData -errAEDescNotFound = -1701 #errAEDescNotFound -errAECoercionFail = -1700 #bad parameter data or unable to coerce the data supplied -errFSIteratorNotSupported = -1424 #The iterator's flags or container are not supported by this call -errFSIteratorNotFound = -1423 #Passed FSIterator is not an open iterator -errFSBadIteratorFlags = -1422 #Flags passed to FSOpenIterator are bad -errFSForkExists = -1421 #Named fork already exists. -errFSRefsDifferent = -1420 #FSCompareFSRefs; refs are for different objects -errFSBadSearchParams = -1419 #Something wrong with CatalogSearch searchParams -errFSBadItemCount = -1418 #maximumItems was zero -errFSNoMoreItems = -1417 #Iteration ran out of items to return -errFSBadAllocFlags = -1413 #Invalid bits set in allocationFlags -errFSBadPosMode = -1412 #Newline bits set in positionMode -errFSMissingName = -1411 #A Unicode name parameter was NULL or nameLength parameter was zero -errFSNameTooLong = -1410 #File/fork name is too long to create/rename -errFSForkNotFound = -1409 #Named fork does not exist -errFSNotAFolder = -1407 #Expected a folder, got a file -errFSMissingCatInfo = -1406 #A CatalogInfo parameter was NULL -errFSBadInfoBitmap = -1405 #A CatalogInfoBitmap or VolumeInfoBitmap has reserved or invalid bits set -errFSBadForkRef = -1404 #A ForkRefNum parameter was bad -errFSBadBuffer = -1403 #A buffer parameter was bad -errFSBadForkName = -1402 #Fork name parameter is bad -errFSBadFSRef = -1401 #FSRef parameter is bad -errFSUnknownCall = -1400 #selector is not recognized by this filesystem -badFCBErr = -1327 #FCBRecPtr is not valid -volVMBusyErr = -1311 #can't eject because volume is in use by VM -fsDataTooBigErr = -1310 #file or volume is too big for system -fileBoundsErr = -1309 #file's EOF, offset, mark or size is too big -notARemountErr = -1308 #when _Mount allows only remounts and doesn't get one -badFidErr = -1307 #file id is dangling or doesn't match with the file number -sameFileErr = -1306 #can't exchange a file with itself -desktopDamagedErr = -1305 #desktop database files are corrupted -catChangedErr = -1304 #the catalog has been modified -diffVolErr = -1303 #files on different volumes -notAFileErr = -1302 #directory specified -fidExists = -1301 #file id already exists -fidNotFound = -1300 #no file thread exists. -errRefNum = -1280 #bad connection refNum -errAborted = -1279 #control call was aborted -errState = -1278 #bad connection state for this operation -errOpening = -1277 #open connection request failed -errAttention = -1276 #attention message too long -errFwdReset = -1275 #read terminated by forward reset -errDSPQueueSize = -1274 #DSP Read/Write Queue Too small -errOpenDenied = -1273 #open connection request was denied -reqAborted = -1105 #reqAborted -noDataArea = -1104 #noDataArea -noSendResp = -1103 #noSendResp -cbNotFound = -1102 #cbNotFound -noRelErr = -1101 #noRelErr -badBuffNum = -1100 #badBuffNum -badATPSkt = -1099 #badATPSkt -tooManySkts = -1098 #tooManySkts -tooManyReqs = -1097 #tooManyReqs -reqFailed = -1096 #reqFailed -aspNoAck = -1075 #No ack on attention request (server err) -aspTooMany = -1074 #Too many clients (server error) -aspSizeErr = -1073 #Command block too big -aspSessClosed = -1072 #Session closed -aspServerBusy = -1071 #Server cannot open another session -aspParamErr = -1070 #Parameter error -aspNoServers = -1069 #No servers at that address -aspNoMoreSess = -1068 #No more sessions on server -aspBufTooSmall = -1067 #Buffer too small -aspBadVersNum = -1066 #Server cannot support this ASP version -nbpNISErr = -1029 #Error trying to open the NIS -nbpNotFound = -1028 #Name not found on remove -nbpDuplicate = -1027 #Duplicate name exists already -nbpConfDiff = -1026 #Name confirmed at different socket -nbpNoConfirm = -1025 #nbpNoConfirm -nbpBuffOvr = -1024 #Buffer overflow in LookupName -noMaskFoundErr = -1000 #Icon Utilties Error -kFMFontContainerAccessErr = -985 #kFMFontContainerAccessErr -kFMFontTableAccessErr = -984 #kFMFontTableAccessErr -kFMIterationScopeModifiedErr = -983 #kFMIterationScopeModifiedErr -kFMInvalidFontErr = -982 #kFMInvalidFontErr -kFMInvalidFontFamilyErr = -981 #kFMInvalidFontFamilyErr -kFMIterationCompleted = -980 #kFMIterationCompleted -guestNotAllowedErr = -932 #destination port requires authentication -badLocNameErr = -931 #location name malformed -badServiceMethodErr = -930 #illegal service type, or not supported -noUserRecErr = -928 #Invalid user reference number -authFailErr = -927 #unable to authenticate user at destination -noInformErr = -926 #PPCStart failed because destination did not have inform pending -networkErr = -925 #An error has occurred in the network, not too likely -noUserRefErr = -924 #unable to create a new userRefNum -notLoggedInErr = -923 #The default userRefNum does not yet exist -noDefaultUserErr = -922 #user hasn't typed in owners name in Network Setup Control Pannel -badPortNameErr = -919 #PPCPortRec malformed -sessClosedErr = -917 #session was closed -portClosedErr = -916 #port was closed -noResponseErr = -915 #unable to contact destination -noToolboxNameErr = -914 #A system resource is missing, not too likely -noMachineNameErr = -913 #user hasn't named his Macintosh in the Network Setup Control Panel -userRejectErr = -912 #Destination rejected the session request -noUserNameErr = -911 #user name unknown on destination machine -portNameExistsErr = -910 #port is already open (perhaps in another app) -badReqErr = -909 #bad parameter or invalid state for operation -noSessionErr = -908 #Invalid session reference number -sessTableErr = -907 #Out of session tables, try again later -destPortErr = -906 #Port does not exist at destination -localOnlyErr = -905 #Network activity is currently disabled -noGlobalsErr = -904 #The system is hosed, better re-boot -noPortErr = -903 #Unable to open port or bad portRefNum. If you're calling -nameTypeErr = -902 #Invalid or inappropriate locationKindSelector in locationName -notInitErr = -900 #PPCToolBox not initialized -notAppropriateForClassic = -877 #This application won't or shouldn't run on Classic (Problem 2481058). -appVersionTooOld = -876 #The application's creator and version are incompatible with the current version of Mac OS. -wrongApplicationPlatform = -875 #The application could not launch because the required platform is not available -hmCloseViewActive = -863 #Returned from HMRemoveBalloon if CloseView was active -hmNoBalloonUp = -862 #Returned from HMRemoveBalloon if no balloon was visible when call was made -hmOperationUnsupported = -861 #Returned from HMShowBalloon call if bad method passed to routine -hmUnknownHelpType = -859 #Returned if help msg record contained a bad type -hmWrongVersion = -858 #Returned if help mgr resource was the wrong version -hmSkippedBalloon = -857 #Returned from calls if helpmsg specified a skip balloon -hmHelpManagerNotInited = -855 #Returned from HMGetHelpMenuHandle if help menu not setup -hmSameAsLastBalloon = -854 #Returned from HMShowMenuBalloon if menu & item is same as last time -hmBalloonAborted = -853 #Returned if mouse was moving or mouse wasn't in window port rect -hmHelpDisabled = -850 #Show Balloons mode was off, call to routine ignored -rcDBPackNotInited = -813 #attempt to call other routine before InitDBPack -rcDBWrongVersion = -812 #incompatible versions -rcDBNoHandler = -811 #no app handler for specified data type -rcDBBadAsyncPB = -810 #tried to kill a bad pb -rcDBAsyncNotSupp = -809 #ddev does not support async calls -rcDBBadDDEV = -808 #bad ddev specified on DBInit -rcDBBadSessNum = -807 #bad session number for DBGetConnInfo -rcDBBadSessID = -806 #rcDBBadSessID -rcDBExec = -805 #rcDBExec -rcDBBreak = -804 #rcDBBreak -rcDBBadType = -803 #rcDBBadType -rcDBError = -802 #rcDBError -rcDBValue = -801 #rcDBValue -rcDBNull = -800 #rcDBNull -icTooManyProfilesErr = -677 #too many profiles in database -icProfileNotFoundErr = -676 #profile not found -icConfigInappropriateErr = -675 #incorrect manufacturer code -icConfigNotFoundErr = -674 #no internet configuration was found -icNoURLErr = -673 #no URL found -icNothingToOverrideErr = -672 #no component for the override component to capture -icNoMoreWritersErr = -671 #you cannot begin a write session because someone else is already doing it -icTruncatedErr = -670 #more data was present than was returned -icInternalErr = -669 #Internet Config internal error -icPrefDataErr = -668 #problem with preference data -icPermErr = -667 #cannot set preference -icPrefNotFoundErr = -666 #Internet preference not found -vmInvalidOwningProcessErr = -648 #current process does not own the BackingFileID or FileViewID -vmAddressNotInFileViewErr = -647 #address is not in a FileView -vmNoMoreFileViewsErr = -646 #no more FileViews were found -vmFileViewAccessErr = -645 #requested FileViewAccess cannot be obtained -vmInvalidFileViewIDErr = -644 #invalid FileViewID -vmNoMoreBackingFilesErr = -643 #no more BackingFiles were found -vmBusyBackingFileErr = -642 #open views found on BackingFile -vmMappingPrivilegesErr = -641 #requested MappingPrivileges cannot be obtained -vmInvalidBackingFileIDErr = -640 #invalid BackingFileID -noMMUErr = -626 #no MMU present -cannotDeferErr = -625 #unable to defer additional functions -interruptsMaskedErr = -624 #donÕt call with interrupts masked -notLockedErr = -623 #specified range of memory is not locked -cannotMakeContiguousErr = -622 #cannot make specified range contiguous -notHeldErr = -621 #specified range of memory is not held -notEnoughMemoryErr = -620 #insufficient physical memory -threadProtocolErr = -619 #threadProtocolErr -threadNotFoundErr = -618 #threadNotFoundErr -threadTooManyReqsErr = -617 #threadTooManyReqsErr -noUserInteractionAllowed = -610 #no user interaction allowed -connectionInvalid = -609 #connectionInvalid -noOutstandingHLE = -608 #noOutstandingHLE -bufferIsSmall = -607 #error returns from Post and Accept -appIsDaemon = -606 #app is BG-only, and launch flags disallow this -appMemFullErr = -605 #application SIZE not big enough for launch -hardwareConfigErr = -604 #hardware configuration not correct for call -protocolErr = -603 #app made module calls in improper order -appModeErr = -602 #memory mode is 32-bit, but app not 32-bit clean -memFragErr = -601 #not enough room to launch app w/special requirements -procNotFound = -600 #no eligible process with specified descriptor -driverHardwareGoneErr = -503 #disk driver's hardware was disconnected -hwParamErr = -502 #bad selector for _HWPriv -teScrapSizeErr = -501 #scrap item too big for text edit record -rgnTooBigErr = -500 #rgnTooBigErr -exUserBreak = -492 #user debugger break; execute debugger commands on stack -strUserBreak = -491 #user debugger break; display string on stack -userBreak = -490 #user debugger break -notThePublisherWrn = -463 #not the first registered publisher for that container -containerAlreadyOpenWrn = -462 #container already opened by this section -containerNotFoundWrn = -461 #could not find editionContainer at this time -multiplePublisherWrn = -460 #A Publisher is already registered for that container -badSubPartErr = -454 #can not use sub parts in this release -badEditionFileErr = -453 #edition file is corrupt -notRegisteredSectionErr = -452 #not a registered SectionRecord -badSectionErr = -451 #not a valid SectionRecord -editionMgrInitErr = -450 #edition manager not inited by this app -fsmUnknownFSMMessageErr = -438 #unknown message passed to FSM -fsmNoAlternateStackErr = -437 #no alternate stack for HFS CI -fsmBadFSDVersionErr = -436 #FSM version incompatible with FSD -fsmDuplicateFSIDErr = -435 #FSID already exists on InstallFS -fsmBadFSDLenErr = -434 #FSD size incompatible with current FSM vers -fsmBadFFSNameErr = -433 #Name length not 1 <= length <= 31 -fsmBusyFFSErr = -432 #File system is busy, cannot be removed -fsmFFSNotFoundErr = -431 #Foreign File system does not exist - new Pack2 could return this error too -btKeyAttrErr = -417 #There is no such a key attribute. -btKeyLenErr = -416 #Maximum key length is too long or equal to zero. -btRecNotFnd = -415 #Record cannot be found. -btDupRecErr = -414 #Record already exists. -btNoSpace = -413 #Can't allocate disk space. -notBTree = -410 #The file is not a dictionary. -gcrOnMFMErr = -400 #gcr format on high density media error -slotNumErr = -360 #invalid slot # error -smRecNotFnd = -351 #Record not found in the SRT. -smSRTOvrFlErr = -350 #SRT over flow. -smNoGoodOpens = -349 #No opens were successfull in the loop. -smOffsetErr = -348 #Offset was too big (temporary error -smByteLanesErr = -347 #NumByteLanes was determined to be zero. -smBadsPtrErr = -346 #Bad pointer was passed to sCalcsPointer -smsGetDrvrErr = -345 #Error occurred during _sGetDriver. -smNoMoresRsrcs = -344 #No more sResources -smDisDrvrNamErr = -343 #Error occurred during _sDisDrvrName. -smGetDrvrNamErr = -342 #Error occurred during _sGetDrvrName. -smCkStatusErr = -341 #Status of slot = fail. -smBlkMoveErr = -340 #_BlockMove error -smNewPErr = -339 #_NewPtr error -smSelOOBErr = -338 #Selector out of bounds error -smSlotOOBErr = -337 #Slot out of bounds error -smNilsBlockErr = -336 #Nil sBlock error (Dont allocate and try to use a nil sBlock) -smsPointerNil = -335 #LPointer is nil From sOffsetData. If this error occurs; check sInfo rec for more information. -smCPUErr = -334 #Code revision is wrong -smCodeRevErr = -333 #Code revision is wrong -smReservedErr = -332 #Reserved field not zero -smBadsList = -331 #Bad sList: Id1 < Id2 < Id3 ...format is not followed. -smBadRefId = -330 #Reference Id not found in List -smBusErrTO = -320 #BusError time out. -smBadBoardId = -319 #BoardId was wrong; re-init the PRAM record. -smReservedSlot = -318 #slot is reserved, VM should not use this address space. -smInitTblVErr = -317 #An error occurred while trying to initialize the Slot Resource Table. -smInitStatVErr = -316 #The InitStatusV field was negative after primary or secondary init. -smNoBoardId = -315 #No Board Id. -smGetPRErr = -314 #Error occurred during _sGetPRAMRec (See SIMStatus). -smNoBoardSRsrc = -313 #No Board sResource. -smDisposePErr = -312 #_DisposePointer error -smFHBlkDispErr = -311 #Error occurred during _sDisposePtr (Dispose of FHeader block). -smFHBlockRdErr = -310 #Error occurred during _sGetFHeader. -smBLFieldBad = -309 #ByteLanes field was bad. -smUnExBusErr = -308 #Unexpected BusError -smResrvErr = -307 #Fatal reserved error. Resreved field <> 0. -smNosInfoArray = -306 #No sInfoArray. Memory Mgr error. -smDisabledSlot = -305 #This slot is disabled (-305 use to be smLWTstBad) -smNoDir = -304 #Directory offset is Nil -smRevisionErr = -303 #Wrong revison level -smFormatErr = -302 #FHeader Format is not Apple's -smCRCFail = -301 #CRC check failed for declaration data -smEmptySlot = -300 #No card in slot -nmTypErr = -299 #Notification Manager:wrong queue type -smPriInitErr = -293 #Error; Cards could not be initialized. -smPRAMInitErr = -292 #Error; Slot Resource Table could not be initialized. -smSRTInitErr = -291 #Error; Slot Resource Table could not be initialized. -smSDMInitErr = -290 #Error; SDM could not be initialized. -midiInvalidCmdErr = -261 #command not supported for port type -midiDupIDErr = -260 #duplicate client ID -midiNameLenErr = -259 #name supplied is longer than 31 characters -midiWriteErr = -258 #MIDIWritePacket couldn't write to all connected ports -midiNoConErr = -257 #no connection exists between specified ports -midiVConnectRmvd = -256 #pending virtual connection removed -midiVConnectMade = -255 #pending virtual connection resolved -midiVConnectErr = -254 #pending virtual connection created -midiTooManyConsErr = -253 #too many connections made -midiTooManyPortsErr = -252 #too many ports already installed in the system -midiNoPortErr = -251 #no port with that ID found -midiNoClientErr = -250 #no client with that ID found -badInputText = -247 #badInputText -badDictFormat = -246 #badDictFormat -incompatibleVoice = -245 #incompatibleVoice -voiceNotFound = -244 #voiceNotFound -bufTooSmall = -243 #bufTooSmall -synthNotReady = -242 #synthNotReady -synthOpenFailed = -241 #synthOpenFailed -noSynthFound = -240 #noSynthFound -siUnknownQuality = -232 #invalid quality selector (returned by driver) -siUnknownInfoType = -231 #invalid info type selector (returned by driver) -siInputDeviceErr = -230 #input device hardware failure -siBadRefNum = -229 #invalid input device reference number -siBadDeviceName = -228 #input device could not be opened -siDeviceBusyErr = -227 #input device already in use -siInvalidSampleSize = -226 #invalid sample size -siInvalidSampleRate = -225 #invalid sample rate -siHardDriveTooSlow = -224 #hard drive too slow to record to disk -siInvalidCompression = -223 #invalid compression type -siNoBufferSpecified = -222 #returned by synchronous SPBRecord if nil buffer passed -siBadSoundInDevice = -221 #invalid index passed to SoundInGetIndexedDevice -siNoSoundInHardware = -220 #no Sound Input hardware -siVBRCompressionNotSupported = -213 #vbr audio compression not supported for this operation -noMoreRealTime = -212 #not enough CPU cycles left to add another task -channelNotBusy = -211 #channelNotBusy -buffersTooSmall = -210 #can not operate in the memory allowed -channelBusy = -209 #the Channel is being used for a PFD already -badFileFormat = -208 #was not type AIFF or was of bad format,corrupt -notEnoughBufferSpace = -207 #could not allocate enough memory -badFormat = -206 #Sound Manager Error Returns -badChannel = -205 #Sound Manager Error Returns -resProblem = -204 #Sound Manager Error Returns -queueFull = -203 #Sound Manager Error Returns -notEnoughHardwareErr = -201 #Sound Manager Error Returns -noHardwareErr = -200 #Sound Manager Error Returns -mapReadErr = -199 #map inconsistent with operation -resAttrErr = -198 #attribute inconsistent with operation -rmvRefFailed = -197 #RmveReference failed -rmvResFailed = -196 #RmveResource failed -addRefFailed = -195 #AddReference failed -addResFailed = -194 #AddResource failed -resFNotFound = -193 #Resource file not found -resNotFound = -192 #Resource not found -inputOutOfBounds = -190 #Offset of Count out of bounds -writingPastEnd = -189 #Writing past end of file -resourceInMemory = -188 #Resource already in memory -CantDecompress = -186 #resource bent ("the bends") - can't decompress a compressed resource -badExtResource = -185 #extended resource has a bad format. -cmNoCurrentProfile = -182 #Responder error -cmUnsupportedDataType = -181 #Responder error -cmCantDeleteProfile = -180 #Responder error -cmCantXYZ = -179 #CMM cant handle XYZ space -cmCantConcatenateError = -178 #Profile can't be concatenated -cmProfilesIdentical = -177 #Profiles the same -cmProfileNotFound = -176 #Responder error -cmMethodNotFound = -175 #CMM not present -cmMethodError = -171 #cmMethodError -cmProfileError = -170 #cmProfileError -cDepthErr = -157 #invalid pixel depth -cResErr = -156 #invalid resolution for MakeITable -cDevErr = -155 #invalid type of graphics device -cProtectErr = -154 #colorTable entry protection violation -cRangeErr = -153 #range error on colorTable request -cNoMemErr = -152 #failed to allocate memory for structure -cTempMemErr = -151 #failed to allocate memory for temporary structures -cMatchErr = -150 #Color2Index failed to find an index -insufficientStackErr = -149 #insufficientStackErr -pixMapTooDeepErr = -148 #pixMapTooDeepErr -rgnOverflowErr = -147 #rgnOverflowErr -noMemForPictPlaybackErr = -145 #noMemForPictPlaybackErr -userCanceledErr = -128 #userCanceledErr -hMenuFindErr = -127 #could not find HMenu's parent in MenuKey (wrong error code - obsolete) -mBarNFnd = -126 #system error code for MBDF not found -updPixMemErr = -125 #insufficient memory to update a pixmap -volGoneErr = -124 #Server volume has been disconnected. -wrgVolTypErr = -123 #Wrong volume type error [operation not supported for MFS] -badMovErr = -122 #Move into offspring error -tmwdoErr = -121 #No free WDCB available -dirNFErr = -120 #Directory not found -memLockedErr = -117 #trying to move a locked block (MoveHHi) -memSCErr = -116 #Size Check failed -memBCErr = -115 #Block Check failed -memPCErr = -114 #Pointer Check failed -memAZErr = -113 #Address in zone check failed -memPurErr = -112 #trying to purge a locked or non-purgeable block -memWZErr = -111 #WhichZone failed (applied to free block) -memAdrErr = -110 #address was odd; or out of range -nilHandleErr = -109 #Master Pointer was NIL in HandleZone or other -memFullErr = -108 #Not enough room in heap zone -noTypeErr = -102 #No object of that type in scrap -noScrapErr = -100 #No scrap exists error -memROZWarn = -99 #soft error in ROZ -portNotCf = -98 #driver Open error code (parameter RAM not configured for this connection) -portInUse = -97 #driver Open error code (port is in use) -portNotPwr = -96 #serial port not currently powered -excessCollsns = -95 #excessive collisions on write -lapProtErr = -94 #error in attaching/detaching protocol -noBridgeErr = -93 #no network bridge for non-local send -eLenErr = -92 #Length error ddpLenErr -eMultiErr = -91 #Multicast address error ddpSktErr -breakRecd = -90 #Break received (SCC) -rcvrErr = -89 #SCC receiver error (framing; parity; OR) -prInitErr = -88 #InitUtil found the parameter ram uninitialized -prWrErr = -87 #parameter ram written didn't read-verify -clkWrErr = -86 #time written did not verify -clkRdErr = -85 #unable to read same clock value twice -verErr = -84 #track failed to verify -fmt2Err = -83 #can't get enough sync -fmt1Err = -82 #can't find sector 0 after track format -sectNFErr = -81 #sector number never found on a track -seekErr = -80 #track number wrong on address mark -spdAdjErr = -79 #unable to correctly adjust disk speed -twoSideErr = -78 #tried to read 2nd side on a 1-sided drive -initIWMErr = -77 #unable to initialize IWM -tk0BadErr = -76 #track 0 detect doesn't change -cantStepErr = -75 #step handshake failed -wrUnderrun = -74 #write underrun occurred -badDBtSlp = -73 #bad data mark bit slip nibbles -badDCksum = -72 #bad data mark checksum -noDtaMkErr = -71 #couldn't find a data mark header -badBtSlpErr = -70 #bad addr mark bit slip nibbles -badCksmErr = -69 #addr mark checksum didn't check -dataVerErr = -68 #read verify compare failed -noAdrMkErr = -67 #couldn't find valid addr mark -noNybErr = -66 #couldn't find 5 nybbles in 200 tries -offLinErr = -65 #r/w requested for an off-line drive -fontDecError = -64 #error during font declaration -wrPermErr = -61 #write permissions error -badMDBErr = -60 #bad master directory block -fsRnErr = -59 #file system internal error:during rename the old entry was deleted but could not be restored. -extFSErr = -58 #volume in question belongs to an external fs -noMacDskErr = -57 #not a mac diskette (sig bytes are wrong) -nsDrvErr = -56 #no such drive (tried to mount a bad drive num) -volOnLinErr = -55 #drive volume already on-line at MountVol -permErr = -54 #permissions error (on file open) -volOffLinErr = -53 #volume not on line error (was Ejected) -gfpErr = -52 #get file position error -rfNumErr = -51 #refnum error -paramErr = -50 #error in user parameter list -opWrErr = -49 #file already open with with write permission -dupFNErr = -48 #duplicate filename (rename) -fBsyErr = -47 #File is busy (delete) -vLckdErr = -46 #volume is locked -fLckdErr = -45 #file is locked -wPrErr = -44 #diskette is write protected. -fnfErr = -43 #File not found -tmfoErr = -42 #too many files open -mFulErr = -41 #memory full (open) or file won't fit (load) -posErr = -40 #tried to position to before start of file (r/w) -eofErr = -39 #End of file -fnOpnErr = -38 #File not open -bdNamErr = -37 #there may be no bad names in the final system! -ioErr = -36 #I/O error (bummers) -nsvErr = -35 #no such volume -dskFulErr = -34 #disk full -dirFulErr = -33 #Directory full -dceExtErr = -30 #dce extension error -unitTblFullErr = -29 #unit table has no more entries -notOpenErr = -28 #Couldn't rd/wr/ctl/sts cause driver not opened -iIOAbortErr = -27 #IO abort error (Printing Manager) -dInstErr = -26 #DrvrInstall couldn't find driver in resources -dRemovErr = -25 #tried to remove an open driver -closErr = -24 #I/O System Errors -openErr = -23 #I/O System Errors -unitEmptyErr = -22 #I/O System Errors -badUnitErr = -21 #I/O System Errors -writErr = -20 #I/O System Errors -readErr = -19 #I/O System Errors -statusErr = -18 #I/O System Errors -controlErr = -17 #I/O System Errors -dsExtensionsDisabled = -13 #say –Extensions Disabled” -dsHD20Installed = -12 #say –HD20 Startup” -dsDisassemblerInstalled = -11 #say –Disassembler Installed” -dsMacsBugInstalled = -10 #say –MacsBug Installed” -seNoDB = -8 #no debugger installed to handle debugger command -SlpTypeErr = -5 #invalid queue element -unimpErr = -4 #unimplemented core routine -corErr = -3 #core routine number out of range -dsNoExtsDisassembler = -2 #not a SysErr, just a placeholder -qErr = -1 #queue element not found during deletion -tsmComponentNoErr = 0 #component result = no error -EPERM = 1 #Operation not permitted -ENOENT = 2 #No such file or directory -ESRCH = 3 #No such process -EINTR = 4 #Interrupted system call -EIO = 5 #Input/output error -ENXIO = 6 #Device not configured -E2BIG = 7 #Argument list too long -ENOEXEC = 8 #Exec format error -EBADF = 9 #Bad file descriptor -ECHILD = 10 #No child processes -EDEADLK = 11 #Resource deadlock avoided -ENOMEM = 12 #Cannot allocate memory -EACCES = 13 #Permission denied -EFAULT = 14 #Bad address -ECANCELED = 15 #Operation cancelled -EBUSY = 16 #Device busy -EEXIST = 17 #File exists -EXDEV = 18 #Cross-device link -ENODEV = 19 #Operation not supported by device -ENOTDIR = 20 #Not a directory -EISDIR = 21 #Is a directory -EINVAL = 22 #Invalid argument -ENFILE = 23 #Too many open files in system -EMFILE = 24 #Too many open files -ENOTTY = 25 #Inappropriate ioctl for device -ESIGPARM = 26 #Signal error -EFBIG = 27 #File too large -ENOSPC = 28 #No space left on device -ESPIPE = 29 #Illegal seek -EROFS = 30 #Read-only file system -EMLINK = 31 #Too many links -EPIPE = 32 #Broken pipe -EDOM = 33 #Numerical argument out of domain -ERANGE = 34 #Result too large -EAGAIN = 35 #Resource temporarily unavailable -EINPROGRESS = 36 #Operation now in progress -EALREADY = 37 #Operation already in progress -ENOTSOCK = 38 #Socket operation on non-socket -EDESTADDRREQ = 39 #Destination address required -EMSGSIZE = 40 #Message too long -EPROTOTYPE = 41 #Protocol wrong type for socket -ENOPROTOOPT = 42 #Protocol not available -EPROTONOSUPPORT = 43 #Protocol not supported -ESOCKTNOSUPPORT = 44 #Socket type not supported -EOPNOTSUPP = 45 #Operation not supported -EPFNOSUPPORT = 46 #Protocol family not supported -EAFNOSUPPORT = 47 #Address family not supported by protocol family -EADDRINUSE = 48 #Address already in use -EADDRNOTAVAIL = 49 #Can't assign requested address -ENETDOWN = 50 #Network is down -ENETUNREACH = 51 #Network is unreachable -ENETRESET = 52 #Network dropped connection on reset -ECONNABORTED = 53 #Software caused connection abort -ECONNRESET = 54 #Connection reset by peer -ENOBUFS = 55 #No buffer space available -EISCONN = 56 #Socket is already connected -ENOTCONN = 57 #Socket is not connected -ESHUTDOWN = 58 #Can't send after socket shutdown -ETOOMANYREFS = 59 #Too many references: can't splice -ETIMEDOUT = 60 #Operation timed out -ECONNREFUSED = 61 #Connection refused -ELOOP = 62 #Too many levels of symbolic links -ENAMETOOLONG = 63 #File name too long -EHOSTDOWN = 64 #Host is down -EHOSTUNREACH = 65 #No route to host -ENOTEMPTY = 66 #Directory not empty -ELOOK = 67 #Internal mapping for kOTLookErr, don't return to client -ENOLCK = 77 #No locks available -ENOSYS = 78 #Function not implemented -EILSEQ = 88 #Wide character encoding error -EUNKNOWN = 99 #Unknown error +svTempDisable = -32768 #svTempDisable +svDisabled = -32640 #Reserve range -32640 to -32768 for Apple temp disables. +fontNotOutlineErr = -32615 #bitmap font passed to routine that does outlines only +kURL68kNotSupportedError = -30788 #kURL68kNotSupportedError +kURLAccessNotAvailableError = -30787 #kURLAccessNotAvailableError +kURLInvalidConfigurationError = -30786 #kURLInvalidConfigurationError +kURLExtensionFailureError = -30785 #kURLExtensionFailureError +kURLFileEmptyError = -30783 #kURLFileEmptyError +kURLInvalidCallError = -30781 #kURLInvalidCallError +kURLUnsettablePropertyError = -30780 #kURLUnsettablePropertyError +kURLPropertyBufferTooSmallError = -30779 #kURLPropertyBufferTooSmallError +kURLUnknownPropertyError = -30778 #kURLUnknownPropertyError +kURLPropertyNotYetKnownError = -30777 #kURLPropertyNotYetKnownError +kURLAuthenticationError = -30776 #kURLAuthenticationError +kURLServerBusyError = -30775 #kURLServerBusyError +kURLUnsupportedSchemeError = -30774 #kURLUnsupportedSchemeError +kURLInvalidURLError = -30773 #kURLInvalidURLError +kURLDestinationExistsError = -30772 #kURLDestinationExistsError +kURLProgressAlreadyDisplayedError = -30771 #kURLProgressAlreadyDisplayedError +kURLInvalidURLReferenceError = -30770 #kURLInvalidURLReferenceError +controlHandleInvalidErr = -30599 #controlHandleInvalidErr +controlInvalidDataVersionErr = -30597 #controlInvalidDataVersionErr +errItemNotControl = -30596 #errItemNotControl +errCantEmbedRoot = -30595 #errCantEmbedRoot +errCantEmbedIntoSelf = -30594 #errCantEmbedIntoSelf +errWindowRegionCodeInvalid = -30593 #errWindowRegionCodeInvalid +errControlHiddenOrDisabled = -30592 #errControlHiddenOrDisabled +errDataSizeMismatch = -30591 #errDataSizeMismatch +errControlIsNotEmbedder = -30590 #errControlIsNotEmbedder +errControlsAlreadyExist = -30589 #errControlsAlreadyExist +errInvalidPartCode = -30588 #errInvalidPartCode +errRootAlreadyExists = -30587 #errRootAlreadyExists +errNoRootControl = -30586 #errNoRootControl +errCouldntSetFocus = -30585 #errCouldntSetFocus +errUnknownControl = -30584 #errUnknownControl +errWindowDoesntSupportFocus = -30583 #errWindowDoesntSupportFocus +errControlDoesntSupportFocus = -30582 #errControlDoesntSupportFocus +errDataNotSupported = -30581 #errDataNotSupported +errMessageNotSupported = -30580 #errMessageNotSupported +themeMonitorDepthNotSupportedErr = -30567 #theme not supported at monitor depth +themeScriptFontNotFoundErr = -30566 #theme font requested for uninstalled script system +themeBadCursorIndexErr = -30565 #themeBadCursorIndexErr +themeHasNoAccentsErr = -30564 #themeHasNoAccentsErr +themeBadTextColorErr = -30563 #themeBadTextColorErr +themeProcessNotRegisteredErr = -30562 #themeProcessNotRegisteredErr +themeProcessRegisteredErr = -30561 #themeProcessRegisteredErr +themeInvalidBrushErr = -30560 #pattern index invalid +qtvrUninitialized = -30555 #qtvrUninitialized +qtvrLibraryLoadErr = -30554 #qtvrLibraryLoadErr +streamingNodeNotReadyErr = -30553 #streamingNodeNotReadyErr +noMemoryNodeFailedInitialize = -30552 #noMemoryNodeFailedInitialize +invalidHotSpotIDErr = -30551 #invalidHotSpotIDErr +invalidNodeFormatErr = -30550 #invalidNodeFormatErr +limitReachedErr = -30549 #limitReachedErr +settingNotSupportedByNodeErr = -30548 #settingNotSupportedByNodeErr +propertyNotSupportedByNodeErr = -30547 #propertyNotSupportedByNodeErr +timeNotInViewErr = -30546 #timeNotInViewErr +invalidViewStateErr = -30545 #invalidViewStateErr +invalidNodeIDErr = -30544 #invalidNodeIDErr +selectorNotSupportedByNodeErr = -30543 #selectorNotSupportedByNodeErr +callNotSupportedByNodeErr = -30542 #callNotSupportedByNodeErr +constraintReachedErr = -30541 #constraintReachedErr +notAQTVRMovieErr = -30540 #notAQTVRMovieErr +kFBCnoSuchHit = -30532 #kFBCnoSuchHit +kFBCbadSearchSession = -30531 #kFBCbadSearchSession +kFBCindexDiskIOFailed = -30530 #kFBCindexDiskIOFailed +kFBCsummarizationCanceled = -30529 #kFBCsummarizationCanceled +kFBCbadIndexFileVersion = -30528 #kFBCbadIndexFileVersion +kFBCanalysisNotAvailable = -30527 #kFBCanalysisNotAvailable +kFBCillegalSessionChange = -30526 #tried to add/remove vols to a session +kFBCsomeFilesNotIndexed = -30525 #kFBCsomeFilesNotIndexed +kFBCsearchFailed = -30524 #kFBCsearchFailed +kFBCindexNotAvailable = -30523 #kFBCindexNotAvailable +kFBCindexFileDestroyed = -30522 #kFBCindexFileDestroyed +kFBCaccessCanceled = -30521 #kFBCaccessCanceled +kFBCindexingCanceled = -30520 #kFBCindexingCanceled +kFBCnoSearchSession = -30519 #kFBCnoSearchSession +kFBCindexNotFound = -30518 #kFBCindexNotFound +kFBCflushFailed = -30517 #kFBCflushFailed +kFBCaddDocFailed = -30516 #kFBCaddDocFailed +kFBCaccessorStoreFailed = -30515 #kFBCaccessorStoreFailed +kFBCindexCreationFailed = -30514 #couldn't create index +kFBCmergingFailed = -30513 #couldn't merge index files +kFBCtokenizationFailed = -30512 #couldn't read from document or query +kFBCmoveFailed = -30511 #V-Twin exception caught +kFBCdeletionFailed = -30510 #V-Twin exception caught +kFBCcommitFailed = -30509 #V-Twin exception caught +kFBCindexingFailed = -30508 #V-Twin exception caught +kFBCvalidationFailed = -30507 #V-Twin exception caught +kFBCcompactionFailed = -30506 #V-Twin exception caught +kFBCbadIndexFile = -30505 #bad FSSpec, or bad data in file +kFBCfileNotIndexed = -30504 #kFBCfileNotIndexed +kFBCbadParam = -30503 #kFBCbadParam +kFBCallocFailed = -30502 #probably low memory +kFBCnoIndexesFound = -30501 #kFBCnoIndexesFound +kFBCvTwinExceptionErr = -30500 #no telling what it was +kDSpStereoContextErr = -30450 #kDSpStereoContextErr +kDSpInternalErr = -30449 #kDSpInternalErr +kDSpConfirmSwitchWarning = -30448 #kDSpConfirmSwitchWarning +kDSpFrameRateNotReadyErr = -30447 #kDSpFrameRateNotReadyErr +kDSpContextNotFoundErr = -30446 #kDSpContextNotFoundErr +kDSpContextNotReservedErr = -30445 #kDSpContextNotReservedErr +kDSpContextAlreadyReservedErr = -30444 #kDSpContextAlreadyReservedErr +kDSpInvalidAttributesErr = -30443 #kDSpInvalidAttributesErr +kDSpInvalidContextErr = -30442 #kDSpInvalidContextErr +kDSpSystemSWTooOldErr = -30441 #kDSpSystemSWTooOldErr +kDSpNotInitializedErr = -30440 #kDSpNotInitializedErr +kISpListBusyErr = -30429 #kISpListBusyErr +kISpDeviceActiveErr = -30428 #kISpDeviceActiveErr +kISpSystemActiveErr = -30427 #kISpSystemActiveErr +kISpDeviceInactiveErr = -30426 #kISpDeviceInactiveErr +kISpSystemInactiveErr = -30425 #kISpSystemInactiveErr +kISpElementNotInListErr = -30424 #kISpElementNotInListErr +kISpElementInListErr = -30423 #kISpElementInListErr +kISpBufferToSmallErr = -30422 #kISpBufferToSmallErr +kISpSystemListErr = -30421 #kISpSystemListErr +kISpInternalErr = -30420 #kISpInternalErr +kNSpJoinFailedErr = -30399 #kNSpJoinFailedErr +kNSpCantBlockErr = -30398 #kNSpCantBlockErr +kNSpMessageTooBigErr = -30397 #kNSpMessageTooBigErr +kNSpSendFailedErr = -30396 #kNSpSendFailedErr +kNSpConnectFailedErr = -30395 #kNSpConnectFailedErr +kNSpGameTerminatedErr = -30394 #kNSpGameTerminatedErr +kNSpTimeoutErr = -30393 #kNSpTimeoutErr +kNSpInvalidProtocolListErr = -30392 #kNSpInvalidProtocolListErr +kNSpInvalidProtocolRefErr = -30391 #kNSpInvalidProtocolRefErr +kNSpInvalidDefinitionErr = -30390 #kNSpInvalidDefinitionErr +kNSpAddPlayerFailedErr = -30389 #kNSpAddPlayerFailedErr +kNSpCreateGroupFailedErr = -30388 #kNSpCreateGroupFailedErr +kNSpNoHostVolunteersErr = -30387 #kNSpNoHostVolunteersErr +kNSpNoGroupsErr = -30386 #kNSpNoGroupsErr +kNSpNoPlayersErr = -30385 #kNSpNoPlayersErr +kNSpInvalidGroupIDErr = -30384 #kNSpInvalidGroupIDErr +kNSpInvalidPlayerIDErr = -30383 #kNSpInvalidPlayerIDErr +kNSpNameRequiredErr = -30382 #kNSpNameRequiredErr +kNSpFeatureNotImplementedErr = -30381 #kNSpFeatureNotImplementedErr +kNSpAddressInUseErr = -30380 #kNSpAddressInUseErr +kNSpRemovePlayerFailedErr = -30379 #kNSpRemovePlayerFailedErr +kNSpFreeQExhaustedErr = -30378 #kNSpFreeQExhaustedErr +kNSpInvalidAddressErr = -30377 #kNSpInvalidAddressErr +kNSpNotAdvertisingErr = -30376 #kNSpNotAdvertisingErr +kNSpAlreadyAdvertisingErr = -30374 #kNSpAlreadyAdvertisingErr +kNSpMemAllocationErr = -30373 #kNSpMemAllocationErr +kNSpOTVersionTooOldErr = -30371 #kNSpOTVersionTooOldErr +kNSpOTNotPresentErr = -30370 #kNSpOTNotPresentErr +kNSpInvalidParameterErr = -30369 #kNSpInvalidParameterErr +kNSpInvalidGameRefErr = -30367 #kNSpInvalidGameRefErr +kNSpProtocolNotAvailableErr = -30366 #kNSpProtocolNotAvailableErr +kNSpHostFailedErr = -30365 #kNSpHostFailedErr +kNSpPipeFullErr = -30364 #kNSpPipeFullErr +kNSpTopologyNotSupportedErr = -30362 #kNSpTopologyNotSupportedErr +kNSpAlreadyInitializedErr = -30361 #kNSpAlreadyInitializedErr +kNSpInitializationFailedErr = -30360 #kNSpInitializationFailedErr +kSSpScaleToZeroErr = -30344 #kSSpScaleToZeroErr +kSSpParallelUpVectorErr = -30343 #kSSpParallelUpVectorErr +kSSpCantInstallErr = -30342 #kSSpCantInstallErr +kSSpVersionErr = -30341 #kSSpVersionErr +kSSpInternalErr = -30340 #kSSpInternalErr +kALMInternalErr = -30049 #kALMInternalErr +kALMGroupNotFoundErr = -30048 #kALMGroupNotFoundErr +kALMNoSuchModuleErr = -30047 #kALMNoSuchModuleErr +kALMModuleCommunicationErr = -30046 #kALMModuleCommunicationErr +kALMDuplicateModuleErr = -30045 #kALMDuplicateModuleErr +kALMInstallationErr = -30044 #kALMInstallationErr +kALMDeferSwitchErr = -30043 #kALMDeferSwitchErr +kALMRebootFlagsLevelErr = -30042 #kALMRebootFlagsLevelErr +kLocalesDefaultDisplayStatus = -30029 #Requested display locale unavailable, used default +kLocalesTableFormatErr = -30002 #kLocalesTableFormatErr +kLocalesBufferTooSmallErr = -30001 #kLocalesBufferTooSmallErr +kFNSNameNotFoundErr = -29589 #The name with the requested paramters was not found +kFNSBadFlattenedSizeErr = -29587 #flattened size didn't match input or was too small +kFNSInsufficientDataErr = -29586 #insufficient data for the operation +kFNSMismatchErr = -29585 #reference didn't match or wasn't found in profile +kFNSDuplicateReferenceErr = -29584 #the ref. being added is already in the profile +kFNSBadProfileVersionErr = -29583 #profile version is out of known range +kFNSInvalidProfileErr = -29582 #profile is NULL or otherwise bad +kFNSBadReferenceVersionErr = -29581 #ref. version is out of known range +kFNSInvalidReferenceErr = -29580 #ref. was NULL or otherwise bad +kCollateInvalidCollationRef = -29507 #kCollateInvalidCollationRef +kCollateBufferTooSmall = -29506 #kCollateBufferTooSmall +kCollateInvalidChar = -29505 #kCollateInvalidChar +kCollatePatternNotFoundErr = -29504 #kCollatePatternNotFoundErr +kCollateUnicodeConvertFailedErr = -29503 #kCollateUnicodeConvertFailedErr +kCollateMissingUnicodeTableErr = -29502 #kCollateMissingUnicodeTableErr +kCollateInvalidOptions = -29501 #kCollateInvalidOptions +kCollateAttributesNotFoundErr = -29500 #kCollateAttributesNotFoundErr +kMPInvalidIDErr = -29299 #kMPInvalidIDErr +kMPInsufficientResourcesErr = -29298 #kMPInsufficientResourcesErr +kMPTaskAbortedErr = -29297 #kMPTaskAbortedErr +kMPTimeoutErr = -29296 #kMPTimeoutErr +kMPDeletedErr = -29295 #kMPDeletedErr +kMPBlueBlockingErr = -29293 #kMPBlueBlockingErr +kMPTaskStoppedErr = -29292 #A convention used with MPThrowException. +kMPTaskBlockedErr = -29291 #kMPTaskBlockedErr +kMPTaskCreatedErr = -29290 #kMPTaskCreatedErr +kMPProcessTerminatedErr = -29289 #kMPProcessTerminatedErr +kMPProcessCreatedErr = -29288 #kMPProcessCreatedErr +kMPPrivilegedErr = -29276 #kMPPrivilegedErr +kMPIterationEndErr = -29275 #kMPIterationEndErr +kUCTextBreakLocatorMissingType = -25341 #Unicode text break error +kUCOutputBufferTooSmall = -25340 #Output buffer too small for Unicode string result +errKCCreateChainFailed = -25318 #errKCCreateChainFailed +errKCDataNotModifiable = -25317 #errKCDataNotModifiable +errKCDataNotAvailable = -25316 #errKCDataNotAvailable +errKCInteractionRequired = -25315 #errKCInteractionRequired +errKCNoPolicyModule = -25314 #errKCNoPolicyModule +errKCNoCertificateModule = -25313 #errKCNoCertificateModule +errKCNoStorageModule = -25312 #errKCNoStorageModule +errKCKeySizeNotAllowed = -25311 #errKCKeySizeNotAllowed +errKCWrongKCVersion = -25310 #errKCWrongKCVersion +errKCReadOnlyAttr = -25309 #errKCReadOnlyAttr +errKCInteractionNotAllowed = -25308 #errKCInteractionNotAllowed +errKCNoDefaultKeychain = -25307 #errKCNoDefaultKeychain +errKCNoSuchClass = -25306 #errKCNoSuchClass +errKCInvalidSearchRef = -25305 #errKCInvalidSearchRef +errKCInvalidItemRef = -25304 #errKCInvalidItemRef +errKCNoSuchAttr = -25303 #errKCNoSuchAttr +errKCDataTooLarge = -25302 #errKCDataTooLarge +errKCBufferTooSmall = -25301 #errKCBufferTooSmall +errKCItemNotFound = -25300 #errKCItemNotFound +errKCDuplicateItem = -25299 #errKCDuplicateItem +errKCInvalidCallback = -25298 #errKCInvalidCallback +errKCDuplicateCallback = -25297 #errKCDuplicateCallback +errKCDuplicateKeychain = -25296 #errKCDuplicateKeychain +errKCInvalidKeychain = -25295 #errKCInvalidKeychain +errKCNoSuchKeychain = -25294 #errKCNoSuchKeychain +errKCAuthFailed = -25293 #errKCAuthFailed +errKCReadOnly = -25292 #errKCReadOnly +errKCNotAvailable = -25291 #errKCNotAvailable +printerStatusOpCodeNotSupportedErr = -25280 #printerStatusOpCodeNotSupportedErr +kTXNOutsideOfFrameErr = -22018 #kTXNOutsideOfFrameErr +kTXNOutsideOfLineErr = -22017 #kTXNOutsideOfLineErr +kTXNATSUIIsNotInstalledErr = -22016 #kTXNATSUIIsNotInstalledErr +kTXNDataTypeNotAllowedErr = -22015 #kTXNDataTypeNotAllowedErr +kTXNCopyNotAllowedInEchoModeErr = -22014 #kTXNCopyNotAllowedInEchoModeErr +kTXNCannotTurnTSMOffWhenUsingUnicodeErr = -22013 #kTXNCannotTurnTSMOffWhenUsingUnicodeErr +kTXNAlreadyInitializedErr = -22012 #kTXNAlreadyInitializedErr +kTXNInvalidRunIndex = -22011 #kTXNInvalidRunIndex +kTXNSomeOrAllTagsInvalidForRunErr = -22010 #kTXNSomeOrAllTagsInvalidForRunErr +kTXNAttributeTagInvalidForRunErr = -22009 #dataValue is set to this per invalid tag +kTXNNoMatchErr = -22008 #kTXNNoMatchErr +kTXNRunIndexOutofBoundsErr = -22007 #kTXNRunIndexOutofBoundsErr +kTXNCannotSetAutoIndentErr = -22006 #kTXNCannotSetAutoIndentErr +kTXNBadDefaultFileTypeWarning = -22005 #kTXNBadDefaultFileTypeWarning +kTXNUserCanceledOperationErr = -22004 #kTXNUserCanceledOperationErr +kTXNIllegalToCrossDataBoundariesErr = -22003 #kTXNIllegalToCrossDataBoundariesErr +kTXNInvalidFrameIDErr = -22002 #kTXNInvalidFrameIDErr +kTXNCannotAddFrameErr = -22001 #kTXNCannotAddFrameErr +kTXNEndIterationErr = -22000 #kTXNEndIterationErr +invalidIndexErr = -20002 #The recordIndex parameter is not valid. +recordDataTooBigErr = -20001 #The record data is bigger than buffer size (1024 bytes). +unknownInsertModeErr = -20000 #There is no such an insert mode. +kModemScriptMissing = -14002 #kModemScriptMissing +kModemPreferencesMissing = -14001 #kModemPreferencesMissing +kModemOutOfMemory = -14000 #kModemOutOfMemory +kHIDBaseError = -13950 #kHIDBaseError +kHIDNullStateErr = -13949 #kHIDNullStateErr +kHIDBufferTooSmallErr = -13948 #kHIDBufferTooSmallErr +kHIDValueOutOfRangeErr = -13947 #kHIDValueOutOfRangeErr +kHIDUsageNotFoundErr = -13946 #kHIDUsageNotFoundErr +kHIDNotValueArrayErr = -13945 #kHIDNotValueArrayErr +kHIDInvalidPreparsedDataErr = -13944 #kHIDInvalidPreparsedDataErr +kHIDIncompatibleReportErr = -13943 #kHIDIncompatibleReportErr +kHIDBadLogPhysValuesErr = -13942 #kHIDBadLogPhysValuesErr +kHIDInvalidReportTypeErr = -13941 #kHIDInvalidReportTypeErr +kHIDInvalidReportLengthErr = -13940 #kHIDInvalidReportLengthErr +kHIDNullPointerErr = -13939 #kHIDNullPointerErr +kHIDBadParameterErr = -13938 #kHIDBadParameterErr +kHIDNotEnoughMemoryErr = -13937 #kHIDNotEnoughMemoryErr +kHIDEndOfDescriptorErr = -13936 #kHIDEndOfDescriptorErr +kHIDUsagePageZeroErr = -13935 #kHIDUsagePageZeroErr +kHIDBadLogicalMinimumErr = -13934 #kHIDBadLogicalMinimumErr +kHIDBadLogicalMaximumErr = -13933 #kHIDBadLogicalMaximumErr +kHIDInvertedLogicalRangeErr = -13932 #kHIDInvertedLogicalRangeErr +kHIDInvertedPhysicalRangeErr = -13931 #kHIDInvertedPhysicalRangeErr +kHIDUnmatchedUsageRangeErr = -13930 #kHIDUnmatchedUsageRangeErr +kHIDInvertedUsageRangeErr = -13929 #kHIDInvertedUsageRangeErr +kHIDUnmatchedStringRangeErr = -13928 #kHIDUnmatchedStringRangeErr +kHIDUnmatchedDesignatorRangeErr = -13927 #kHIDUnmatchedDesignatorRangeErr +kHIDReportSizeZeroErr = -13926 #kHIDReportSizeZeroErr +kHIDReportCountZeroErr = -13925 #kHIDReportCountZeroErr +kHIDReportIDZeroErr = -13924 #kHIDReportIDZeroErr +kHIDInvalidRangePageErr = -13923 #kHIDInvalidRangePageErr +kHIDDeviceNotReady = -13910 #The device is still initializing, try again later +kHIDVersionIncompatibleErr = -13909 #kHIDVersionIncompatibleErr +debuggingNoMatchErr = -13887 #debugging component or option not found at this index +debuggingNoCallbackErr = -13886 #debugging component has no callback +debuggingInvalidNameErr = -13885 #componentName or optionName is invalid (NULL) +debuggingInvalidOptionErr = -13884 #optionSelectorNum is not registered +debuggingInvalidSignatureErr = -13883 #componentSignature not registered +debuggingDuplicateOptionErr = -13882 #optionSelectorNum already registered +debuggingDuplicateSignatureErr = -13881 #componentSignature already registered +debuggingExecutionContextErr = -13880 #routine cannot be called at this time +kBridgeSoftwareRunningCantSleep = -13038 #kBridgeSoftwareRunningCantSleep +kNoSuchPowerSource = -13020 #kNoSuchPowerSource +kProcessorTempRoutineRequiresMPLib2 = -13014 #kProcessorTempRoutineRequiresMPLib2 +kCantReportProcessorTemperatureErr = -13013 #kCantReportProcessorTemperatureErr +kPowerMgtRequestDenied = -13010 #kPowerMgtRequestDenied +kPowerMgtMessageNotHandled = -13009 #kPowerMgtMessageNotHandled +kPowerHandlerNotFoundForProcErr = -13008 #kPowerHandlerNotFoundForProcErr +kPowerHandlerNotFoundForDeviceErr = -13007 #kPowerHandlerNotFoundForDeviceErr +kPowerHandlerExistsForDeviceErr = -13006 #kPowerHandlerExistsForDeviceErr +pmRecvEndErr = -13005 #during receive, pmgr did not finish hs configured for this connection +pmRecvStartErr = -13004 #during receive, pmgr did not start hs +pmSendEndErr = -13003 #during send, pmgr did not finish hs +pmSendStartErr = -13002 #during send, pmgr did not start hs +pmReplyTOErr = -13001 #Timed out waiting for reply +pmBusyErr = -13000 #Power Mgr never ready to start handshake +pictureDataErr = -11005 #the picture data was invalid +colorsRequestedErr = -11004 #the number of colors requested was illegal +cantLoadPickMethodErr = -11003 #unable to load the custom pick proc +pictInfoVerbErr = -11002 #the passed verb was invalid +pictInfoIDErr = -11001 #the internal consistancy check for the PictInfoID is wrong +pictInfoVersionErr = -11000 #wrong version of the PictInfo structure +errTaskNotFound = -10780 #no task with that task id exists +telNotEnoughdspBW = -10116 #not enough real-time for allocation +telBadSampleRate = -10115 #incompatible sample rate +telBadSWErr = -10114 #Software not installed properly +telDetAlreadyOn = -10113 #detection is already turned on +telAutoAnsNotOn = -10112 #autoAnswer in not turned on +telValidateFailed = -10111 #telValidate failed +telBadProcID = -10110 #invalid procID +telDeviceNotFound = -10109 #device not found +telBadCodeResource = -10108 #code resource not found +telInitFailed = -10107 #initialization failed +telNoCommFolder = -10106 #Communications/Extensions € not found +telUnknownErr = -10103 #unable to set config +telNoSuchTool = -10102 #unable to find tool with name specified +telBadFunction = -10091 #bad msgCode specified +telPBErr = -10090 #parameter block error, bad format +telCANotDeflectable = -10082 #CA not "deflectable" +telCANotRejectable = -10081 #CA not "rejectable" +telCANotAcceptable = -10080 #CA not "acceptable" +telTermNotOpen = -10072 #terminal not opened via TELOpenTerm +telStillNeeded = -10071 #terminal driver still needed by someone else +telAlreadyOpen = -10070 #terminal already open +telNoCallbackRef = -10064 #no call back reference was specified, but is required +telDisplayModeNotSupp = -10063 #display mode not supported by tool +telBadDisplayMode = -10062 #bad display mode specified +telFwdTypeNotSupp = -10061 #forward type not supported by tool +telDNTypeNotSupp = -10060 #DN type not supported by tool +telBadRate = -10059 #bad rate specified +telBadBearerType = -10058 #bad bearerType specified +telBadSelect = -10057 #unable to select or deselect DN +telBadParkID = -10056 #bad park id specified +telBadPickupGroupID = -10055 #bad pickup group ID specified +telBadFwdType = -10054 #bad fwdType specified +telBadFeatureID = -10053 #bad feature ID specified +telBadIntercomID = -10052 #bad intercom ID specified +telBadPageID = -10051 #bad page ID specified +telBadDNType = -10050 #DN type invalid +telConfLimitExceeded = -10047 #attempt to exceed switch conference limits +telCBErr = -10046 #call back feature not set previously +telTransferRej = -10045 #transfer request rejected +telTransferErr = -10044 #transfer not prepared +telConfRej = -10043 #conference request was rejected +telConfErr = -10042 #conference was not prepared +telConfNoLimit = -10041 #no limit was specified but required +telConfLimitErr = -10040 #limit specified is too high for this configuration +telFeatNotSupp = -10033 #feature program call not supported by this tool +telFeatActive = -10032 #feature already active +telFeatNotAvail = -10031 #feature subscribed but not available +telFeatNotSub = -10030 #feature not subscribed +errAEPropertiesClash = -10025 #illegal combination of properties settings for Set Data, make new, or duplicate +errAECantPutThatThere = -10024 #in make new, duplicate, etc. class can't be an element of container +errAENotAnEnumMember = -10023 #enumerated value in SetData is not allowed for this property +telIntExtNotSupp = -10022 #internal external type not supported by this tool +telBadIntExt = -10021 #bad internal external error +telStateNotSupp = -10020 #device state not supported by tool +telBadStateErr = -10019 #bad device state specified +telIndexNotSupp = -10018 #index not supported by this tool +telBadIndex = -10017 #bad index specified +telAPattNotSupp = -10016 #alerting pattern not supported by tool +telBadAPattErr = -10015 #bad alerting pattern specified +telVTypeNotSupp = -10014 #volume type not supported by this tool +telBadVTypeErr = -10013 #bad volume type error +telBadLevelErr = -10012 #bad volume level setting +telHTypeNotSupp = -10011 #hook type not supported by this tool +telBadHTypeErr = -10010 #bad hook type specified +errAECantSupplyType = -10009 #errAECantSupplyType +telNoOpenErr = -10008 #unable to open terminal +telNoMemErr = -10007 #no memory to allocate handle +errOSACantAssign = -10006 #Signaled when an object cannot be set in a container. +telBadProcErr = -10005 #bad msgProc specified +telBadHandErr = -10004 #bad handle specified +OSAIllegalAssign = -10003 #Signaled when an object can never be set in a container +telBadDNErr = -10002 #TELDNHandle not found or invalid +telBadTermErr = -10001 #invalid TELHandle or handle not found +errAEEventFailed = -10000 #errAEEventFailed +cannotMoveAttachedController = -9999 #cannotMoveAttachedController +controllerHasFixedHeight = -9998 #controllerHasFixedHeight +cannotSetWidthOfAttachedController = -9997 #cannotSetWidthOfAttachedController +controllerBoundsNotExact = -9996 #controllerBoundsNotExact +editingNotAllowed = -9995 #editingNotAllowed +badControllerHeight = -9994 #badControllerHeight +deviceCantMeetRequest = -9408 #deviceCantMeetRequest +seqGrabInfoNotAvailable = -9407 #seqGrabInfoNotAvailable +badSGChannel = -9406 #badSGChannel +couldntGetRequiredComponent = -9405 #couldntGetRequiredComponent +notEnoughDiskSpaceToGrab = -9404 #notEnoughDiskSpaceToGrab +notEnoughMemoryToGrab = -9403 #notEnoughMemoryToGrab +cantDoThatInCurrentMode = -9402 #cantDoThatInCurrentMode +grabTimeComplete = -9401 #grabTimeComplete +noDeviceForChannel = -9400 #noDeviceForChannel +kNoCardBusCISErr = -9109 #No valid CIS exists for this CardBus card +kNotZVCapableErr = -9108 #This socket does not support Zoomed Video +kCardPowerOffErr = -9107 #Power to the card has been turned off +kAttemptDupCardEntryErr = -9106 #The Enabler was asked to create a duplicate card entry +kAlreadySavedStateErr = -9105 #The state has been saved on previous call +kTooManyIOWindowsErr = -9104 #device requested more than one I/O window +kNotReadyErr = -9103 #PC Card failed to go ready +kClientRequestDenied = -9102 #CS Clients should return this code inorder to +kNoCompatibleNameErr = -9101 #There is no compatible driver name for this device +kNoEnablerForCardErr = -9100 #No Enablers were found that can support the card +kNoCardEnablersFoundErr = -9099 #No Enablers were found +kUnsupportedCardErr = -9098 #Card not supported by generic enabler +kNoClientTableErr = -9097 #The client table has not be initialized yet +kNoMoreInterruptSlotsErr = -9096 #All internal Interrupt slots are in use +kNoMoreTimerClientsErr = -9095 #All timer callbacks are in use +kNoIOWindowRequestedErr = -9094 #Request I/O window before calling configuration +kBadCustomIFIDErr = -9093 #Custom interface ID is invalid +kBadTupleDataErr = -9092 #Data in tuple is invalid +kInvalidCSClientErr = -9091 #Card Services ClientID is not registered +kUnsupportedVsErr = -9090 #Unsupported Voltage Sense +kInvalidDeviceNumber = -9089 #kInvalidDeviceNumber +kPostCardEventErr = -9088 #_PCCSLPostCardEvent failed and dropped an event +kCantConfigureCardErr = -9087 #kCantConfigureCardErr +kPassCallToChainErr = -9086 #kPassCallToChainErr +kCardBusCardErr = -9085 #kCardBusCardErr +k16BitCardErr = -9084 #k16BitCardErr +kBadDeviceErr = -9083 #kBadDeviceErr +kBadLinkErr = -9082 #kBadLinkErr +kInvalidRegEntryErr = -9081 #kInvalidRegEntryErr +kNoCardSevicesSocketsErr = -9080 #kNoCardSevicesSocketsErr +kOutOfResourceErr = -9079 #Card Services has exhausted the resource +kNoMoreItemsErr = -9078 #there are no more of the requested item +kInUseErr = -9077 #requested resource is being used by a client +kConfigurationLockedErr = -9076 #a configuration has already been locked +kWriteProtectedErr = -9075 #media is write-protected +kBusyErr = -9074 #unable to process request at this time - try later +kUnsupportedModeErr = -9073 #mode is not supported +kUnsupportedFunctionErr = -9072 #function is not supported by this implementation +kNoCardErr = -9071 #no PC card in the socket +kGeneralFailureErr = -9070 #an undefined error has occurred +kWriteFailureErr = -9069 #unable to complete write request +kReadFailureErr = -9068 #unable to complete read request +kBadSpeedErr = -9067 #specified speed is unavailable +kBadCISErr = -9066 #CIS on card is invalid +kBadHandleErr = -9065 #clientHandle is invalid +kBadArgsErr = -9064 #values in argument packet are invalid +kBadArgLengthErr = -9063 #ArgLength argument is invalid +kBadWindowErr = -9062 #specified window is invalid +kBadVppErr = -9061 #specified Vpp1 or Vpp2 power level index is invalid +kBadVccErr = -9060 #specified Vcc power level index is invalid +kBadTypeErr = -9059 #specified window or interface type is invalid +kBadSocketErr = -9058 #specified logical or physical socket number is invalid +kBadSizeErr = -9057 #specified size is invalid +kBadPageErr = -9056 #specified page is invalid +kBadOffsetErr = -9055 #specified PC card memory array offset is invalid +kBadIRQErr = -9054 #specified IRQ level is invalid +kBadEDCErr = -9053 #specified EDC generator specified is invalid +kBadBaseErr = -9052 #specified base system memory address is invalid +kBadAttributeErr = -9051 #specified attributes field value is invalid +kBadAdapterErr = -9050 #invalid adapter number +codecOffscreenFailedPleaseRetryErr = -8992 #codecOffscreenFailedPleaseRetryErr +lockPortBitsWrongGDeviceErr = -8991 #lockPortBitsWrongGDeviceErr +directXObjectAlreadyExists = -8990 #directXObjectAlreadyExists +codecDroppedFrameErr = -8989 #returned from ImageCodecDrawBand +codecOffscreenFailedErr = -8988 #codecOffscreenFailedErr +codecNeedAccessKeyErr = -8987 #codec needs password in order to decompress +codecParameterDialogConfirm = -8986 #codecParameterDialogConfirm +lockPortBitsSurfaceLostErr = -8985 #lockPortBitsSurfaceLostErr +lockPortBitsBadPortErr = -8984 #lockPortBitsBadPortErr +lockPortBitsWindowClippedErr = -8983 #lockPortBitsWindowClippedErr +lockPortBitsWindowResizedErr = -8982 #lockPortBitsWindowResizedErr +lockPortBitsWindowMovedErr = -8981 #lockPortBitsWindowMovedErr +lockPortBitsBadSurfaceErr = -8980 #lockPortBitsBadSurfaceErr +codecNeedToFlushChainErr = -8979 #codecNeedToFlushChainErr +codecDisabledErr = -8978 #codec disabled itself -- pass codecFlagReenable to reset +codecNoMemoryPleaseWaitErr = -8977 #codecNoMemoryPleaseWaitErr +codecNothingToBlitErr = -8976 #codecNothingToBlitErr +codecCantQueueErr = -8975 #codecCantQueueErr +codecCantWhenErr = -8974 #codecCantWhenErr +codecOpenErr = -8973 #codecOpenErr +codecConditionErr = -8972 #codecConditionErr +codecExtensionNotFoundErr = -8971 #codecExtensionNotFoundErr +codecDataVersErr = -8970 #codecDataVersErr +codecBadDataErr = -8969 #codecBadDataErr +codecWouldOffscreenErr = -8968 #codecWouldOffscreenErr +codecAbortErr = -8967 #codecAbortErr +codecSpoolErr = -8966 #codecSpoolErr +codecImageBufErr = -8965 #codecImageBufErr +codecScreenBufErr = -8964 #codecScreenBufErr +codecSizeErr = -8963 #codecSizeErr +codecUnimpErr = -8962 #codecUnimpErr +noCodecErr = -8961 #noCodecErr +codecErr = -8960 #codecErr +kIllegalClockValueErr = -8852 #kIllegalClockValueErr +kUTCOverflowErr = -8851 #kUTCOverflowErr +kUTCUnderflowErr = -8850 #kUTCUnderflowErr +kATSULastErr = -8809 #The last ATSUI error code. +kATSULineBreakInWord = -8808 #This is not an error code but is returned by ATSUBreakLine to +kATSUCoordinateOverflowErr = -8807 #Used to indicate the coordinates provided to an ATSUI routine caused +kATSUNoFontScalerAvailableErr = -8806 #Used when no font scaler is available for the font passed +kATSUNoFontCmapAvailableErr = -8805 #Used when no CMAP table can be accessed or synthesized for the +kATSULowLevelErr = -8804 #Used when an error was encountered within the low level ATS +kATSUQuickDrawTextErr = -8803 #Used when QuickDraw Text encounters an error rendering or measuring +kATSUNoStyleRunsAssignedErr = -8802 #Used when an attempt was made to measure, highlight or draw +kATSUNotSetErr = -8801 #Used when the client attempts to retrieve an attribute, +kATSUInvalidCacheErr = -8800 #Used when an attempt was made to read in style data +kATSUInvalidAttributeTagErr = -8799 #Used when an attempt was made to use a tag value that +kATSUInvalidAttributeSizeErr = -8798 #Used when an attempt was made to use an attribute with a +kATSUInvalidAttributeValueErr = -8797 #Used when an attempt was made to use an attribute with +kATSUInvalidFontErr = -8796 #Used when an attempt was made to use an invalid font ID. +kATSUNoCorrespondingFontErr = -8795 #This value is retrned by font ID conversion +kATSUFontsNotMatched = -8794 #This value is returned by ATSUMatchFontsToText() +kATSUFontsMatched = -8793 #This is not an error code but is returned by +kATSUInvalidTextRangeErr = -8792 #An attempt was made to extract information +kATSUInvalidStyleErr = -8791 #An attempt was made to use a ATSUStyle which +kATSUInvalidTextLayoutErr = -8790 #An attempt was made to use a ATSUTextLayout +kTECOutputBufferFullStatus = -8785 #output buffer has no room for conversion of next input text element (partial conversion) +kTECNeedFlushStatus = -8784 #kTECNeedFlushStatus +kTECUsedFallbacksStatus = -8783 #kTECUsedFallbacksStatus +kTECItemUnavailableErr = -8771 #item (e.g. name) not available for specified region (& encoding if relevant) +kTECGlobalsUnavailableErr = -8770 #globals have already been deallocated (premature TERM) +unicodeChecksumErr = -8769 #unicodeChecksumErr +unicodeNoTableErr = -8768 #unicodeNoTableErr +unicodeVariantErr = -8767 #unicodeVariantErr +unicodeFallbacksErr = -8766 #unicodeFallbacksErr +unicodePartConvertErr = -8765 #unicodePartConvertErr +unicodeBufErr = -8764 #unicodeBufErr +unicodeCharErr = -8763 #unicodeCharErr +unicodeElementErr = -8762 #unicodeElementErr +unicodeNotFoundErr = -8761 #unicodeNotFoundErr +unicodeTableFormatErr = -8760 #unicodeTableFormatErr +unicodeDirectionErr = -8759 #unicodeDirectionErr +unicodeContextualErr = -8758 #unicodeContextualErr +unicodeTextEncodingDataErr = -8757 #unicodeTextEncodingDataErr +kTECDirectionErr = -8756 #direction stack overflow, etc. +kTECIncompleteElementErr = -8755 #text element may be incomplete or is too long for internal buffers +kTECUnmappableElementErr = -8754 #kTECUnmappableElementErr +kTECPartialCharErr = -8753 #input buffer ends in the middle of a multibyte character, conversion stopped +kTECBadTextRunErr = -8752 #kTECBadTextRunErr +kTECArrayFullErr = -8751 #supplied name buffer or TextRun, TextEncoding, or UnicodeMapping array is too small +kTECBufferBelowMinimumSizeErr = -8750 #output buffer too small to allow processing of first input text element +kTECNoConversionPathErr = -8749 #kTECNoConversionPathErr +kTECCorruptConverterErr = -8748 #invalid converter object reference +kTECTableFormatErr = -8747 #kTECTableFormatErr +kTECTableChecksumErr = -8746 #kTECTableChecksumErr +kTECMissingTableErr = -8745 #kTECMissingTableErr +kTextUndefinedElementErr = -8740 #text conversion errors +kTextMalformedInputErr = -8739 #in DBCS, for example, high byte followed by invalid low byte +kTextUnsupportedEncodingErr = -8738 #specified encoding not supported for this operation +kRANotEnabled = -7139 #kRANotEnabled +kRACallBackFailed = -7138 #kRACallBackFailed +kRADuplicateIPAddr = -7137 #kRADuplicateIPAddr +kRANCPRejectedbyPeer = -7136 #kRANCPRejectedbyPeer +kRAExtAuthenticationFailed = -7135 #kRAExtAuthenticationFailed +kRAATalkInactive = -7134 #kRAATalkInactive +kRAPeerNotResponding = -7133 #kRAPeerNotResponding +kRAPPPPeerDisconnected = -7132 #kRAPPPPeerDisconnected +kRAPPPUserDisconnected = -7131 #kRAPPPUserDisconnected +kRAPPPNegotiationFailed = -7130 #kRAPPPNegotiationFailed +kRAPPPAuthenticationFailed = -7129 #kRAPPPAuthenticationFailed +kRAPPPProtocolRejected = -7128 #kRAPPPProtocolRejected +dcmBufferOverflowErr = -7127 #data is larger than buffer size +kRANotPrimaryInterface = -7126 #when IPCP is not primary TCP/IP intf. +kRATCPIPNotConfigured = -7125 #TCP/IP not configured, could be loaded +kRATCPIPInactive = -7124 #TCP/IP inactive, cannot be loaded +kRARemoteAccessNotReady = -7123 #kRARemoteAccessNotReady +kRAInitOpenTransportFailed = -7122 #kRAInitOpenTransportFailed +dcmProtectedErr = -7121 #need keyword to use dictionary +kRAUserPwdEntryRequired = -7120 #kRAUserPwdEntryRequired +kRAUserPwdChangeRequired = -7119 #kRAUserPwdChangeRequired +dcmBadFindMethodErr = -7118 #no such find method supported +kRAInvalidSerialProtocol = -7117 #kRAInvalidSerialProtocol +kRAInvalidPortState = -7116 #kRAInvalidPortState +dcmBadKeyErr = -7115 #bad key information +kRAPortBusy = -7114 #kRAPortBusy +kRAInstallationDamaged = -7113 #kRAInstallationDamaged +dcmBadFieldTypeErr = -7112 #no such field type supported +dcmBadFieldInfoErr = -7111 #incomplete information +dcmNecessaryFieldErr = -7110 #lack required/identify field +dcmDupRecordErr = -7109 #same record already exist +kRANotConnected = -7108 #kRANotConnected +dcmBlockFullErr = -7107 #dictionary block full +kRAMissingResources = -7106 #kRAMissingResources +dcmDictionaryBusyErr = -7105 #dictionary is busy +dcmDictionaryNotOpenErr = -7104 #dictionary not opened +dcmPermissionErr = -7103 #invalid permission +dcmBadDictionaryErr = -7102 #invalid dictionary +dcmNotDictionaryErr = -7101 #not dictionary +kRAInvalidParameter = -7100 #kRAInvalidParameter +laEngineNotFoundErr = -7000 #can't find the engine +laPropertyErr = -6999 #Error in properties +kUSBUnknownDeviceErr = -6998 #device ref not recognised +laPropertyIsReadOnlyErr = -6997 #the property is read only +laPropertyUnknownErr = -6996 #the property is unknown to this environment +laPropertyValueErr = -6995 #Invalid property value +laDictionaryTooManyErr = -6994 #too many dictionaries +laDictionaryUnknownErr = -6993 #can't use this dictionary with this environment +laDictionaryNotOpenedErr = -6992 #the dictionary is not opened +laTextOverFlowErr = -6991 #text is too long +laFailAnalysisErr = -6990 #analysis failed +laNoMoreMorphemeErr = -6989 #nothing to read +laInvalidPathErr = -6988 #path is not correct +kUSBNotHandled = -6987 #Notification was not handled (same as NotFound) +laEnvironmentNotFoundErr = -6986 #can't fint the specified environment +laEnvironmentBusyErr = -6985 #specified environment is used +laTooSmallBufferErr = -6984 #output buffer is too small to store any result +kUSBFlagsError = -6983 #Unused flags not zeroed +kUSBAbortedError = -6982 #Pipe aborted +kUSBNoBandwidthError = -6981 #Not enough bandwidth available +kUSBPipeIdleError = -6980 #Pipe is Idle, it will not accept transactions +kUSBPipeStalledError = -6979 #Pipe has stalled, error needs to be cleared +kUSBUnknownInterfaceErr = -6978 #Interface ref not recognised +kUSBDeviceBusy = -6977 #Device is already being configured +kUSBDevicePowerProblem = -6976 #Device has a power problem +kUSBInvalidBuffer = -6975 #bad buffer, usually nil +kUSBDeviceSuspended = -6974 #Device is suspended +kUSBDeviceNotSuspended = -6973 #device is not suspended for resume +kUSBDeviceDisconnected = -6972 #Disconnected during suspend or reset +kUSBTimedOut = -6971 #Transaction timed out. +kUSBQueueAborted = -6970 #Pipe zero stall cleared. +kUSBPortDisabled = -6969 #The port you are attached to is disabled, use USBDeviceReset. +kUSBBadDispatchTable = -6950 #Improper driver dispatch table +kUSBUnknownNotification = -6949 #Notification type not defined +kUSBQueueFull = -6948 #Internal queue maxxed +kUSBLinkErr = -6916 #kUSBLinkErr +kUSBCRCErr = -6915 #Pipe stall, bad CRC +kUSBBitstufErr = -6914 #Pipe stall, bitstuffing +kUSBDataToggleErr = -6913 #Pipe stall, Bad data toggle +kUSBEndpointStallErr = -6912 #Device didn't understand +kUSBNotRespondingErr = -6911 #Pipe stall, No device, device hung +kUSBPIDCheckErr = -6910 #Pipe stall, PID CRC error +kUSBWrongPIDErr = -6909 #Pipe stall, Bad or wrong PID +kUSBOverRunErr = -6908 #Packet too large or more data than buffer +kUSBUnderRunErr = -6907 #Less data than buffer +kUSBRes1Err = -6906 #kUSBRes1Err +kUSBRes2Err = -6905 #kUSBRes2Err +kUSBBufOvrRunErr = -6904 #Host hardware failure on data in, PCI busy? +kUSBBufUnderRunErr = -6903 #Host hardware failure on data out, PCI busy? +kUSBNotSent1Err = -6902 #Transaction not sent +kUSBNotSent2Err = -6901 #Transaction not sent +kDMFoundErr = -6232 #Did not proceed because we found an item +kDMMainDisplayCannotMoveErr = -6231 #Trying to move main display (or a display mirrored to it) +kDMDisplayAlreadyInstalledErr = -6230 #Attempt to add an already installed display. +kDMDisplayNotFoundErr = -6229 #Could not find item (will someday remove). +kDMDriverNotDisplayMgrAwareErr = -6228 #Video Driver does not support display manager. +kDMSWNotInitializedErr = -6227 #Required software not initialized (eg windowmanager or display mgr). +kSysSWTooOld = -6226 #Missing critical pieces of System Software. +kDMMirroringNotOn = -6225 #Returned by all calls that need mirroring to be on to do their thing. +kDMCantBlock = -6224 #Mirroring is already on, canÕt Block now (call DMUnMirror() first). +kDMMirroringBlocked = -6223 #DMBlockMirroring() has been called. +kDMWrongNumberOfDisplays = -6222 #Can only handle 2 displays for now. +kDMMirroringOnAlready = -6221 #Returned by all calls that need mirroring to be off to do their thing. +kDMGenErr = -6220 #Unexpected Error +kQTSSUnknownErr = -6150 #kQTSSUnknownErr +collectionVersionErr = -5753 #collectionVersionErr +collectionIndexRangeErr = -5752 #collectionIndexRangeErr +collectionItemNotFoundErr = -5751 #collectionItemNotFoundErr +collectionItemLockedErr = -5750 #collectionItemLockedErr +kNavMissingKindStringErr = -5699 #kNavMissingKindStringErr +kNavInvalidCustomControlMessageErr = -5698 #kNavInvalidCustomControlMessageErr +kNavCustomControlMessageFailedErr = -5697 #kNavCustomControlMessageFailedErr +kNavInvalidSystemConfigErr = -5696 #kNavInvalidSystemConfigErr +kNavWrongDialogClassErr = -5695 #kNavWrongDialogClassErr +kNavWrongDialogStateErr = -5694 #kNavWrongDialogStateErr +dialogNoTimeoutErr = -5640 #dialogNoTimeoutErr +menuInvalidErr = -5623 #menu is invalid +menuItemNotFoundErr = -5622 #specified menu item wasn't found +menuUsesSystemDefErr = -5621 #GetMenuDefinition failed because the menu uses the system MDEF +menuNotFoundErr = -5620 #specified menu or menu ID wasn't found +windowWrongStateErr = -5615 #window is not in a state that is valid for the current action +windowManagerInternalErr = -5614 #something really weird happened inside the window manager +windowAttributesConflictErr = -5613 #passed some attributes that are mutually exclusive +windowAttributeImmutableErr = -5612 #tried to change attributes which can't be changed +errWindowDoesNotFitOnscreen = -5611 #ConstrainWindowToScreen could not make the window fit onscreen +errWindowNotFound = -5610 #returned from FindWindowOfClass +errFloatingWindowsNotInitialized = -5609 #called HideFloatingWindows or ShowFloatingWindows without calling InitFloatingWindows +errWindowsAlreadyInitialized = -5608 #tried to call InitFloatingWindows twice, or called InitWindows and then floating windows +errUserWantsToDragWindow = -5607 #if returned from TrackWindowProxyDrag, you should call DragWindow on the window +errCorruptWindowDescription = -5606 #tried to load a corrupt window description (size or version fields incorrect) +errUnrecognizedWindowClass = -5605 #tried to create a window with a bad WindowClass +errWindowPropertyNotFound = -5604 #tried to get a nonexistent property +errInvalidWindowProperty = -5603 #tried to access a property tag with private creator +errWindowDoesNotHaveProxy = -5602 #tried to do something requiring a proxy to a window which doesnÕt have a proxy +errUnsupportedWindowAttributesForClass = -5601 #tried to create a window with WindowAttributes not supported by the WindowClass +errInvalidWindowPtr = -5600 #tried to pass a bad WindowRef argument +gestaltLocationErr = -5553 #gestalt function ptr wasn't in sysheap +gestaltDupSelectorErr = -5552 #tried to add an entry that already existed +gestaltUndefSelectorErr = -5551 #undefined selector was passed to Gestalt +gestaltUnknownErr = -5550 #value returned if Gestalt doesn't know the answer +envVersTooBig = -5502 #Version bigger than call can handle +envBadVers = -5501 #Version non-positive +envNotPresent = -5500 #returned by glue. +qtsAddressBusyErr = -5421 #qtsAddressBusyErr +qtsConnectionFailedErr = -5420 #qtsConnectionFailedErr +qtsTimeoutErr = -5408 #qtsTimeoutErr +qtsUnknownValueErr = -5407 #qtsUnknownValueErr +qtsTooMuchDataErr = -5406 #qtsTooMuchDataErr +qtsUnsupportedFeatureErr = -5405 #qtsUnsupportedFeatureErr +qtsUnsupportedRateErr = -5404 #qtsUnsupportedRateErr +qtsUnsupportedDataTypeErr = -5403 #qtsUnsupportedDataTypeErr +qtsBadDataErr = -5402 #something is wrong with the data +qtsBadStateErr = -5401 #qtsBadStateErr +qtsBadSelectorErr = -5400 #qtsBadSelectorErr +errIAEndOfTextRun = -5388 #errIAEndOfTextRun +errIATextExtractionErr = -5387 #errIATextExtractionErr +errIAInvalidDocument = -5386 #errIAInvalidDocument +errIACanceled = -5385 #errIACanceled +errIABufferTooSmall = -5384 #errIABufferTooSmall +errIANoMoreItems = -5383 #errIANoMoreItems +errIAParamErr = -5382 #errIAParamErr +errIAAllocationErr = -5381 #errIAAllocationErr +errIAUnknownErr = -5380 #errIAUnknownErr +hrURLNotHandledErr = -5363 #hrURLNotHandledErr +hrUnableToResizeHandleErr = -5362 #hrUnableToResizeHandleErr +hrMiscellaneousExceptionErr = -5361 #hrMiscellaneousExceptionErr +hrHTMLRenderingLibNotInstalledErr = -5360 #hrHTMLRenderingLibNotInstalledErr +errCannotUndo = -5253 #errCannotUndo +errNonContiuousAttribute = -5252 #errNonContiuousAttribute +errUnknownElement = -5251 #errUnknownElement +errReadOnlyText = -5250 #errReadOnlyText +errEmptyScrap = -5249 #errEmptyScrap +errNoHiliteText = -5248 #errNoHiliteText +errOffsetNotOnElementBounday = -5247 #errOffsetNotOnElementBounday +errInvalidRange = -5246 #errInvalidRange +errIteratorReachedEnd = -5245 #errIteratorReachedEnd +errEngineNotFound = -5244 #errEngineNotFound +errAlreadyInImagingMode = -5243 #errAlreadyInImagingMode +errNotInImagingMode = -5242 #errNotInImagingMode +errMarginWilllNotFit = -5241 #errMarginWilllNotFit +errUnknownAttributeTag = -5240 #errUnknownAttributeTag +afpSameNodeErr = -5063 #An Attempt was made to connect to a file server running on the same machine +afpAlreadyMounted = -5062 #The volume is already mounted +afpCantMountMoreSrvre = -5061 #The Maximum number of server connections has been reached +afpBadDirIDType = -5060 #afpBadDirIDType +afpCallNotAllowed = -5048 #The server knows what you wanted to do, but won't let you do it just now +afpAlreadyLoggedInErr = -5047 #User has been authenticated but is already logged in from another machine (and that's not allowed on this server) +afpPwdPolicyErr = -5046 #Password does not conform to servers password policy +afpPwdNeedsChangeErr = -5045 #The password needs to be changed +afpInsideTrashErr = -5044 #The folder being shared is inside the trash folder OR the shared folder is being moved into the trash folder +afpInsideSharedErr = -5043 #The folder being shared is inside a shared folder OR the folder contains a shared folder and is being moved into a shared folder +afpPwdExpiredErr = -5042 #The password being used is too old: this requires the user to change the password before log-in can continue +afpPwdTooShortErr = -5041 #The password being set is too short: there is a minimum length that must be met or exceeded +afpPwdSameErr = -5040 #Someone tried to change their password to the same password on a mantadory password change +afpBadIDErr = -5039 #afpBadIDErr +afpSameObjectErr = -5038 #afpSameObjectErr +afpCatalogChanged = -5037 #afpCatalogChanged +afpDiffVolErr = -5036 #afpDiffVolErr +afpIDExists = -5035 #afpIDExists +afpIDNotFound = -5034 #afpIDNotFound +afpContainsSharedErr = -5033 #the folder being shared contains a shared folder +afpObjectLocked = -5032 #Object is M/R/D/W inhibited +afpVolLocked = -5031 #Volume is Read-Only +afpIconTypeError = -5030 #Icon size specified different from existing icon size +afpDirNotFound = -5029 #Unknown directory specified +afpCantRename = -5028 #AFPRename cannot rename volume +afpServerGoingDown = -5027 #Server is shutting down +afpTooManyFilesOpen = -5026 #Maximum open file count reached +afpObjectTypeErr = -5025 #File/Directory specified where Directory/File expected +afpCallNotSupported = -5024 #Unsupported AFP call was made +afpUserNotAuth = -5023 #No AFPLogin call has successfully been made for this session +afpSessClosed = -5022 #Session closed +afpRangeOverlap = -5021 #Some or all of range already locked by same user +afpRangeNotLocked = -5020 #Tried to unlock range that was not locked by user +afpParmErr = -5019 #A specified parameter was out of allowable range +afpObjectNotFound = -5018 #Specified file or directory does not exist +afpObjectExists = -5017 #Specified destination file or directory already exists +afpNoServer = -5016 #Server not responding +afpNoMoreLocks = -5015 #Maximum lock limit reached +afpMiscErr = -5014 #Unexpected error encountered during execution +afpLockErr = -5013 #Some or all of requested range is locked by another user +afpItemNotFound = -5012 #Unknown UserName/UserID or missing comment/APPL entry +afpFlatVol = -5011 #Cannot create directory on specified volume +afpFileBusy = -5010 #Cannot delete an open file +afpEofError = -5009 #Read beyond logical end-of-file +afpDiskFull = -5008 #Insufficient free space on volume for operation +afpDirNotEmpty = -5007 #Cannot delete non-empty directory +afpDenyConflict = -5006 #Specified open/deny modes conflict with current open modes +afpCantMove = -5005 #Move destination is offspring of source, or root was specified +afpBitmapErr = -5004 #Bitmap contained bits undefined for call +afpBadVersNum = -5003 #Unknown AFP protocol version number specified +afpBadUAM = -5002 #Unknown user authentication method specified +afpAuthContinue = -5001 #Further information required to complete AFPLogin call +afpAccessDenied = -5000 #Insufficient access privileges for operation +illegalScrapFlavorSizeErr = -4999 #illegalScrapFlavorSizeErr +illegalScrapFlavorTypeErr = -4998 #illegalScrapFlavorTypeErr +illegalScrapFlavorFlagsErr = -4997 #illegalScrapFlavorFlagsErr +scrapFlavorSizeMismatchErr = -4996 #scrapFlavorSizeMismatchErr +scrapFlavorFlagsMismatchErr = -4995 #scrapFlavorFlagsMismatchErr +nilScrapFlavorDataErr = -4994 #nilScrapFlavorDataErr +noScrapPromiseKeeperErr = -4993 #noScrapPromiseKeeperErr +scrapPromiseNotKeptErr = -4992 #scrapPromiseNotKeptErr +processStateIncorrectErr = -4991 #processStateIncorrectErr +badScrapRefErr = -4990 #badScrapRefErr +duplicateScrapFlavorErr = -4989 #duplicateScrapFlavorErr +internalScrapErr = -4988 #internalScrapErr +coreFoundationUnknownErr = -4960 #coreFoundationUnknownErr +badRoutingSizeErr = -4276 #badRoutingSizeErr +routingNotFoundErr = -4275 #routingNotFoundErr +duplicateRoutingErr = -4274 #duplicateRoutingErr +invalidFolderTypeErr = -4273 #invalidFolderTypeErr +noMoreFolderDescErr = -4272 #noMoreFolderDescErr +duplicateFolderDescErr = -4271 #duplicateFolderDescErr +badFolderDescErr = -4270 #badFolderDescErr +cmCantGamutCheckError = -4217 #Gammut checking not supported by this ColorWorld +cmNamedColorNotFound = -4216 #NamedColor not found +cmCantCopyModifiedV1Profile = -4215 #Illegal to copy version 1 profiles that have been modified +cmRangeOverFlow = -4214 #Color conversion warning that some output color values over/underflowed and were clipped +cmInvalidProfileComment = -4213 #Bad Profile comment during drawpicture +cmNoGDevicesError = -4212 #Begin/End Matching -- no gdevices available +cmInvalidDstMap = -4211 #Destination pix/bit map was invalid +cmInvalidSrcMap = -4210 #Source pix/bit map was invalid +cmInvalidColorSpace = -4209 #Profile colorspace does not match bitmap type +cmErrIncompatibleProfile = -4208 #Other ColorSync Errors +cmSearchError = -4207 #cmSearchError +cmInvalidSearch = -4206 #Bad Search Handle +cmInvalidProfileLocation = -4205 #Operation not supported for this profile location +cmInvalidProfile = -4204 #A Profile must contain a 'cs1 ' tag to be valid +cmFatalProfileErr = -4203 #cmFatalProfileErr +cmCantDeleteElement = -4202 #cmCantDeleteElement +cmIndexRangeErr = -4201 #Tag index out of range +kNSLInitializationFailed = -4200 #UNABLE TO INITIALIZE THE MANAGER!!!!! DO NOT CONTINUE!!!! +kNSLNotInitialized = -4199 #kNSLNotInitialized +kNSLInsufficientSysVer = -4198 #kNSLInsufficientSysVer +kNSLInsufficientOTVer = -4197 #kNSLInsufficientOTVer +kNSLNoElementsInList = -4196 #kNSLNoElementsInList +kNSLBadReferenceErr = -4195 #kNSLBadReferenceErr +kNSLBadServiceTypeErr = -4194 #kNSLBadServiceTypeErr +kNSLBadDataTypeErr = -4193 #kNSLBadDataTypeErr +kNSLBadNetConnection = -4192 #kNSLBadNetConnection +kNSLNoSupportForService = -4191 #kNSLNoSupportForService +kNSLInvalidPluginSpec = -4190 #kNSLInvalidPluginSpec +kNSLRequestBufferAlreadyInList = -4189 #kNSLRequestBufferAlreadyInList +kNSLNoContextAvailable = -4188 #(ContinueLookup function ptr invalid) +kNSLBufferTooSmallForData = -4187 #(Client buffer too small for data from plugin) +kNSLCannotContinueLookup = -4186 #(Can't continue lookup; error or bad state) +kNSLBadClientInfoPtr = -4185 #(nil ClientAsyncInfoPtr; no reference available) +kNSLNullListPtr = -4184 #(client is trying to add items to a nil list) +kNSLBadProtocolTypeErr = -4183 #(client is trying to add a null protocol type) +kNSLPluginLoadFailed = -4182 #(manager unable to load one of the plugins) +kNSLNoPluginsFound = -4181 #(manager didn't find any valid plugins to load) +kNSLSearchAlreadyInProgress = -4180 #(you can only have one ongoing search per clientRef) +kNSLNoPluginsForSearch = -4179 #(no plugins will respond to search request; bad protocol(s)?) +kNSLNullNeighborhoodPtr = -4178 #(client passed a null neighborhood ptr) +kNSLSomePluginsFailedToLoad = -4177 #(one or more plugins failed to load, but at least one did load; this error isn't fatal) +kNSLErrNullPtrError = -4176 #kNSLErrNullPtrError +kNSLNotImplementedYet = -4175 #kNSLNotImplementedYet +kNSLUILibraryNotAvailable = -4174 #The NSL UI Library needs to be in the Extensions Folder +kNSLNoCarbonLib = -4173 #kNSLNoCarbonLib +kNSLBadURLSyntax = -4172 #URL contains illegal characters +kNSLSchedulerError = -4171 #A custom thread routine encountered an error +kNSL68kContextNotSupported = -4170 #no 68k allowed +noHelpForItem = -4009 #noHelpForItem +badProfileError = -4008 #badProfileError +colorSyncNotInstalled = -4007 #colorSyncNotInstalled +pickerCantLive = -4006 #pickerCantLive +cantLoadPackage = -4005 #cantLoadPackage +cantCreatePickerWindow = -4004 #cantCreatePickerWindow +cantLoadPicker = -4003 #cantLoadPicker +pickerResourceError = -4002 #pickerResourceError +requiredFlagsDontMatch = -4001 #requiredFlagsDontMatch +firstPickerError = -4000 #firstPickerError +kOTPortLostConnection = -3285 # +kOTUserRequestedErr = -3284 # +kOTConfigurationChangedErr = -3283 # +kOTBadConfigurationErr = -3282 # +kOTPortWasEjectedErr = -3281 # +kOTPortHasDiedErr = -3280 # +kOTClientNotInittedErr = -3279 # +kENOMSGErr = -3278 # +kESRCHErr = -3277 # +kEINPROGRESSErr = -3276 # +kENODATAErr = -3275 # +kENOSTRErr = -3274 # +kECANCELErr = -3273 # +kEBADMSGErr = -3272 # +kENOSRErr = -3271 # +kETIMEErr = -3270 # +kEPROTOErr = -3269 #‚‚‚ fill out missing codes ‚‚‚ +kEHOSTUNREACHErr = -3264 #No route to host +kEHOSTDOWNErr = -3263 #Host is down +kECONNREFUSEDErr = -3260 #Connection refused +kETIMEDOUTErr = -3259 #Connection timed out +kETOOMANYREFSErr = -3258 #Too many references: can't splice +kESHUTDOWNErr = -3257 #Can't send after socket shutdown +kENOTCONNErr = -3256 #Socket is not connected +kEISCONNErr = -3255 #Socket is already connected +kENOBUFSErr = -3254 #No buffer space available +kECONNRESETErr = -3253 #Connection reset by peer +kECONNABORTEDErr = -3252 #Software caused connection abort +kENETRESETErr = -3251 #Network dropped connection on reset +kENETUNREACHErr = -3250 #Network is unreachable +kENETDOWNErr = -3249 #Network is down +kEADDRNOTAVAILErr = -3248 #Can't assign requested address +kEADDRINUSEErr = -3247 #Address already in use +kEOPNOTSUPPErr = -3244 #Operation not supported on socket +kESOCKTNOSUPPORTErr = -3243 #Socket type not supported +kEPROTONOSUPPORTErr = -3242 #Protocol not supported +kENOPROTOOPTErr = -3241 #Protocol not available +kEPROTOTYPEErr = -3240 #Protocol wrong type for socket +kEMSGSIZEErr = -3239 #Message too long +kEDESTADDRREQErr = -3238 #Destination address required +kENOTSOCKErr = -3237 #Socket operation on non-socket +kEALREADYErr = -3236 # +kEWOULDBLOCKErr = -3234 #Call would block, so was aborted +kERANGEErr = -3233 #Message size too large for STREAM +kEPIPEErr = -3231 #Broken pipe +kENOTTYErr = -3224 #Not a character device +kEINVALErr = -3221 #Invalid argument +kENODEVErr = -3218 #No such device +kOTDuplicateFoundErr = -3216 #OT generic duplicate found error +kEBUSYErr = -3215 #Device or resource busy +kEFAULTErr = -3213 #Bad address +kEACCESErr = -3212 #Permission denied +kOTOutOfMemoryErr = -3211 #OT ran out of memory, may be a temporary +kEAGAINErr = -3210 #Try operation again later +kEBADFErr = -3208 #Bad file number +kENXIOErr = -3205 #No such device or address +kEIOErr = -3204 #I/O error +kEINTRErr = -3203 #Interrupted system service +kENORSRCErr = -3202 #No such resource +kOTNotFoundErr = -3201 #OT generic not found error +kEPERMErr = -3200 #Permission denied +kOTCanceledErr = -3180 #XTI2OSStatus(TCANCELED) The command was cancelled +kOTBadSyncErr = -3179 #XTI2OSStatus(TBADSYNC) A synchronous call at interrupt time +kOTProtocolErr = -3178 #XTI2OSStatus(TPROTO) An unspecified provider error occurred +kOTQFullErr = -3177 #XTI2OSStatus(TQFULL) +kOTResAddressErr = -3176 #XTI2OSStatus(TRESADDR) +kOTResQLenErr = -3175 #XTI2OSStatus(TRESQLEN) +kOTProviderMismatchErr = -3174 #XTI2OSStatus(TPROVMISMATCH) Tried to accept on incompatible endpoint +kOTIndOutErr = -3173 #XTI2OSStatus(TINDOUT) Accept failed because of pending listen +kOTAddressBusyErr = -3172 #XTI2OSStatus(TADDRBUSY) Address requested is already in use +kOTBadQLenErr = -3171 #XTI2OSStatus(TBADQLEN) A Bind to an in-use addr with qlen > 0 +kOTBadNameErr = -3170 #XTI2OSStatus(TBADNAME) A bad endpoint name was supplied +kOTNoStructureTypeErr = -3169 #XTI2OSStatus(TNOSTRUCTYPE) Bad structure type requested for OTAlloc +kOTStateChangeErr = -3168 #XTI2OSStatus(TSTATECHNG) State is changing - try again later +kOTNotSupportedErr = -3167 #XTI2OSStatus(TNOTSUPPORT) Command is not supported +kOTNoReleaseErr = -3166 #XTI2OSStatus(TNOREL) No orderly release indication available +kOTBadFlagErr = -3165 #XTI2OSStatus(TBADFLAG) A Bad flag value was supplied +kOTNoUDErrErr = -3164 #XTI2OSStatus(TNOUDERR) No Unit Data Error indication available +kOTNoDisconnectErr = -3163 #XTI2OSStatus(TNODIS) No disconnect indication available +kOTNoDataErr = -3162 #XTI2OSStatus(TNODATA) No data available for reading +kOTFlowErr = -3161 #XTI2OSStatus(TFLOW) Provider is flow-controlled +kOTBufferOverflowErr = -3160 #XTI2OSStatus(TBUFOVFLW) Passed buffer not big enough +kOTBadDataErr = -3159 #XTI2OSStatus(TBADDATA) An illegal amount of data was specified +kOTLookErr = -3158 #XTI2OSStatus(TLOOK) An event occurred - call Look() +kOTSysErrorErr = -3157 #XTI2OSStatus(TSYSERR) A system error occurred +kOTBadSequenceErr = -3156 #XTI2OSStatus(TBADSEQ) Sequence specified does not exist +kOTOutStateErr = -3155 #XTI2OSStatus(TOUTSTATE) Call issued in wrong state +kOTNoAddressErr = -3154 #XTI2OSStatus(TNOADDR) No address was specified +kOTBadReferenceErr = -3153 #XTI2OSStatus(TBADF) Bad provider reference +kOTAccessErr = -3152 #XTI2OSStatus(TACCES) Missing access permission +kOTBadOptionErr = -3151 #XTI2OSStatus(TBADOPT) A Bad option was specified +kOTBadAddressErr = -3150 #XTI2OSStatus(TBADADDR) A Bad address was specified +sktClosedErr = -3109 #sktClosedErr +recNotFnd = -3108 #recNotFnd +atpBadRsp = -3107 #atpBadRsp +atpLenErr = -3106 #atpLenErr +readQErr = -3105 #readQErr +extractErr = -3104 #extractErr +ckSumErr = -3103 #ckSumErr +noMPPErr = -3102 #noMPPErr +buf2SmallErr = -3101 #buf2SmallErr +noPrefAppErr = -3032 #noPrefAppErr +badTranslationSpecErr = -3031 #badTranslationSpecErr +noTranslationPathErr = -3030 #noTranslationPathErr +couldNotParseSourceFileErr = -3026 #Source document does not contain source type +invalidTranslationPathErr = -3025 #Source type to destination type not a valid path +retryComponentRegistrationErr = -3005 #retryComponentRegistrationErr +unresolvedComponentDLLErr = -3004 #unresolvedComponentDLLErr +componentDontRegister = -3003 #componentDontRegister +componentNotCaptured = -3002 #componentNotCaptured +validInstancesExist = -3001 #validInstancesExist +invalidComponentID = -3000 #invalidComponentID +cfragLastErrCode = -2899 #The last value in the range of CFM errors. +cfragOutputLengthErr = -2831 #An output parameter is too small to hold the value. +cfragAbortClosureErr = -2830 #Used by notification handlers to abort a closure. +cfragClosureIDErr = -2829 #The closure ID was not valid. +cfragContainerIDErr = -2828 #The fragment container ID was not valid. +cfragNoRegistrationErr = -2827 #The registration name was not found. +cfragNotClosureErr = -2826 #The closure ID was actually a connection ID. +cfragFileSizeErr = -2825 #A file was too large to be mapped. +cfragFragmentUsageErr = -2824 #A semantic error in usage of the fragment. +cfragArchitectureErr = -2823 #A fragment has an unacceptable architecture. +cfragNoApplicationErr = -2822 #No application member found in the cfrg resource. +cfragInitFunctionErr = -2821 #A fragment's initialization routine returned an error. +cfragFragmentCorruptErr = -2820 #A fragment's container was corrupt (known format). +cfragCFMInternalErr = -2819 #An internal inconstistancy has been detected. +cfragCFMStartupErr = -2818 #Internal error during CFM initialization. +cfragLibConnErr = -2817 # +cfragInitAtBootErr = -2816 #A boot library has an initialization function. (System 7 only) +cfragInitLoopErr = -2815 #Circularity in required initialization order. +cfragImportTooNewErr = -2814 #An import library was too new for a client. +cfragImportTooOldErr = -2813 #An import library was too old for a client. +cfragInitOrderErr = -2812 # +cfragNoIDsErr = -2811 #No more CFM IDs for contexts, connections, etc. +cfragNoClientMemErr = -2810 #Out of memory for fragment mapping or section instances. +cfragNoPrivateMemErr = -2809 #Out of memory for internal bookkeeping. +cfragNoPositionErr = -2808 #The registration insertion point was not found. +cfragUnresolvedErr = -2807 #A fragment had "hard" unresolved imports. +cfragFragmentFormatErr = -2806 #A fragment's container format is unknown. +cfragDupRegistrationErr = -2805 #The registration name was already in use. +cfragNoLibraryErr = -2804 #The named library was not found. +cfragNoSectionErr = -2803 #The specified section was not found. +cfragNoSymbolErr = -2802 #The specified symbol was not found. +cfragConnectionIDErr = -2801 #The connection ID was not valid. +cfragFirstErrCode = -2800 #The first value in the range of CFM errors. +errASInconsistentNames = -2780 #English errors: +errASNoResultReturned = -2763 #The range -2780 thru -2799 is reserved for dialect specific error codes. (Error codes from different dialects may overlap.) +errASParameterNotForEvent = -2762 #errASParameterNotForEvent +errASIllegalFormalParameter = -2761 #errASIllegalFormalParameter +errASTerminologyNestingTooDeep = -2760 #errASTerminologyNestingTooDeep +OSAControlFlowError = -2755 #Signaled when illegal control flow occurs in an application (no catcher for throw, non-lexical loop exit, etc.) +OSAInconsistentDeclarations = -2754 #Signaled when a variable is declared inconsistently in the same scope, such as both local and global +OSAUndefinedVariable = -2753 #Signaled when a variable is accessed that has no value +OSADuplicateHandler = -2752 #Signaled when more than one handler is defined with the same name in a scope where the language doesn't allow it +OSADuplicateProperty = -2751 #Signaled when a formal parameter, local variable, or instance variable is specified more than once. +OSADuplicateParameter = -2750 #Signaled when a formal parameter, local variable, or instance variable is specified more than once +OSATokenTooLong = -2742 #Signaled when a name or number is too long to be parsed +OSASyntaxTypeError = -2741 #Signaled when another form of syntax was expected. (e.g. "expected a but found ") +OSASyntaxError = -2740 #Signaled when a syntax error occurs. (e.g. "Syntax error" or " can't go after ") +errASCantCompareMoreThan32k = -2721 #Parser/Compiler errors: +errASCantConsiderAndIgnore = -2720 #errASCantConsiderAndIgnore +errOSACantCreate = -2710 #errOSACantCreate +errOSACantGetTerminology = -2709 #errOSACantGetTerminology +errOSADataBlockTooLarge = -2708 #Signaled when an intrinsic limitation is exceeded for the size of a value or data structure. +errOSAInternalTableOverflow = -2707 #Signaled when a runtime internal data structure overflows +errOSAStackOverflow = -2706 #Signaled when the runtime stack overflows +errOSACorruptTerminology = -2705 #Signaled when an application's terminology resource is not readable +errOSAAppNotHighLevelEventAware = -2704 #Signaled when an application can't respond to AppleEvents +errOSACantLaunch = -2703 #Signaled when application can't be launched or when it is remote and program linking is not enabled +errOSANumericOverflow = -2702 #Signaled when integer or real value is too large to be represented +errOSADivideByZero = -2701 #Signaled when there is an attempt to divide by zero +errOSAGeneralError = -2700 #Signaled by user scripts or applications when no actual error code is to be returned. +noIconDataAvailableErr = -2582 #The necessary icon data is not available +noSuchIconErr = -2581 #The requested icon could not be found +invalidIconRefErr = -2580 #The icon ref is not valid +nrCallNotSupported = -2557 #This call is not available or supported on this machine +nrTransactionAborted = -2556 #transaction was aborted +nrExitedIteratorScope = -2555 #outer scope of iterator was exited +nrIterationDone = -2554 #iteration operation is done +nrPropertyAlreadyExists = -2553 #property already exists +nrInvalidEntryIterationOp = -2552 #invalid entry iteration operation +nrPathBufferTooSmall = -2551 #buffer for path is too small +nrPathNotFound = -2550 #a path component lookup failed +nrResultCodeBase = -2549 #nrResultCodeBase +nrOverrunErr = -2548 #nrOverrunErr +nrNotModifiedErr = -2547 #nrNotModifiedErr +nrTypeMismatchErr = -2546 #nrTypeMismatchErr +nrPowerSwitchAbortErr = -2545 #nrPowerSwitchAbortErr +nrPowerErr = -2544 #nrPowerErr +nrDataTruncatedErr = -2543 #nrDataTruncatedErr +nrNotSlotDeviceErr = -2542 #nrNotSlotDeviceErr +nrNameErr = -2541 #nrNameErr +nrNotCreatedErr = -2540 #nrNotCreatedErr +nrNotFoundErr = -2539 #nrNotFoundErr +nrInvalidNodeErr = -2538 #nrInvalidNodeErr +nrNotEnoughMemoryErr = -2537 #nrNotEnoughMemoryErr +nrLockedErr = -2536 #nrLockedErr +mmInternalError = -2526 #mmInternalError +tsmDefaultIsNotInputMethodErr = -2524 #Current Input source is KCHR or uchr, not Input Method (GetDefaultInputMethod) +tsmNoStem = -2523 #No stem exists for the token +tsmNoMoreTokens = -2522 #No more tokens are available for the source text +tsmNoHandler = -2521 #No Callback Handler exists for callback +tsmInvalidContext = -2520 #Invalid TSMContext specified in call +tsmUnknownErr = -2519 #any other errors +tsmUnsupportedTypeErr = -2518 #unSupported interface type error +tsmScriptHasNoIMErr = -2517 #script has no imput method or is using old IM +tsmInputMethodIsOldErr = -2516 #returned by GetDefaultInputMethod +tsmComponentAlreadyOpenErr = -2515 #text service already opened for the document +tsmTSNotOpenErr = -2514 #text service is not open +tsmTSHasNoMenuErr = -2513 #the text service has no menu +tsmUseInputWindowErr = -2512 #not TSM aware because we are using input window +tsmDocumentOpenErr = -2511 #there are open documents +tsmTextServiceNotFoundErr = -2510 #no text service found +tsmCantOpenComponentErr = -2509 #canÕt open the component +tsmNoOpenTSErr = -2508 #no open text service +tsmDocNotActiveErr = -2507 #document is NOT active +tsmTSMDocBusyErr = -2506 #document is still active +tsmInvalidDocIDErr = -2505 #invalid TSM documentation id +tsmNeverRegisteredErr = -2504 #app never registered error (not TSM aware) +tsmAlreadyRegisteredErr = -2503 #want to register again error +tsmNotAnAppErr = -2502 #not an application error +tsmInputMethodNotFoundErr = -2501 #tsmInputMethodNotFoundErr +tsmUnsupScriptLanguageErr = -2500 #tsmUnsupScriptLanguageErr +kernelUnrecoverableErr = -2499 #kernelUnrecoverableErr +kernelReturnValueErr = -2422 #kernelReturnValueErr +kernelAlreadyFreeErr = -2421 #kernelAlreadyFreeErr +kernelIDErr = -2419 #kernelIDErr +kernelExceptionErr = -2418 #kernelExceptionErr +kernelTerminatedErr = -2417 #kernelTerminatedErr +kernelInUseErr = -2416 #kernelInUseErr +kernelTimeoutErr = -2415 #kernelTimeoutErr +kernelAsyncReceiveLimitErr = -2414 #kernelAsyncReceiveLimitErr +kernelAsyncSendLimitErr = -2413 #kernelAsyncSendLimitErr +kernelAttributeErr = -2412 #kernelAttributeErr +kernelExecutionLevelErr = -2411 #kernelExecutionLevelErr +kernelDeletePermissionErr = -2410 #kernelDeletePermissionErr +kernelExecutePermissionErr = -2409 #kernelExecutePermissionErr +kernelReadPermissionErr = -2408 #kernelReadPermissionErr +kernelWritePermissionErr = -2407 #kernelWritePermissionErr +kernelObjectExistsErr = -2406 #kernelObjectExistsErr +kernelUnsupportedErr = -2405 #kernelUnsupportedErr +kernelPrivilegeErr = -2404 #kernelPrivilegeErr +kernelOptionsErr = -2403 #kernelOptionsErr +kernelCanceledErr = -2402 #kernelCanceledErr +kernelIncompleteErr = -2401 #kernelIncompleteErr +badCallOrderErr = -2209 #Usually due to a status call being called prior to being setup first +noDMAErr = -2208 #CanÕt do DMA digitizing (i.e. can't go to requested dest +badDepthErr = -2207 #CanÕt digitize into this depth +notExactSizeErr = -2206 #CanÕt do exact size requested +noMoreKeyColorsErr = -2205 #all key indexes in use +notExactMatrixErr = -2204 #warning of bad matrix, digitizer did its best +matrixErr = -2203 #bad matrix, digitizer did nothing +qtParamErr = -2202 #bad input parameter (out of range, etc) +digiUnimpErr = -2201 #feature unimplemented +qtXMLApplicationErr = -2159 #qtXMLApplicationErr +qtXMLParseErr = -2158 #qtXMLParseErr +qtActionNotHandledErr = -2157 #qtActionNotHandledErr +notEnoughDataErr = -2149 #notEnoughDataErr +urlDataHFTPURLErr = -2148 #urlDataHFTPURLErr +urlDataHFTPServerDisconnectedErr = -2147 #urlDataHFTPServerDisconnectedErr +urlDataHFTPNoPasswordErr = -2146 #urlDataHFTPNoPasswordErr +urlDataHFTPNeedPasswordErr = -2145 #urlDataHFTPNeedPasswordErr +urlDataHFTPBadNameListErr = -2144 #urlDataHFTPBadNameListErr +urlDataHFTPNoNetDriverErr = -2143 #urlDataHFTPNoNetDriverErr +urlDataHFTPFilenameErr = -2142 #urlDataHFTPFilenameErr +urlDataHFTPPermissionsErr = -2141 #urlDataHFTPPermissionsErr +urlDataHFTPQuotaErr = -2140 #urlDataHFTPQuotaErr +urlDataHFTPNoDirectoryErr = -2139 #urlDataHFTPNoDirectoryErr +urlDataHFTPDataConnectionErr = -2138 #urlDataHFTPDataConnectionErr +urlDataHFTPServerErr = -2137 #urlDataHFTPServerErr +urlDataHFTPBadPasswordErr = -2136 #urlDataHFTPBadPasswordErr +urlDataHFTPBadUserErr = -2135 #urlDataHFTPBadUserErr +urlDataHFTPShutdownErr = -2134 #urlDataHFTPShutdownErr +urlDataHFTPProtocolErr = -2133 #urlDataHFTPProtocolErr +urlDataHHTTPRedirectErr = -2132 #urlDataHHTTPRedirectErr +urlDataHHTTPURLErr = -2131 #urlDataHHTTPURLErr +urlDataHHTTPNoNetDriverErr = -2130 #urlDataHHTTPNoNetDriverErr +urlDataHHTTPProtocolErr = -2129 #urlDataHHTTPProtocolErr +qtNetworkAlreadyAllocatedErr = -2127 #qtNetworkAlreadyAllocatedErr +notAllowedToSaveMovieErr = -2126 #notAllowedToSaveMovieErr +fileOffsetTooBigErr = -2125 #fileOffsetTooBigErr +ASDEntryNotFoundErr = -2124 #ASDEntryNotFoundErr +ASDBadForkErr = -2123 #ASDBadForkErr +ASDBadHeaderErr = -2122 #ASDBadHeaderErr +AAPNotFoundErr = -2121 #AAPNotFoundErr +AAPNotCreatedErr = -2120 #AAPNotCreatedErr +qfcbNotCreatedErr = -2119 #qfcbNotCreatedErr +qfcbNotFoundErr = -2118 #qfcbNotFoundErr +wackBadMetaDataErr = -2117 #wackBadMetaDataErr +wackForkNotFoundErr = -2116 #wackForkNotFoundErr +wackBadFileErr = -2115 #wackBadFileErr +unknownFormatErr = -2114 #unknownFormatErr +pathNotVerifiedErr = -2113 #pathNotVerifiedErr +noPathMappingErr = -2112 #noPathMappingErr +emptyPathErr = -2111 #emptyPathErr +pathTooLongErr = -2110 #pathTooLongErr +cannotBeLeafAtomErr = -2109 #cannotBeLeafAtomErr +invalidAtomTypeErr = -2108 #invalidAtomTypeErr +invalidAtomContainerErr = -2107 #invalidAtomContainerErr +invalidAtomErr = -2106 #invalidAtomErr +duplicateAtomTypeAndIDErr = -2105 #duplicateAtomTypeAndIDErr +atomIndexInvalidErr = -2104 #atomIndexInvalidErr +atomsNotOfSameTypeErr = -2103 #atomsNotOfSameTypeErr +notLeafAtomErr = -2102 #notLeafAtomErr +cannotFindAtomErr = -2101 #cannotFindAtomErr +unsupportedProcessorErr = -2097 #unsupportedProcessorErr +unsupportedOSErr = -2096 #unsupportedOSErr +qtmlUninitialized = -2095 #qtmlUninitialized +qtmlDllEntryNotFoundErr = -2094 #Windows specific errors (when qtml is loading) +qtmlDllLoadErr = -2093 #Windows specific errors (when qtml is loading) +componentDllEntryNotFoundErr = -2092 #Windows specific errors (when component is loading) +componentDllLoadErr = -2091 #Windows specific errors (when component is loading) +videoOutputInUseErr = -2090 #videoOutputInUseErr +noExportProcAvailableErr = -2089 #noExportProcAvailableErr +tuneParseOSErr = -2087 #tuneParseOSErr +tunePlayerFullOSErr = -2086 #tunePlayerFullOSErr +noteChannelNotAllocatedOSErr = -2085 #noteChannelNotAllocatedOSErr +illegalNoteChannelOSErr = -2084 #illegalNoteChannelOSErr +synthesizerOSErr = -2083 #synthesizerOSErr +synthesizerNotRespondingOSErr = -2082 #synthesizerNotRespondingOSErr +midiManagerAbsentOSErr = -2081 #midiManagerAbsentOSErr +illegalControllerOSErr = -2080 #illegalControllerOSErr +illegalInstrumentOSErr = -2079 #illegalInstrumentOSErr +illegalKnobValueOSErr = -2078 #illegalKnobValueOSErr +illegalKnobOSErr = -2077 #illegalKnobOSErr +illegalChannelOSErr = -2076 #illegalChannelOSErr +illegalPartOSErr = -2075 #illegalPartOSErr +illegalVoiceAllocationOSErr = -2074 #illegalVoiceAllocationOSErr +cantReceiveFromSynthesizerOSErr = -2073 #cantReceiveFromSynthesizerOSErr +cantSendToSynthesizerOSErr = -2072 #cantSendToSynthesizerOSErr +notImplementedMusicOSErr = -2071 #notImplementedMusicOSErr +internalComponentErr = -2070 #internalComponentErr +invalidSpriteIDErr = -2069 #invalidSpriteIDErr +invalidImageIndexErr = -2068 #invalidImageIndexErr +invalidSpriteIndexErr = -2067 #invalidSpriteIndexErr +gWorldsNotSameDepthAndSizeErr = -2066 #gWorldsNotSameDepthAndSizeErr +invalidSpritePropertyErr = -2065 #invalidSpritePropertyErr +invalidSpriteWorldPropertyErr = -2064 #invalidSpriteWorldPropertyErr +missingRequiredParameterErr = -2063 #missingRequiredParameterErr +movieTextNotFoundErr = -2062 #movieTextNotFoundErr +sourceNotFoundErr = -2061 #sourceNotFoundErr +noSourceTreeFoundErr = -2060 #noSourceTreeFoundErr +samplesAlreadyInMediaErr = -2059 #samplesAlreadyInMediaErr +auxiliaryExportDataUnavailable = -2058 #auxiliaryExportDataUnavailable +unsupportedAuxiliaryImportData = -2057 #unsupportedAuxiliaryImportData +soundSupportNotAvailableErr = -2056 #QT for Windows error +noSoundTrackInMovieErr = -2055 #QT for Windows error +noVideoTrackInMovieErr = -2054 #QT for Windows error +featureUnsupported = -2053 #featureUnsupported +couldNotUseAnExistingSample = -2052 #couldNotUseAnExistingSample +noDefaultDataRef = -2051 #noDefaultDataRef +badDataRefIndex = -2050 #badDataRefIndex +invalidDataRefContainer = -2049 #invalidDataRefContainer +noMovieFound = -2048 #noMovieFound +dataNoDataRef = -2047 #dataNoDataRef +endOfDataReached = -2046 #endOfDataReached +dataAlreadyClosed = -2045 #dataAlreadyClosed +dataAlreadyOpenForWrite = -2044 #dataAlreadyOpenForWrite +dataNotOpenForWrite = -2043 #dataNotOpenForWrite +dataNotOpenForRead = -2042 #dataNotOpenForRead +invalidSampleDescription = -2041 #invalidSampleDescription +invalidChunkCache = -2040 #invalidChunkCache +invalidSampleDescIndex = -2039 #invalidSampleDescIndex +invalidChunkNum = -2038 #invalidChunkNum +invalidSampleNum = -2037 #invalidSampleNum +invalidRect = -2036 #invalidRect +cantEnableTrack = -2035 #cantEnableTrack +internalQuickTimeError = -2034 #internalQuickTimeError +badEditIndex = -2033 #badEditIndex +timeNotInMedia = -2032 #timeNotInMedia +timeNotInTrack = -2031 #timeNotInTrack +trackNotInMovie = -2030 #trackNotInMovie +trackIDNotFound = -2029 #trackIDNotFound +badTrackIndex = -2028 #badTrackIndex +maxSizeToGrowTooSmall = -2027 #maxSizeToGrowTooSmall +userDataItemNotFound = -2026 #userDataItemNotFound +staleEditState = -2025 #staleEditState +nonMatchingEditState = -2024 #nonMatchingEditState +invalidEditState = -2023 #invalidEditState +cantCreateSingleForkFile = -2022 #happens when file already exists +wfFileNotFound = -2021 #wfFileNotFound +movieToolboxUninitialized = -2020 #movieToolboxUninitialized +progressProcAborted = -2019 #progressProcAborted +mediaTypesDontMatch = -2018 #mediaTypesDontMatch +badEditList = -2017 #badEditList +cantPutPublicMovieAtom = -2016 #cantPutPublicMovieAtom +invalidTime = -2015 #invalidTime +invalidDuration = -2014 #invalidDuration +invalidHandler = -2013 #invalidHandler +invalidDataRef = -2012 #invalidDataRef +invalidSampleTable = -2011 #invalidSampleTable +invalidMovie = -2010 #invalidMovie +invalidTrack = -2009 #invalidTrack +invalidMedia = -2008 #invalidMedia +noDataHandler = -2007 #noDataHandler +noMediaHandler = -2006 #noMediaHandler +badComponentType = -2005 #badComponentType +cantOpenHandler = -2004 #cantOpenHandler +cantFindHandler = -2003 #cantFindHandler +badPublicMovieAtom = -2002 #badPublicMovieAtom +badImageDescription = -2001 #badImageDescription +couldNotResolveDataRef = -2000 #couldNotResolveDataRef +nonDragOriginatorErr = -1862 #illegal attempt at originator only data +badImageErr = -1861 #bad translucent image PixMap +badImageRgnErr = -1860 #bad translucent image region +noSuitableDisplaysErr = -1859 #no displays support translucency +unsupportedForPlatformErr = -1858 #call is for PowerPC only +dragNotAcceptedErr = -1857 #drag was not accepted by receiver +handlerNotFoundErr = -1856 #handler not found +duplicateHandlerErr = -1855 #handler already exists +cantGetFlavorErr = -1854 #error while trying to get flavor data +duplicateFlavorErr = -1853 #flavor type already exists +badDragFlavorErr = -1852 #unknown flavor type +badDragItemErr = -1851 #unknown drag item reference +badDragRefErr = -1850 #unknown drag reference +errEndOfBody = -1813 #errEndOfBody +errEndOfDocument = -1812 #errEndOfDocument +errTopOfBody = -1811 #errTopOfBody +errTopOfDocument = -1810 #errTopOfDocument +errOffsetIsOutsideOfView = -1801 #errOffsetIsOutsideOfView +errOffsetInvalid = -1800 #errOffsetInvalid +errOSACantOpenComponent = -1762 #Can't connect to scripting system with that ID +errOSAComponentMismatch = -1761 #Parameters are from 2 different components +errOSADataFormatTooNew = -1759 #errOSADataFormatTooNew +errOSADataFormatObsolete = -1758 #errOSADataFormatObsolete +errOSANoSuchDialect = -1757 #errOSANoSuchDialect +errOSASourceNotAvailable = -1756 #errOSASourceNotAvailable +errOSABadSelector = -1754 #errOSABadSelector +errOSAScriptError = -1753 #errOSAScriptError +errOSABadStorageType = -1752 #errOSABadStorageType +errOSAInvalidID = -1751 #errOSAInvalidID +errOSASystemError = -1750 #errOSASystemError +errAEBufferTooSmall = -1741 #buffer for AEFlattenDesc too small +errAEBuildSyntaxError = -1740 #AEBuildDesc and friends detected a syntax error +errAEDescIsNull = -1739 #attempting to perform an invalid operation on a null descriptor +errAEStreamAlreadyConverted = -1738 #attempt to convert a stream that has already been converted +errAEStreamBadNesting = -1737 #nesting violation while streaming +errAEDuplicateHandler = -1736 #attempt to install handler in table for identical class and id (1.1 or greater) +errAEEventFiltered = -1735 #event has been filtered, and should not be propogated (1.1 or greater) +errAEReceiveEscapeCurrent = -1734 #break out of only lowest level of AEReceive (1.1 or greater) +errAEReceiveTerminate = -1733 #break out of all levels of AEReceive to the topmost (1.1 or greater) +errAERecordingIsAlreadyOn = -1732 #available only in version 1.0.1 or greater +errAEUnknownObjectType = -1731 #available only in version 1.0.1 or greater +errAEEmptyListContainer = -1730 #Attempt to pass empty list as container to accessor +errAENegativeCount = -1729 #CountProc returned negative value +errAENoSuchObject = -1728 #e.g.,: specifier asked for the 3rd, but there are only 2. Basically, this indicates a run-time resolution error. +errAENotAnObjSpec = -1727 #Param to AEResolve not of type 'obj ' +errAEBadTestKey = -1726 #Test is neither typeLogicalDescriptor nor typeCompDescriptor +errAENoSuchLogical = -1725 #Something other than AND, OR, or NOT +errAEAccessorNotFound = -1723 #Accessor proc matching wantClass and containerType or wildcards not found +errAEWrongNumberArgs = -1721 #Logical op kAENOT used with other than 1 term +errAEImpossibleRange = -1720 #A range like 3rd to 2nd, or 1st to all. +errAEIllegalIndex = -1719 #index is out of range in a put operation +errAEReplyNotArrived = -1718 #the contents of the reply you are accessing have not arrived yet +errAEHandlerNotFound = -1717 #no handler in the dispatch tables fits the parameters to AEGetEventHandler or AEGetCoercionHandler +errAEUnknownAddressType = -1716 #the target address type is not known +errAEParamMissed = -1715 #a required parameter was not accessed +errAENotASpecialFunction = -1714 #there is no special function for/with this keyword +errAENoUserInteraction = -1713 #no user interaction is allowed +errAETimeout = -1712 #the AppleEvent timed out +errAEWaitCanceled = -1711 #in AESend, the user cancelled out of wait loop for reply or receipt +errAEUnknownSendMode = -1710 #mode wasn't NoReply, WaitReply, or QueueReply or Interaction level is unknown +errAEReplyNotValid = -1709 #AEResetTimer was passed an invalid reply parameter +errAEEventNotHandled = -1708 #the AppleEvent was not handled by any handler +errAENotAppleEvent = -1707 #the event is not in AppleEvent format +errAENewerVersion = -1706 #need newer version of the AppleEvent manager +errAEBadListItem = -1705 #the specified list item does not exist +errAENotAEDesc = -1704 #errAENotAEDesc +errAEWrongDataType = -1703 #errAEWrongDataType +errAECorruptData = -1702 #errAECorruptData +errAEDescNotFound = -1701 #errAEDescNotFound +errAECoercionFail = -1700 #bad parameter data or unable to coerce the data supplied +errFSIteratorNotSupported = -1424 #The iterator's flags or container are not supported by this call +errFSIteratorNotFound = -1423 #Passed FSIterator is not an open iterator +errFSBadIteratorFlags = -1422 #Flags passed to FSOpenIterator are bad +errFSForkExists = -1421 #Named fork already exists. +errFSRefsDifferent = -1420 #FSCompareFSRefs; refs are for different objects +errFSBadSearchParams = -1419 #Something wrong with CatalogSearch searchParams +errFSBadItemCount = -1418 #maximumItems was zero +errFSNoMoreItems = -1417 #Iteration ran out of items to return +errFSBadAllocFlags = -1413 #Invalid bits set in allocationFlags +errFSBadPosMode = -1412 #Newline bits set in positionMode +errFSMissingName = -1411 #A Unicode name parameter was NULL or nameLength parameter was zero +errFSNameTooLong = -1410 #File/fork name is too long to create/rename +errFSForkNotFound = -1409 #Named fork does not exist +errFSNotAFolder = -1407 #Expected a folder, got a file +errFSMissingCatInfo = -1406 #A CatalogInfo parameter was NULL +errFSBadInfoBitmap = -1405 #A CatalogInfoBitmap or VolumeInfoBitmap has reserved or invalid bits set +errFSBadForkRef = -1404 #A ForkRefNum parameter was bad +errFSBadBuffer = -1403 #A buffer parameter was bad +errFSBadForkName = -1402 #Fork name parameter is bad +errFSBadFSRef = -1401 #FSRef parameter is bad +errFSUnknownCall = -1400 #selector is not recognized by this filesystem +badFCBErr = -1327 #FCBRecPtr is not valid +volVMBusyErr = -1311 #can't eject because volume is in use by VM +fsDataTooBigErr = -1310 #file or volume is too big for system +fileBoundsErr = -1309 #file's EOF, offset, mark or size is too big +notARemountErr = -1308 #when _Mount allows only remounts and doesn't get one +badFidErr = -1307 #file id is dangling or doesn't match with the file number +sameFileErr = -1306 #can't exchange a file with itself +desktopDamagedErr = -1305 #desktop database files are corrupted +catChangedErr = -1304 #the catalog has been modified +diffVolErr = -1303 #files on different volumes +notAFileErr = -1302 #directory specified +fidExists = -1301 #file id already exists +fidNotFound = -1300 #no file thread exists. +errRefNum = -1280 #bad connection refNum +errAborted = -1279 #control call was aborted +errState = -1278 #bad connection state for this operation +errOpening = -1277 #open connection request failed +errAttention = -1276 #attention message too long +errFwdReset = -1275 #read terminated by forward reset +errDSPQueueSize = -1274 #DSP Read/Write Queue Too small +errOpenDenied = -1273 #open connection request was denied +reqAborted = -1105 #reqAborted +noDataArea = -1104 #noDataArea +noSendResp = -1103 #noSendResp +cbNotFound = -1102 #cbNotFound +noRelErr = -1101 #noRelErr +badBuffNum = -1100 #badBuffNum +badATPSkt = -1099 #badATPSkt +tooManySkts = -1098 #tooManySkts +tooManyReqs = -1097 #tooManyReqs +reqFailed = -1096 #reqFailed +aspNoAck = -1075 #No ack on attention request (server err) +aspTooMany = -1074 #Too many clients (server error) +aspSizeErr = -1073 #Command block too big +aspSessClosed = -1072 #Session closed +aspServerBusy = -1071 #Server cannot open another session +aspParamErr = -1070 #Parameter error +aspNoServers = -1069 #No servers at that address +aspNoMoreSess = -1068 #No more sessions on server +aspBufTooSmall = -1067 #Buffer too small +aspBadVersNum = -1066 #Server cannot support this ASP version +nbpNISErr = -1029 #Error trying to open the NIS +nbpNotFound = -1028 #Name not found on remove +nbpDuplicate = -1027 #Duplicate name exists already +nbpConfDiff = -1026 #Name confirmed at different socket +nbpNoConfirm = -1025 #nbpNoConfirm +nbpBuffOvr = -1024 #Buffer overflow in LookupName +noMaskFoundErr = -1000 #Icon Utilties Error +kFMFontContainerAccessErr = -985 #kFMFontContainerAccessErr +kFMFontTableAccessErr = -984 #kFMFontTableAccessErr +kFMIterationScopeModifiedErr = -983 #kFMIterationScopeModifiedErr +kFMInvalidFontErr = -982 #kFMInvalidFontErr +kFMInvalidFontFamilyErr = -981 #kFMInvalidFontFamilyErr +kFMIterationCompleted = -980 #kFMIterationCompleted +guestNotAllowedErr = -932 #destination port requires authentication +badLocNameErr = -931 #location name malformed +badServiceMethodErr = -930 #illegal service type, or not supported +noUserRecErr = -928 #Invalid user reference number +authFailErr = -927 #unable to authenticate user at destination +noInformErr = -926 #PPCStart failed because destination did not have inform pending +networkErr = -925 #An error has occurred in the network, not too likely +noUserRefErr = -924 #unable to create a new userRefNum +notLoggedInErr = -923 #The default userRefNum does not yet exist +noDefaultUserErr = -922 #user hasn't typed in owners name in Network Setup Control Pannel +badPortNameErr = -919 #PPCPortRec malformed +sessClosedErr = -917 #session was closed +portClosedErr = -916 #port was closed +noResponseErr = -915 #unable to contact destination +noToolboxNameErr = -914 #A system resource is missing, not too likely +noMachineNameErr = -913 #user hasn't named his Macintosh in the Network Setup Control Panel +userRejectErr = -912 #Destination rejected the session request +noUserNameErr = -911 #user name unknown on destination machine +portNameExistsErr = -910 #port is already open (perhaps in another app) +badReqErr = -909 #bad parameter or invalid state for operation +noSessionErr = -908 #Invalid session reference number +sessTableErr = -907 #Out of session tables, try again later +destPortErr = -906 #Port does not exist at destination +localOnlyErr = -905 #Network activity is currently disabled +noGlobalsErr = -904 #The system is hosed, better re-boot +noPortErr = -903 #Unable to open port or bad portRefNum. If you're calling +nameTypeErr = -902 #Invalid or inappropriate locationKindSelector in locationName +notInitErr = -900 #PPCToolBox not initialized +notAppropriateForClassic = -877 #This application won't or shouldn't run on Classic (Problem 2481058). +appVersionTooOld = -876 #The application's creator and version are incompatible with the current version of Mac OS. +wrongApplicationPlatform = -875 #The application could not launch because the required platform is not available +hmCloseViewActive = -863 #Returned from HMRemoveBalloon if CloseView was active +hmNoBalloonUp = -862 #Returned from HMRemoveBalloon if no balloon was visible when call was made +hmOperationUnsupported = -861 #Returned from HMShowBalloon call if bad method passed to routine +hmUnknownHelpType = -859 #Returned if help msg record contained a bad type +hmWrongVersion = -858 #Returned if help mgr resource was the wrong version +hmSkippedBalloon = -857 #Returned from calls if helpmsg specified a skip balloon +hmHelpManagerNotInited = -855 #Returned from HMGetHelpMenuHandle if help menu not setup +hmSameAsLastBalloon = -854 #Returned from HMShowMenuBalloon if menu & item is same as last time +hmBalloonAborted = -853 #Returned if mouse was moving or mouse wasn't in window port rect +hmHelpDisabled = -850 #Show Balloons mode was off, call to routine ignored +rcDBPackNotInited = -813 #attempt to call other routine before InitDBPack +rcDBWrongVersion = -812 #incompatible versions +rcDBNoHandler = -811 #no app handler for specified data type +rcDBBadAsyncPB = -810 #tried to kill a bad pb +rcDBAsyncNotSupp = -809 #ddev does not support async calls +rcDBBadDDEV = -808 #bad ddev specified on DBInit +rcDBBadSessNum = -807 #bad session number for DBGetConnInfo +rcDBBadSessID = -806 #rcDBBadSessID +rcDBExec = -805 #rcDBExec +rcDBBreak = -804 #rcDBBreak +rcDBBadType = -803 #rcDBBadType +rcDBError = -802 #rcDBError +rcDBValue = -801 #rcDBValue +rcDBNull = -800 #rcDBNull +icTooManyProfilesErr = -677 #too many profiles in database +icProfileNotFoundErr = -676 #profile not found +icConfigInappropriateErr = -675 #incorrect manufacturer code +icConfigNotFoundErr = -674 #no internet configuration was found +icNoURLErr = -673 #no URL found +icNothingToOverrideErr = -672 #no component for the override component to capture +icNoMoreWritersErr = -671 #you cannot begin a write session because someone else is already doing it +icTruncatedErr = -670 #more data was present than was returned +icInternalErr = -669 #Internet Config internal error +icPrefDataErr = -668 #problem with preference data +icPermErr = -667 #cannot set preference +icPrefNotFoundErr = -666 #Internet preference not found +vmInvalidOwningProcessErr = -648 #current process does not own the BackingFileID or FileViewID +vmAddressNotInFileViewErr = -647 #address is not in a FileView +vmNoMoreFileViewsErr = -646 #no more FileViews were found +vmFileViewAccessErr = -645 #requested FileViewAccess cannot be obtained +vmInvalidFileViewIDErr = -644 #invalid FileViewID +vmNoMoreBackingFilesErr = -643 #no more BackingFiles were found +vmBusyBackingFileErr = -642 #open views found on BackingFile +vmMappingPrivilegesErr = -641 #requested MappingPrivileges cannot be obtained +vmInvalidBackingFileIDErr = -640 #invalid BackingFileID +noMMUErr = -626 #no MMU present +cannotDeferErr = -625 #unable to defer additional functions +interruptsMaskedErr = -624 #donÕt call with interrupts masked +notLockedErr = -623 #specified range of memory is not locked +cannotMakeContiguousErr = -622 #cannot make specified range contiguous +notHeldErr = -621 #specified range of memory is not held +notEnoughMemoryErr = -620 #insufficient physical memory +threadProtocolErr = -619 #threadProtocolErr +threadNotFoundErr = -618 #threadNotFoundErr +threadTooManyReqsErr = -617 #threadTooManyReqsErr +noUserInteractionAllowed = -610 #no user interaction allowed +connectionInvalid = -609 #connectionInvalid +noOutstandingHLE = -608 #noOutstandingHLE +bufferIsSmall = -607 #error returns from Post and Accept +appIsDaemon = -606 #app is BG-only, and launch flags disallow this +appMemFullErr = -605 #application SIZE not big enough for launch +hardwareConfigErr = -604 #hardware configuration not correct for call +protocolErr = -603 #app made module calls in improper order +appModeErr = -602 #memory mode is 32-bit, but app not 32-bit clean +memFragErr = -601 #not enough room to launch app w/special requirements +procNotFound = -600 #no eligible process with specified descriptor +driverHardwareGoneErr = -503 #disk driver's hardware was disconnected +hwParamErr = -502 #bad selector for _HWPriv +teScrapSizeErr = -501 #scrap item too big for text edit record +rgnTooBigErr = -500 #rgnTooBigErr +exUserBreak = -492 #user debugger break; execute debugger commands on stack +strUserBreak = -491 #user debugger break; display string on stack +userBreak = -490 #user debugger break +notThePublisherWrn = -463 #not the first registered publisher for that container +containerAlreadyOpenWrn = -462 #container already opened by this section +containerNotFoundWrn = -461 #could not find editionContainer at this time +multiplePublisherWrn = -460 #A Publisher is already registered for that container +badSubPartErr = -454 #can not use sub parts in this release +badEditionFileErr = -453 #edition file is corrupt +notRegisteredSectionErr = -452 #not a registered SectionRecord +badSectionErr = -451 #not a valid SectionRecord +editionMgrInitErr = -450 #edition manager not inited by this app +fsmUnknownFSMMessageErr = -438 #unknown message passed to FSM +fsmNoAlternateStackErr = -437 #no alternate stack for HFS CI +fsmBadFSDVersionErr = -436 #FSM version incompatible with FSD +fsmDuplicateFSIDErr = -435 #FSID already exists on InstallFS +fsmBadFSDLenErr = -434 #FSD size incompatible with current FSM vers +fsmBadFFSNameErr = -433 #Name length not 1 <= length <= 31 +fsmBusyFFSErr = -432 #File system is busy, cannot be removed +fsmFFSNotFoundErr = -431 #Foreign File system does not exist - new Pack2 could return this error too +btKeyAttrErr = -417 #There is no such a key attribute. +btKeyLenErr = -416 #Maximum key length is too long or equal to zero. +btRecNotFnd = -415 #Record cannot be found. +btDupRecErr = -414 #Record already exists. +btNoSpace = -413 #Can't allocate disk space. +notBTree = -410 #The file is not a dictionary. +gcrOnMFMErr = -400 #gcr format on high density media error +slotNumErr = -360 #invalid slot # error +smRecNotFnd = -351 #Record not found in the SRT. +smSRTOvrFlErr = -350 #SRT over flow. +smNoGoodOpens = -349 #No opens were successfull in the loop. +smOffsetErr = -348 #Offset was too big (temporary error +smByteLanesErr = -347 #NumByteLanes was determined to be zero. +smBadsPtrErr = -346 #Bad pointer was passed to sCalcsPointer +smsGetDrvrErr = -345 #Error occurred during _sGetDriver. +smNoMoresRsrcs = -344 #No more sResources +smDisDrvrNamErr = -343 #Error occurred during _sDisDrvrName. +smGetDrvrNamErr = -342 #Error occurred during _sGetDrvrName. +smCkStatusErr = -341 #Status of slot = fail. +smBlkMoveErr = -340 #_BlockMove error +smNewPErr = -339 #_NewPtr error +smSelOOBErr = -338 #Selector out of bounds error +smSlotOOBErr = -337 #Slot out of bounds error +smNilsBlockErr = -336 #Nil sBlock error (Dont allocate and try to use a nil sBlock) +smsPointerNil = -335 #LPointer is nil From sOffsetData. If this error occurs; check sInfo rec for more information. +smCPUErr = -334 #Code revision is wrong +smCodeRevErr = -333 #Code revision is wrong +smReservedErr = -332 #Reserved field not zero +smBadsList = -331 #Bad sList: Id1 < Id2 < Id3 ...format is not followed. +smBadRefId = -330 #Reference Id not found in List +smBusErrTO = -320 #BusError time out. +smBadBoardId = -319 #BoardId was wrong; re-init the PRAM record. +smReservedSlot = -318 #slot is reserved, VM should not use this address space. +smInitTblVErr = -317 #An error occurred while trying to initialize the Slot Resource Table. +smInitStatVErr = -316 #The InitStatusV field was negative after primary or secondary init. +smNoBoardId = -315 #No Board Id. +smGetPRErr = -314 #Error occurred during _sGetPRAMRec (See SIMStatus). +smNoBoardSRsrc = -313 #No Board sResource. +smDisposePErr = -312 #_DisposePointer error +smFHBlkDispErr = -311 #Error occurred during _sDisposePtr (Dispose of FHeader block). +smFHBlockRdErr = -310 #Error occurred during _sGetFHeader. +smBLFieldBad = -309 #ByteLanes field was bad. +smUnExBusErr = -308 #Unexpected BusError +smResrvErr = -307 #Fatal reserved error. Resreved field <> 0. +smNosInfoArray = -306 #No sInfoArray. Memory Mgr error. +smDisabledSlot = -305 #This slot is disabled (-305 use to be smLWTstBad) +smNoDir = -304 #Directory offset is Nil +smRevisionErr = -303 #Wrong revison level +smFormatErr = -302 #FHeader Format is not Apple's +smCRCFail = -301 #CRC check failed for declaration data +smEmptySlot = -300 #No card in slot +nmTypErr = -299 #Notification Manager:wrong queue type +smPriInitErr = -293 #Error; Cards could not be initialized. +smPRAMInitErr = -292 #Error; Slot Resource Table could not be initialized. +smSRTInitErr = -291 #Error; Slot Resource Table could not be initialized. +smSDMInitErr = -290 #Error; SDM could not be initialized. +midiInvalidCmdErr = -261 #command not supported for port type +midiDupIDErr = -260 #duplicate client ID +midiNameLenErr = -259 #name supplied is longer than 31 characters +midiWriteErr = -258 #MIDIWritePacket couldn't write to all connected ports +midiNoConErr = -257 #no connection exists between specified ports +midiVConnectRmvd = -256 #pending virtual connection removed +midiVConnectMade = -255 #pending virtual connection resolved +midiVConnectErr = -254 #pending virtual connection created +midiTooManyConsErr = -253 #too many connections made +midiTooManyPortsErr = -252 #too many ports already installed in the system +midiNoPortErr = -251 #no port with that ID found +midiNoClientErr = -250 #no client with that ID found +badInputText = -247 #badInputText +badDictFormat = -246 #badDictFormat +incompatibleVoice = -245 #incompatibleVoice +voiceNotFound = -244 #voiceNotFound +bufTooSmall = -243 #bufTooSmall +synthNotReady = -242 #synthNotReady +synthOpenFailed = -241 #synthOpenFailed +noSynthFound = -240 #noSynthFound +siUnknownQuality = -232 #invalid quality selector (returned by driver) +siUnknownInfoType = -231 #invalid info type selector (returned by driver) +siInputDeviceErr = -230 #input device hardware failure +siBadRefNum = -229 #invalid input device reference number +siBadDeviceName = -228 #input device could not be opened +siDeviceBusyErr = -227 #input device already in use +siInvalidSampleSize = -226 #invalid sample size +siInvalidSampleRate = -225 #invalid sample rate +siHardDriveTooSlow = -224 #hard drive too slow to record to disk +siInvalidCompression = -223 #invalid compression type +siNoBufferSpecified = -222 #returned by synchronous SPBRecord if nil buffer passed +siBadSoundInDevice = -221 #invalid index passed to SoundInGetIndexedDevice +siNoSoundInHardware = -220 #no Sound Input hardware +siVBRCompressionNotSupported = -213 #vbr audio compression not supported for this operation +noMoreRealTime = -212 #not enough CPU cycles left to add another task +channelNotBusy = -211 #channelNotBusy +buffersTooSmall = -210 #can not operate in the memory allowed +channelBusy = -209 #the Channel is being used for a PFD already +badFileFormat = -208 #was not type AIFF or was of bad format,corrupt +notEnoughBufferSpace = -207 #could not allocate enough memory +badFormat = -206 #Sound Manager Error Returns +badChannel = -205 #Sound Manager Error Returns +resProblem = -204 #Sound Manager Error Returns +queueFull = -203 #Sound Manager Error Returns +notEnoughHardwareErr = -201 #Sound Manager Error Returns +noHardwareErr = -200 #Sound Manager Error Returns +mapReadErr = -199 #map inconsistent with operation +resAttrErr = -198 #attribute inconsistent with operation +rmvRefFailed = -197 #RmveReference failed +rmvResFailed = -196 #RmveResource failed +addRefFailed = -195 #AddReference failed +addResFailed = -194 #AddResource failed +resFNotFound = -193 #Resource file not found +resNotFound = -192 #Resource not found +inputOutOfBounds = -190 #Offset of Count out of bounds +writingPastEnd = -189 #Writing past end of file +resourceInMemory = -188 #Resource already in memory +CantDecompress = -186 #resource bent ("the bends") - can't decompress a compressed resource +badExtResource = -185 #extended resource has a bad format. +cmNoCurrentProfile = -182 #Responder error +cmUnsupportedDataType = -181 #Responder error +cmCantDeleteProfile = -180 #Responder error +cmCantXYZ = -179 #CMM cant handle XYZ space +cmCantConcatenateError = -178 #Profile can't be concatenated +cmProfilesIdentical = -177 #Profiles the same +cmProfileNotFound = -176 #Responder error +cmMethodNotFound = -175 #CMM not present +cmMethodError = -171 #cmMethodError +cmProfileError = -170 #cmProfileError +cDepthErr = -157 #invalid pixel depth +cResErr = -156 #invalid resolution for MakeITable +cDevErr = -155 #invalid type of graphics device +cProtectErr = -154 #colorTable entry protection violation +cRangeErr = -153 #range error on colorTable request +cNoMemErr = -152 #failed to allocate memory for structure +cTempMemErr = -151 #failed to allocate memory for temporary structures +cMatchErr = -150 #Color2Index failed to find an index +insufficientStackErr = -149 #insufficientStackErr +pixMapTooDeepErr = -148 #pixMapTooDeepErr +rgnOverflowErr = -147 #rgnOverflowErr +noMemForPictPlaybackErr = -145 #noMemForPictPlaybackErr +userCanceledErr = -128 #userCanceledErr +hMenuFindErr = -127 #could not find HMenu's parent in MenuKey (wrong error code - obsolete) +mBarNFnd = -126 #system error code for MBDF not found +updPixMemErr = -125 #insufficient memory to update a pixmap +volGoneErr = -124 #Server volume has been disconnected. +wrgVolTypErr = -123 #Wrong volume type error [operation not supported for MFS] +badMovErr = -122 #Move into offspring error +tmwdoErr = -121 #No free WDCB available +dirNFErr = -120 #Directory not found +memLockedErr = -117 #trying to move a locked block (MoveHHi) +memSCErr = -116 #Size Check failed +memBCErr = -115 #Block Check failed +memPCErr = -114 #Pointer Check failed +memAZErr = -113 #Address in zone check failed +memPurErr = -112 #trying to purge a locked or non-purgeable block +memWZErr = -111 #WhichZone failed (applied to free block) +memAdrErr = -110 #address was odd; or out of range +nilHandleErr = -109 #Master Pointer was NIL in HandleZone or other +memFullErr = -108 #Not enough room in heap zone +noTypeErr = -102 #No object of that type in scrap +noScrapErr = -100 #No scrap exists error +memROZWarn = -99 #soft error in ROZ +portNotCf = -98 #driver Open error code (parameter RAM not configured for this connection) +portInUse = -97 #driver Open error code (port is in use) +portNotPwr = -96 #serial port not currently powered +excessCollsns = -95 #excessive collisions on write +lapProtErr = -94 #error in attaching/detaching protocol +noBridgeErr = -93 #no network bridge for non-local send +eLenErr = -92 #Length error ddpLenErr +eMultiErr = -91 #Multicast address error ddpSktErr +breakRecd = -90 #Break received (SCC) +rcvrErr = -89 #SCC receiver error (framing; parity; OR) +prInitErr = -88 #InitUtil found the parameter ram uninitialized +prWrErr = -87 #parameter ram written didn't read-verify +clkWrErr = -86 #time written did not verify +clkRdErr = -85 #unable to read same clock value twice +verErr = -84 #track failed to verify +fmt2Err = -83 #can't get enough sync +fmt1Err = -82 #can't find sector 0 after track format +sectNFErr = -81 #sector number never found on a track +seekErr = -80 #track number wrong on address mark +spdAdjErr = -79 #unable to correctly adjust disk speed +twoSideErr = -78 #tried to read 2nd side on a 1-sided drive +initIWMErr = -77 #unable to initialize IWM +tk0BadErr = -76 #track 0 detect doesn't change +cantStepErr = -75 #step handshake failed +wrUnderrun = -74 #write underrun occurred +badDBtSlp = -73 #bad data mark bit slip nibbles +badDCksum = -72 #bad data mark checksum +noDtaMkErr = -71 #couldn't find a data mark header +badBtSlpErr = -70 #bad addr mark bit slip nibbles +badCksmErr = -69 #addr mark checksum didn't check +dataVerErr = -68 #read verify compare failed +noAdrMkErr = -67 #couldn't find valid addr mark +noNybErr = -66 #couldn't find 5 nybbles in 200 tries +offLinErr = -65 #r/w requested for an off-line drive +fontDecError = -64 #error during font declaration +wrPermErr = -61 #write permissions error +badMDBErr = -60 #bad master directory block +fsRnErr = -59 #file system internal error:during rename the old entry was deleted but could not be restored. +extFSErr = -58 #volume in question belongs to an external fs +noMacDskErr = -57 #not a mac diskette (sig bytes are wrong) +nsDrvErr = -56 #no such drive (tried to mount a bad drive num) +volOnLinErr = -55 #drive volume already on-line at MountVol +permErr = -54 #permissions error (on file open) +volOffLinErr = -53 #volume not on line error (was Ejected) +gfpErr = -52 #get file position error +rfNumErr = -51 #refnum error +paramErr = -50 #error in user parameter list +opWrErr = -49 #file already open with with write permission +dupFNErr = -48 #duplicate filename (rename) +fBsyErr = -47 #File is busy (delete) +vLckdErr = -46 #volume is locked +fLckdErr = -45 #file is locked +wPrErr = -44 #diskette is write protected. +fnfErr = -43 #File not found +tmfoErr = -42 #too many files open +mFulErr = -41 #memory full (open) or file won't fit (load) +posErr = -40 #tried to position to before start of file (r/w) +eofErr = -39 #End of file +fnOpnErr = -38 #File not open +bdNamErr = -37 #there may be no bad names in the final system! +ioErr = -36 #I/O error (bummers) +nsvErr = -35 #no such volume +dskFulErr = -34 #disk full +dirFulErr = -33 #Directory full +dceExtErr = -30 #dce extension error +unitTblFullErr = -29 #unit table has no more entries +notOpenErr = -28 #Couldn't rd/wr/ctl/sts cause driver not opened +iIOAbortErr = -27 #IO abort error (Printing Manager) +dInstErr = -26 #DrvrInstall couldn't find driver in resources +dRemovErr = -25 #tried to remove an open driver +closErr = -24 #I/O System Errors +openErr = -23 #I/O System Errors +unitEmptyErr = -22 #I/O System Errors +badUnitErr = -21 #I/O System Errors +writErr = -20 #I/O System Errors +readErr = -19 #I/O System Errors +statusErr = -18 #I/O System Errors +controlErr = -17 #I/O System Errors +dsExtensionsDisabled = -13 #say –Extensions Disabled” +dsHD20Installed = -12 #say –HD20 Startup” +dsDisassemblerInstalled = -11 #say –Disassembler Installed” +dsMacsBugInstalled = -10 #say –MacsBug Installed” +seNoDB = -8 #no debugger installed to handle debugger command +SlpTypeErr = -5 #invalid queue element +unimpErr = -4 #unimplemented core routine +corErr = -3 #core routine number out of range +dsNoExtsDisassembler = -2 #not a SysErr, just a placeholder +qErr = -1 #queue element not found during deletion +tsmComponentNoErr = 0 #component result = no error +EPERM = 1 #Operation not permitted +ENOENT = 2 #No such file or directory +ESRCH = 3 #No such process +EINTR = 4 #Interrupted system call +EIO = 5 #Input/output error +ENXIO = 6 #Device not configured +E2BIG = 7 #Argument list too long +ENOEXEC = 8 #Exec format error +EBADF = 9 #Bad file descriptor +ECHILD = 10 #No child processes +EDEADLK = 11 #Resource deadlock avoided +ENOMEM = 12 #Cannot allocate memory +EACCES = 13 #Permission denied +EFAULT = 14 #Bad address +ECANCELED = 15 #Operation cancelled +EBUSY = 16 #Device busy +EEXIST = 17 #File exists +EXDEV = 18 #Cross-device link +ENODEV = 19 #Operation not supported by device +ENOTDIR = 20 #Not a directory +EISDIR = 21 #Is a directory +EINVAL = 22 #Invalid argument +ENFILE = 23 #Too many open files in system +EMFILE = 24 #Too many open files +ENOTTY = 25 #Inappropriate ioctl for device +ESIGPARM = 26 #Signal error +EFBIG = 27 #File too large +ENOSPC = 28 #No space left on device +ESPIPE = 29 #Illegal seek +EROFS = 30 #Read-only file system +EMLINK = 31 #Too many links +EPIPE = 32 #Broken pipe +EDOM = 33 #Numerical argument out of domain +ERANGE = 34 #Result too large +EAGAIN = 35 #Resource temporarily unavailable +EINPROGRESS = 36 #Operation now in progress +EALREADY = 37 #Operation already in progress +ENOTSOCK = 38 #Socket operation on non-socket +EDESTADDRREQ = 39 #Destination address required +EMSGSIZE = 40 #Message too long +EPROTOTYPE = 41 #Protocol wrong type for socket +ENOPROTOOPT = 42 #Protocol not available +EPROTONOSUPPORT = 43 #Protocol not supported +ESOCKTNOSUPPORT = 44 #Socket type not supported +EOPNOTSUPP = 45 #Operation not supported +EPFNOSUPPORT = 46 #Protocol family not supported +EAFNOSUPPORT = 47 #Address family not supported by protocol family +EADDRINUSE = 48 #Address already in use +EADDRNOTAVAIL = 49 #Can't assign requested address +ENETDOWN = 50 #Network is down +ENETUNREACH = 51 #Network is unreachable +ENETRESET = 52 #Network dropped connection on reset +ECONNABORTED = 53 #Software caused connection abort +ECONNRESET = 54 #Connection reset by peer +ENOBUFS = 55 #No buffer space available +EISCONN = 56 #Socket is already connected +ENOTCONN = 57 #Socket is not connected +ESHUTDOWN = 58 #Can't send after socket shutdown +ETOOMANYREFS = 59 #Too many references: can't splice +ETIMEDOUT = 60 #Operation timed out +ECONNREFUSED = 61 #Connection refused +ELOOP = 62 #Too many levels of symbolic links +ENAMETOOLONG = 63 #File name too long +EHOSTDOWN = 64 #Host is down +EHOSTUNREACH = 65 #No route to host +ENOTEMPTY = 66 #Directory not empty +ELOOK = 67 #Internal mapping for kOTLookErr, don't return to client +ENOLCK = 77 #No locks available +ENOSYS = 78 #Function not implemented +EILSEQ = 88 #Wide character encoding error +EUNKNOWN = 99 #Unknown error diff --git a/Lib/plat-mac/macfs.py b/Lib/plat-mac/macfs.py index 8c26dd5fbf8..11dbbeb3cd2 100644 --- a/Lib/plat-mac/macfs.py +++ b/Lib/plat-mac/macfs.py @@ -28,25 +28,25 @@ 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) + _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) + 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 @@ -56,60 +56,60 @@ error = Carbon.File.Error # 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) - + 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) - + 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 - + 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: @@ -120,21 +120,21 @@ FInfoType = FInfo # Global functions: def ResolveAliasFile(fss, chain=1): - fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain) - return FSSpec(fss), isdir, isalias - + fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain) + return FSSpec(fss), isdir, isalias + def RawFSSpec(data): - return FSSpec(rawdata=data) - + return FSSpec(rawdata=data) + def RawAlias(data): - return Alias(rawdata=data) - + return Alias(rawdata=data) + def FindApplication(*args): - raise NotImplementedError, "FindApplication no longer implemented" - + raise NotImplementedError, "FindApplication no longer implemented" + def NewAliasMinimalFromFullPath(path): - return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', '')) - + return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', '')) + # Another global function: from Carbon.Folder import FindFolder @@ -145,54 +145,54 @@ from Carbon.Folder import FindFolder _curfolder = None def StandardGetFile(*typelist): - """Ask for an input file, optionally specifying 4-char file types that are - allowable""" - return PromptGetFile('', *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", + """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 + 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", + """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 - + 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", + 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 - + if _curfolder: + rv = FSSpec(_curfolder) + else: + rv = None + _curfolder = folder + return rv + def _handleSetFolder(): - global _curfolder - rv = _curfolder - _curfolder = None - return rv - + 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", + """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 + fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec, + defaultLocation=_handleSetFolder()) + return fss, not fss is None diff --git a/Lib/plat-mac/macresource.py b/Lib/plat-mac/macresource.py index d8733c29bed..e4c3f62dfc0 100644 --- a/Lib/plat-mac/macresource.py +++ b/Lib/plat-mac/macresource.py @@ -10,137 +10,137 @@ 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)""" + """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 - + 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 - + """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 - + """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__) - + """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 + # 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 diff --git a/Lib/plat-mac/pimp.py b/Lib/plat-mac/pimp.py index 6664475d425..786f40a43f5 100644 --- a/Lib/plat-mac/pimp.py +++ b/Lib/plat-mac/pimp.py @@ -43,756 +43,756 @@ DEFAULT_INSTALLDIR=distutils.sysconfig.get_python_lib() DEFAULT_PIMPDATABASE="http://www.cwi.nl/~jack/pimp/pimp-%s.plist" % distutils.util.get_platform() ARCHIVE_FORMATS = [ - (".tar.Z", "zcat \"%s\" | tar -xf -"), - (".taz", "zcat \"%s\" | tar -xf -"), - (".tar.gz", "zcat \"%s\" | tar -xf -"), - (".tgz", "zcat \"%s\" | tar -xf -"), - (".tar.bz", "bzcat \"%s\" | tar -xf -"), - (".zip", "unzip \"%s\""), + (".tar.Z", "zcat \"%s\" | tar -xf -"), + (".taz", "zcat \"%s\" | tar -xf -"), + (".tar.gz", "zcat \"%s\" | tar -xf -"), + (".tgz", "zcat \"%s\" | tar -xf -"), + (".tar.bz", "bzcat \"%s\" | tar -xf -"), + (".zip", "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 installDir: - installDir = DEFAULT_INSTALLDIR - if not pimpDatabase: - pimpDatabase = DEFAULT_PIMPDATABASE - self.flavorOrder = flavorOrder - self.downloadDir = downloadDir - self.buildDir = buildDir - self.installDir = installDir - self.pimpDatabase = pimpDatabase - - 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) - + """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 installDir: + installDir = DEFAULT_INSTALLDIR + if not pimpDatabase: + pimpDatabase = DEFAULT_PIMPDATABASE + self.flavorOrder = flavorOrder + self.downloadDir = downloadDir + self.buildDir = buildDir + self.installDir = installDir + self.pimpDatabase = pimpDatabase + + 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._urllist = [] - self._version = "" - self._maintainer = "" - 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 - dict = plistlib.Plist.fromFile(fp) - # Test here for Pimp version, etc - if not included: - self._version = dict.get('Version', '0.1') - if self._version != PIMP_VERSION: - sys.stderr.write("Warning: database version %s does not match %s\n" - % (self._version, PIMP_VERSION)) - self._maintainer = dict.get('Maintainer', '') - self._description = dict.get('Description', '') - self._appendPackages(dict['Packages']) - others = dict.get('Include', []) - for url in others: - self.appendURL(url, included=1) - - def _appendPackages(self, packages): - """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) - flavor = p.get('Flavor') - if flavor == 'source': - pkg = PimpPackage_source(self, p) - elif flavor == 'binary': - pkg = PimpPackage_binary(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()) - dict = { - 'Version': self._version, - 'Maintainer': self._maintainer, - 'Description': self._description, - 'Packages': packages - } - plist = plistlib.Plist(**dict) - 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 - + """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._urllist = [] + self._version = "" + self._maintainer = "" + 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 + dict = plistlib.Plist.fromFile(fp) + # Test here for Pimp version, etc + if not included: + self._version = dict.get('Version', '0.1') + if self._version != PIMP_VERSION: + sys.stderr.write("Warning: database version %s does not match %s\n" + % (self._version, PIMP_VERSION)) + self._maintainer = dict.get('Maintainer', '') + self._description = dict.get('Description', '') + self._appendPackages(dict['Packages']) + others = dict.get('Include', []) + for url in others: + self.appendURL(url, included=1) + + def _appendPackages(self, packages): + """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) + flavor = p.get('Flavor') + if flavor == 'source': + pkg = PimpPackage_source(self, p) + elif flavor == 'binary': + pkg = PimpPackage_binary(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()) + dict = { + 'Version': self._version, + 'Maintainer': self._maintainer, + 'Description': self._description, + 'Packages': packages + } + plist = plistlib.Plist(**dict) + 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" + "Name", + "Version", + "Flavor", + "Description", + "Home-page", + "Download-URL", + "Install-test", + "Install-command", + "Pre-install-command", + "Post-install-command", + "Prerequisites", + "MD5Sum" ] class PimpPackage: - """Class representing a single package.""" - - def __init__(self, db, dict): - self._db = db - name = dict["Name"] - for k in dict.keys(): - if not k in ALLOWED_KEYS: - sys.stderr.write("Warning: %s: unknown key %s\n" % (name, k)) - self._dict = dict - - def __getitem__(self, key): - return self._dict[key] - - def name(self): return self._dict['Name'] - def version(self): return self._dict['Version'] - def flavor(self): return self._dict['Flavor'] - def description(self): return self._dict['Description'] - def homepage(self): return self._dict.get('Home-page') - def downloadURL(self): return self._dict['Download-URL'] - - 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 not self._dict.get('Download-URL'): - # 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'): - return [(None, - "%s: This package needs to be installed manually (no Download-URL field)" % - 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.description() - rv.append((pkg, descr)) - return rv - - def _cmd(self, 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() - - 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 - if self._cmd(output, self._db.preferences.downloadDir, - "curl", - "--output", self.archiveFilename, - self._dict['Download-URL']): - 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, cmd in ARCHIVE_FORMATS: - if filename[-len(ext):] == ext: - break - else: - return "unknown extension for archive file: %s" % filename - self.basename = filename[:-len(ext)] - cmd = cmd % self.archiveFilename - if self._cmd(output, self._db.preferences.buildDir, cmd): - return "unpack command failed" - - 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['Download-URL']: - return "%s: This package needs to be installed manually (no Download-URL field)" % _fmtpackagename(self) - 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) + """Class representing a single package.""" + + def __init__(self, db, dict): + self._db = db + name = dict["Name"] + for k in dict.keys(): + if not k in ALLOWED_KEYS: + sys.stderr.write("Warning: %s: unknown key %s\n" % (name, k)) + self._dict = dict + + def __getitem__(self, key): + return self._dict[key] + + def name(self): return self._dict['Name'] + def version(self): return self._dict['Version'] + def flavor(self): return self._dict['Flavor'] + def description(self): return self._dict['Description'] + def homepage(self): return self._dict.get('Home-page') + def downloadURL(self): return self._dict['Download-URL'] + + 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 not self._dict.get('Download-URL'): + # 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'): + return [(None, + "%s: This package needs to be installed manually (no Download-URL field)" % + 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.description() + rv.append((pkg, descr)) + return rv + + def _cmd(self, 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() + + 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 + if self._cmd(output, self._db.preferences.downloadDir, + "curl", + "--output", self.archiveFilename, + self._dict['Download-URL']): + 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, cmd in ARCHIVE_FORMATS: + if filename[-len(ext):] == ext: + break + else: + return "unknown extension for archive file: %s" % filename + self.basename = filename[:-len(ext)] + cmd = cmd % self.archiveFilename + if self._cmd(output, self._db.preferences.buildDir, cmd): + return "unpack command failed" + + 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['Download-URL']: + return "%s: This package needs to be installed manually (no Download-URL field)" % _fmtpackagename(self) + 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) 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.""" - print 'PimpPackage_binary installPackageOnly' - - msgs = [] - if self._dict.has_key('Pre-install-command'): - msg.append("%s: Pre-install-command ignored" % self.fullname()) - if self._dict.has_key('Install-command'): - msgs.append("%s: Install-command ignored" % self.fullname()) - if self._dict.has_key('Post-install-command'): - msgs.append("%s: Post-install-command ignored" % self.fullname()) - - self.beforeInstall() + 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.""" + print 'PimpPackage_binary installPackageOnly' + + msgs = [] + if self._dict.has_key('Pre-install-command'): + msg.append("%s: Pre-install-command ignored" % self.fullname()) + if self._dict.has_key('Install-command'): + msgs.append("%s: Install-command ignored" % self.fullname()) + if self._dict.has_key('Post-install-command'): + msgs.append("%s: Post-install-command ignored" % self.fullname()) + + self.beforeInstall() - # Install by unpacking - filename = os.path.split(self.archiveFilename)[1] - for ext, cmd in ARCHIVE_FORMATS: - if filename[-len(ext):] == ext: - break - else: - return "unknown extension for archive file: %s" % filename - - # Extract the files in the root folder. - cmd = cmd % self.archiveFilename - if self._cmd(output, "/", cmd): - return "unpack command failed" - - self.afterInstall() - - if self._dict.has_key('Post-install-command'): - if self._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 - - + # Install by unpacking + filename = os.path.split(self.archiveFilename)[1] + for ext, cmd in ARCHIVE_FORMATS: + if filename[-len(ext):] == ext: + break + else: + return "unknown extension for archive file: %s" % filename + + # Extract the files in the root folder. + cmd = cmd % self.archiveFilename + if self._cmd(output, "/", cmd): + return "unpack command failed" + + self.afterInstall() + + if self._dict.has_key('Post-install-command'): + if self._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_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 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 self._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 not installcmd: - installcmd = '"%s" setup.py install' % sys.executable - if self._cmd(output, self._buildDirname, installcmd): - return "install %s: running \"%s\" failed" % \ - (self.fullname(), installcmd) - - self.afterInstall() - - if self._dict.has_key('Post-install-command'): - if self._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 - - + 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 self._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 not installcmd: + installcmd = '"%s" setup.py install' % sys.executable + if self._cmd(output, self._buildDirname, installcmd): + return "install %s: running \"%s\" failed" % \ + (self.fullname(), installcmd) + + self.afterInstall() + + if self._dict.has_key('Post-install-command'): + if self._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 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.insert(0, 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, force, recursive) - else: - self._curmessages.append("Requires: %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 - - - + """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.insert(0, 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, force, recursive) + else: + self._curmessages.append("Requires: %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): - """Engine for the main program""" - - prefs = PimpPreferences() - prefs.check() - 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.description() - pkgname = pkg.fullname() - else: - description = 'Error: no such package' - print "%-20.20s\t%s" % (pkgname, description) - if verbose: - print "\tHome page:\t", pkg.homepage() - print "\tDownload URL:\t", pkg.downloadURL() - 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 + """Engine for the main program""" + + prefs = PimpPreferences() + prefs.check() + 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.description() + pkgname = pkg.fullname() + else: + description = 'Error: no such package' + print "%-20.20s\t%s" % (pkgname, description) + if verbose: + print "\tHome page:\t", pkg.homepage() + print "\tDownload URL:\t", pkg.downloadURL() + 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 [-v] -s [package ...] List installed status" - print " pimp [-v] -l [package ...] Show package information" - print " pimp [-vf] -i package ... Install packages" - print " pimp -d Dump database to stdout" - print "Options:" - print " -v Verbose" - print " -f Force installation" - sys.exit(1) - - try: - opts, args = getopt.getopt(sys.argv[1:], "slifvd") - except getopt.Error: - _help() - if not opts and not args: - _help() - mode = None - force = 0 - verbose = 0 - 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 == '-i': - mode = 'install' - if o == '-f': - force = 1 - if o == '-v': - verbose = 1 - if not mode: - _help() - _run(mode, verbose, force, args) - + """Minimal commandline tool to drive pimp.""" + + import getopt + def _help(): + print "Usage: pimp [-v] -s [package ...] List installed status" + print " pimp [-v] -l [package ...] Show package information" + print " pimp [-vf] -i package ... Install packages" + print " pimp -d Dump database to stdout" + print "Options:" + print " -v Verbose" + print " -f Force installation" + sys.exit(1) + + try: + opts, args = getopt.getopt(sys.argv[1:], "slifvd") + except getopt.Error: + _help() + if not opts and not args: + _help() + mode = None + force = 0 + verbose = 0 + 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 == '-i': + mode = 'install' + if o == '-f': + force = 1 + if o == '-v': + verbose = 1 + if not mode: + _help() + _run(mode, verbose, force, args) + if __name__ == '__main__': - main() - - + main() + + diff --git a/Lib/plat-mac/plistlib.py b/Lib/plat-mac/plistlib.py index 9c914d208c0..40e2675afbe 100644 --- a/Lib/plat-mac/plistlib.py +++ b/Lib/plat-mac/plistlib.py @@ -33,29 +33,29 @@ The plist data has (limited) support through the Date class. Generate Plist example: - pl = Plist( - aString="Doodah", - aList=["A", "B", 12, 32.1, [1, 2, 3]], - aFloat = 0.1, - anInt = 728, - aDict=Dict( - anotherString="", - aUnicodeValue=u'M\xe4ssig, Ma\xdf', - aTrueValue=True, - aFalseValue=False, - ), - someData = Data(""), - someMoreData = Data("" * 10), - aDate = Date(time.mktime(time.gmtime())), - ) - # unicode keys are possible, but a little awkward to use: - pl[u'\xc5benraa'] = "That was a unicode key." - pl.write(fileName) + pl = Plist( + aString="Doodah", + aList=["A", "B", 12, 32.1, [1, 2, 3]], + aFloat = 0.1, + anInt = 728, + aDict=Dict( + anotherString="", + aUnicodeValue=u'M\xe4ssig, Ma\xdf', + aTrueValue=True, + aFalseValue=False, + ), + someData = Data(""), + someMoreData = Data("" * 10), + aDate = Date(time.mktime(time.gmtime())), + ) + # unicode keys are possible, but a little awkward to use: + pl[u'\xc5benraa'] = "That was a unicode key." + pl.write(fileName) Parse Plist example: - pl = Plist.fromFile(pathOrFile) - print pl.aKey + pl = Plist.fromFile(pathOrFile) + print pl.aKey """ @@ -71,40 +71,40 @@ INDENT = "\t" class DumbXMLWriter: - def __init__(self, file): - self.file = file - self.stack = [] - self.indentLevel = 0 + def __init__(self, file): + self.file = file + self.stack = [] + self.indentLevel = 0 - def beginElement(self, element): - self.stack.append(element) - self.writeln("<%s>" % element) - self.indentLevel += 1 + 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("" % element) + def endElement(self, element): + assert self.indentLevel > 0 + assert self.stack.pop() == element + self.indentLevel -= 1 + self.writeln("" % element) - def simpleElement(self, element, value=None): - if value: - value = _encode(value) - self.writeln("<%s>%s" % (element, value, element)) - else: - self.writeln("<%s/>" % element) + def simpleElement(self, element, value=None): + if value: + value = _encode(value) + self.writeln("<%s>%s" % (element, value, element)) + else: + self.writeln("<%s/>" % element) - def writeln(self, line): - if line: - self.file.write(self.indentLevel * INDENT + line + "\n") - else: - self.file.write("\n") + def writeln(self, line): + if line: + self.file.write(self.indentLevel * INDENT + line + "\n") + else: + self.file.write("\n") def _encode(text): - text = text.replace("&", "&") - text = text.replace("<", "<") - return text.encode("utf-8") + text = text.replace("&", "&") + text = text.replace("<", "<") + return text.encode("utf-8") PLISTHEADER = """\ @@ -114,323 +114,323 @@ PLISTHEADER = """\ class PlistWriter(DumbXMLWriter): - def __init__(self, file): - file.write(PLISTHEADER) - DumbXMLWriter.__init__(self, file) + def __init__(self, file): + file.write(PLISTHEADER) + DumbXMLWriter.__init__(self, file) - 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): - # should perhaps use repr() for better precision? - self.simpleElement("real", str(value)) - elif isinstance(value, (dict, Dict)): - self.writeDict(value) - elif isinstance(value, Data): - self.writeData(value) - elif isinstance(value, Date): - self.simpleElement("date", value.toString()) - elif isinstance(value, (tuple, list)): - self.writeArray(value) - else: - assert 0, "unsuported type: %s" % type(value) + 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): + # should perhaps use repr() for better precision? + self.simpleElement("real", str(value)) + elif isinstance(value, (dict, Dict)): + self.writeDict(value) + elif isinstance(value, Data): + self.writeData(value) + elif isinstance(value, Date): + self.simpleElement("date", value.toString()) + elif isinstance(value, (tuple, list)): + self.writeArray(value) + else: + assert 0, "unsuported type: %s" % type(value) - def writeData(self, data): - self.beginElement("data") - for line in data.asBase64().split("\n"): - if line: - self.writeln(line) - self.endElement("data") + def writeData(self, data): + self.beginElement("data") + for line in data.asBase64().split("\n"): + if line: + self.writeln(line) + self.endElement("data") - def writeDict(self, d): - self.beginElement("dict") - items = d.items() - items.sort() - for key, value in items: - assert isinstance(key, (str, unicode)), "keys must be strings" - self.simpleElement("key", key) - self.writeValue(value) - self.endElement("dict") + def writeDict(self, d): + self.beginElement("dict") + items = d.items() + items.sort() + for key, value in items: + assert isinstance(key, (str, unicode)), "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") + def writeArray(self, array): + self.beginElement("array") + for value in array: + self.writeValue(value) + self.endElement("array") class Dict: - """Dict wrapper for convenient access of values through attributes.""" + """Dict wrapper for convenient access of values through attributes.""" - def __init__(self, **kwargs): - self.__dict__.update(kwargs) + def __init__(self, **kwargs): + self.__dict__.update(kwargs) - def __cmp__(self, other): - if isinstance(other, self.__class__): - return cmp(self.__dict__, other.__dict__) - elif isinstance(other, dict): - return cmp(self.__dict__, other) - else: - return cmp(id(self), id(other)) + def __cmp__(self, other): + if isinstance(other, self.__class__): + return cmp(self.__dict__, other.__dict__) + elif isinstance(other, dict): + return cmp(self.__dict__, other) + else: + return cmp(id(self), id(other)) - def __str__(self): - return "%s(**%s)" % (self.__class__.__name__, self.__dict__) - __repr__ = __str__ + def __str__(self): + return "%s(**%s)" % (self.__class__.__name__, self.__dict__) + __repr__ = __str__ - def copy(self): - return self.__class__(**self.__dict__) + def copy(self): + return self.__class__(**self.__dict__) - def __getattr__(self, attr): - """Delegate everything else to the dict object.""" - return getattr(self.__dict__, attr) + def __getattr__(self, attr): + """Delegate everything else to the dict object.""" + return getattr(self.__dict__, attr) class Plist(Dict): - """The main Plist object. Basically a dict (the toplevel object - of a plist is a dict) with two additional methods to read from - and write to files. - """ + """The main Plist object. Basically a dict (the toplevel object + of a plist is a dict) with two additional methods to read from + and write to files. + """ - def fromFile(cls, pathOrFile): - didOpen = 0 - if not hasattr(pathOrFile, "write"): - pathOrFile = open(pathOrFile) - didOpen = 1 - p = PlistParser() - plist = p.parse(pathOrFile) - if didOpen: - pathOrFile.close() - return plist - fromFile = classmethod(fromFile) + def fromFile(cls, pathOrFile): + didOpen = 0 + if not hasattr(pathOrFile, "write"): + pathOrFile = open(pathOrFile) + didOpen = 1 + p = PlistParser() + plist = p.parse(pathOrFile) + if didOpen: + pathOrFile.close() + return plist + fromFile = classmethod(fromFile) - def write(self, pathOrFile): - if not hasattr(pathOrFile, "write"): - pathOrFile = open(pathOrFile, "w") - didOpen = 1 - else: - didOpen = 0 + def write(self, pathOrFile): + if not hasattr(pathOrFile, "write"): + pathOrFile = open(pathOrFile, "w") + didOpen = 1 + else: + didOpen = 0 - writer = PlistWriter(pathOrFile) - writer.writeln("") - writer.writeDict(self.__dict__) - writer.writeln("") + writer = PlistWriter(pathOrFile) + writer.writeln("") + writer.writeDict(self.__dict__) + writer.writeln("") - if didOpen: - pathOrFile.close() + if didOpen: + pathOrFile.close() class Data: - """Wrapper for binary data.""" + """Wrapper for binary data.""" - def __init__(self, data): - self.data = data + def __init__(self, data): + self.data = data - def fromBase64(cls, data): - import base64 - return cls(base64.decodestring(data)) - fromBase64 = classmethod(fromBase64) + def fromBase64(cls, data): + import base64 + return cls(base64.decodestring(data)) + fromBase64 = classmethod(fromBase64) - def asBase64(self): - import base64 - return base64.encodestring(self.data) + def asBase64(self): + import base64 + return base64.encodestring(self.data) - 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 __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)) + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self.data)) class Date: - """Primitive date wrapper, uses time floats internally, is agnostic - about time zones. - """ + """Primitive date wrapper, uses time floats internally, is agnostic + about time zones. + """ - def __init__(self, date): - if isinstance(date, str): - from xml.utils.iso8601 import parse - date = parse(date) - self.date = date + def __init__(self, date): + if isinstance(date, str): + from xml.utils.iso8601 import parse + date = parse(date) + self.date = date - def toString(self): - from xml.utils.iso8601 import tostring - return tostring(self.date) + def toString(self): + from xml.utils.iso8601 import tostring + return tostring(self.date) - def __cmp__(self, other): - if isinstance(other, self.__class__): - return cmp(self.date, other.date) - elif isinstance(other, (int, float)): - return cmp(self.date, other) - else: - return cmp(id(self), id(other)) + def __cmp__(self, other): + if isinstance(other, self.__class__): + return cmp(self.date, other.date) + elif isinstance(other, (int, float)): + return cmp(self.date, other) + else: + return cmp(id(self), id(other)) - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self.toString())) + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self.toString())) class PlistParser: - def __init__(self): - self.stack = [] - self.currentKey = None - self.root = None + def __init__(self): + self.stack = [] + self.currentKey = None + self.root = None - def parse(self, file): - from xml.parsers.expat import ParserCreate - parser = ParserCreate() - parser.StartElementHandler = self.handleBeginElement - parser.EndElementHandler = self.handleEndElement - parser.CharacterDataHandler = self.handleData - parser.ParseFile(file) - return self.root + def parse(self, file): + from xml.parsers.expat import ParserCreate + parser = ParserCreate() + parser.StartElementHandler = self.handleBeginElement + parser.EndElementHandler = self.handleEndElement + parser.CharacterDataHandler = self.handleData + parser.ParseFile(file) + return self.root - def handleBeginElement(self, element, attrs): - self.data = [] - handler = getattr(self, "begin_" + element, None) - if handler is not None: - handler(attrs) + 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 handleEndElement(self, element): + handler = getattr(self, "end_" + element, None) + if handler is not None: + handler() - def handleData(self, data): - self.data.append(data) + 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 - assert self.root is value - else: - self.stack[-1].append(value) + 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 + assert self.root is 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 + def getData(self): + data = "".join(self.data) + try: + data = data.encode("ascii") + except UnicodeError: + pass + self.data = [] + return data - # element handlers + # element handlers - def begin_dict(self, attrs): - if self.root is None: - self.root = d = Plist() - else: - d = Dict() - self.addObject(d) - self.stack.append(d) - def end_dict(self): - self.stack.pop() + def begin_dict(self, attrs): + if self.root is None: + self.root = d = Plist() + else: + d = Dict() + self.addObject(d) + self.stack.append(d) + def end_dict(self): + self.stack.pop() - def end_key(self): - self.currentKey = self.getData() + 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 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(Date(self.getData())) + 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(Date(self.getData())) # cruft to support booleans in Python <= 2.3 import sys if sys.version_info[:2] < (2, 3): - # Python 2.2 and earlier: no booleans - # Python 2.2.x: booleans are ints - class bool(int): - """Imitation of the Python 2.3 bool object.""" - def __new__(cls, value): - return int.__new__(cls, not not value) - def __repr__(self): - if self: - return "True" - else: - return "False" - True = bool(1) - False = bool(0) + # Python 2.2 and earlier: no booleans + # Python 2.2.x: booleans are ints + class bool(int): + """Imitation of the Python 2.3 bool object.""" + def __new__(cls, value): + return int.__new__(cls, not not value) + def __repr__(self): + if self: + return "True" + else: + return "False" + True = bool(1) + False = bool(0) else: - # Bind the boolean builtins to local names - True = True - False = False - bool = bool + # Bind the boolean builtins to local names + True = True + False = False + bool = bool if __name__ == "__main__": - from StringIO import StringIO - import time - if len(sys.argv) == 1: - pl = Plist( - aString="Doodah", - aList=["A", "B", 12, 32.1, [1, 2, 3]], - aFloat = 0.1, - anInt = 728, - aDict=Dict( - anotherString="", - aUnicodeValue=u'M\xe4ssig, Ma\xdf', - aTrueValue=True, - aFalseValue=False, - ), - someData = Data(""), - someMoreData = Data("" * 10), - aDate = Date(time.mktime(time.gmtime())), - ) - elif len(sys.argv) == 2: - pl = Plist.fromFile(sys.argv[1]) - else: - print "Too many arguments: at most 1 plist file can be given." - sys.exit(1) + from StringIO import StringIO + import time + if len(sys.argv) == 1: + pl = Plist( + aString="Doodah", + aList=["A", "B", 12, 32.1, [1, 2, 3]], + aFloat = 0.1, + anInt = 728, + aDict=Dict( + anotherString="", + aUnicodeValue=u'M\xe4ssig, Ma\xdf', + aTrueValue=True, + aFalseValue=False, + ), + someData = Data(""), + someMoreData = Data("" * 10), + aDate = Date(time.mktime(time.gmtime())), + ) + elif len(sys.argv) == 2: + pl = Plist.fromFile(sys.argv[1]) + else: + print "Too many arguments: at most 1 plist file can be given." + sys.exit(1) - # unicode keys are possible, but a little awkward to use: - pl[u'\xc5benraa'] = "That was a unicode key." - f = StringIO() - pl.write(f) - xml = f.getvalue() - print xml - f.seek(0) - pl2 = Plist.fromFile(f) - assert pl == pl2 - f = StringIO() - pl2.write(f) - assert xml == f.getvalue() - #print repr(pl2) + # unicode keys are possible, but a little awkward to use: + pl[u'\xc5benraa'] = "That was a unicode key." + f = StringIO() + pl.write(f) + xml = f.getvalue() + print xml + f.seek(0) + pl2 = Plist.fromFile(f) + assert pl == pl2 + f = StringIO() + pl2.write(f) + assert xml == f.getvalue() + #print repr(pl2) diff --git a/Lib/plat-mac/videoreader.py b/Lib/plat-mac/videoreader.py index 615328714c0..646c72628de 100644 --- a/Lib/plat-mac/videoreader.py +++ b/Lib/plat-mac/videoreader.py @@ -13,280 +13,280 @@ from Carbon import Qdoffs from Carbon import QDOffscreen from Carbon import Res try: - import MediaDescr + import MediaDescr except ImportError: - def _audiodescr(data): - return None + def _audiodescr(data): + return None else: - def _audiodescr(data): - return MediaDescr.SoundDescription.decode(data) + def _audiodescr(data): + return MediaDescr.SoundDescription.decode(data) try: - from imgformat import macrgb + from imgformat import macrgb except ImportError: - macrgb = "Macintosh RGB format" + 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 - + 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 __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 __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 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 + 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 - + 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) - + _test() + sys.exit(1) +