[Python-checkins] CVS: python/dist/src/Mac/Modules/cg CFMLateImport.c,NONE,1.1 CFMLateImport.h,NONE,1.1 CGStubLib,NONE,1.1 CGStubLib.exp,NONE,1.1 CGStubLib.readme,NONE,1.1 _CGmodule.c,NONE,1.1 cgscan.py,NONE,1.1 cgsupport.py,NONE,1.1

Just van Rossum jvr@users.sourceforge.net
Thu, 13 Dec 2001 05:17:22 -0800


Update of /cvsroot/python/python/dist/src/Mac/Modules/cg
In directory usw-pr-cvs1:/tmp/cvs-serv3616

Added Files:
	CFMLateImport.c CFMLateImport.h CGStubLib CGStubLib.exp 
	CGStubLib.readme _CGmodule.c cgscan.py cgsupport.py 
Log Message:
second CoreGraphics batch

--- NEW FILE: CFMLateImport.c ---
/*
	File:		CFMLateImport.c

	Contains:	Implementation of CFM late import library.

	Written by:	Quinn

	Copyright:	Copyright © 1999 by Apple Computer, Inc., all rights reserved.

				You may incorporate this Apple sample source code into your program(s) without
				restriction. This Apple sample source code has been provided "AS IS" and the
				responsibility for its operation is yours. You are not permitted to redistribute
				this Apple sample source code as "Apple sample source code" after having made
				changes. If you're going to re-distribute the source, we require that you make
				it clear in the source that the code was descended from Apple sample source
				code, but that you've made changes.

	Change History (most recent first):

[...1321 lines suppressed...]
			err = cfragNoSymbolErr;
		}
	}
	if (symNameStr != nil) {
		CFRelease(symNameStr);
	}
	return err;
}

extern pascal OSStatus CFMLateImportBundle(const CFragSystem7DiskFlatLocator *fragToFixLocator,
										CFragConnectionID fragToFixConnID,
										CFragInitFunction fragToFixInitRoutine,
										ConstStr255Param weakLinkedLibraryName,
										CFBundleRef bundleToImport)
	// See comments in interface part.
{
	MoreAssertQ(bundleToImport != nil);
	return CFMLateImportCore(fragToFixLocator, fragToFixConnID, fragToFixInitRoutine,
										weakLinkedLibraryName, BundleLookup, bundleToImport);
}

--- NEW FILE: CFMLateImport.h ---
/*
	File:		CFMLateImport.h

	Contains:	Interface to CFM late import library.

	Written by:	Quinn

	Copyright:	Copyright © 1999 by Apple Computer, Inc., all rights reserved.

				You may incorporate this Apple sample source code into your program(s) without
				restriction. This Apple sample source code has been provided "AS IS" and the
				responsibility for its operation is yours. You are not permitted to redistribute
				this Apple sample source code as "Apple sample source code" after having made
				changes. If you're going to re-distribute the source, we require that you make
				it clear in the source that the code was descended from Apple sample source
				code, but that you've made changes.

	Change History (most recent first):

         <6>     21/9/01    Quinn   Changes for CWPro7 Mach-O build.
         <5>     19/9/01    Quinn   Change comments to reflect the fact that an unpacked data
                                    section is no longer required.
         <4>     19/9/01    Quinn   Simplified API and implementation after a suggestion by Eric
                                    Grant. You no longer have to CFM export a dummy function; you
                                    can just pass in the address of your fragment's init routine.
         <3>    16/11/00    Quinn   Allow symbol finding via a callback and use that to implement
                                    CFBundle support.
         <2>    18/10/99    Quinn   Renamed CFMLateImport to CFMLateImportLibrary to allow for
                                    possible future API expansion.
         <1>     15/6/99    Quinn   First checked in.
*/

#pragma once

/////////////////////////////////////////////////////////////////

// MoreIsBetter Setup

//#include "MoreSetup.h"

