Commits

Ronald Oussoren  committed 6c9fa20

Drop sandbox version of Scripts/CodeGenerators.

  • Participants
  • Parent commits 7144c7d
  • Branches pyobjc-ancient

Comments (0)

Files changed (8)

File sandbox/CodeGenerators/__init__.py

Empty file removed.

File sandbox/CodeGenerators/cocoa_generator.py

-#
-# This script generates part of the python-wrappers around Cocoa.
-#
-# This script is based on some (not to clever) regular expressions, and seems
-# to work pretty well with the current version of the Cocoa headers.
-#
-# NOTES:
-# - This script is probably MacOSX specific.
-# - This script should be rewritten, it's getting unmaintainable.
-#
-import enum_generator
-import strconst_generator
-import var_generator
-import func_collector
-import func_builder
-import os
-import sys
-from dupfile import dupfile
-
-#
-# This script contains some MacOS X version dependencies. Because uname
-# doesn't tell anything usefull, we use sw_vers to find the actual OS version.
-#
-import os
-import sys
-VER=None
-
-if sys.platform == "darwin":
-    fd = os.popen('/usr/bin/sw_vers', 'r')
-    for ln in fd.readlines():
-        if ln.startswith('ProductVersion:'):
-            VER=ln.split()[-1]
-    fd.close()
-    fd = None
-    VER = 'MacOS X ' + '.'.join(VER.split('.')[:2])
-
-    FRAMEWORKS="/System/Library/Frameworks"
-
-    ADDRESSBOOK_HDRS=os.path.join(FRAMEWORKS, "AddressBook.framework", "Headers")
-    APPKIT_HDRS=os.path.join(FRAMEWORKS, "AppKit.framework", "Headers")
-    FOUNDATION_HDRS=os.path.join(FRAMEWORKS, "Foundation.framework", "Headers")
-    FOUNDATION_FUNCTION_PREFIX="FOUNDATION_EXPORT"
-    FOUNDATION_INLINE_PREFIX='FOUNDATION_STATIC_INLINE'
-    FOUNDATION_VAR_PREFIX="FOUNDATION_EXPORT"
-
-    IB_HDRS=os.path.join(FRAMEWORKS, "InterfaceBuilder.framework", "Headers")
-    PREFPANES_HDRS=os.path.join(FRAMEWORKS, "PreferencePanes.framework", "Headers")
-    SECINT_HDRS=os.path.join(FRAMEWORKS, "SecurityInterface.framework", "Headers")
-    if not os.path.exists(SECINT_HDRS):
-        SECINT_HDRS=None
-
-    WEBKIT_HDRS=os.path.join(FRAMEWORKS, "WebKit.framework", "Headers")
-    EXCHND_HDRS=os.path.join(FRAMEWORKS, "ExceptionHandling.framework", "Headers")
-
-else:
-    # This is probably incorrect, and was added to help a future
-    # port to GNUstep
-    x = os.uname()
-    VER = x[0] + ' ' + x[2]
-
-    HDR_BASE=os.environ.get('GNUSTEP_SYSTEM_ROOT')
-    HDR_BASE=os.path.join(HDR_BASE, "Library", "Headers")
-
-    ADDRESSBOOK_HDRS=os.path.join(HDR_BASE, "AddressBook")
-    if not os.path.exists(ADDRESSBOOK_HDRS):
-        ADDRESSBOOK_HDRS=None
-
-    APPKIT_HDRS=os.path.join(HDR_BASE, "AppKit")
-    if not os.path.exists(APPKIT_HDRS):
-        APPKIT_HDRS=None
-
-    FOUNDATION_HDRS=os.path.join(HDR_BASE, "Foundation")
-    FOUNDATION_FUNCTION_PREFIX="GS_EXPORT"
-    FOUNDATION_INLINE_PREFIX='GS_GEOM_SCOPE'
-    FOUNDATION_VAR_PREFIX="GS_EXPORT"
-    if not os.path.exists(FOUNDATION_HDRS):
-        FOUNDATION_HDRS=None
-
-    IB_HDRS=os.path.join(HDR_BASE, "InterfaceBuilder")
-    if not os.path.exists(IB_HDRS):
-        IB_HDRS=None
-
-    PREFPANES_HDRS=os.path.join(HDR_BASE, "PreferencePanes")
-    if not os.path.exists(PREFPANES_HDRS):
-        PREFPANES_HDRS=None
-
-    WEBKIT_HDRS=os.path.join(HDR_BASE, "WebKit")
-    if not os.path.exists(WEBKIT_HDRS):
-        WEBKIT_HDRS=None
-
-    EXCHND_HDRS=os.path.join(HDR_BASE, "ExceptionHandling")
-    if not os.path.exists(EXCHND_HDRS):
-        EXCHND_HDRS=None
-
-    SECINT_HDRS=os.path.join(HDR_BASE, "SecurityInterface")
-    if not os.path.exists(SECINT_HDRS):
-        SECINT_HDRS=None
-
-
-if not os.path.isdir('Modules'):
-    print "Run me from the root of the PyObjC source tree"
-    sys.exit(1)
-
-if not os.path.exists('build'):
-    os.mkdir('build')
-
-if not os.path.exists('build/codegen'):
-    os.mkdir('build/codegen')
-
-
-
-def filterAddressBookHeaders(fn):
-    if fn[-3:] == 'C.h':
-        return 0
-
-    if fn == 'ABPeoplePickerView.h':
-        return 0
-
-    return 1
-
-if FOUNDATION_HDRS is not None:
-    enum_generator.generate(
-            FOUNDATION_HDRS,
-            'build/codegen/_Fnd_Enum.inc')
-    strconst_generator.generate(
-            FOUNDATION_HDRS,
-            'build/codegen/_Fnd_Str.inc',
-            ignore=(
-                # Declared on GNUstep, but not actually inside the
-                # shared lib?
-                'ConnectionBecameInvalidNotification',
-            )
-    )
-    FOUNDATION_IGNORE_LIST=(
-        # All have types that are not (yet) mapped to python
-        "NSNonOwnedPointerHashCallBacks",
-        "NSNonRetainedObjectHashCallBacks",
-        "NSObjectHashCallBacks",
-        "NSOwnedObjectIdentityHashCallBacks",
-        "NSOwnedPointerHashCallBacks",
-        "NSPointerToStructHashCallBacks",
-        "NSIntMapKeyCallBacks",
-        "NSNonOwnedPointerMapKeyCallBacks",
-        "NSNonOwnedPointerOrNullMapKeyCallBacks",
-        "NSNonRetainedObjectMapKeyCallBacks",
-        "NSObjectMapKeyCallBacks",
-        "NSOwnedPointerMapKeyCallBacks",
-        "NSIntMapValueCallBacks",
-        "NSNonOwnedPointerMapValueCallBacks",
-        "NSObjectMapValueCallBacks",
-        "NSNonRetainedObjectMapValueCallBacks",
-        "NSOwnedPointerMapValueCallBacks",
-        "NSIntHashCallBacks",
-        "NSHangOnMallocError",
-    )
-
-    var_generator.generate(
-            FOUNDATION_HDRS,
-            'build/codegen/_Fnd_Var.inc',
-            FOUNDATION_VAR_PREFIX,
-            FOUNDATION_IGNORE_LIST)
-
-    FOUNDATION_IGNORE_LIST=(
-        # Private functions
-        '_NSAddHandler2(',
-        '_NSRemoveHandler2(',
-        '_NSExceptionObjectFromHandler2(',
-        '_NSAutoreleaseNoPool(',
-        '_NSAutoreleaseFreedObject(',
-        '_NSAutoreleaseHighWaterLog(',
-        'NXReadNSObjectFromCoder(',
-
-
-        # List of functions that are not usefull from Python:
-        'NSFrameAddress(',
-        'NSReturnAddress(',
-        'NSRecordAllocationEvent(',
-        'NSCreateHashTableWithZone(',
-        'NSCreateHashTable(',
-        'NSFreeHashTable(',
-        'NSResetHashTable(',
-        'NSCompareHashTables(',
-        'NSCopyHashTableWithZone(',
-        'NSHashGet(',
-        'NSHashInsert(',
-        'NSHashInsertKnownAbsent(',
-        'NSHashInsertIfAbsent(',
-        'NSHashRemove(',
-        'NSEnumerateHashTable(',
-        'NSNextHashEnumeratorItem(',
-        'NSEndHashTableEnumeration(',
-        'NSCountHashTable(',
-        'NSStringFromHashTable(',
-        'NSAllHashTableObjects(',
-        'NSJavaClassesFromPath(',
-        'NSJavaClassesForBundle(',
-        'NSCreateMapTableWithZone(',
-        'NSCreateMapTable(',
-        'NSFreeMapTable(',
-        'NSResetMapTable(',
-        'NSCompareMapTables(',
-        'NSCopyMapTableWithZone(',
-        'NSMapMember(',
-        'NSMapGet(',
-        'NSMapInsert(',
-        'NSMapInsertKnownAbsent(',
-        'NSMapInsertIfAbsent(',
-        'NSMapRemove(',
-        'NSEnumerateMapTable(',
-        'NSNextMapEnumeratorPair(',
-        'NSEndMapTableEnumeration(',
-        'NSCountMapTable(',
-        'NSStringFromMapTable(',
-        'NSAllMapTableKeys(',
-        'NSAllMapTableValues(',
-        'NSGetSizeAndAlignment(', # Hmm, shouldn't we use this in the bridge?
-        'NSLogv(',
-        'NSLog(',
-        'NSAllocateObject(',
-        'NSCopyObject(',
-        'NSShouldRetainWithZone(',
-        'NSAllocateMemoryPages(',
-        'NSDeallocateMemoryPages(',
-        'NSCopyMemoryPages(',
-
-
-        # List of manually wrapped functions:
-        'NSFileTypeForHFSTypeCode(',
-        'NSHFSTypeCodeFromFileType(',
-        'NSStringFromPoint',
-        'NSDivideRect(',
-
-        # Zones might be usefull someday
-        'NSCreateZone(',
-        'NSRecycleZone(',
-        'NSSetZoneName(',
-        'NSZoneName(',
-        'NSZoneFromPointer(',
-        'NSZoneMalloc(',
-        'NSZoneCalloc(',
-        'NSZoneRealloc(',
-        'NSZoneFree(',
-        'NSDefaultMallocZone(',
-
-        # TODO
-        'NSUncaughtExceptionHandler(',
-        'NSSetUncaughtExceptionHandler(',
-        'NSGetUncaughtExceptionHandler(',
-
-        # GNUstep functions
-        'GSDebugAllocationClassList(',
-        '_NSAddHandler(',
-        '_NSRemoveHandler(',
-        'NSStringFromMapTable(',
-        'GSLogLock(',
-        'NSLogv (',
-        'NSLog (',
-        'NSCreateZone (',
-        'NSZoneFromPointer (',
-        'NSZoneCalloc (',
-        'NSSetZoneName (',
-        'NSAllocateMemoryPages (',
-        'NSDeallocateMemoryPages (',
-        'NSCopyMemoryPages (',
-        'GSDebugAllocation',
-        'NSStringFromMapTable (',
-        'NSDeallocateObject(',
-        'GSDebugFunctionMsg(',
-        'GSDebugMethodMsg(',
-    )
-
-    func_collector.generate(
-            FOUNDATION_HDRS,
-            'build/codegen/Foundation.prototypes',
-            FOUNDATION_FUNCTION_PREFIX,
-            FOUNDATION_IGNORE_LIST)
-
-    func_collector.generate(
-            FOUNDATION_HDRS,
-            'build/codegen/Foundation.prototype2',
-            FOUNDATION_INLINE_PREFIX,
-            FOUNDATION_IGNORE_LIST)
-
-
-
-    for arg in [
-        'NSSearchPathDomainMask', 'NSCalculationError',
-        'NSComparisonResult', 'NSInsertionPosition',
-        'NSNotificationCoalescing', 'NSNotificationCoalescing',
-        'NSRectEdge', 'NSRelativePosition',
-        'NSRoundingMode', 'NSSaveOptions', 'NSSearchPathDirectory',
-        'NSSearchPathDomainMask', 'NSTestComparisonOperation',
-        'NSURLHandleStatus', 'NSWhoseSubelementIdentifier']:
-        func_builder.TYPE_ALIASES[arg] = 'int'
-
-    func_builder.TYPE_ALIASES['NSGlyph'] = 'unsigned int'
-
-    func_builder.IGNORE_VARARGS.extend([
-        # Some of these are Foundation some are AppKit
-        'NSGetInformationalAlertPanel',
-        'NSRunAlertPanel',
-        'NSRunInformationalAlertPanel',
-        'NSRunCriticalAlertPanel',
-        'NSRunAlertPanelRelativeToWindow',
-        'NSRunInformationalAlertPanelRelativeToWindow',
-        'NSRunCriticalAlertPanelRelativeToWindow',
-        'NSBeginAlertSheet',
-        'NSBeginInformationalAlertSheet',
-        'NSBeginCriticalAlertSheet',
-        'NSGetAlertPanel',
-        'NSGetCriticalAlertPanel',
-    ])
-
-    def BeginSheetMapper(funcname, args):
-        new_args = []
-        for tp, name in args:
-            if name == 'contextInfo':
-                tp = 'PYOBJC_VOIDPTR'
-            new_args.append((tp, name))
-        return tuple(new_args)
-
-    func_builder.FUNC_MAP['NSBeginAlertSheet'] = BeginSheetMapper
-    func_builder.FUNC_MAP['NSBeginInformationalAlertSheet'] = BeginSheetMapper
-    func_builder.FUNC_MAP['NSBeginCriticalAlertSheet'] = BeginSheetMapper
-
-    fd = dupfile('build/codegen/_Fnd_Functions.inc', 'w')
-
-    func_builder.SIMPLE_TYPES['NSDecimal*'] = (
-            '\tresult = Decimal_New(%(varname)s);\n\tif (result == NULL) return NULL;',
-            'O&',
-            'Decimal_Convert, &%(varname)s'
-        )
-
-    structs = ['NSPoint', 'NSSize', 'NSRect', 'NSRange', 'NSSwappedFloat', 'NSSwappedDouble']
-    if sys.platform == 'darwin':
-        structs.append('NSTimeInterval')
-    for s in structs:
-        func_builder.SIMPLE_TYPES[s] = (
-            '\tresult = PyObjC_ObjCToPython(@encode(%s), (void*)&%%(varname)s); \n\tif (result == NULL) return NULL;'%s,
-            'O&',
-            'convert_%s, &%%(varname)s'%s
-        )
-        fd.write('''\
-
-    static inline int convert_%(type)s(PyObject* object, void* pvar)
-    {
-            int err;
-
-            err = PyObjC_PythonToObjC(@encode(%(type)s), object, pvar);
-            if (err == -1) {
-                    return 0;
-            }
-            return 1;
-    }
-    '''%{'type': s })
-
-    fd.write('typedef void* PYOBJC_VOIDPTR;\n')
-
-    funcs = func_builder.process_list(fd , file('build/codegen/Foundation.prototypes'))
-    funcs2 = func_builder.process_list(fd , file('build/codegen/Foundation.prototype2'))
-
-    # These are macro's
-    funcs3 = func_builder.process_list(fd, [
-        'NSString* NSLocalizedString(NSString* key, NSString* comment);',
-        'NSString* NSLocalizedStringFromTable(NSString* key, NSString* tableName, NSString* comment);',
-        'NSString* NSLocalizedStringFromTableInBundle(NSString* key, NSString* tableName, NSString* comment, NSBundle* bunlde);',
-    ])
-    func_builder.gen_method_table_entries(fd, funcs + funcs2 + funcs3)
-    fd = None
-    for s in structs:
-        del func_builder.SIMPLE_TYPES[s]
-
-
-if APPKIT_HDRS is not None:
-    enum_generator.generate(
-            APPKIT_HDRS,
-            'build/codegen/_App_Enum.inc')
-
-    strconst_generator.generate(
-            APPKIT_HDRS,
-            'build/codegen/_App_Str.inc')
-    APPKIT_PREFIX="APPKIT_EXTERN"
-    APPKIT_IGNORE_LIST=(
-        # First two have types that are not yet mapped
-        'NSIconSize',
-        'NSTokenSize',
-
-        # NSApp is a 'real' variable, will probably add get/set functions
-        'NSApp')
-
-    var_generator.generate(
-            APPKIT_HDRS,
-            'build/codegen/_App_Var.inc',
-            APPKIT_PREFIX,
-            APPKIT_IGNORE_LIST)
-
-    APPKIT_IGNORE_LIST=(
-        # List of manually wrapped functions:
-        'NSApplicationMain(',
-        'NSCountWindows(',
-        'NSCountWindowsForContext(',
-        'NSAvailableWindowDepths(',
-        'NSRectFillList(',
-        'NSGetWindowServerMemory(',
-        'NSDrawTiledRects(',
-        'NSDrawColorTiledRects(',
-        'NSRectFillListWithGrays(',
-        'NSRectFillListWithColors(',
-        'NSRectFillListUsingOperation(',
-        'NSRectFillListWithColorsUsingOperation(',
-        'NSRectClipList(',
-        'NSWindowList(',
-        'NSWindowListForContext(',
-        'NSBestDepth (',
-        'NSAvailableWindowDepths (',
-
-        #TODO:
-        'NSDrawBitmap(',
-    )
-
-    if VER == "MacOS X 10.1":
-        APPKIT_IGNORE_LIST = APPKIT_IGNORE_LIST + ('NSCopyBitmapFromGState',)
-
-    func_collector.generate(
-            APPKIT_HDRS,
-            'build/codegen/AppKit.prototypes',
-            APPKIT_PREFIX,
-            APPKIT_IGNORE_LIST)
-
-    func_builder.FUNC_MAP['NSShowAnimationEffect'] = BeginSheetMapper
-
-    fd = dupfile('build/codegen/_App_Functions.inc', 'w')
-    structs = ['NSAffineTransformStruct', 'NSRect', 'NSPoint']
-    for s in structs:
-        func_builder.SIMPLE_TYPES[s] = (
-            '\tresult = PyObjC_ObjCToPython(@encode(%s), (void*)&%%(varname)s); \n\tif (result == NULL) return NULL;'%s,
-            'O&',
-            'convert_%s, &%%(varname)s'%s
-        )
-        fd.write('''\
-    static inline int convert_%(type)s(PyObject* object, void* pvar)
-    {
-            int err;
-
-            err = PyObjC_PythonToObjC(@encode(%(type)s), object, pvar);
-            if (err == -1) {
-                    return 0;
-            }
-            return 1;
-    }
-    '''%{'type': s })
-
-    for arg in [
-        'NSApplicationTerminateReply', 'NSBackingStoreType',
-        'NSBezelStyle', 'NSBezierPathElement',
-        'NSBitmapImageFileType', 'NSBorderType', 'NSBoxType',
-        'NSButtonType', 'NSCellAttribute', 'NSCellImagePosition',
-        'NSCellStateValue', 'NSCellType', 'NSCompositingOperation',
-        'NSControlSize', 'NSControlTint', 'NSDocumentChangeType',
-        'NSDragOperation', 'NSDrawerState', 'NSEventType',
-        'NSFocusRingPlacement', 'NSFontAction', 'NSFontTraitMask',
-        'NSGlyph', 'NSGlyphInscription', 'NSGlyphLayoutMode',
-        'NSGlyphRelation', 'NSGradientType', 'NSImageAlignment',
-        'NSImageFrameStyle', 'NSImageInterpolation', 'NSImageScaling',
-        'NSInterfaceStyle', 'NSLayoutDirection', 'NSLayoutStatus',
-        'NSLineBreakMode', 'NSLineCapStyle', 'NSLineJoinStyle',
-        'NSLineMovementDirection', 'NSLineSweepDirection',
-        'NSMatrixMode', 'NSMultibyteGlyphPacking', 'NSOpenGLContextParameter',
-        'NSOpenGLGlobalOption', 'NSOpenGLPixelFormatAttribute',
-        'NSPopUpArrowPosition', 'NSPrinterTableStatus',
-        'NSPrintingOrientation', 'NSPrintingPageOrder',
-        'NSPrintingPaginationMode', 'NSProgressIndicatorThickness',
-        'NSQTMovieLoopMode', 'NSRequestUserAttentionType',
-        'NSRulerOrientation', 'NSSaveOperationType',
-        'NSScrollArrowPosition', 'NSScrollerArrow',
-        'NSScrollerPart', 'NSSelectionAffinity',
-        'NSSelectionDirection', 'NSSelectionGranularity',
-        'NSTabState', 'NSTabViewState', 'NSTableViewDropOperation',
-        'NSTextAlignment', 'NSTextTabType', 'NSTickMarkPosition',
-        'NSTIFFCompression', 'NSTitlePosition', 'NSToolbarDisplayMode',
-        'NSToolTipTag', 'NSTrackingRectTag', 'NSUsableScrollerParts',
-        'NSWindingRule', 'NSWindowDepth', 'NSWindowOrderingMode',
-        ]:
-        func_builder.TYPE_ALIASES[arg] = 'int'
-
-
-    fd.write('typedef void* PYOBJC_VOIDPTR;\n')
-    funcs = func_builder.process_list(fd, file('build/codegen/AppKit.prototypes'))
-
-    funcs2 = func_builder.process_list(fd, [
-
-            # This is a very ugly macro, it access 'glyphs' in the enclosing
-            # block ???
-            #'void NSGlyphInfoAtIndex(int IX);',
-        ])
-
-    func_builder.gen_method_table_entries(fd, funcs + funcs2)
-    for s in structs:
-        del func_builder.SIMPLE_TYPES[s]
-
-
-if ADDRESSBOOK_HDRS is not None:
-    enum_generator.generate(
-            ADDRESSBOOK_HDRS,
-            'build/codegen/_Addr_Enum.inc',
-            filter=filterAddressBookHeaders)
-    strconst_generator.generate(
-            ADDRESSBOOK_HDRS,
-                'build/codegen/_Addr_Str.inc',
-                filter=filterAddressBookHeaders)
-
-if PREFPANES_HDRS is not None:
-    enum_generator.generate(
-            PREFPANES_HDRS,
-            'build/codegen/_PreferencePanes_Enum.inc')
-    strconst_generator.generate(
-            PREFPANES_HDRS,
-            'build/codegen/_PreferencePanes_Str.inc')
-
-if IB_HDRS is not None:
-    enum_generator.generate(
-            IB_HDRS,
-            'build/codegen/_InterfaceBuilder_Enum.inc')
-    strconst_generator.generate(
-            IB_HDRS,
-            'build/codegen/_InterfaceBuilder_Str.inc')
-
-if WEBKIT_HDRS is not None:
-    enum_generator.generate(
-            WEBKIT_HDRS,
-            'build/codegen/_WebKit_Enum.inc',
-                ignore_files=['npapi.h', 'npruntime.h', 'npfunctions.h'])
-
-    # The two items on the ignore-list cause link errors,
-    # to-be-investigated.
-    strconst_generator.generate(WEBKIT_HDRS,
-                                'build/codegen/_WebKit_Str.inc',
-                                ignore=('WebElementImageAltStringKey',
-                                        'WebPreferencesChangedNotification')
-    )
-
-if EXCHND_HDRS is not None:
-    enum_generator.generate(
-            EXCHND_HDRS,
-            'build/codegen/_ExceptionHandling_Enum.inc')
-
-    # The two items on the ignore-list cause link errors,
-    # to-be-investigated.
-    strconst_generator.generate(
-        EXCHND_HDRS,
-        'build/codegen/_ExceptionHandling_Str.inc')
-
-
-if SECINT_HDRS is not None:
-    enum_generator.generate(
-            SECINT_HDRS,
-            'build/codegen/_SecInt_Enum.inc')
-    strconst_generator.generate(
-            SECINT_HDRS,
-            'build/codegen/_SecInt_Str.inc')

