Whitespace normalization.
[python/dscho.git] / Mac / Modules / file / filesupport.py
blobf06bbb8f2dfcae62df63dc55da9d77677264630d
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 #include <Carbon/Carbon.h>
127 #ifdef USE_TOOLBOX_OBJECT_GLUE
128 extern int _PyMac_GetFSSpec(PyObject *v, FSSpec *spec);
129 extern int _PyMac_GetFSRef(PyObject *v, FSRef *fsr);
130 extern PyObject *_PyMac_BuildFSSpec(FSSpec *spec);
131 extern PyObject *_PyMac_BuildFSRef(FSRef *spec);
133 #define PyMac_GetFSSpec _PyMac_GetFSSpec
134 #define PyMac_GetFSRef _PyMac_GetFSRef
135 #define PyMac_BuildFSSpec _PyMac_BuildFSSpec
136 #define PyMac_BuildFSRef _PyMac_BuildFSRef
137 #else
138 extern int PyMac_GetFSSpec(PyObject *v, FSSpec *spec);
139 extern int PyMac_GetFSRef(PyObject *v, FSRef *fsr);
140 extern PyObject *PyMac_BuildFSSpec(FSSpec *spec);
141 extern PyObject *PyMac_BuildFSRef(FSRef *spec);
142 #endif
144 /* Forward declarations */
145 static PyObject *FInfo_New(FInfo *itself);
146 static PyObject *FSRef_New(FSRef *itself);
147 static PyObject *FSSpec_New(FSSpec *itself);
148 static PyObject *Alias_New(AliasHandle itself);
149 static int FInfo_Convert(PyObject *v, FInfo *p_itself);
150 #define FSRef_Convert PyMac_GetFSRef
151 #define FSSpec_Convert PyMac_GetFSSpec
152 static int Alias_Convert(PyObject *v, AliasHandle *p_itself);
155 ** UTCDateTime records
157 static int
158 UTCDateTime_Convert(PyObject *v, UTCDateTime *ptr)
160 return PyArg_Parse(v, "(HlH)", &ptr->highSeconds, &ptr->lowSeconds, &ptr->fraction);
163 static PyObject *
164 UTCDateTime_New(UTCDateTime *ptr)
166 return Py_BuildValue("(HlH)", ptr->highSeconds, ptr->lowSeconds, ptr->fraction);
170 ** Optional fsspec and fsref pointers. None will pass NULL
172 static int
173 myPyMac_GetOptFSSpecPtr(PyObject *v, FSSpec **spec)
175 if (v == Py_None) {
176 *spec = NULL;
177 return 1;
179 return PyMac_GetFSSpec(v, *spec);
182 static int
183 myPyMac_GetOptFSRefPtr(PyObject *v, FSRef **ref)
185 if (v == Py_None) {
186 *ref = NULL;
187 return 1;
189 return PyMac_GetFSRef(v, *ref);
193 ** Parse/generate objsect
195 static PyObject *
196 PyMac_BuildHFSUniStr255(HFSUniStr255 *itself)
199 return Py_BuildValue("u#", itself->unicode, itself->length);
203 finalstuff = finalstuff + """
205 PyMac_GetFSSpec(PyObject *v, FSSpec *spec)
207 Str255 path;
208 short refnum;
209 long parid;
210 OSErr err;
211 FSRef fsr;
213 if (FSSpec_Check(v)) {
214 *spec = ((FSSpecObject *)v)->ob_itself;
215 return 1;
218 if (PyArg_Parse(v, "(hlO&)",
219 &refnum, &parid, PyMac_GetStr255, &path)) {
220 err = FSMakeFSSpec(refnum, parid, path, spec);
221 if ( err && err != fnfErr ) {
222 PyMac_Error(err);
223 return 0;
225 return 1;
227 PyErr_Clear();
228 /* Otherwise we try to go via an FSRef. On OSX we go all the way,
229 ** on OS9 we accept only a real FSRef object
231 if ( PyMac_GetFSRef(v, &fsr) ) {
232 err = FSGetCatalogInfo(&fsr, kFSCatInfoNone, NULL, NULL, spec, NULL);
233 if (err != noErr) {
234 PyMac_Error(err);
235 return 0;
237 return 1;
239 return 0;
243 PyMac_GetFSRef(PyObject *v, FSRef *fsr)
245 OSStatus err;
246 FSSpec fss;
248 if (FSRef_Check(v)) {
249 *fsr = ((FSRefObject *)v)->ob_itself;
250 return 1;
253 /* On OSX we now try a pathname */
254 if ( PyString_Check(v) || PyUnicode_Check(v)) {
255 char *path = NULL;
256 if (!PyArg_Parse(v, "et", Py_FileSystemDefaultEncoding, &path))
257 return NULL;
258 if ( (err=FSPathMakeRef(path, fsr, NULL)) ) {
259 PyMac_Error(err);
260 return 0;
262 return 1;
264 /* XXXX Should try unicode here too */
265 /* Otherwise we try to go via an FSSpec */
266 if (FSSpec_Check(v)) {
267 fss = ((FSSpecObject *)v)->ob_itself;
268 if ((err=FSpMakeFSRef(&fss, fsr)) == 0)
269 return 1;
270 PyMac_Error(err);
271 return 0;
273 PyErr_SetString(PyExc_TypeError, "FSRef, FSSpec or pathname required");
274 return 0;
277 extern PyObject *
278 PyMac_BuildFSSpec(FSSpec *spec)
280 return FSSpec_New(spec);
283 extern PyObject *
284 PyMac_BuildFSRef(FSRef *spec)
286 return FSRef_New(spec);
290 initstuff = initstuff + """
291 PyMac_INIT_TOOLBOX_OBJECT_NEW(FSSpec *, PyMac_BuildFSSpec);
292 PyMac_INIT_TOOLBOX_OBJECT_NEW(FSRef *, PyMac_BuildFSRef);
293 PyMac_INIT_TOOLBOX_OBJECT_CONVERT(FSSpec, PyMac_GetFSSpec);
294 PyMac_INIT_TOOLBOX_OBJECT_CONVERT(FSRef, PyMac_GetFSRef);
297 execfile(string.lower(MODPREFIX) + 'typetest.py')
299 # Our object types:
300 class FSCatalogInfoDefinition(PEP253Mixin, ObjectDefinition):
301 getsetlist = [
302 ("nodeFlags",
303 "return Py_BuildValue(\"H\", self->ob_itself.nodeFlags);",
304 "return PyArg_Parse(v, \"H\", &self->ob_itself.nodeFlags)-1;",
305 None
307 ("volume",
308 "return Py_BuildValue(\"h\", self->ob_itself.volume);",
309 "return PyArg_Parse(v, \"h\", &self->ob_itself.volume)-1;",
310 None
312 ("parentDirID",
313 "return Py_BuildValue(\"l\", self->ob_itself.parentDirID);",
314 "return PyArg_Parse(v, \"l\", &self->ob_itself.parentDirID)-1;",
315 None
317 ("nodeID",
318 "return Py_BuildValue(\"l\", self->ob_itself.nodeID);",
319 "return PyArg_Parse(v, \"l\", &self->ob_itself.nodeID)-1;",
320 None
322 ("createDate",
323 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.createDate);",
324 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.createDate)-1;",
325 None
327 ("contentModDate",
328 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.contentModDate);",
329 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.contentModDate)-1;",
330 None
332 ("attributeModDate",
333 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.attributeModDate);",
334 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.attributeModDate)-1;",
335 None
337 ("accessDate",
338 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.accessDate);",
339 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.accessDate)-1;",
340 None
342 ("backupDate",
343 "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.backupDate);",
344 "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.backupDate)-1;",
345 None
347 ("permissions",
348 "return Py_BuildValue(\"(llll)\", self->ob_itself.permissions[0], self->ob_itself.permissions[1], self->ob_itself.permissions[2], self->ob_itself.permissions[3]);",
349 "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;",
350 None
352 # XXXX FinderInfo TBD
353 # XXXX FinderXInfo TBD
354 ("valence",
355 "return Py_BuildValue(\"l\", self->ob_itself.valence);",
356 "return PyArg_Parse(v, \"l\", &self->ob_itself.valence)-1;",
357 None
359 ("dataLogicalSize",
360 "return Py_BuildValue(\"l\", self->ob_itself.dataLogicalSize);",
361 "return PyArg_Parse(v, \"l\", &self->ob_itself.dataLogicalSize)-1;",
362 None
364 ("dataPhysicalSize",
365 "return Py_BuildValue(\"l\", self->ob_itself.dataPhysicalSize);",
366 "return PyArg_Parse(v, \"l\", &self->ob_itself.dataPhysicalSize)-1;",
367 None
369 ("rsrcLogicalSize",
370 "return Py_BuildValue(\"l\", self->ob_itself.rsrcLogicalSize);",
371 "return PyArg_Parse(v, \"l\", &self->ob_itself.rsrcLogicalSize)-1;",
372 None
374 ("rsrcPhysicalSize",
375 "return Py_BuildValue(\"l\", self->ob_itself.rsrcPhysicalSize);",
376 "return PyArg_Parse(v, \"l\", &self->ob_itself.rsrcPhysicalSize)-1;",
377 None
379 ("sharingFlags",
380 "return Py_BuildValue(\"l\", self->ob_itself.sharingFlags);",
381 "return PyArg_Parse(v, \"l\", &self->ob_itself.sharingFlags)-1;",
382 None
384 ("userPrivileges",
385 "return Py_BuildValue(\"b\", self->ob_itself.userPrivileges);",
386 "return PyArg_Parse(v, \"b\", &self->ob_itself.userPrivileges)-1;",
387 None
390 # The same info, but in a different form
391 INITFORMAT = "HhllO&O&O&O&O&llllllb"
392 INITARGS = """&((FSCatalogInfoObject *)self)->ob_itself.nodeFlags,
393 &((FSCatalogInfoObject *)self)->ob_itself.volume,
394 &((FSCatalogInfoObject *)self)->ob_itself.parentDirID,
395 &((FSCatalogInfoObject *)self)->ob_itself.nodeID,
396 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.createDate,
397 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.contentModDate,
398 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.attributeModDate,
399 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.accessDate,
400 UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.backupDate,
401 &((FSCatalogInfoObject *)self)->ob_itself.valence,
402 &((FSCatalogInfoObject *)self)->ob_itself.dataLogicalSize,
403 &((FSCatalogInfoObject *)self)->ob_itself.dataPhysicalSize,
404 &((FSCatalogInfoObject *)self)->ob_itself.rsrcLogicalSize,
405 &((FSCatalogInfoObject *)self)->ob_itself.rsrcPhysicalSize,
406 &((FSCatalogInfoObject *)self)->ob_itself.sharingFlags,
407 &((FSCatalogInfoObject *)self)->ob_itself.userPrivileges"""
408 INITNAMES = """
409 "nodeFlags",
410 "volume",
411 "parentDirID",
412 "nodeID",
413 "createDate",
414 "contentModDate",
415 "atributeModDate",
416 "accessDate",
417 "backupDate",
418 "valence",
419 "dataLogicalSize",
420 "dataPhysicalSize",
421 "rsrcLogicalSize",
422 "rsrcPhysicalSize",
423 "sharingFlags",
424 "userPrivileges"
427 def __init__(self, name, prefix, itselftype):
428 ObjectDefinition.__init__(self, name, prefix, itselftype)
429 self.argref = "*" # Store FSSpecs, but pass them by address
431 def outputCheckNewArg(self):
432 Output("if (itself == NULL) return Py_None;")
434 def output_tp_newBody(self):
435 Output("PyObject *self;");
436 Output()
437 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
438 Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));",
439 self.objecttype, self.itselftype)
440 Output("return self;")
442 def output_tp_initBody(self):
443 Output("static char *kw[] = {%s, 0};", self.INITNAMES)
444 Output()
445 Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|%s\", kw, %s))",
446 self.INITFORMAT, self.INITARGS)
447 OutLbrace()
448 Output("return -1;")
449 OutRbrace()
450 Output("return 0;")
452 class FInfoDefinition(PEP253Mixin, ObjectDefinition):
453 getsetlist = [
454 ("Type",
455 "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdType);",
456 "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdType)-1;",
457 "4-char file type"
459 ("Creator",
460 "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdCreator);",
461 "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdCreator)-1;",
462 "4-char file creator"
464 ("Flags",
465 "return Py_BuildValue(\"H\", self->ob_itself.fdFlags);",
466 "return PyArg_Parse(v, \"H\", &self->ob_itself.fdFlags)-1;",
467 "Finder flag bits"
469 ("Location",
470 "return Py_BuildValue(\"O&\", PyMac_BuildPoint, self->ob_itself.fdLocation);",
471 "return PyArg_Parse(v, \"O&\", PyMac_GetPoint, &self->ob_itself.fdLocation)-1;",
472 "(x, y) location of the file's icon in its parent finder window"
474 ("Fldr",
475 "return Py_BuildValue(\"h\", self->ob_itself.fdFldr);",
476 "return PyArg_Parse(v, \"h\", &self->ob_itself.fdFldr)-1;",
477 "Original folder, for 'put away'"
482 def __init__(self, name, prefix, itselftype):
483 ObjectDefinition.__init__(self, name, prefix, itselftype)
484 self.argref = "*" # Store FSSpecs, but pass them by address
486 def outputCheckNewArg(self):
487 Output("if (itself == NULL) return PyMac_Error(resNotFound);")
489 def output_tp_newBody(self):
490 Output("PyObject *self;");
491 Output()
492 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
493 Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));",
494 self.objecttype, self.itselftype)
495 Output("return self;")
497 def output_tp_initBody(self):
498 Output("%s *itself = NULL;", self.itselftype)
499 Output("static char *kw[] = {\"itself\", 0};")
500 Output()
501 Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"|O&\", kw, FInfo_Convert, &itself))")
502 OutLbrace()
503 Output("if (itself) memcpy(&((%s *)self)->ob_itself, itself, sizeof(%s));",
504 self.objecttype, self.itselftype)
505 Output("return 0;")
506 OutRbrace()
507 Output("return -1;")
509 class FSSpecDefinition(PEP253Mixin, ObjectDefinition):
510 getsetlist = [
511 ("data",
512 "return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));",
513 None,
514 "Raw data of the FSSpec object"
518 def __init__(self, name, prefix, itselftype):
519 ObjectDefinition.__init__(self, name, prefix, itselftype)
520 self.argref = "*" # Store FSSpecs, but pass them by address
522 def outputCheckNewArg(self):
523 Output("if (itself == NULL) return PyMac_Error(resNotFound);")
525 # We do Convert ourselves (with PyMac_GetFSxxx)
526 def outputConvert(self):
527 pass
529 def output_tp_newBody(self):
530 Output("PyObject *self;");
531 Output()
532 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
533 Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));",
534 self.objecttype, self.itselftype)
535 Output("return self;")
537 def output_tp_initBody(self):
538 Output("PyObject *v = NULL;")
539 Output("char *rawdata = NULL;")
540 Output("int rawdatalen = 0;")
541 Output("static char *kw[] = {\"itself\", \"rawdata\", 0};")
542 Output()
543 Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))")
544 Output("return -1;")
545 Output("if (v && rawdata)")
546 OutLbrace()
547 Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");")
548 Output("return -1;")
549 OutRbrace()
550 Output("if (!v && !rawdata)")
551 OutLbrace()
552 Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");")
553 Output("return -1;")
554 OutRbrace()
555 Output("if (rawdata)")
556 OutLbrace()
557 Output("if (rawdatalen != sizeof(%s))", self.itselftype)
558 OutLbrace()
559 Output("PyErr_SetString(PyExc_TypeError, \"%s rawdata incorrect size\");",
560 self.itselftype)
561 Output("return -1;")
562 OutRbrace()
563 Output("memcpy(&((%s *)self)->ob_itself, rawdata, rawdatalen);", self.objecttype)
564 Output("return 0;")
565 OutRbrace()
566 Output("if (PyMac_GetFSSpec(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype)
567 Output("return -1;")
569 def outputRepr(self):
570 Output()
571 Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype)
572 OutLbrace()
573 Output("char buf[512];")
574 Output("""PyOS_snprintf(buf, sizeof(buf), \"%%s((%%d, %%ld, '%%.*s'))\",
575 self->ob_type->tp_name,
576 self->ob_itself.vRefNum,
577 self->ob_itself.parID,
578 self->ob_itself.name[0], self->ob_itself.name+1);""")
579 Output("return PyString_FromString(buf);")
580 OutRbrace()
582 class FSRefDefinition(PEP253Mixin, ObjectDefinition):
583 getsetlist = [
584 ("data",
585 "return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));",
586 None,
587 "Raw data of the FSRef object"
591 def __init__(self, name, prefix, itselftype):
592 ObjectDefinition.__init__(self, name, prefix, itselftype)
593 self.argref = "*" # Store FSRefs, but pass them by address
595 def outputCheckNewArg(self):
596 Output("if (itself == NULL) return PyMac_Error(resNotFound);")
598 # We do Convert ourselves (with PyMac_GetFSxxx)
599 def outputConvert(self):
600 pass
602 def output_tp_newBody(self):
603 Output("PyObject *self;");
604 Output()
605 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
606 Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));",
607 self.objecttype, self.itselftype)
608 Output("return self;")
610 def output_tp_initBody(self):
611 Output("PyObject *v = NULL;")
612 Output("char *rawdata = NULL;")
613 Output("int rawdatalen = 0;")
614 Output("static char *kw[] = {\"itself\", \"rawdata\", 0};")
615 Output()
616 Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))")
617 Output("return -1;")
618 Output("if (v && rawdata)")
619 OutLbrace()
620 Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");")
621 Output("return -1;")
622 OutRbrace()
623 Output("if (!v && !rawdata)")
624 OutLbrace()
625 Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");")
626 Output("return -1;")
627 OutRbrace()
628 Output("if (rawdata)")
629 OutLbrace()
630 Output("if (rawdatalen != sizeof(%s))", self.itselftype)
631 OutLbrace()
632 Output("PyErr_SetString(PyExc_TypeError, \"%s rawdata incorrect size\");",
633 self.itselftype)
634 Output("return -1;")
635 OutRbrace()
636 Output("memcpy(&((%s *)self)->ob_itself, rawdata, rawdatalen);", self.objecttype)
637 Output("return 0;")
638 OutRbrace()
639 Output("if (PyMac_GetFSRef(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype)
640 Output("return -1;")
642 class AliasDefinition(PEP253Mixin, ObjectDefinition):
643 # XXXX Should inherit from resource?
644 getsetlist = [
645 ("data",
646 """int size;
647 PyObject *rv;
649 size = GetHandleSize((Handle)self->ob_itself);
650 HLock((Handle)self->ob_itself);
651 rv = PyString_FromStringAndSize(*(Handle)self->ob_itself, size);
652 HUnlock((Handle)self->ob_itself);
653 return rv;
654 """,
655 None,
656 "Raw data of the alias object"
660 def outputCheckNewArg(self):
661 Output("if (itself == NULL) return PyMac_Error(resNotFound);")
663 def outputStructMembers(self):
664 ObjectDefinition.outputStructMembers(self)
665 Output("void (*ob_freeit)(%s ptr);", self.itselftype)
667 def outputInitStructMembers(self):
668 ObjectDefinition.outputInitStructMembers(self)
669 Output("it->ob_freeit = NULL;")
671 def outputCleanupStructMembers(self):
672 Output("if (self->ob_freeit && self->ob_itself)")
673 OutLbrace()
674 Output("self->ob_freeit(self->ob_itself);")
675 OutRbrace()
676 Output("self->ob_itself = NULL;")
678 def output_tp_newBody(self):
679 Output("PyObject *self;");
680 Output()
681 Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
682 Output("((%s *)self)->ob_itself = NULL;", self.objecttype)
683 Output("return self;")
685 def output_tp_initBody(self):
686 Output("%s itself = NULL;", self.itselftype)
687 Output("char *rawdata = NULL;")
688 Output("int rawdatalen = 0;")
689 Output("Handle h;")
690 Output("static char *kw[] = {\"itself\", \"rawdata\", 0};")
691 Output()
692 Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|O&s#\", kw, %s_Convert, &itself, &rawdata, &rawdatalen))",
693 self.prefix)
694 Output("return -1;")
695 Output("if (itself && rawdata)")
696 OutLbrace()
697 Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");")
698 Output("return -1;")
699 OutRbrace()
700 Output("if (!itself && !rawdata)")
701 OutLbrace()
702 Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");")
703 Output("return -1;")
704 OutRbrace()
705 Output("if (rawdata)")
706 OutLbrace()
707 Output("if ((h = NewHandle(rawdatalen)) == NULL)")
708 OutLbrace()
709 Output("PyErr_NoMemory();")
710 Output("return -1;")
711 OutRbrace()
712 Output("HLock(h);")
713 Output("memcpy((char *)*h, rawdata, rawdatalen);")
714 Output("HUnlock(h);")
715 Output("((%s *)self)->ob_itself = (%s)h;", self.objecttype, self.itselftype)
716 Output("return 0;")
717 OutRbrace()
718 Output("((%s *)self)->ob_itself = itself;", self.objecttype)
719 Output("return 0;")
721 # Alias methods come in two flavors: those with the alias as arg1 and
722 # those with the alias as arg 2.
723 class Arg2MethodGenerator(OSErrMethodGenerator):
724 """Similar to MethodGenerator, but has self as second argument"""
726 def parseArgumentList(self, args):
727 args0, arg1, argsrest = args[:1], args[1], args[2:]
728 t0, n0, m0 = arg1
729 args = args0 + argsrest
730 if m0 != InMode:
731 raise ValueError, "method's 'self' must be 'InMode'"
732 self.itself = Variable(t0, "_self->ob_itself", SelfMode)
733 FunctionGenerator.parseArgumentList(self, args)
734 self.argumentList.insert(2, self.itself)
736 # From here on it's basically all boiler plate...
738 # Create the generator groups and link them
739 module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff,
740 longname=LONGMODNAME)
742 fscataloginfoobject = FSCatalogInfoDefinition('FSCatalogInfo', 'FSCatalogInfo', 'FSCatalogInfo')
743 finfoobject = FInfoDefinition('FInfo', 'FInfo', 'FInfo')
744 aliasobject = AliasDefinition('Alias', 'Alias', 'AliasHandle')
745 fsspecobject = FSSpecDefinition('FSSpec', 'FSSpec', 'FSSpec')
746 fsrefobject = FSRefDefinition('FSRef', 'FSRef', 'FSRef')
748 module.addobject(fscataloginfoobject)
749 module.addobject(finfoobject)
750 module.addobject(aliasobject)
751 module.addobject(fsspecobject)
752 module.addobject(fsrefobject)
754 # Create the generator classes used to populate the lists
755 Function = OSErrFunctionGenerator
756 Method = OSErrMethodGenerator
758 # Create and populate the lists
759 functions = []
760 alias_methods = []
761 fsref_methods = []
762 fsspec_methods = []
763 execfile(INPUTFILE)
765 # Manual generators:
766 FSRefMakePath_body = """
767 OSStatus _err;
768 #define MAXPATHNAME 1024
769 UInt8 path[MAXPATHNAME];
770 UInt32 maxPathSize = MAXPATHNAME;
772 if (!PyArg_ParseTuple(_args, ""))
773 return NULL;
774 _err = FSRefMakePath(&_self->ob_itself,
775 path,
776 maxPathSize);
777 if (_err != noErr) return PyMac_Error(_err);
778 _res = Py_BuildValue("s", path);
779 return _res;
781 f = ManualGenerator("FSRefMakePath", FSRefMakePath_body)
782 f.docstring = lambda: "() -> string"
783 fsref_methods.append(f)
785 FSRef_as_pathname_body = """
786 if (!PyArg_ParseTuple(_args, ""))
787 return NULL;
788 _res = FSRef_FSRefMakePath(_self, _args);
789 return _res;
791 f = ManualGenerator("as_pathname", FSRef_as_pathname_body)
792 f.docstring = lambda: "() -> string"
793 fsref_methods.append(f)
795 FSSpec_as_pathname_body = """
796 char strbuf[1024];
797 OSErr err;
799 if (!PyArg_ParseTuple(_args, ""))
800 return NULL;
801 err = PyMac_GetFullPathname(&_self->ob_itself, strbuf, sizeof(strbuf));
802 if ( err ) {
803 PyMac_Error(err);
804 return NULL;
806 _res = PyString_FromString(strbuf);
807 return _res;
809 f = ManualGenerator("as_pathname", FSSpec_as_pathname_body)
810 f.docstring = lambda: "() -> string"
811 fsspec_methods.append(f)
813 FSSpec_as_tuple_body = """
814 if (!PyArg_ParseTuple(_args, ""))
815 return NULL;
816 _res = Py_BuildValue("(iis#)", _self->ob_itself.vRefNum, _self->ob_itself.parID,
817 &_self->ob_itself.name[1], _self->ob_itself.name[0]);
818 return _res;
820 f = ManualGenerator("as_tuple", FSSpec_as_tuple_body)
821 f.docstring = lambda: "() -> (vRefNum, dirID, name)"
822 fsspec_methods.append(f)
824 pathname_body = """
825 PyObject *obj;
827 if (!PyArg_ParseTuple(_args, "O", &obj))
828 return NULL;
829 if (PyString_Check(obj)) {
830 Py_INCREF(obj);
831 return obj;
833 if (PyUnicode_Check(obj))
834 return PyUnicode_AsEncodedString(obj, "utf8", "strict");
835 _res = PyObject_CallMethod(obj, "as_pathname", NULL);
836 return _res;
838 f = ManualGenerator("pathname", pathname_body)
839 f.docstring = lambda: "(str|unicode|FSSpec|FSref) -> pathname"
840 functions.append(f)
842 # add the populated lists to the generator groups
843 # (in a different wordl the scan program would generate this)
844 for f in functions: module.add(f)
845 for f in alias_methods: aliasobject.add(f)
846 for f in fsspec_methods: fsspecobject.add(f)
847 for f in fsref_methods: fsrefobject.add(f)
849 # generate output (open the output file as late as possible)
850 SetOutputFileName(OUTPUTFILE)
851 module.generate()