// Mac OS Interfaces

#if ! MORE_FRAMEWORK_INCLUDES
	#include <MacTypes.h>
	#include <CodeFragments.h>
	#include <Devices.h>
	#include <CFBundle.h>
#endif

/////////////////////////////////////////////////////////////////

#ifdef __cplusplus
extern "C" {
#endif

/*	FAQ
	---
	
	Q:	What does this library do?
	A:	It allows you to resolve a weak linked library at runtime,
	   	by supply a CFM connection to the library that should substitute
	   	for the weak linked one.
	
	Q:	Does the substituted library have to have the same name as the
		weak linked library.
	A:	No.
	
	Q:	What's this useful for?
	A:	The most obvious example of where this is useful is when
		you rely on shared libraries that the user might delete
		or move.  To can find the shared library (possibly even
		using CatSearch), call GetDiskFragment to open a connection
		to it, late import it using this library, and then the
		rest of your code can continue to use the shared library
		as if nothing had happened.  No more defining thousands
		of stub routines which call through routine pointers.
		
		There are, however, numerous less obvious uses.  You can
		use this code to make a 'self repairing' application.  If
		the user removes your shared library from the Extensions
		folder, the startup code for your application can offer
		tor re-install it.  If the user agrees, you can then
		re-install your shared library, late import it, and then
		continue running your application if nothing happened.
		
		You can even use this code to free yourself from the
		Extensions folder entirely.  Say you have a suite of
		applications that currently installs a dozen shared 
		libraries in the Extensions folder.  You can move those
		libraries to another folder entirely and each application's
		startup code can track down the library (using an alias
		in the Preferences file) and late import it.
		
		An even cooler use is to provide easy abstraction layers.
		Say you have a network code for both the MacTCP
		API and the Open Transport API.  Typically, you would be
		force to do this by having an abstraction layer where every
		routine contains a switch between MacTCP and OT.  Your
		OpenSocket routine might look like:

			static int OpenSocket(void)
			{
			    if (gOTAvailable) {
			        return OpenSocketOT();
			    } else {
			        return OpenSocketMacTCP();
			    }
			}
		
		With this code, you can avoid that entirely.  Simply
		weak link to a shared library that you know is never
		going to be implemented ("crea;MySocketsDummy") and then, 
		at runtime, decide whether the system has MacTCP or OT
		and late import the relevant real implementation
		("crea;MySocketsMacTCP" or "crea;MySocketsOT").
		One benefit of this approach is that only the MacTCP or
		the OT code is resident in memory on any given system.
*/

typedef pascal OSStatus (*CFMLateImportLookupProc)(ConstStr255Param symName, CFragSymbolClass symClass,
													void **symAddr, void *refCon);
	// CFMLateImportLookupProc defines a callback for CFMLateImportCore.
	// The routine is expected to look up the address of the symbol named 
	// symName and return it in *symAddr.  The symbol should be of class 
	// symClass, although the callback decides whether a class mismatch is 
	// an error.  refCon is an application defined value that was originally 
	// passed in to CFMLateImportCore.
	//
	// If this routine returns an error, a symbol address of 0 is assumed. 
	// If the symbol is marked as a weak import, the CFMLateImportCore will 
	// continue, otherwise the CFMLateImportCore routine will fail with the 
	// error.
	
extern pascal OSStatus CFMLateImportCore(const CFragSystem7DiskFlatLocator *fragToFixLocator,
										CFragConnectionID fragToFixConnID,
										CFragInitFunction fragToFixInitRoutine,
										ConstStr255Param weakLinkedLibraryName,
										CFMLateImportLookupProc lookup,
										void *refCon);
	// This routine will link you, at runtime, to some library 
	// that you were weak linked to and wasn't present when your
	// fragment was prepared.  As well as the obvious functionality
	// of being able to resolve weak links after prepare time,
	// this functionality can be put to a number of less obvious uses,
	// some of which are discussed at the top of this header file.
	//
	// To call this routine, you need a number of pieces of information:
	//
	// 1. fragToFixLocator, fragToFixConnID:  The location of your own
	//    code fragment on disk and the CFM connection ID to your own
	//    code fragment.  Typically you get this information from your 
	//    fragment's CFM init routine.  You must ensure that
	//    fragToFixLocator->fileSpec points to an FSSpec of the
	//    file which holds your code fragment.
	//
	//    IMPORTANT:
	//    The fact that you pass in a CFragSystem7DiskFlatLocator as the
	//    fragToFixLocator implies that the fragment to be fixed up must
	//    be in the data fork of a file.  The code could be modified
	//    to remove this requirement, but on disk code fragments are the most
	//    common case.
	//
	//    IMPORTANT:
	//    The fragment to fix may have a packed data section.  Packing the 
	//    data section will reduce the size of your fragment on disk, but it 
	//    will significantly increase the memory needed by this routine 
	//    (it increases memory usage by the sum of the sizes of the packed 
	//    and unpacked data section).  See below for instructions on how to 
	//    create an unpacked data section.
	//
	// 2. fragToFixInitRoutine:  A pointer to your own code fragment's
	//    fragment initialiser routine.  You necessarily have one of these 
	//    because you need it to get values for the fragToFixLocator and 
	//    fragToFixConnID parameters.  Just pass its address in as a parameter 
	//    as well. 
	//
	// 3. weakLinkedLibraryName:  The name of the weak linked library which
	//    failed to link.  You must have weak linked to this library.
	//    It is oxymoric for you to pass a strong linked library here,
	//    because your code would not have prepared if a strong linked
	//    library failed to prepare, and so you couldn't supply a valid
	///   fragToFix.
	//
	// 4. lookup, refCon:  A pointer to a callback function that the 
	//	  routine calls to look up the address of a symbol, and a refCon 
	//    for that callback routine.
	//
	// Note:
	// The fragToFixLocator and fragToFixInitRoutine parameters
	// are artifacts of the way in which this functionality is implemented.
	// In an ideal world, where CFM exported decent introspection APIs
	// to third party developers, these parameters would not be necessary.
	// If you're using this code inside Apple, you probably should investigate
	// using the CFM private APIs for getting at the information these
	// parameters are needed for.  See the comments inside the implementation
	// for more details.
	//
	// Note:
	// The extra memory taken when you use a packed data section is also an 
	// artifact of my workaround for the lack of CFM introspection APIs.  In 
	// my opinion it's better to use an unpacked data section and consume more 
	// space on disk while saving memory.  In CodeWarrior you can switch to an 
	// unpacked data section by checking the "Expand Uninitialized Data" 
	// checkbox in the "PPC PEF" settings panel.  In MPW, specified the
	// "-packdata off" option to PPCLink.
	//
	// When the routine returns, any symbols that you imported from the
	// library named weakLinkedLibraryName will be resolved to the address
	// of the symbol provided by the "lookup" callback routine.
	//
	// It is possible for an unresolved import to remain unresolved after
	// this routine returns.  If the symbol import is marked as weak (as
	// opposed to the library, which *must* be marked as weak) and the symbol
	// is not found by the "lookup" callback, the routine will simple skip 
	// that symbol.  If the symbol isn't marked as weak, the routine will fail 
	// in that case.
	//
	// Most of the possible error results are co-opted CFM errors.  These
	// include:
	//
	// cfragFragmentFormatErr  -- The fragment to fix is is an unknown format.
	// cfragNoSectionErr       -- Could not find the loader section in the fragment to fix.
	// cfragNoLibraryErr       -- The fragment to fix is not weak linked to weakLinkedLibraryName.
	// cfragFragmentUsageErr   -- The fragment to fix doesn't have a data section.
	//                         -- The fragment to fix is strong linked to weakLinkedLibraryName.
	//                         -- The fragment doesn't have an init routine.
	// cfragFragmentCorruptErr -- Encountered an undefined relocation opcode.
	// unimpErr                -- Encountered an unimplement relocation opcode.  The
	//                            relocation engine only implements a subset of the CFM
	//                            relocation opcodes, the subset most commonly used by
	//                            MPW and CodeWarrior PEF containers.  If you encounter
	//                            this error, you'll probably have to add the weird
	//                            relocation opcode to the engine, which shouldn't be
	//                            be too hard.
	// memFullErr			   -- It's likely that this error is triggered by the memory 
	//                            needed to unpack your data section.  Either make your 
	//                            data section smaller, or unpack it (see above).
	// errors returned by FindSymbol
	// errors returned by Memory Manager
	//
	// The routine needs enough memory to hold the loader section of the fragment
	// to fix in memory.  It allocates that memory using NewPtr and dispsoses of 
	// it before it returns.  You may want to change the memory allocator, which
	// is very simple.

extern pascal OSStatus CFMLateImportLibrary(const CFragSystem7DiskFlatLocator *fragToFixLocator,
										CFragConnectionID fragToFixConnID,
										CFragInitFunction fragToFixInitRoutine,
										ConstStr255Param weakLinkedLibraryName,
										CFragConnectionID connIDToImport);
	// A wrapper around CFMLateImportCore that looks up symbols by calling 
	// FindSymbol on a connection to a CFM library (connIDToImport).
	// You can get this connection ID through any standard CFM API, for example
	// GetSharedLibrary, GetDiskFragment, or GetMemFragment.
	//
	// IMPORTANT:
	// The fragment name for connIDToImport *does not* have to match
	// weakLinkedLibraryName.  This is part of the power of this library.

extern pascal OSStatus CFMLateImportBundle(const CFragSystem7DiskFlatLocator *fragToFixLocator,
										CFragConnectionID fragToFixConnID,
										CFragInitFunction fragToFixInitRoutine,
										ConstStr255Param weakLinkedLibraryName,
										CFBundleRef bundleToImport);
	// A wrapper around CFMLateImportCore that looks up symbols by calling 
	// CFBundleGetFunctionPointerForName on a reference to a Core Foundation 
	// bundle (bundleToImport).  You can get this reference through any 
	// Core Foundation bundle API, for example CFBundleCreate.

#ifdef __cplusplus
}
#endif