File sandbox/CodeGenerators/dupfile.py

-"""
-Implements class dupfile. This is a variant on file that won't actually change
-the fs representation of a file unless you write a different contents, used
-to avoid rebuilding the bridge on every call to setup.py
-"""
-import os
-
-def cmpfile(fn1, fn2):
-    return open(fn1).read() == open(fn2).read()
-
-class dupfile:
-    def __init__(self, fname, mode):
-        self.fname = fname
-        self.done = 0
-        self.tfile = fname + ".wrk"
-        self.mode = mode
-
-        if mode == 'w':
-            self.fp = open(self.tfile, "w")
-        else:
-            self.fp = open(self.fname, mode)
-
-
-    def read(self, bytes=None):
-        if bytes is None:
-            return self.fp.read()
-        else:
-            return self.fp.read(bytes)
-
-    def write(self, bytes):
-        self.fp.write(bytes)
-
-    def flush(self):
-        self.fp.flush()
-
-    def close(self):
-        self.fp.close()
-        self.fp = None
-        if self.mode == 'w':
-            if os.path.exists(self.fname) and cmpfile(self.tfile, self.fname):
-                os.unlink(self.tfile)
-            else:
-                os.rename(self.tfile, self.fname)
-        self.done = 1
-
-    def __del__(self):
-        if self.done:
-            return
-        if self.mode == 'w':
-            if self.fp is not None:
-                self.fp.close()
-                self.fp = None
-            if os.path.exists(self.fname) and cmpfile(self.tfile, self.fname):
-                os.unlink(self.tfile)
-            else:
-                os.rename(self.tfile, self.fname)

