summaryrefslogtreecommitdiffstats
path: root/Mac/Modules/cg/cgsupport.py
blob: d09068553447c5a260d2cdd7f2fe3690255762cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# 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 *

CGrafPtr = OpaqueByValueType("CGrafPtr", "GrafObj")
RgnHandle = OpaqueByValueType("RgnHandle", "ResObj")

# Create the type objects

includestuff = includestuff + """
#ifdef WITHOUT_FRAMEWORKS
#include <Quickdraw.h>
#include <CGContext.h>
#else
#include <ApplicationServices/ApplicationServices.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)

# manual method, lives in Quickdraw.h
f = Method(void, 'SyncCGContextOriginWithPort',
    (CGContextRef, 'ctx', InMode),
    (CGrafPtr, 'port', InMode),
)
CGContextRef_methods.append(f)

# manual method, lives in Quickdraw.h
f = Method(void, 'ClipCGContextToRegion',
    (CGContextRef, 'ctx', InMode),
    (Rect, 'portRect', InMode),
    (RgnHandle, 'region', InMode),
)
CGContextRef_methods.append(f)


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()