--- NEW FILE: CGStubLib ---
(This file must be converted with BinHex 4.0)
:!!"cG(9L69"6)!#3"!L3!!!!!BUjr%T[H5&`C@CQF(G`B`!!!!'i-rHh!*!0!3#
3"[q3"!#3$JJm!!!!8!3"!*!1rj!%!*!%rj!%!*!%rj!%!*!A1!!!"2!!!!!$!!!
!1N0(3fpZG'9iG&0SEhG8CAKd3A43EfPZG%0(3fpZG'9iG&0SEhG8CAKd3dG$Efj
dCAKd8f9XC@0d4QpZG%0(3fpZG'9iG&0PG&4PH(4%FQ&hD@jR6@pNC80(3fpZG'9
iG%4bBAG3BA4S3dG$EfjdCAKd8f9d6'PZC8T[D@j$4d0[ER4PH(46CA4-D@jP3f&
`3dG$EfjdCAKd4f9d9'9iG&"[FfPdD@pZ3dG$EfjdCAKd4f9d8'&dD%0eFR*PER4
3EfPZG%0(3fpZG'9iG&0PG&0SEh9XC%&ZG'PKE'PKFd0(3fpZG'9iG&0jEQ0SFQp
ZDATP3dG$EfjdCAKd4QaeFfK$4d0[ER4PH(4&EQ43B@GP3dG$EfjdCAKd8f9d4Qp
ZG&0THQ9$4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k!*!%rri#!!0S!*!%rri#!!30!*!%rri#!!$$!*!%rri#!!+1!*!
%rri#!!)H!*!%rri#!!2L!*!%rri#!!+I!*!%rri#!!&3!*!%rri#!!1V!*!%rri
#!!*!!*!%rri#!!0-!*!%rri#!!1!!*!%rri#!!'%!*!%rri#!!52!*!%rri#!!1
A!*!%rri#!!1p!*!%rri#!!5I!*!%rri!N!3E2!!!!3!!!!&B!!!!@!!!!$)!N20
8!*!,!3#3%`&`Gh"M!*!5!`%!N"%d#80(8h4eBNaTBJ!!!3!!!!&B!!!!@!!!!$*
66e*8"*B!J!!F!$)!!'0QFQF!!!!+!!$rr`#3#2Ib:
--- NEW FILE: CGStubLib.exp ---
CGContextShowTextAtPoint
CGContextShowText
CGContextSelectFont
CGContextSetTextDrawingMode
CGContextDrawPath
CGContextSetLineJoin
CGContextSetLineCap
CGContextGetTextPosition
CGContextGetPathCurrentPoint
CGContextSetShouldAntialias
CGContextSynchronize
CGContextFlush
CGContextEndPage
CGContextSetFontSize
CGContextGetTextMatrix
CGContextSetTextMatrix
CGContextSetTextPosition
CGContextSetCharacterSpacing
CGContextSetCMYKStrokeColor
CGContextSetCMYKFillColor
CGContextSetRGBStrokeColor
CGContextSetRGBFillColor
CGContextSetGrayStrokeColor
CGContextSetGrayFillColor
CGContextClipToRect
CGContextEOClip
CGContextClip
CGContextClearRect
CGContextStrokeRectWithWidth
CGContextStrokeRect
CGContextFillRect
CGContextStrokePath
CGContextEOFillPath
CGContextFillPath
CGContextGetPathBoundingBox
CGContextIsPathEmpty
CGContextAddArcToPoint
CGContextAddArc
CGContextAddRect
CGContextClosePath
CGContextAddQuadCurveToPoint
CGContextAddCurveToPoint
CGContextAddLineToPoint
CGContextMoveToPoint
CGContextBeginPath
CGContextSetAlpha
CGContextSetFlatness
CGContextSetMiterLimit
CGContextSetLineWidth
CGContextGetCTM
CGContextConcatCTM
CGContextRotateCTM
CGContextTranslateCTM
CGContextScaleCTM
CGContextRestoreGState
CGContextSaveGState
CGContextRelease
CreateCGContextForPort

--- NEW FILE: CGStubLib.readme ---
# CGStubLib was created by issuing this command in MPW:

MakeStub CGStubLib.exp -o CGStubLib

--- NEW FILE: _CGmodule.c ---

/* =========================== Module _CG =========================== */

#include "Python.h"



#include "macglue.h"
#include "pymactoolbox.h"

/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL )  {\
    	PyErr_SetString(PyExc_NotImplementedError, \
    	"Not available in this shared library/OS version"); \
    	return NULL; \
    }} while(0)


