summaryrefslogtreecommitdiffstats
path: root/Tools/modulator/modulator.py
blob: 48287431b0d05bc9fadd352ab1da976e3b7cbb81 (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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#! /usr/bin/env python
#
# Modulator - Generate skeleton modules.
#
# The user fills out some forms with information about what the module
# should support (methods, objects), names of these things, prefixes to
# use for C code, whether the objects should also support access as numbers,
# etc etc etc.
# When the user presses 'Generate code' we generate a complete skeleton
# module in C.
#
# Alternatively, the selections made can be save to a python sourcefile and
# this sourcefile can be passed on the command line (resulting in the same
# skeleton C code).
#
# Jack Jansen, CWI, October 1994.
#

import sys, os
if os.name <> 'mac':
    sys.path.append(os.path.join(os.environ['HOME'],
                                 'src/python/Tools/modulator'))

from Tkinter import *
from Tkextra import *
from ScrolledListbox import ScrolledListbox
import sys
import genmodule
import string

oops = 'oops'

IDENTSTARTCHARS = string.letters + '_'
IDENTCHARS = string.letters + string.digits + '_'

# Check that string is a legal C identifier
def checkid(str):
    if not str: return 0
    if not str[0] in IDENTSTARTCHARS:
        return 0
    for c in str[1:]:
        if not c in IDENTCHARS:
            return 0
    return 1

def getlistlist(list):
    rv = []
    n = list.size()
    for i in range(n):
        rv.append(list.get(i))
    return rv
    
class UI:
    def __init__(self):
        self.main = Frame()
        self.main.pack()
        self.main.master.title('Modulator: Module view')
        self.cmdframe = Frame(self.main, {'relief':'raised', 'bd':'0.5m',
                                          Pack:{'side':'top',
                                                 'fill':'x'}})
        self.objframe = Frame(self.main, {Pack:{'side':'top', 'fill':'x',
                                                'expand':1}})


        self.check_button = Button(self.cmdframe,
                                  {'text':'Check', 'command':self.cb_check,
                                   Pack:{'side':'left', 'padx':'0.5m'}})
        self.save_button = Button(self.cmdframe,
                                  {'text':'Save...', 'command':self.cb_save,
                                   Pack:{'side':'left', 'padx':'0.5m'}})
        self.code_button = Button(self.cmdframe,
                                  {'text':'Generate code...',
                                   'command':self.cb_gencode,
                                   Pack:{'side':'left', 'padx':'0.5m'}})
        self.quit_button = Button(self.cmdframe,
                                  {'text':'Quit',
                                   'command':self.cb_quit,
                                   Pack:{'side':'right', 'padx':'0.5m'}})

        self.module = UI_module(self)
        self.objects = []
        self.modified = 0

    def run(self):
        self.main.mainloop()

    def cb_quit(self, *args):
        if self.modified:
            if not askyn('You have not saved\nAre you sure you want to quit?'):
                return
        sys.exit(0)

    def cb_check(self, *args):
        try:
            self.module.synchronize()
            for o in self.objects:
                o.synchronize()
        except oops:
            pass
        
    def cb_save(self, *args):
        try:
            pycode = self.module.gencode('m', self.objects)
        except oops:
            return

        fn = askfile('Python file name: ')
        if not fn:
            return

        fp = open(fn, 'w')

        fp.write(pycode)
        fp.close()

    def cb_gencode(self, *args):
        try:
            pycode = self.module.gencode('m', self.objects)
        except oops:
            pass

        fn = askfile('C file name: ')
        if not fn:
            return

        fp = open(fn, 'w')

        try:
            exec pycode
        except:
            message('An error occurred:-)')
            return
        genmodule.write(fp, m)
        fp.close()

class UI_module:
    def __init__(self, parent):
        self.parent = parent
        self.frame = Frame(parent.objframe, {'relief':'raised', 'bd':'0.2m',
                                             Pack:{'side':'top',
                                                   'fill':'x'}})
        self.f1 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
                                           'fill':'x'}})
        self.f2 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
                                           'fill':'x'}})
        self.f3 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
                                           'fill':'x'}})
        self.f4 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
                                           'fill':'x'}})

        self.l1 = Label(self.f1, {'text':'Module:', Pack:{'side':'left',
                                                        'padx':'0.5m'}})
        self.name_entry = Entry(self.f1, {'relief':'sunken',
                              Pack:{'side':'left', 'padx':'0.5m', 'expand':1}})
        self.l2 = Label(self.f1, {'text':'Abbrev:', Pack:{'side':'left',
                                                        'padx':'0.5m'}})
        self.abbrev_entry = Entry(self.f1, {'relief':'sunken', 'width':5,
                              Pack:{'side':'left', 'padx':'0.5m'}})

        self.l3 = Label(self.f2, {'text':'Methods:', Pack:{'side':'left',
                                                        'padx':'0.5m'}})
        self.method_list = ScrolledListbox(self.f2, {'relief':'sunken','bd':2,
                                      Pack:{'side':'left', 'expand':1,
                                            'padx':'0.5m', 'fill':'both'}})

        self.l4 = Label(self.f3, {'text':'Add method:', Pack:{'side':'left',
                                                              'padx':'0.5m'}})
        self.method_entry = Entry(self.f3, {'relief':'sunken',
                             Pack:{'side':'left', 'padx':'0.5m', 'expand':1}})
        self.method_entry.bind('<Return>', self.cb_method)
        self.delete_button = Button(self.f3, {'text':'Delete method',
                                              'command':self.cb_delmethod,
                                              Pack:{'side':'left',
                                                    'padx':'0.5m'}})

        self.newobj_button = Button(self.f4, {'text':'new object',
                                              'command':self.cb_newobj,
                                              Pack:{'side':'left',
                                                    'padx':'0.5m'}})
        
    def cb_delmethod(self, *args):
        list = self.method_list.curselection()
        for i in list:
            self.method_list.delete(i)
        
    def cb_newobj(self, *arg):
        self.parent.objects.append(UI_object(self.parent))

    def cb_method(self, *arg):
        name = self.method_entry.get()
        if not name:
            return
        self.method_entry.delete('0', 'end')
        self.method_list.insert('end', name)

    def synchronize(self):
        n = self.name_entry.get()
        if not n:
            message('Module name not set')
            raise oops
        if not checkid(n):
            message('Module name not an identifier:\n'+n)
            raise oops
        if not self.abbrev_entry.get():
            self.abbrev_entry.insert('end', n)
        m = getlistlist(self.method_list)
        for n in m:
            if not checkid(n):
                message('Method name not an identifier:\n'+n)
                raise oops
            
    def gencode(self, name, objects):
        rv = ''
        self.synchronize()
        for o in objects:
            o.synchronize()
        onames = []
        for i in range(len(objects)):
            oname = 'o%d' % (i+1)
            rv = rv + objects[i].gencode(oname)
            onames.append(oname)
        rv = rv + '%s = genmodule.module()\n' % (name,)
        rv = rv + '%s.name = %r\n' % (name, self.name_entry.get())
        rv = rv + '%s.abbrev = %r\n' % (name, self.abbrev_entry.get())
        rv = rv + '%s.methodlist = %r\n' % (name, getlistlist(self.method_list))
        rv = rv + '%s.objects = [%s]\n' % (name, ','.join(onames))
        rv = rv + '\n'
        return rv
        