File sandbox/CodeGenerators/enum_generator.py

-# This script generates a constant table containing the enum values for
-# enumerations in the specified header file.
-#
-# This is script is rather fragile, and tuned to the MacOS 10.1 header-files.
-#
-# We should probably use bgen, but how does one use that tool?
-
-import re
-import os
-import sys
-from dupfile import dupfile
-
-START_RE=re.compile('(typedef[\w]|)enum.*{')
-START_RE2=re.compile('(typedef[\w]|)enum(?:\s+[A-Za-z_][A-Za-z0-9]*)?\s*$')
-END_RE=re.compile('}')
-IDENT_RE=re.compile('(^|[^A-Za-z_0-9])(?P<identifier>[A-Za-z_][A-Za-z_0-9]*)')
-LINE_COMMENT_RE=re.compile('//.*')
-SINGLE_LINE_RE=re.compile('enum.*{([^}]*)}')
-BLOCK_1_RE=re.compile('/\*([^*]|(\*[^/]))*\*/')
-BLOCK_S_RE=re.compile('/\*')
-BLOCK_E_RE=re.compile('\*/')
-
-DEFINE_RE=re.compile('^#\s*define\s+([A-Za-z_][A-Za-z0-9]*)\s+(\d+)$')
-
-def entry(fp, val):
-    if val.endswith('Mask'):
-        unsigned = 1
-    else:
-        unsigned = 0
-    fp.write('\t { "%s", %d, %s },\n'%(val, unsigned, val))
-
-def process_file(outfp, filename):
-    fp = open(filename, 'r')
-
-    outfp.write("\n\t/* From: %s */\n"%os.path.basename(filename))
-
-    in_enum = 0
-    in_comment = 0
-
-    for ln in fp.xreadlines():
-        ln = LINE_COMMENT_RE.sub('', ln)
-
-        m = DEFINE_RE.match(ln)
-        if m is not None:
-            name, value = m.group(1), m.group(2)
-            if name == 'nil':
-                # Grr, the compiler on GNUstep complains about this one
-                continue
-            entry(outfp, name)
-            continue
-
-        if not in_enum:
-            m = SINGLE_LINE_RE.search(ln)
-            if m:
-                values = m.group(1)
-                values = values.split(',')
-
-                for v in values:
-                    m = IDENT_RE.search(v)
-                    if not m:
-                        continue
-
-                    ident = m.group('identifier')
-                    entry(outfp, ident)
-            elif START_RE.search(ln):
-                in_enum = 1
-                need_brace=0
-            elif START_RE2.search(ln):
-                in_enum = 1
-                need_brace=1
-        else:
-            if in_comment:
-                m = BLOCK_E_RE.search(ln)
-                if not m:
-                    continue
-                ln = ln[m.end():]
-                in_comment = 0
-
-
-            if END_RE.match(ln):
-                in_enum = 0
-                continue
-
-            ln = BLOCK_1_RE.sub('', ln)
-            m = BLOCK_S_RE.search(ln)
-            if m:
-                in_comment = 1
-                ln = ln[:m.start()]
-
-            if need_brace:
-                if not ln.strip().startswith('{'):
-                    in_enum=0
-                    continue
-                need_brace = 0
-
-
-            m = IDENT_RE.search(ln)
-            if not m:
-                continue
-
-            ident = m.group('identifier')
-            if not ident in ['if', 'endif', 'else']:
-                entry(outfp, ident)
-
-
-def generate(dirname, fn = None, filter = lambda x: 1, ignore_files=()):
-    if not os.path.exists(dirname): return
-
-    if fn:
-        fp = dupfile(fn, 'w')
-    else:
-        fp = sys.stdout
-
-    fnames = [ os.path.join(dirname, fn)
-                        for fn in os.listdir(dirname)
-                        if fn.endswith('.h') and filter(fn) ]
-    fnames.sort()
-    for fname in fnames:
-        fmwkname = os.path.dirname(os.path.dirname(fname))
-        if fmwkname.endswith('.framework'):
-            fp.write("#import <%s/%s>\n" % (os.path.splitext(os.path.basename(fmwkname))[0], os.path.basename(fname)))
-    fp.write("/*\n")
-    fp.write(" * Enumeration constants. This file is generated from files in\n")
-    fp.write(" * %s\n"%dirname)
-    fp.write(" */\n")
-    fp.write("static struct inttable enum_table[] = {\n")
-    for f in fnames:
-        if os.path.basename(f) in ignore_files:
-            continue
-        process_file(fp, f)
-    fp.write("\t{0, 0, 0} /* Sentinel */\n")
-    fp.write("};\n")
-    fp.close()
-
-if __name__ == "__main__":
-    import sys
-    generate(sys.argv[1])