#ifdef WITHOUT_FRAMEWORKS
[...1293 lines suppressed...]
		PyErr_SetString(PyExc_ImportError, "CoreCraphics not supported");
		return;
	};
#endif  /* !TARGET_API_MAC_OSX */


	m = Py_InitModule("_CG", CG_methods);
	d = PyModule_GetDict(m);
	CG_Error = PyMac_GetOSErrException();
	if (CG_Error == NULL ||
	    PyDict_SetItemString(d, "Error", CG_Error) != 0)
		return;
	CGContextRef_Type.ob_type = &PyType_Type;
	Py_INCREF(&CGContextRef_Type);
	if (PyDict_SetItemString(d, "CGContextRefType", (PyObject *)&CGContextRef_Type) != 0)
		Py_FatalError("can't initialize CGContextRefType");
}

/* ========================= End module _CG ========================= */


--- NEW FILE: cgscan.py ---
# Scan an Apple header file, generating a Python file of generator calls.

import sys
import os
BGENDIR=os.path.join(sys.prefix, ':Tools:bgen:bgen')
sys.path.append(BGENDIR)
from scantools import Scanner_OSX
from bgenlocations import TOOLBOXDIR

LONG = "CoreGraphics"
SHORT = "cg"
OBJECTS = ("CGContextRef", 
		)