object_number = 0

class UI_object:
    def __init__(self, parent):
        global object_number

        object_number = object_number + 1
        self.num = object_number
        self.vpref = 'o%r_' % self.num
        self.frame = Toplevel(parent.objframe)
#       self.frame.pack()
        self.frame.title('Modulator: object view')
#       self.frame = Frame(parent.objframe, {'relief':'raised', 'bd':'0.2m',
#                                            Pack:{'side':'top',
#                                                  'fill':'x'}})
        self.f1 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
                                           'fill':'x'}})
        self.f2 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
                                           'fill':'x'}})
        self.f3 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
                                           'fill':'x'}})
        self.f4 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
                                           'fill':'x'}})
        

        self.l1 = Label(self.f1, {'text':'Object:', Pack:{'side':'left',
                                                        'padx':'0.5m'}})
        self.name_entry = Entry(self.f1, {'relief':'sunken',
                              Pack:{'side':'left', 'padx':'0.5m', 'expand':1}})
        self.l2 = Label(self.f1, {'text':'Abbrev:', Pack:{'side':'left',
                                                        'padx':'0.5m'}})
        self.abbrev_entry = Entry(self.f1, {'relief':'sunken', 'width':5,
                              Pack:{'side':'left', 'padx':'0.5m'}})

        self.l3 = Label(self.f2, {'text':'Methods:', Pack:{'side':'left',
                                                        'padx':'0.5m'}})
        self.method_list = ScrolledListbox(self.f2, {'relief':'sunken','bd':2,
                                      Pack:{'side':'left', 'expand':1,
                                            'padx':'0.5m', 'fill':'both'}})

        self.l4 = Label(self.f3, {'text':'Add method:', Pack:{'side':'left',
                                                              'padx':'0.5m'}})
        self.method_entry = Entry(self.f3, {'relief':'sunken',
                             Pack:{'side':'left', 'padx':'0.5m', 'expand':1}})
        self.method_entry.bind('<Return>', self.cb_method)
        self.delete_button = Button(self.f3, {'text':'Delete method',
                                              'command':self.cb_delmethod,
                                              Pack:{'side':'left',
                                                    'padx':'0.5m'}})


        self.l5 = Label(self.f4, {'text':'functions:',
                                  Pack:{'side':'left',
                                        'padx':'0.5m'}})
        self.f5 = Frame(self.f4, {Pack:{'side':'left', 'pady':'0.5m',
                                           'fill':'both'}})
        self.l6 = Label(self.f4, {'text':'Types:',
                                  Pack:{'side':'left', 'padx':'0.5m'}})
        self.f6 = Frame(self.f4, {Pack:{'side':'left', 'pady':'0.5m',
                                           'fill':'x'}})
        self.funcs = {}
        for i in genmodule.FUNCLIST:
            vname = self.vpref+i
            self.f5.setvar(vname, 0)
            b = Checkbutton(self.f5, {'variable':vname, 'text':i,
                                      Pack:{'side':'top', 'pady':'0.5m',
                                            'anchor':'w','expand':1}})
            self.funcs[i] = b
        self.f5.setvar(self.vpref+'new', 1)

        self.types = {}
        for i in genmodule.TYPELIST:
            vname = self.vpref + i
            self.f6.setvar(vname, 0)
            b = Checkbutton(self.f6, {'variable':vname, 'text':i,
                                      Pack:{'side':'top', 'pady':'0.5m',
                                            'anchor':'w'}})
            self.types[i] = b
        
    def cb_method(self, *arg):
        name = self.method_entry.get()
        if not name:
            return
        self.method_entry.delete('0', 'end')
        self.method_list.insert('end', name)

    def cb_delmethod(self, *args):
        list = self.method_list.curselection()
        for i in list:
            self.method_list.delete(i)
        
    def synchronize(self):
        n = self.name_entry.get()
        if not n:
            message('Object name not set')
            raise oops
        if not self.abbrev_entry.get():
            self.abbrev_entry.insert('end', n)
        n = self.abbrev_entry.get()
        if not checkid(n):
            message('Abbreviation not an identifier:\n'+n)
            raise oops
        m = getlistlist(self.method_list)
        for n in m:
            if not checkid(n):
                message('Method name not an identifier:\n'+n)
                raise oops
        if m:
            self.f5.setvar(self.vpref+'tp_getattr', 1)
        pass
        
    def gencode(self, name):
        rv = ''
        rv = rv + '%s = genmodule.object()\n' % (name,)
        rv = rv + '%s.name = %r\n' % (name, self.name_entry.get())
        rv = rv + '%s.abbrev = %r\n' % (name, self.abbrev_entry.get())
        rv = rv + '%s.methodlist = %r\n' % (name, getlistlist(self.method_list))
        fl = []
        for fn in genmodule.FUNCLIST:
            vname = self.vpref + fn
            if self.f5.getvar(vname) == '1':
                fl.append(fn)
        rv = rv + '%s.funclist = %r\n' % (name, fl)

        fl = []
        for fn in genmodule.TYPELIST:
            vname = self.vpref + fn
            if self.f5.getvar(vname) == '1':
                fl.append(fn)
                
        rv = rv + '%s.typelist = %r\n' % (name, fl)

        rv = rv + '\n'
        return rv
        

def main():
    if len(sys.argv) < 2:
        ui = UI()
        ui.run()
    elif len(sys.argv) == 2:
        fp = open(sys.argv[1])
        pycode = fp.read()
        try:
            exec pycode
        except:
            sys.stderr.write('An error occurred:-)\n')
            sys.exit(1)
        ##genmodule.write(sys.stdout, m)
    else:
        sys.stderr.write('Usage: modulator [file]\n')
        sys.exit(1)
        
main()