Move setting of ioready 'wait' earlier in call chain, to
[python/dscho.git] / Mac / Modules / file / filesupport.py
blob1237d2200efd54b5070b865fae8fbf8a908ffb1b
1 # This script generates a Python interface for an Apple Macintosh Manager.
2 # It uses the "bgen" package to generate C code.
3 # The function specifications are generated by scanning the mamager's header file,
4 # using the "scantools" package (customized for this particular manager).
6 # XXXX TO DO:
7 # - Implement correct missing FSSpec handling for Alias methods
8 # - Implement FInfo
10 import string
12 # Declarations that change for each manager
13 #MACHEADERFILE = 'Files.h' # The Apple header file
14 MODNAME = '_File' # The name of the module
15 LONGMODNAME = 'Carbon.File' # The "normal" external name of the module
17 # The following is *usually* unchanged but may still require tuning
18 MODPREFIX = 'File' # The prefix for module-wide routines
19 INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner
20 OUTPUTFILE = MODNAME + "module.c" # The file generated by this program
22 from macsupport import *
24 # Various integers:
25 SInt64 = Type("SInt64", "L")
26 UInt64 = Type("UInt64", "L")
27 FNMessage = Type("FNMessage", "l")
28 FSAllocationFlags = Type("FSAllocationFlags", "H")
29 FSCatalogInfoBitmap = Type("FSCatalogInfoBitmap", "l")
30 FSIteratorFlags = Type("FSIteratorFlags", "l")
31 FSVolumeRefNum = Type("FSVolumeRefNum", "h")
32 AliasInfoType = Type("AliasInfoType", "h")
34 # Various types of strings:
35 #class UniCharCountBuffer(InputOnlyType):
36 # pass
37 class VarReverseInputBufferType(ReverseInputBufferMixin, VarInputBufferType):
38 pass
39 FullPathName = VarReverseInputBufferType()
40 ConstStr31Param = OpaqueArrayType("Str31", "PyMac_BuildStr255", "PyMac_GetStr255")
41 ConstStr32Param = OpaqueArrayType("Str32", "PyMac_BuildStr255", "PyMac_GetStr255")
42 ConstStr63Param = OpaqueArrayType("Str63", "PyMac_BuildStr255", "PyMac_GetStr255")
43 Str63 = OpaqueArrayType("Str63", "PyMac_BuildStr255", "PyMac_GetStr255")
45 HFSUniStr255 = OpaqueType("HFSUniStr255", "PyMac_BuildHFSUniStr255", "PyMac_GetHFSUniStr255")
46 UInt8_ptr = InputOnlyType("UInt8 *", "s")
48 # Other types:
49 class OptionalFSxxxType(OpaqueByValueType):
50 def declare(self, name):
51 Output("%s %s__buf__;", self.typeName, name)
52 Output("%s *%s = &%s__buf__;", self.typeName, name, name)
54 class FSCatalogInfoAndBitmapType(InputOnlyType):
56 def __init__(self):
57 InputOnlyType.__init__(self, "BUG", "BUG")
59 def declare(self, name):
60 Output("PyObject *%s__object = NULL;", name)
61 Output("FSCatalogInfoBitmap %s__bitmap = 0;", name)
62 Output("FSCatalogInfo %s;", name)
64 def getargsFormat(self):
65 return "lO"
67 def getargsArgs(self, name):
68 return "%s__bitmap, %s__object"%(name, name)
70 def getargsCheck(self, name):
71 Output("if (!convert_FSCatalogInfo(%s__object, %s__bitmap, &%s)) return NULL;", name, name, name)
73 def passInput(self, name):
74 return "%s__bitmap, &%s"% (name, name)
76 def passOutput(self, name):
77 return "%s__bitmap, &%s"% (name, name)
79 def mkvalueFormat(self):
80 return "O"
82 def mkvalueArgs(self, name):
83 return "%s__object" % (name)
85 def xxxxmkvalueCheck(self, name):
86 Output("if ((%s__object = new_FSCatalogInfo(%s__bitmap, &%s)) == NULL) return NULL;", name, name)
88 class FSCatalogInfoAndBitmap_inType(FSCatalogInfoAndBitmapType, InputOnlyMixIn):
90 def xxxxmkvalueCheck(self, name):
91 pass
93 class FSCatalogInfoAndBitmap_outType(FSCatalogInfoAndBitmapType):
95 def getargsFormat(self):
96 return "l"
98 def getargsArgs(self, name):
99 return "%s__bitmap" % name
101 def getargsCheck(self, name):
102 pass
104 FInfo = OpaqueType("FInfo", "FInfo")
105 FInfo_ptr = OpaqueType("FInfo", "FInfo")
106 AliasHandle = OpaqueByValueType("AliasHandle", "Alias")
107 FSSpec = OpaqueType("FSSpec", "FSSpec")
108 FSSpec_ptr = OpaqueType("FSSpec", "FSSpec")
109 OptFSSpecPtr = OptionalFSxxxType("FSSpec", "BUG", "myPyMac_GetOptFSSpecPtr")
110 FSRef = OpaqueType("FSRef", "FSRef")
111 FSRef_ptr = OpaqueType("FSRef", "FSRef")
112 OptFSRefPtr = OptionalFSxxxType("FSRef", "BUG", "myPyMac_GetOptFSRefPtr")
113 FSCatalogInfo = OpaqueType("FSCatalogInfo", "FSCatalogInfo")
114 FSCatalogInfo_ptr = OpaqueType("FSCatalogInfo", "FSCatalogInfo")
116 # To be done:
117 #CatPositionRec
118 #FSCatalogInfo
119 #FSForkInfo
120 #FSIterator
121 #FSVolumeInfo
122 #FSSpecArrayPtr
124 includestuff = includestuff + """
125 #ifdef WITHOUT_FRAMEWORKS
126 #include <Files.h>
127 #else
128 #include <Carbon/Carbon.h>
129 #endif
131 #ifdef USE_TOOLBOX_OBJECT_GLUE
132 extern int _PyMac_GetFSSpec(PyObject *v, FSSpec *spec);
133 extern int _PyMac_GetFSRef(PyObject *v, FSRef *fsr);
134 extern PyObject *_PyMac_BuildFSSpec(FSSpec *spec);
135 extern PyObject *_PyMac_BuildFSRef(FSRef *spec);
137 #define PyMac_GetFSSpec _PyMac_GetFSSpec
138 #define PyMac_GetFSRef _PyMac_GetFSRef
139 #define PyMac_BuildFSSpec _PyMac_BuildFSSpec
140 #define PyMac_BuildFSRef _PyMac_BuildFSRef
141 #else
142 extern int PyMac_GetFSSpec(PyObject *v, FSSpec *spec);
143 extern int PyMac_GetFSRef(PyObject *v, FSRef *fsr);
144 extern PyObject *PyMac_BuildFSSpec(FSSpec *spec);
145 extern PyObject *PyMac_BuildFSRef(FSRef *spec);
146 #endif
148 /* Forward declarations */
149 static PyObject *FInfo_New(FInfo *itself);
150 static PyObject *FSRef_New(FSRef *itself);
151 static PyObject *FSSpec_New(FSSpec *itself);
152 static PyObject *Alias_New(AliasHandle itself);
153 static int FInfo_Convert(PyObject *v, FInfo *p_itself);
154 #define FSRef_Convert PyMac_GetFSRef
155 #define FSSpec_Convert PyMac_GetFSSpec
156 static int Alias_Convert(PyObject *v, AliasHandle *p_itself);
159 ** UTCDateTime records
161 static int
162 UTCDateTime_Convert(PyObject *v, UTCDateTime *ptr)
164 return PyArg_Parse(v, "(HlH)", &ptr->highSeconds, &ptr->lowSeconds, &ptr->fraction);
167 static PyObject *
168 UTCDateTime_New(UTCDateTime *ptr)
170 return Py_BuildValue("(HlH)", ptr->highSeconds, ptr->lowSeconds, ptr->fraction);
174 ** Optional fsspec and fsref pointers. None will pass NULL
176 static int
177 myPyMac_GetOptFSSpecPtr(PyObject *v, FSSpec **spec)
179 if (v == Py_None) {
180 *spec = NULL;
181 return 1;
183 return PyMac_GetFSSpec(v, *spec);
186 static int
187 myPyMac_GetOptFSRefPtr(PyObject *v, FSRef **ref)
189 if (v == Py_None) {
190 *ref = NULL;
191 return 1;
193 return PyMac_GetFSRef(v, *ref);
197 ** Parse/generate objsect
199 static PyObject *
200 PyMac_BuildHFSUniStr255(HFSUniStr255 *itself)
203 return Py_BuildValue("u#", itself->unicode, itself->length);
207 finalstuff = finalstuff + """
209 PyMac_GetFSSpec(PyObject *v, FSSpec *spec)
211 Str255 path;
212 short refnum;
213 long parid;
214 OSErr err;
215 FSRef fsr;
217 if (FSSpec_Check(v)) {
218 *spec = ((FSSpecObject *)v)->ob_itself;
219 return 1;
222 if (PyArg_Parse(v, "(hlO&)",
223 &refnum, &parid, PyMac_GetStr255, &path)) {
224 err = FSMakeFSSpec(refnum, parid, path, spec);
225 if ( err && err != fnfErr ) {
226 PyMac_Error(err);
227 return 0;
229 return 1;
231 PyErr_Clear();
232 #if !TARGET_API_MAC_OSX
233 /* On OS9 we now try a pathname */
234 if ( PyString_Check(v) ) {
235 /* It's a pathname */
236 if( !PyArg_Parse(v, "O&", PyMac_GetStr255, &path) )
237 return 0;
238 refnum = 0; /* XXXX Should get CurWD here?? */
239 parid = 0;
240 err = FSMakeFSSpec(refnum, parid, path, spec);
241 if ( err && err != fnfErr ) {
242 PyMac_Error(err);
243 return 0;
245 return 1;
247 PyErr_Clear();
248 #endif
249 /* Otherwise we try to go via an FSRef. On OSX we go all the way,
250 ** on OS9 we accept only a real FSRef object
252 #if TARGET_API_MAC_OSX
253 if ( PyMac_GetFSRef(v, &fsr) ) {
254 #else
255 if ( PyArg_Parse(v, "O&", FSRef_Convert, &fsr) ) {
256 #endif
257 err = FSGetCatalogInfo(&fsr, kFSCatInfoNone, NULL, NULL, spec, NULL);
258 if (err != noErr) {
259 PyMac_Error(err);
260 return 0;
262 return 1;
264 #if !TARGET_API_MAC_OSX
265 PyErr_SetString(PyExc_TypeError, "FSSpec, FSRef, pathname or (refnum, parid, path) required");
266 #endif
267 return 0;
271 PyMac_GetFSRef(PyObject *v, FSRef *fsr)
273 OSStatus err;
274 FSSpec fss;
276 if (FSRef_Check(v)) {
277 *fsr = ((FSRefObject *)v)->ob_itself;
278 return 1;
281 #if TARGET_API_MAC_OSX
282 /* On OSX we now try a pathname */
283 if ( PyString_Check(v) || PyUnicode_Check(v)) {
284 char *path = NULL;
285 if (!PyArg_Parse(v, "et", Py_FileSystemDefaultEncoding, &path))
286 return NULL;
287 if ( (err=FSPathMakeRef(path, fsr, NULL)) ) {
288 PyMac_Error(err);
289 return 0;
291 return 1;
293 /* XXXX Should try unicode here too */
294 #endif
295 /* Otherwise we try to go via an FSSpec */
296 #if TARGET_API_MAC_OSX
297 if (FSSpec_Check(v)) {
298 fss = ((FSSpecObject *)v)->ob_itself;
299 #else
300 if (PyMac_GetFSSpec(v, &fss)) {
301 #endif
302 if ((err=FSpMakeFSRef(&fss, fsr)) == 0)
303 return 1;
304 PyMac_Error(err);
305 return 0;
307 PyErr_SetString(PyExc_TypeError, "FSRef, FSSpec or pathname required");
308 return 0;
311 extern PyObject *
312 PyMac_BuildFSSpec(FSSpec *spec)
314 return FSSpec_New(spec);
317 extern PyObject *
318 PyMac_BuildFSRef(FSRef *spec)
320 return FSRef_New(spec);
324 initstuff = initstuff + """
325 PyMac_INIT_TOOLBOX_OBJECT_NEW(FSSpec *, PyMac_BuildFSSpec);
326 PyMac_INIT_TOOLBOX_OBJECT_NEW(FSRef *, PyMac_BuildFSRef);
327 PyMac_INIT_TOOLBOX_OBJECT_CONVERT(FSSpec, PyMac_GetFSSpec);
328 PyMac_INIT_TOOLBOX_OBJECT_CONVERT(FSRef, PyMac_GetFSRef);
331 execfile(string.lower(MODPREFIX) + 'typetest.py')
333 # Our object types:
334 class FSCatalogInfoDefinition(PEP253Mixin, ObjectDefinition):
335 getsetlist = [
336 ("nodeFlags",
337 "return Py_BuildValue(\"H\", self->ob_itself.nodeFlags);",
338 "return PyArg_Parse(v, \"H\", &self->ob_itself.nodeFlags)-1;",
339 None
341 ("volume",
342 "return Py_BuildValue(\"h\", self->ob_itself.volume);",
343 "return PyArg_Parse(v, \"h\", &self->ob_itself.volume)-1;",
344 None
346 ("parentDirID",
347 "return Py_BuildValue(\"l\", self->ob_itself.parentDirID);",
348 "return PyArg_Parse(v, \"l\", &self->ob_itself.parentDirID)-1;",
349 None
351 ("nodeID",
352 "return Py_BuildValue(\"l\", self->ob_itself.nodeID);",
353 "return PyArg_Parse(v, \"l\", &self->ob_itself.nodeID)-1;",
354 None
356 ("createDate",
357 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.createDate);",
358 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.createDate)-1;",
359 None
361 ("contentModDate",
362 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.contentModDate);",
363 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.contentModDate)-1;",
364 None
366 ("attributeModDate",
367 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.attributeModDate);",
368 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.attributeModDate)-1;",
369 None
371 ("accessDate",
372 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.accessDate);",
373 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.accessDate)-1;",
374 None
376 ("backupDate",
377 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.backupDate);",
378 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.backupDate)-1;",
379 None
381 ("permissions",
382 "return Py_BuildValue(\"(llll)\", self->ob_itself.permissions[0], self->ob_itself.permissions[1], self->ob_itself.permissions[2], self->ob_itself.permissions[3]);",
383 "return PyArg_Parse(v, \"(llll)\", &self->ob_itself.permissions[0], &self->ob_itself.permissions[1], &self->ob_itself.permissions[2], &self->ob_itself.permissions[3])-1;",
384 None
386 # XXXX FinderInfo TBD
387 # XXXX FinderXInfo TBD
388 ("valence",
389 "return Py_BuildValue(\"l\", self->ob_itself.valence);",
390 "return PyArg_Parse(v, \"l\", &self->ob_itself.valence)-1;",
391 None
393 ("dataLogicalSize",
394 "return Py_BuildValue(\"l\", self->ob_itself.dataLogicalSize);",
395 "return PyArg_Parse(v, \"l\", &self->ob_itself.dataLogicalSize)-1;",
396 None
398 ("dataPhysicalSize",
399 "return Py_BuildValue(\"l\", self->ob_itself.dataPhysicalSize);",
400 "return PyArg_Parse(v, \"l\", &self->ob_itself.dataPhysicalSize)-1;",
401 None
403 ("rsrcLogicalSize",
404 "return Py_BuildValue(\"l\", self->ob_itself.rsrcLogicalSize);",
405 "return PyArg_Parse(v, \"l\", &self->ob_itself.rsrcLogicalSize)-1;",
406 None
408 ("rsrcPhysicalSize",
409 "return Py_BuildValue(\"l\", self->ob_itself.rsrcPhysicalSize);",
410 "return PyArg_Parse(v, \"l\", &self->ob_itself.rsrcPhysicalSize)-1;",
411 None
413 ("sharingFlags",
414 "return Py_BuildValue(\"l\", self->ob_itself.sharingFlags);",
415 "return PyArg_Parse(v, \"l\", &self->ob_itself.sharingFlags)-1;",
416 None
418 ("userPrivileges",
419 "return Py_BuildValue(\"b\", self->ob_itself.userPrivileges);",
420 "return PyArg_Parse(v, \"b\", &self->ob_itself.userPrivileges)-1;",
421 None
424 # The same info, but in a different form
425 INITFORMAT = "HhllO&O&O&O&O&llllllb"
426 INITARGS = """&((FSCatalogInfoObject *)self)->ob_itself.nodeFlags,
427 &((FSCatalogInfoObject *)self)->ob_itself.volume,
428 &((FSCatalogInfoObject *)self)->ob_itself.parentDirID,
429 &((FSCatalogInfoObject *)self)->ob_itself.nodeID,
430 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.createDate,
431 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.contentModDate,
432 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.attributeModDate,
433 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.accessDate,
434 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.backupDate,
435 &((FSCatalogInfoObject *)self)->ob_itself.valence,
436 &((FSCatalogInfoObject *)self)->ob_itself.dataLogicalSize,
437 &((FSCatalogInfoObject *)self)->ob_itself.dataPhysicalSize,
438 &((FSCatalogInfoObject *)self)->ob_itself.rsrcLogicalSize,
439 &((FSCatalogInfoObject *)self)->ob_itself.rsrcPhysicalSize,
440 &((FSCatalogInfoObject *)self)->ob_itself.sharingFlags,
441 &((FSCatalogInfoObject *)self)->ob_itself.userPrivileges"""
442 INITNAMES = """
443 "nodeFlags",
444 "volume",
445 "parentDirID",
446 "nodeID",
447 "createDate",
448 "contentModDate",
449 "atributeModDate",
450 "accessDate",
451 "backupDate",
452 "valence",
453 "dataLogicalSize",
454 "dataPhysicalSize",
455 "rsrcLogicalSize",
456 "rsrcPhysicalSize",
457 "sharingFlags",
458 "userPrivileges"
461 def __init__(self, name, prefix, itselftype):
462 ObjectDefinition.__init__(self, name, prefix, itselftype)
463 self.argref = "*" # Store FSSpecs, but pass them by address
465 def outputCheckNewArg(self):
466 Output("if (itself == NULL) return Py_None;")
468 def output_tp_newBody(self):
469 Output("PyObject *self;");
470 Output()
471 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
472 Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));",
473 self.objecttype, self.itselftype)
474 Output("return self;")
476 def output_tp_initBody(self):
477 Output("static char *kw[] = {%s, 0};", self.INITNAMES)
478 Output()
479 Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|%s\", kw, %s))",
480 self.INITFORMAT, self.INITARGS)
481 OutLbrace()
482 Output("return -1;")
483 OutRbrace()
484 Output("return 0;")
486 class FInfoDefinition(PEP253Mixin, ObjectDefinition):
487 getsetlist = [
488 ("Type",
489 "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdType);",
490 "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdType)-1;",
491 "4-char file type"
493 ("Creator",
494 "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdCreator);",
495 "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdCreator)-1;",
496 "4-char file creator"
498 ("Flags",
499 "return Py_BuildValue(\"H\", self->ob_itself.fdFlags);",
500 "return PyArg_Parse(v, \"H\", &self->ob_itself.fdFlags)-1;",
501 "Finder flag bits"
503 ("Location",
504 "return Py_BuildValue(\"O&\", PyMac_BuildPoint, self->ob_itself.fdLocation);",
505 "return PyArg_Parse(v, \"O&\", PyMac_GetPoint, &self->ob_itself.fdLocation)-1;",
506 "(x, y) location of the file's icon in its parent finder window"
508 ("Fldr",
509 "return Py_BuildValue(\"h\", self->ob_itself.fdFldr);",
510 "return PyArg_Parse(v, \"h\", &self->ob_itself.fdFldr)-1;",
511 "Original folder, for 'put away'"
516 def __init__(self, name, prefix, itselftype):
517 ObjectDefinition.__init__(self, name, prefix, itselftype)
518 self.argref = "*" # Store FSSpecs, but pass them by address
520 def outputCheckNewArg(self):
521 Output("if (itself == NULL) return PyMac_Error(resNotFound);")
523 def output_tp_newBody(self):
524 Output("PyObject *self;");
525 Output()
526 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
527 Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));",
528 self.objecttype, self.itselftype)
529 Output("return self;")
531 def output_tp_initBody(self):
532 Output("%s *itself = NULL;", self.itselftype)
533 Output("static char *kw[] = {\"itself\", 0};")
534 Output()
535 Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"|O&\", kw, FInfo_Convert, &itself))")
536 OutLbrace()
537 Output("if (itself) memcpy(&((%s *)self)->ob_itself, itself, sizeof(%s));",
538 self.objecttype, self.itselftype)
539 Output("return 0;")
540 OutRbrace()
541 Output("return -1;")
543 class FSSpecDefinition(PEP253Mixin, ObjectDefinition):
544 getsetlist = [
545 ("data",
546 "return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));",
547 None,
548 "Raw data of the FSSpec object"
552 def __init__(self, name, prefix, itselftype):
553 ObjectDefinition.__init__(self, name, prefix, itselftype)
554 self.argref = "*" # Store FSSpecs, but pass them by address
556 def outputCheckNewArg(self):
557 Output("if (itself == NULL) return PyMac_Error(resNotFound);")
559 # We do Convert ourselves (with PyMac_GetFSxxx)
560 def outputConvert(self):
561 pass
563 def output_tp_newBody(self):
564 Output("PyObject *self;");
565 Output()
566 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
567 Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));",
568 self.objecttype, self.itselftype)
569 Output("return self;")
571 def output_tp_initBody(self):
572 Output("PyObject *v = NULL;")
573 Output("char *rawdata = NULL;")
574 Output("int rawdatalen = 0;")
575 Output("static char *kw[] = {\"itself\", \"rawdata\", 0};")
576 Output()
577 Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))")
578 Output("return -1;")
579 Output("if (v && rawdata)")
580 OutLbrace()
581 Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");")
582 Output("return -1;")
583 OutRbrace()
584 Output("if (!v && !rawdata)")
585 OutLbrace()
586 Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");")
587 Output("return -1;")
588 OutRbrace()
589 Output("if (rawdata)")
590 OutLbrace()
591 Output("if (rawdatalen != sizeof(%s))", self.itselftype)
592 OutLbrace()
593 Output("PyErr_SetString(PyExc_TypeError, \"%s rawdata incorrect size\");",
594 self.itselftype)
595 Output("return -1;")
596 OutRbrace()
597 Output("memcpy(&((%s *)self)->ob_itself, rawdata, rawdatalen);", self.objecttype)
598 Output("return 0;")
599 OutRbrace()
600 Output("if (PyMac_GetFSSpec(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype)
601 Output("return -1;")
603 def outputRepr(self):
604 Output()
605 Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype)
606 OutLbrace()
607 Output("char buf[512];")
608 Output("""PyOS_snprintf(buf, sizeof(buf), \"%%s((%%d, %%ld, '%%.*s'))\",
609 self->ob_type->tp_name,
610 self->ob_itself.vRefNum,
611 self->ob_itself.parID,
612 self->ob_itself.name[0], self->ob_itself.name+1);""")
613 Output("return PyString_FromString(buf);")
614 OutRbrace()
616 class FSRefDefinition(PEP253Mixin, ObjectDefinition):
617 getsetlist = [
618 ("data",
619 "return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));",
620 None,
621 "Raw data of the FSRef object"
625 def __init__(self, name, prefix, itselftype):
626 ObjectDefinition.__init__(self, name, prefix, itselftype)
627 self.argref = "*" # Store FSRefs, but pass them by address
629 def outputCheckNewArg(self):
630 Output("if (itself == NULL) return PyMac_Error(resNotFound);")
632 # We do Convert ourselves (with PyMac_GetFSxxx)
633 def outputConvert(self):
634 pass
636 def output_tp_newBody(self):
637 Output("PyObject *self;");
638 Output()
639 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
640 Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));",
641 self.objecttype, self.itselftype)
642 Output("return self;")
644 def output_tp_initBody(self):
645 Output("PyObject *v = NULL;")
646 Output("char *rawdata = NULL;")
647 Output("int rawdatalen = 0;")
648 Output("static char *kw[] = {\"itself\", \"rawdata\", 0};")
649 Output()
650 Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))")
651 Output("return -1;")
652 Output("if (v && rawdata)")
653 OutLbrace()
654 Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");")
655 Output("return -1;")
656 OutRbrace()
657 Output("if (!v && !rawdata)")
658 OutLbrace()
659 Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");")
660 Output("return -1;")
661 OutRbrace()
662 Output("if (rawdata)")
663 OutLbrace()
664 Output("if (rawdatalen != sizeof(%s))", self.itselftype)
665 OutLbrace()
666 Output("PyErr_SetString(PyExc_TypeError, \"%s rawdata incorrect size\");",
667 self.itselftype)
668 Output("return -1;")
669 OutRbrace()
670 Output("memcpy(&((%s *)self)->ob_itself, rawdata, rawdatalen);", self.objecttype)
671 Output("return 0;")
672 OutRbrace()
673 Output("if (PyMac_GetFSRef(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype)
674 Output("return -1;")
676 class AliasDefinition(PEP253Mixin, ObjectDefinition):
677 # XXXX Should inherit from resource?
678 getsetlist = [
679 ("data",
680 """int size;
681 PyObject *rv;
683 size = GetHandleSize((Handle)self->ob_itself);
684 HLock((Handle)self->ob_itself);
685 rv = PyString_FromStringAndSize(*(Handle)self->ob_itself, size);
686 HUnlock((Handle)self->ob_itself);
687 return rv;
688 """,
689 None,
690 "Raw data of the alias object"
694 def outputCheckNewArg(self):
695 Output("if (itself == NULL) return PyMac_Error(resNotFound);")
697 def outputStructMembers(self):
698 ObjectDefinition.outputStructMembers(self)
699 Output("void (*ob_freeit)(%s ptr);", self.itselftype)
701 def outputInitStructMembers(self):
702 ObjectDefinition.outputInitStructMembers(self)
703 Output("it->ob_freeit = NULL;")
705 def outputCleanupStructMembers(self):
706 Output("if (self->ob_freeit && self->ob_itself)")
707 OutLbrace()
708 Output("self->ob_freeit(self->ob_itself);")
709 OutRbrace()
710 Output("self->ob_itself = NULL;")
712 def output_tp_newBody(self):
713 Output("PyObject *self;");
714 Output()
715 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
716 Output("((%s *)self)->ob_itself = NULL;", self.objecttype)
717 Output("return self;")
719 def output_tp_initBody(self):
720 Output("%s itself = NULL;", self.itselftype)
721 Output("char *rawdata = NULL;")
722 Output("int rawdatalen = 0;")
723 Output("Handle h;")
724 Output("static char *kw[] = {\"itself\", \"rawdata\", 0};")
725 Output()
726 Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|O&s#\", kw, %s_Convert, &itself, &rawdata, &rawdatalen))",
727 self.prefix)
728 Output("return -1;")
729 Output("if (itself && rawdata)")
730 OutLbrace()
731 Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");")
732 Output("return -1;")
733 OutRbrace()
734 Output("if (!itself && !rawdata)")
735 OutLbrace()
736 Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");")
737 Output("return -1;")
738 OutRbrace()
739 Output("if (rawdata)")
740 OutLbrace()
741 Output("if ((h = NewHandle(rawdatalen)) == NULL)")
742 OutLbrace()
743 Output("PyErr_NoMemory();")
744 Output("return -1;")
745 OutRbrace()
746 Output("HLock(h);")
747 Output("memcpy((char *)*h, rawdata, rawdatalen);")
748 Output("HUnlock(h);")
749 Output("((%s *)self)->ob_itself = (%s)h;", self.objecttype, self.itselftype)
750 Output("return 0;")
751 OutRbrace()
752 Output("((%s *)self)->ob_itself = itself;", self.objecttype)
753 Output("return 0;")
755 # Alias methods come in two flavors: those with the alias as arg1 and
756 # those with the alias as arg 2.
757 class Arg2MethodGenerator(OSErrMethodGenerator):
758 """Similar to MethodGenerator, but has self as second argument"""
760 def parseArgumentList(self, args):
761 args0, arg1, argsrest = args[:1], args[1], args[2:]
762 t0, n0, m0 = arg1
763 args = args0 + argsrest
764 if m0 != InMode:
765 raise ValueError, "method's 'self' must be 'InMode'"
766 self.itself = Variable(t0, "_self->ob_itself", SelfMode)
767 FunctionGenerator.parseArgumentList(self, args)
768 self.argumentList.insert(2, self.itself)
770 # From here on it's basically all boiler plate...
772 # Create the generator groups and link them
773 module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff,
774 longname=LONGMODNAME)
776 fscataloginfoobject = FSCatalogInfoDefinition('FSCatalogInfo', 'FSCatalogInfo', 'FSCatalogInfo')
777 finfoobject = FInfoDefinition('FInfo', 'FInfo', 'FInfo')
778 aliasobject = AliasDefinition('Alias', 'Alias', 'AliasHandle')
779 fsspecobject = FSSpecDefinition('FSSpec', 'FSSpec', 'FSSpec')
780 fsrefobject = FSRefDefinition('FSRef', 'FSRef', 'FSRef')
782 module.addobject(fscataloginfoobject)
783 module.addobject(finfoobject)
784 module.addobject(aliasobject)
785 module.addobject(fsspecobject)
786 module.addobject(fsrefobject)
788 # Create the generator classes used to populate the lists
789 Function = OSErrFunctionGenerator
790 Method = OSErrMethodGenerator
792 # Create and populate the lists
793 functions = []
794 alias_methods = []
795 fsref_methods = []
796 fsspec_methods = []
797 execfile(INPUTFILE)
799 # Manual generators:
800 FSRefMakePath_body = """
801 OSStatus _err;
802 #define MAXPATHNAME 1024
803 UInt8 path[MAXPATHNAME];
804 UInt32 maxPathSize = MAXPATHNAME;
806 if (!PyArg_ParseTuple(_args, ""))
807 return NULL;
808 _err = FSRefMakePath(&_self->ob_itself,
809 path,
810 maxPathSize);
811 if (_err != noErr) return PyMac_Error(_err);
812 _res = Py_BuildValue("s", path);
813 return _res;
815 f = ManualGenerator("FSRefMakePath", FSRefMakePath_body)
816 f.docstring = lambda: "() -> string"
817 fsref_methods.append(f)
819 FSRef_as_pathname_body = """
820 #if TARGET_API_MAC_OSX
821 if (!PyArg_ParseTuple(_args, ""))
822 return NULL;
823 _res = FSRef_FSRefMakePath(_self, _args);
824 #else
825 char strbuf[1024];
826 OSErr err;
827 FSSpec fss;
829 if (!PyArg_ParseTuple(_args, ""))
830 return NULL;
831 if ( !PyMac_GetFSSpec((PyObject *)_self, &fss))
832 return NULL;
833 err = PyMac_GetFullPathname(&fss, strbuf, sizeof(strbuf));
834 if ( err ) {
835 PyMac_Error(err);
836 return NULL;
838 _res = PyString_FromString(strbuf);
839 #endif
840 return _res;
842 f = ManualGenerator("as_pathname", FSRef_as_pathname_body)
843 f.docstring = lambda: "() -> string"
844 fsref_methods.append(f)
846 FSSpec_as_pathname_body = """
847 char strbuf[1024];
848 OSErr err;
850 if (!PyArg_ParseTuple(_args, ""))
851 return NULL;
852 err = PyMac_GetFullPathname(&_self->ob_itself, strbuf, sizeof(strbuf));
853 if ( err ) {
854 PyMac_Error(err);
855 return NULL;
857 _res = PyString_FromString(strbuf);
858 return _res;
860 f = ManualGenerator("as_pathname", FSSpec_as_pathname_body)
861 f.docstring = lambda: "() -> string"
862 fsspec_methods.append(f)
864 FSSpec_as_tuple_body = """
865 if (!PyArg_ParseTuple(_args, ""))
866 return NULL;
867 _res = Py_BuildValue("(iis#)", _self->ob_itself.vRefNum, _self->ob_itself.parID,
868 &_self->ob_itself.name[1], _self->ob_itself.name[0]);
869 return _res;
871 f = ManualGenerator("as_tuple", FSSpec_as_tuple_body)
872 f.docstring = lambda: "() -> (vRefNum, dirID, name)"
873 fsspec_methods.append(f)
875 pathname_body = """
876 PyObject *obj;
878 if (!PyArg_ParseTuple(_args, "O", &obj))
879 return NULL;
880 if (PyString_Check(obj)) {
881 Py_INCREF(obj);
882 return obj;
884 if (PyUnicode_Check(obj))
885 return PyUnicode_AsEncodedString(obj, "utf8", "strict");
886 _res = PyObject_CallMethod(obj, "as_pathname", NULL);
887 return _res;
889 f = ManualGenerator("pathname", pathname_body)
890 f.docstring = lambda: "(str|unicode|FSSpec|FSref) -> pathname"
891 functions.append(f)
893 # add the populated lists to the generator groups
894 # (in a different wordl the scan program would generate this)
895 for f in functions: module.add(f)
896 for f in alias_methods: aliasobject.add(f)
897 for f in fsspec_methods: fsspecobject.add(f)
898 for f in fsref_methods: fsrefobject.add(f)
900 # generate output (open the output file as late as possible)
901 SetOutputFileName(OUTPUTFILE)
902 module.generate()