# ADD object typenames here

def main():
	input = [
		"CGContext.h",
	]
	output = SHORT + "gen.py"
	defsoutput = TOOLBOXDIR + LONG + ".py"
	scanner = MyScanner(input, output, defsoutput)
	scanner.scan()
	scanner.gentypetest(SHORT+"typetest.py")
	scanner.close()
	print "=== Done scanning and generating, now importing the generated code... ==="
	exec "import " + SHORT + "support"
	print "=== Done.  It's up to you to compile it now! ==="

class MyScanner(Scanner_OSX):

	def destination(self, type, name, arglist):
		classname = "Function"
		listname = "functions"
		if arglist:
			t, n, m = arglist[0]
			if t in OBJECTS and m == "InMode":
				classname = "Method"
				listname = t + "_methods"
			# Special case for the silly first AllocatorRef argument
			if t == 'CFAllocatorRef' and m == 'InMode' and len(arglist) > 1:
				t, n, m = arglist[1]
				if t in OBJECTS and m == "InMode":
					classname = "MethodSkipArg1"
					listname = t + "_methods"
		return classname, listname

	def writeinitialdefs(self):
		self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n")

	def makeblacklistnames(self):
		return [
			"CGContextRetain",
			"CGContextRelease",
			]

	def makegreylist(self):
		return []

	def makeblacklisttypes(self):
		return [
			"float_ptr",
			"CGRect_ptr",
			"CGPoint_ptr",
			"CGColorSpaceRef",
			"CGColorRenderingIntent",
			"CGFontRef",
#			"char_ptr",
			"CGGlyph_ptr",
			"CGImageRef",
			"CGPDFDocumentRef",
			]

	def makerepairinstructions(self):
		return [
			([("char_ptr", "cstring", "InMode"), ("size_t", "length", "InMode")],
			 [("InBuffer", "*", "*")]),
#			([("char_ptr", "name", "InMode"),],
#			 [("CCCCC", "*", "*")]),
			]
			