File sandbox/CodeGenerators/func_builder.py

-#
-# this script needs a version of the 'new' pyobjc
-#
-# This generates wrappers for 'simple' functions, basically anything that
-# has only 'by value' arguments, and return a simple object or an 'id'
-#
-
-verbose=0
-
-### We tried to import objc to detect if a name denotes a class. Now that
-# this script is started before we have a valid PyObjC installation this
-# is less usefull. Just rely on the static class list below.
-#
-#try:
-#    import objc
-#except ImportError:
-#    objc = None
-#
-#try:
-#    import AppKit
-#except ImportError:
-#    pass
-
-objc = None
-
-
-import re
-import sys
-import types
-
-# Types that are also simple values (mostly enums)
-TYPE_ALIASES={}
-
-# Varargs functions to be treated like normal functions
-IGNORE_VARARGS = []
-
-# Function mapping
-FUNC_MAP = {}
-DEFAULT_FUNCMAP=None
-
-# FUNCMAPS can set an argument-type to this value ('is' not '==') to remove
-# the argument from the python interface and force it to a specific value.
-FORCE_VALUE="ForceValue"
-
-HDR="""\
-/*
- * This is a generated file.
- */
-
-/*typedef void* PYOBJC_VOIDPTR;*/
-
-"""
-
-PTR_RE=re.compile('[ \t]+\*')
-def simplify_type(typestr):
-    typestr = PTR_RE.sub('*', typestr)
-
-    return typestr
-
-PROT_MATCHER=re.compile('<[A-Za-z0-9_ \t,]*>')
-def is_id(typestr):
-    # Remove protocol 'declarations' (id <NSObject, NSString>)
-    typestr = PROT_MATCHER.sub('', typestr).strip()
-
-
-    if typestr == 'id':
-        return 1
-    elif typestr[-1] != '*':
-        return 0
-
-    if objc != None:
-        try:
-            objc.lookUpClass(typestr[:-1])
-            return 1
-        except:
-            return 0
-    else:
-        # These types are used in function definition (OSX 10.2), this
-        # list is necessary for people that build without an installed
-        # PyObjC.
-        if typestr[:-1] in ('NSString', 'NSArray', 'NSWindow', 'NSColor', 'NSPasteboard', 'NSBundle', 'NSDictionary', 'NSResponder', 'NSThread', 'NSMutableDictionary', ):
-            return 1
-        return 0
-
-# TODO: actually use this, and add more types (when using: always check here
-# first, and then special logic (like handling 'id'-like values)
-# TODO: Use PyObjC_ObjCToPython/PyObjC_PythonToObjC!
-SIMPLE_TYPES={
-    # key: ( 'to_python', 'parse_fmt', 'parse_args' )
-    #      items in the tuple are either None (not needed), a string or
-    #      a function. The string will be %-expanded with a dict containing
-    #      the key 'varname', and varname will be the only argument to
-    #      the function that must return a string.
-    'char': (
-        '\tresult = PyString_FromStringAndSize(&(%(varname)s), 1);\n\tif (result == NULL) return NULL;',
-        'O&',
-        'PyObjC_ConvertChar, &%(varname)s',
-    ),
-    'Class': (
-        '\tresult = PyObjCClass_New(%(varname)s);\n\tif (result == NULL) return NULL;',
-        'O&',
-        'PyObjCClass_Convert, &%(varname)s',
-    ),
-    'int': (
-        "\tresult = PyInt_FromLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-        'i',
-        '&%(varname)s',
-        None
-    ),
-    'PYOBJC_VOIDPTR': (
-        "\tresult = PyInt_FromLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-        'i',
-        '&%(varname)s',
-        None
-    ),
-    'BOOL': (
-        "\tresult = PyBool_FromLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-        'O&',
-        'PyObjC_ConvertBOOL, &%(varname)s',
-        None
-    ),
-    'short': (
-        "\tresult = PyInt_FromLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-        'h',
-        '&%(varname)s',
-        None
-    ),
-    'long': (
-        "\tresult = PyInt_FromLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-        'l',
-        '&%(varname)s',
-        None
-    ),
-    'float': (
-        "\tresult = PyFloat_FromDouble(%(varname)s);\n\tif (result == NULL) return NULL;",
-        'f',
-        '&%(varname)s',
-        None
-    ),
-    'double': (
-        "\tresult = PyFloat_FromDouble(%(varname)s);\n\tif (result == NULL) return NULL;",
-        'd',
-        '&%(varname)s',
-        None
-    ),
-    'long long': (
-        "\t result = PyLong_FromLongLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-        'L',
-        '&%(varname)s',
-        None
-    ),
-    'char*': (
-        "\t result = PyString_FromString(%(varname)s);\n\tif (result == NULL) return NULL;",
-        "s",
-        '&%(varname)s',
-        None
-    ),
-}
-
-if sys.platform == 'darwin':
-    SIMPLE_TYPES['SEL'] = (
-        '\tresult = PyString_FromString(SELNAME(%(varname)s));\n\tif (result == NULL) return NULL;',
-        'O&',
-        'PyObjCSelector_Convert, &%(varname)s',
-    )
-else:
-    SIMPLE_TYPES['SEL'] = (
-        '\tresult = PyString_FromString(sel_get_name(%(varname)s));\n\tif (result == NULL) return NULL;',
-        'O&',
-        'PyObjCSelector_Convert, &%(varname)s',
-    )
-
-SIMPLE_TYPES['unsigned long long'] =  (
-    "\t result = PyLong_FromUnsignedLongLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-    'K',
-    '&%(varname)s',
-    None
-)
-SIMPLE_TYPES['unsigned'] = (
-    "\tresult = PyInt_FromLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-    'I',
-    '&%(varname)s',
-    None
-)
-SIMPLE_TYPES['unsigned int'] = SIMPLE_TYPES['unsigned']
-SIMPLE_TYPES['unsigned long'] = SIMPLE_TYPES['unsigned']
-
-SIMPLE_TYPES['unsigned short'] = (
-    "\tresult = PyInt_FromLong(%(varname)s);\n\tif (result == NULL) return NULL;",
-    'H',
-    '&%(varname)s',
-    None
-)
-
-def hidden_from_python(typestr):
-    if typestr is FORCE_VALUE: return 1
-    if typestr.startswith('const ') or typestr.startswith('const\t'):
-        typestr = typestr[6:].strip()
-
-    if is_id(typestr):
-        return 0
-
-    x = SIMPLE_TYPES[TYPE_ALIASES.get(typestr, typestr)]
-
-    if x[2] is '':
-        return 1
-    return 0
-
-
-def simple_to_python(varname, typestr):
-    if typestr.startswith('const ') or typestr.startswith('const\t'):
-        typestr = typestr[6:].strip()
-
-    if is_id(typestr):
-        return "\tresult = PyObjC_IdToPython(%(varname)s); if (result == NULL) return NULL;"%{ 'varname': varname }
-
-    x = SIMPLE_TYPES[TYPE_ALIASES.get(typestr, typestr)]
-    
-    if x[0] is None:
-        return
-    elif isinstance(x[0], str):
-        return x[0]%{'varname': varname }
-    elif isinstance(x[0], types.FunctionType):
-        return x[0](varname)
-    else:
-        raise ValueError, "Bad config for %s"%typestr
-
-def parsetuple_fmt(typestr):
-    if typestr.startswith('const ') or typestr.startswith('const\t'):
-        typestr = typestr[6:].strip()
-
-    if is_id(typestr):
-        return 'O&';
-
-    x = SIMPLE_TYPES[TYPE_ALIASES.get(typestr, typestr)]
-
-    return x[1]
-
-def parsetuple_arguments(typestr, varname):
-    if typestr.startswith('const ') or typestr.startswith('const\t'):
-        typestr = typestr[6:].strip()
-
-    if is_id(typestr):
-        return "PyObjCObject_Convert, &%(varname)s"%{ 'varname': varname }
-
-    x = SIMPLE_TYPES[TYPE_ALIASES.get(typestr, typestr)]
-    
-    if x[2] is None:
-        return
-    elif isinstance(x[2], str):
-        return x[2]%{'varname': varname }
-    elif isinstance(x[2], types.FunctionType):
-        return x[2](varname)
-    else:
-        raise ValueError, "Bad config for %s"%typestr
-
-def is_simple_type(typestr):
-    if typestr.startswith('const ') or typestr.startswith('const\t'):
-        typestr = typestr[6:].strip()
-
-    return (typestr in TYPE_ALIASES) or (typestr in SIMPLE_TYPES) or is_id(typestr)
-
-def parse_prototype(protostr):
-    protostr = protostr.strip()
-    if protostr[-1] != ')':
-        protostr = protostr.strip()[:-1].strip()
-    idx = protostr.index('(')
-
-    arguments = [ x.strip() for x in protostr[idx+1:-1].split(',') ]
-    before = protostr[:idx].strip()
-    idx=len(before)-1
-    while before[idx].isalnum() or before[idx] == '_':
-        idx -= 1
-
-    funcname = before[idx+1:].strip()
-    retval = simplify_type(before[:idx+1].strip())
-
-    if not is_simple_type(retval) and retval != 'void':
-        raise ValueError, "Complex function (retval) --%s--"%(retval,)
-
-    new_arguments = []
-    if len(arguments)  != 1 or arguments[0] != 'void' and arguments[0] != '':
-        for a in arguments:
-            if a == '...':
-                if funcname in IGNORE_VARARGS:
-                    continue
-                raise ValueError, "Complex function (varargs)"
-            idx = len(a)-1
-            while idx > 0 and (a[idx].isalnum() or a[idx] == '_'):
-                idx -= 1
-            new_arguments.append((simplify_type(a[:idx+1].strip()), a[idx+1:].strip()))
-    arguments = tuple(new_arguments)
-
-    if FUNC_MAP.has_key(funcname):
-        arguments = FUNC_MAP[funcname](funcname, arguments)
-    elif DEFAULT_FUNCMAP is not None:
-        arguments = DEFAULT_FUNCMAP(funcname, arguments)
-
-
-    for tp, name in arguments:
-        if tp is FORCE_VALUE: continue
-        if not is_simple_type(tp):
-            raise ValueError, "Complex function (arg of type %s)"%(tp,)
-
-    return retval, funcname, arguments
-
-def have_func(fname, funclist):
-    for n, l in funclist:
-        if fname == n:
-            return 1
-    return 0
-
-def process_function(fp, protostr, funclist):
-    retval, funcname, arguments = parse_prototype(protostr)
-
-    if have_func(funcname, funclist):
-        return
-
-    fp.write("/* %s */\n"%protostr)
-    fp.write("static PyObject* objc_%s(PyObject* self __attribute__((__unused__)), PyObject* args, PyObject* kwds)\n"%funcname)
-    fp.write("{\n")
-    keywords = [ a[1] for a in arguments if not hidden_from_python(a[0])]
-    keywords = '", "'.join(keywords)
-    if keywords:
-        keywords = '"%s", '%keywords
-    fp.write("static\tchar* keywords[] = { %sNULL };\n"%keywords)
-    fp.write("\tPyObject* result;\n")
-    if retval != 'void':
-        fp.write("\t%s _objc__result_;\n"%retval)
-
-    fmt = ''
-    arglist = ''
-    for tp, name in arguments:
-        if tp is FORCE_VALUE: continue
-        fmt += parsetuple_fmt(tp)
-        v =parsetuple_arguments(tp, "objc_%s"%name)
-        if v:
-            arglist += ", %s"%v
-
-        if is_id(tp):
-            fp.write("\tid objc_%s;\n"%name)
-        else:
-            if hidden_from_python(tp):
-                fp.write("\t%s objc_%s = 0;\n"%(tp, name))
-            else:
-                fp.write("\t%s objc_%s;\n"%(tp, name))
-
-    fp.write("\n")
-
-    fp.write('\tif (!PyArg_ParseTupleAndKeywords(args, kwds, "%s:%s", keywords%s)) return NULL;\n'%(fmt, funcname, arglist))
-
-    fp.write("\tPyObjC_DURING\n")
-    if retval != 'void':
-        fp.write("\t\t_objc__result_ = %s(\n"%funcname,)
-    else:
-        fp.write("\t\t%s(\n"%funcname,)
-    sep = "\t\t\t\t"
-    for tp, name in arguments:
-        if tp is FORCE_VALUE:
-            fp.write("%s%s"%(sep, name))
-        else:
-            fp.write("%sobjc_%s"%(sep, name))
-        sep = ",\n\t\t\t\t"
-    fp.write(");\n")
-    fp.write("\tPyObjC_HANDLER\n")
-    fp.write("\t\tPyObjCErr_FromObjC(localException);\n")
-    fp.write("\tPy_BLOCK_THREADS\n")
-    fp.write("\tNS_VALUERETURN(NULL, PyObject*);\n")
-    fp.write("\tPyObjC_ENDHANDLER\n")
-
-    if retval != 'void':
-        fp.write("\t%s\n"%simple_to_python("_objc__result_", retval))
-    else:
-        fp.write("\tresult = Py_None;\n\tPy_INCREF(Py_None);\n");
-
-    fp.write("\treturn result;\n")
-    fp.write("}\n")
-    return funcname
-
-
-def process_list(fp, lst):
-    ok_count = 0
-    total_count = 0
-    funcs=[]
-
-    fp.write(HDR)
-
-    for i, l in enumerate(lst):
-        l = l.strip()
-        if not l: continue
-        if l[0] == '#': continue
-        total_count += 1
-        try:
-            funcs.append((process_function(fp, l, funcs), l))
-            if verbose:
-                sys.stderr.write("Converting '%s' ..."%l.strip())
-                sys.stderr.write("done\n")
-            sys.stderr.flush()
-            ok_count += 1
-
-        except ValueError, msg:
-            fn = getattr(lst, 'name', None)
-            if fn is not None:
-                sys.stderr.write('%s:%d\n' % (fn, i+1))
-            sys.stderr.write("%s\n"%l.strip())
-            sys.stderr.write("Converting failed: %s\n"%msg)
-            sys.stderr.flush()
-
-    fp.write("\n")
-
-
-
-    if verbose:
-        sys.stderr.write("Converted %d of %d functions\n"%(ok_count, total_count))
-
-    return funcs
-
-def gen_method_table_entries(fp, funcs):
-    if not funcs:
-        fp.write("#define METHOD_TABLE_ENTRIES\n")
-    else:
-        fp.write("#define METHOD_TABLE_ENTRIES \\\n")
-        for f in funcs:
-            if f[0] is None: continue
-            fp.write('\t{ "%(funcname)s", (PyCFunction)objc_%(funcname)s, METH_VARARGS|METH_KEYWORDS, "%(funcproto)s" }, \\\n'%{'funcname':f[0], 'funcproto':f[1]})
-        fp.write("\t/* END */\n")
-
-
-if __name__ == "__main__":
-    import sys
-    TYPE_ALIASES['NSWindowDepth'] = 'int'
-    process_list(sys.stdout, file(sys.argv[1]))

