blob: 3c1343e4f2441140ee4b45a442bf615035127386 [file] [log] [blame]
Jack Jansen0acb7f71996-05-31 13:02:21 +00001"""Creation of PYC resources"""
2import os
3import Res
4import __builtin__
5
6READ = 1
7WRITE = 2
8smAllScripts = -3
9
10def Pstring(str):
11 """Return a pascal-style string from a python-style string"""
12 if len(str) > 255:
13 raise ValueError, 'String too large'
14 return chr(len(str))+str
15
16def create(dst, creator='Pyth'):
17 """Create output file. Return handle and first id to use."""
18
19 try:
20 os.unlink(dst)
21 except os.error:
22 pass
23 Res.FSpCreateResFile(dst, creator, 'rsrc', smAllScripts)
24 return open(dst)
25
26def open(dst):
27 output = Res.FSpOpenResFile(dst, WRITE)
28 Res.UseResFile(output)
29 return output
30
Jack Jansend3b06a81997-06-12 10:50:47 +000031def writemodule(name, id, data, type='PYC ', preload=0):
Jack Jansen0acb7f71996-05-31 13:02:21 +000032 """Write pyc code to a PYC resource with given name and id."""
33 # XXXX Check that it doesn't exist
34 res = Res.Resource(data)
35 res.AddResource(type, id, name)
Jack Jansend3b06a81997-06-12 10:50:47 +000036 if preload:
37 attrs = res.GetResAttrs()
38 attrs = attrs | 0x04
39 res.SetResAttrs(attrs)
Jack Jansen0acb7f71996-05-31 13:02:21 +000040 res.WriteResource()
41 res.ReleaseResource()
42
Jack Jansend3b06a81997-06-12 10:50:47 +000043def frompycfile(file, name=None, preload=0):
Jack Jansen0acb7f71996-05-31 13:02:21 +000044 """Copy one pyc file to the open resource file"""
45 if name == None:
46 d, name = os.path.split(file)
47 name = name[:-4]
48 id = findfreeid()
Jack Jansend3b06a81997-06-12 10:50:47 +000049 writemodule(name, id, __builtin__.open(file, 'rb').read(), preload=preload)
Jack Jansen0acb7f71996-05-31 13:02:21 +000050 return id, name
51
Jack Jansend3b06a81997-06-12 10:50:47 +000052def frompyfile(file, name=None, preload=0):
Jack Jansen0acb7f71996-05-31 13:02:21 +000053 """Compile python source file to pyc file and add to resource file"""
54 import py_compile
55
56 py_compile.compile(file)
57 file = file +'c'
Jack Jansend3b06a81997-06-12 10:50:47 +000058 return frompycfile(file, name, preload=preload)
Jack Jansen0acb7f71996-05-31 13:02:21 +000059
60# XXXX Note this is incorrect, it only handles one type and one file....
61
62_firstfreeid = None
63
64def findfreeid(type='PYC '):
65 """Find next free id-number for given resource type"""
66 global _firstfreeid
67
68 if _firstfreeid == None:
69 Res.SetResLoad(0)
70 highest = 511
71 num = Res.Count1Resources(type)
72 for i in range(1, num+1):
73 r = Res.Get1IndResource(type, i)
74 id, d1, d2 = r.GetResInfo()
75 highest = max(highest, id)
76 Res.SetResLoad(1)
77 _firstfreeid = highest+1
78 id = _firstfreeid
79 _firstfreeid = _firstfreeid+1
80 return id