if __name__ == "__main__":
	main()

--- NEW FILE: cgsupport.py ---
# This script generates a Python interface for an Apple Macintosh Manager.
# It uses the "bgen" package to generate C code.
# The function specifications are generated by scanning the mamager's header file,
# using the "scantools" package (customized for this particular manager).

#error missing SetActionFilter

import string

# Declarations that change for each manager
MODNAME = '_CG'				# The name of the module

# The following is *usually* unchanged but may still require tuning
MODPREFIX = 'CG'			# The prefix for module-wide routines
INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner
OUTPUTFILE = MODNAME + "module.c"	# The file generated by this program

from macsupport import *


# Create the type objects

includestuff = includestuff + """
#ifdef WITHOUT_FRAMEWORKS
#include <Quickdraw.h>
#include <CGContext.h>
#else
#include <CoreGraphics/CoreGraphics.h>
#endif

#if !TARGET_API_MAC_OSX
	/* This code is adapted from the CallMachOFramework demo at:
       http://developer.apple.com/samplecode/Sample_Code/Runtime_Architecture/CallMachOFramework.htm
       It allows us to call Mach-O functions from CFM apps. */

	#include <Folders.h>
	#include "CFMLateImport.h"

	static OSStatus LoadFrameworkBundle(CFStringRef framework, CFBundleRef *bundlePtr)
		// This routine finds a the named framework and creates a CFBundle 
		// object for it.  It looks for the framework in the frameworks folder, 
		// as defined by the Folder Manager.  Currently this is 
		// "/System/Library/Frameworks", but we recommend that you avoid hard coded 
		// paths to ensure future compatibility.
		//
		// You might think that you could use CFBundleGetBundleWithIdentifier but 
		// that only finds bundles that are already loaded into your context. 
		// That would work in the case of the System framework but it wouldn't 
		// work if you're using some other, less-obvious, framework.
	{
		OSStatus 	err;
		FSRef 		frameworksFolderRef;
		CFURLRef	baseURL;
		CFURLRef	bundleURL;
		
		*bundlePtr = nil;
		
		baseURL = nil;
		bundleURL = nil;
		
		// Find the frameworks folder and create a URL for it.
		
		err = FSFindFolder(kOnAppropriateDisk, kFrameworksFolderType, true, &frameworksFolderRef);
		if (err == noErr) {
			baseURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault, &frameworksFolderRef);
			if (baseURL == nil) {
				err = coreFoundationUnknownErr;
			}
		}
		
		// Append the name of the framework to the URL.
		
		if (err == noErr) {
			bundleURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, baseURL, framework, false);
			if (bundleURL == nil) {
				err = coreFoundationUnknownErr;
			}
		}
		
		// Create a bundle based on that URL and load the bundle into memory.
		// We never unload the bundle, which is reasonable in this case because 
		// the sample assumes that you'll be calling functions from this 
		// framework throughout the life of your application.
		
		if (err == noErr) {
			*bundlePtr = CFBundleCreate(kCFAllocatorSystemDefault, bundleURL);
			if (*bundlePtr == nil) {
				err = coreFoundationUnknownErr;
			}
		}
		if (err == noErr) {
		    if ( ! CFBundleLoadExecutable( *bundlePtr ) ) {
				err = coreFoundationUnknownErr;
		    }
		}

		// Clean up.
		
		if (err != noErr && *bundlePtr != nil) {
			CFRelease(*bundlePtr);
			*bundlePtr = nil;
		}
		if (bundleURL != nil) {
			CFRelease(bundleURL);
		}	
		if (baseURL != nil) {
			CFRelease(baseURL);
		}	
		
		return err;
	}



	// The CFMLateImport approach requires that you define a fragment 
	// initialisation routine that latches the fragment's connection 
	// ID and locator.  If your code already has a fragment initialiser 
	// you will have to integrate the following into it.

	static CFragConnectionID 			gFragToFixConnID;
	static FSSpec 						gFragToFixFile;
	static CFragSystem7DiskFlatLocator 	gFragToFixLocator;

	extern OSErr FragmentInit(const CFragInitBlock *initBlock);
	extern OSErr FragmentInit(const CFragInitBlock *initBlock)
	{
		__initialize(initBlock); /* call the "original" initializer */
		gFragToFixConnID	= (CFragConnectionID) initBlock->closureID;
		gFragToFixFile 		= *(initBlock->fragLocator.u.onDisk.fileSpec);
		gFragToFixLocator 	= initBlock->fragLocator.u.onDisk;
		gFragToFixLocator.fileSpec = &gFragToFixFile;
		
		return noErr;
	}

#endif

extern int GrafObj_Convert(PyObject *, GrafPtr *);

/*
** Manual converters
*/

PyObject *CGPoint_New(CGPoint *itself)
{

	return Py_BuildValue("(ff)",
			itself->x,
			itself->y);
}

int
CGPoint_Convert(PyObject *v, CGPoint *p_itself)
{
	if( !PyArg_Parse(v, "(ff)",
			&p_itself->x,
			&p_itself->y) )
		return 0;
	return 1;
}

PyObject *CGRect_New(CGRect *itself)
{

	return Py_BuildValue("(ffff)",
			itself->origin.x,
			itself->origin.y,
			itself->size.width,
			itself->size.height);
}

int
CGRect_Convert(PyObject *v, CGRect *p_itself)
{
	if( !PyArg_Parse(v, "(ffff)",
			&p_itself->origin.x,
			&p_itself->origin.y,
			&p_itself->size.width,
			&p_itself->size.height) )
		return 0;
	return 1;
}

PyObject *CGAffineTransform_New(CGAffineTransform *itself)
{

	return Py_BuildValue("(ffffff)",
			itself->a,
			itself->b,
			itself->c,
			itself->d,
			itself->tx,
			itself->ty);
}

int
CGAffineTransform_Convert(PyObject *v, CGAffineTransform *p_itself)
{
	if( !PyArg_Parse(v, "(ffffff)",
			&p_itself->a,
			&p_itself->b,
			&p_itself->c,
			&p_itself->d,
			&p_itself->tx,
			&p_itself->ty) )
		return 0;
	return 1;
}
"""