File sandbox/CodeGenerators/func_collector.py

-# Non-string variables
-#
-# This is script is rather fragile, and tuned to the MacOS 10.1 header-files.
-#
-# We should probably use bgen, but how does one use that tool?
-
-import re
-import os
-from dupfile import *
-
-IDENT='[A-Za-z_][A-Za-z0-9_]*'
-attribute_unused=re.compile(r'__attribute__\s*\(\(_?_?unused_?_?\)\)')
-attribute_const=re.compile(r'__attribute__\s*\(\(_?_?const_?_?\)\)')
-
-def process_file(outfp, filename, match_prefix='', ignore_list=()):
-
-    MATCH_RE=re.compile('%(match_prefix)s(.+\s+.+\([^);{]+\)\s*(?:[;{]|$))'%{
-            'match_prefix':match_prefix, 'IDENT':IDENT})
-
-    fp = open(filename, 'r')
-
-    outfp.write("\n# From: %s\n"%os.path.basename(filename))
-
-    in_class = 0
-    saved_line = None
-    for ln in fp.xreadlines():
-        ln = attribute_unused.sub(' ', ln)
-        ln = attribute_const.sub(' ', ln)
-        # Skip declarations in objective-C class definitions
-        if not in_class:
-            if ln.startswith("@interface"):
-                saved_line=None
-                in_class = 1
-                continue
-        else:
-            if ln.startswith("@end"):
-                in_class = 0
-            continue
-
-        if saved_line is not None:
-            ln = saved_line.rstrip() + ' ' + ln
-
-        i = ln.find('//')
-        if i != -1:
-            ln = ln[:i]
-
-
-        m = MATCH_RE.match(ln)
-        if not m:
-            if saved_line is None and ln.startswith(match_prefix):
-                saved_line=ln
-            else:
-                saved_line=None
-            continue
-
-        prototype=m.group(1).strip()
-
-        ign = 0
-        for i in ignore_list:
-            if prototype.find(i) != -1:
-                ign=1
-                break
-
-        if not ign:
-            outfp.write('%s\n'%prototype)
-
-def generate(dirname, fn = None, match_prefix='', ignore_list=()):
-    if fn:
-        fp = dupfile(fn, 'w')
-    else:
-        import sys
-        fp = sys.stdout
-        del sys
-
-    fp.write("#\n")
-    fp.write("# List of functions. Generated from files in \n")
-    fp.write("# %s\n"%dirname)
-    fp.write("# \n")
-    fp.write("# Used to check for new functions\n")
-    fp.write("# \n")
-
-    fnames = [ os.path.join(dirname, fn)
-                        for fn in os.listdir(dirname)
-                        if fn.endswith('.h') ]
-    fnames.sort()
-    for f in fnames:
-        process_file(fp, f, match_prefix, ignore_list)
-
-    fp.close()
-
-if __name__ == "__main__":
-    import sys
-    generate(sys.argv[1], match_prefix=sys.argv[2])