initstuff = initstuff + """
#if !TARGET_API_MAC_OSX
CFBundleRef sysBundle;
OSStatus err;

if (&LoadFrameworkBundle == NULL) {
	PyErr_SetString(PyExc_ImportError, "CoreCraphics not supported");
	return;
}
err = LoadFrameworkBundle(CFSTR("ApplicationServices.framework"), &sysBundle);
if (err == noErr)
	err = CFMLateImportBundle(&gFragToFixLocator, gFragToFixConnID, FragmentInit, "\pCGStubLib", sysBundle);
if (err != noErr) {
	PyErr_SetString(PyExc_ImportError, "CoreCraphics not supported");
	return;
};
#endif  /* !TARGET_API_MAC_OSX */
"""

class MyOpaqueByValueType(OpaqueByValueType):
	"""Sort of a mix between OpaqueByValueType and OpaqueType."""
	def mkvalueArgs(self, name):
		return "%s, &%s" % (self.new, name)

CGPoint = MyOpaqueByValueType('CGPoint', 'CGPoint')
CGRect = MyOpaqueByValueType('CGRect', 'CGRect')
CGAffineTransform = MyOpaqueByValueType('CGAffineTransform', 'CGAffineTransform')

char_ptr = Type("char *", "s")

CGTextEncoding = int
CGLineCap = int
CGLineJoin = int
CGTextDrawingMode = int
CGPathDrawingMode = int