File sandbox/CodeGenerators/strconst_generator.py

-# This script generates a constant table containing the enum values for
-# enumerations in the specified header file.
-#
-# This is script is rather fragile, and tuned to the MacOS 10.1 header-files.
-#
-# We should probably use bgen, but how does one use that tool?
-
-import re
-import os
-import sys
-from dupfile import *
-
-ON_OSX= (sys.platform == "darwin")
-
-MATCH_RE=re.compile(r'NSString\s*\*\s*(const\s+)?([A-Za-z_][A-Za-z0-9_]*(\s*,\s*\*\s*[A-Za-z_][A-Za-z0-9_]*)*)(\s+AVAILABLE_\w+)?;')
-
-def entry(fp, val, ignore):
-    vals = val.split(',')
-    if len(vals) == 1:
-        if val in ignore: return
-        if ON_OSX:
-            fp.write('\t { @"%s", @encode(NSString*) },\n'%(val, ))
-        else:
-            fp.write('\t { @"%s", @encode(NSString*), &(%s) },\n'%(val, val))
-    else:
-        for  v in vals:
-            v = v.strip()
-            if v[0] == '*':
-                v = v[1:].strip()
-            if v in ignore: continue
-            if ON_OSX:
-                fp.write('\t { @"%s", @encode(NSString*) },\n'%(v, ))
-            else:
-                fp.write('\t { @"%s", @encode(NSString*), &(%s) },\n'%(v, v))
-
-def process_file(outfp, filename, ignore):
-    fp = open(filename, 'r')
-
-    outfp.write("\n\t/* From: %s */\n"%os.path.basename(filename))
-
-    in_class = 0
-    struct_level = 0
-    maybe_struct_level = 0
-
-    for ln in fp.xreadlines():
-        if maybe_struct_level:
-            if ln.strip().startswith('{'):
-                struct_level += 1
-                continue
-        maybe_struct_level = 0
-
-        # Skip declarations in objective-C class definitions
-        if not in_class:
-            if ln.startswith("@interface"):
-                in_class = 1
-                continue
-        else:
-            if ln.startswith("@end"):
-                in_class = 0
-            continue
-
-        # Also skip struct definitions
-        # XXX: This is very minimal, but good enough..
-        if struct_level:
-            if ln.strip().startswith('}'):
-                struct_level -= 1
-
-        if ln.strip().startswith('struct ') and ln.strip().endswith('{'):
-            struct_level += 1
-        elif ln.strip().startswith('struct '):
-            maybe_struct_level = 1
-
-        if struct_level:
-            continue
-
-
-        m = MATCH_RE.search(ln)
-        if m:
-            ident = m.group(2)
-            entry(outfp, ident, ignore)
-
-
-def generate(dirname, fn = None, ignore=(), filter = lambda x: 1):
-    if not os.path.exists(dirname): return
-
-    if fn:
-        fp = dupfile(fn, 'w')
-    else:
-        import sys
-        fp = sys.stdout
-        del sys
-
-    fp.write("/*\n")
-    fp.write(" * String constants. This file is generated from files in\n")
-    fp.write(" * %s\n"%dirname)
-    fp.write(" */\n")
-    fp.write("static struct vartable string_table[] = {\n")
-    fnames = [ os.path.join(dirname, fn)
-                        for fn in os.listdir(dirname)
-                        if fn.endswith('.h') and filter(fn) ]
-    fnames.sort()
-    for f in fnames:
-        process_file(fp, f, ignore)
-    fp.write("\t{0, 0} /* Sentinel */\n")
-    fp.write("};\n")
-
-if __name__ == "__main__":
-    import sys
-    generate(sys.argv[1])

File sandbox/CodeGenerators/var_generator.py

-# Non-string variables
-#
-# This is script is rather fragile, and tuned to the MacOS 10.1 header-files.
-#
-# We should probably use bgen, but how does one use that tool?
-
-import re
-import os
-from dupfile import *
-
-IDENT='[A-Za-z_][A-Za-z0-9_]*'
-attribute_unused=re.compile(r'__attribute__\(\(_?_?unused_?_?\)\)')
-
-def process_file(outfp, filename, match_prefix='', ignore_list=()):
-
-    MATCH_RE=re.compile(r'%(match_prefix)s\s+(const\s+)?(%(IDENT)s)\s+(%(IDENT)s\s*(,\s*%(IDENT)s)*)\s*;'%{'match_prefix':match_prefix, 'IDENT':IDENT})
-
-    fp = open(filename, 'r')
-
-    outfp.write("\n\t/* From: %s */\n"%os.path.basename(filename))
-
-    in_class = 0
-
-    for ln in fp.xreadlines():
-        ln = attribute_unused.sub(' ', ln.strip())
-        # Skip declarations in objective-C class definitions
-        if not in_class:
-            if ln.startswith("@interface"):
-                in_class = 1
-                continue
-        else:
-            if ln.startswith("@end"):
-                in_class = 0
-            continue
-
-        m = MATCH_RE.search(ln)
-        if not m: continue
-
-
-        tp = m.group(2)
-        ident = m.group(3)
-
-        vals = [ x.strip() for x in ident.split(',') ]
-        for  v in vals:
-            if v in ignore_list: continue
-            outfp.write('\tif (add_%s(d, "%s", %s) < 0) return;\n'%(tp, v, v))
-
-def generate(dirname, fn = None, match_prefix='', ignore_list=()):
-    if fn:
-        fp = dupfile(fn, 'w')
-    else:
-        import sys
-        fp = sys.stdout
-        del sys
-
-    fp.write("/*\n")
-    fp.write(" * Various constants. This file is generated from files in\n")
-    fp.write(" * %s\n"%dirname)
-    fp.write(" * \n")
-    fp.write(" * #Include this into the module init function\n")
-    fp.write(" */\n")
-    fnames = [ os.path.join(dirname, fn)
-                        for fn in os.listdir(dirname)
-                        if fn.endswith('.h') ]
-    for f in fnames:
-        process_file(fp, f, match_prefix, ignore_list)
-
-if __name__ == "__main__":
-    import sys
-    generate(sys.argv[1], match_prefix=sys.argv[2])