# The real objects
CGContextRef = OpaqueByValueType("CGContextRef", "CGContextRefObj")


class MyObjectDefinition(GlobalObjectDefinition):
	def outputStructMembers(self):
		ObjectDefinition.outputStructMembers(self)
	def outputCleanupStructMembers(self):
		Output("CGContextRelease(self->ob_itself);")


# Create the generator groups and link them
module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff)

CGContextRef_object = MyObjectDefinition('CGContextRef', 'CGContextRefObj', 'CGContextRef')


# ADD object here

module.addobject(CGContextRef_object)



Function = FunctionGenerator
Method = MethodGenerator

CGContextRef_methods = []

# ADD _methods initializer here
execfile(INPUTFILE)

CreateCGContextForPort_body = """\
GrafPtr port;
CGContextRef ctx;
OSStatus _err;

if (!PyArg_ParseTuple(_args, "O&", GrafObj_Convert, &port))
	return NULL;

_err = CreateCGContextForPort(port, &ctx);
if (_err != noErr)
	if (_err != noErr) return PyMac_Error(_err);
_res = Py_BuildValue("O&", CGContextRefObj_New, ctx);
return _res;
"""

f = ManualGenerator("CreateCGContextForPort", CreateCGContextForPort_body);
f.docstring = lambda: "(CGrafPtr) -> CGContextRef"
module.add(f)


# ADD add forloop here
for f in CGContextRef_methods:
	CGContextRef_object.add(f)

# generate output (open the output file as late as possible)
SetOutputFileName(OUTPUTFILE)
module.generate()