-
Notifications
You must be signed in to change notification settings - Fork 2
/
codegen_Odoov10.py
457 lines (424 loc) · 18.4 KB
/
codegen_Odoov10.py
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import sys, dia, os
import zipfile
#
# This code is inspired by codegen.py
#
class Klass :
def __init__ (self, name) :
self.name = name
self.attributes = []
# a list, as java/c++ support multiple methods with the same name
self.stereotype = ""
self.operations = []
self.comment = ""
self.parents = []
self.templates = []
self.inheritance_type = ""
def AddAttribute(self, name, type, visibility, value, comment) :
self.attributes.append((name, (type, visibility, value, comment)))
def AddOperation(self, name, type, visibility, params, inheritance_type, comment, class_scope) :
self.operations.append((name,(type, visibility, params, inheritance_type, comment, class_scope)))
def SetComment(self, s) :
self.comment = s
def AddParent(self, parent):
self.parents.append(parent)
def AddTemplate(self, template):
self.templates.append(template)
def SetInheritance_type(self, inheritance_type):
self.inheritance_type = inheritance_type
class ObjRenderer :
"Implements the Object Renderer Interface and transforms diagram into its internal representation"
def __init__ (self) :
# an empty dictionary of classes
self.klasses = {}
self.klass_names = [] # store class names to maintain order
self.arrows = []
self.filename = ""
def begin_render (self, data, filename) :
self.filename = filename
for layer in data.layers :
# for the moment ignore layer info. But we could use this to spread accross different files
for o in layer.objects :
if o.type.name == "UML - Class" :
k = Klass (o.properties["name"].value)
k.SetComment(o.properties["comment"].value)
k.stereotype = o.properties["stereotype"].value
if o.properties["abstract"].value:
k.SetInheritance_type("abstract")
if o.properties["template"].value:
k.SetInheritance_type("template")
for op in o.properties["operations"].value :
# op : a tuple with fixed placing, see: objects/UML/umloperations.c:umloperation_props
# (name, type, comment, stereotype, visibility, inheritance_type, class_scope, params)
params = []
for par in op[8] :
# par : again fixed placement, see objects/UML/umlparameter.c:umlparameter_props
params.append((par[0], par[1]))
k.AddOperation (op[0], op[1], op[4], params, op[5], op[2], op[7])
#print o.properties["attributes"].value
for attr in o.properties["attributes"].value :
# see objects/UML/umlattributes.c:umlattribute_props
#print " ", attr[0], attr[1], attr[4]
k.AddAttribute(attr[0], attr[1], attr[4], attr[2], attr[3])
self.klasses[o.properties["name"].value] = k
self.klass_names += [o.properties["name"].value]
#Connections
elif o.type.name == "UML - Association" :
# should already have got attributes relation by names
pass
# other UML objects which may be interesting
# UML - Note, UML - LargePackage, UML - SmallPackage, UML - Dependency, ...
edges = {}
for layer in data.layers :
for o in layer.objects :
for c in o.connections:
for n in c.connected:
if not n.type.name in ("UML - Generalization", "UML - Realizes"):
continue
if str(n) in edges:
continue
edges[str(n)] = None
if not (n.handles[0].connected_to and n.handles[1].connected_to):
continue
par = n.handles[0].connected_to.object
chi = n.handles[1].connected_to.object
if not par.type.name == "UML - Class" and chi.type.name == "UML - Class":
continue
par_name = par.properties["name"].value
chi_name = chi.properties["name"].value
if n.type.name == "UML - Generalization":
self.klasses[chi_name].AddParent(par_name)
else: self.klasses[chi_name].AddTemplate(par_name)
def end_render(self) :
# without this we would accumulate info from every pass
self.attributes = []
self.operations = {}
class OpenERPRenderer(ObjRenderer) :
def __init__(self) :
ObjRenderer.__init__(self)
def data_get(self):
return {
'file': self.filename,
'module': os.path.basename(self.filename).split('.')[-2]
}
def terp_get(self):
terp = """# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# Generated by the Odoo plugin for Dia !
{
'name': '%(module)s',
'version': '0.1',
'author': 'Bachaco-ve',
'website': 'http://www.bachaco.org.ve',
'category': 'Desconocida',
'sequence': 15,
'summary': 'Desconocida',
'description': \"\"\" Coloque la Descripción \"\"\",
'depends': ['base'],
'data': ['security/ir.model.access.csv', 'views/%(module)s_view.xml'],
'demo': [ ],
'css': ['static/src/less/%(module)s.less'],
'update_xml': [ ],
'installable': True,
'auto_install': False,
'application': True
}""" % self.data_get()
return terp
def html_get(self):
return """
<section class="oe_container">
<div class="oe_row oe_spaced">
<div class="oe_span12">
<h2 class="oe_slogan">Nombre del Módulo</h2>
<h3 class="oe_slogan">Descripción</h3>
</div>
<div class="oe_span12">
<p>Descripción del Modelo</p>
</div>
</div>
</section>
<section class="oe_container oe_dark"></section>
"""
def less_get(self):
return """@charset "utf-8";
/*------------------------------
* Coloque aqui los estilos
*-------------------------------
*/"""
def init_get(self):
return """# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# Generated by the Odoo plugin for Dia !\n#\n\nimport models"""
def security_get(self):
header = """"id","name","model_id:id","group_id:id","perm_read","perm_write","perm_create","perm_unlink"\n"""
rows = """"access_%s","%s","model_%s","base.group_user",1,0,0,0"""
for clas in self.klass_names:
cname = clas.replace('.', '_')
header += rows % (cname, clas, cname) + '\n'
return header
def get_label(self, attrs):
label = None
if attrs[0] == 'Many2many':
for att in attrs[2].split(','):
if 'string' in att:
label = att[8:]
if not label:
label = attrs[2].split(',')[4]
if attrs[0] == 'One2many':
for att in attrs[2].split(','):
if 'string' in att:
label = att[8:]
if not label:
label = attrs[2].split(',')[2]
if attrs[0] == 'Text':
for att in attrs[2].split(','):
if 'string' in att:
label = att[8:]
if not label:
label = attrs[2].split(',')[0]
return label
def view_class_get(self, cn, cd):
data = self.data_get()
i = 1
fields_form = fields_tree = ""
cols = {}
for sa,attr in cd.attributes:
cols[sa] = True
attrs = ''
if attr[0] in ('One2many', 'Many2many', 'Text'):
attrs='colspan="4" nolabel="1" '
field_label = self.get_label(attr)
fields_form += (" <separator string=%s colspan=\"4\"/>\n") % (field_label or 'Unknown')
fields_form += (" <field name=\"%s\" "+attrs+"select=\"%d\"/>\n") % (sa,i)
if attr[0] not in ('One2many', 'Many2many'):
fields_tree += " <field name=\"%s\"/>\n" % (sa,)
if (i==2) or not i:
i=-1
i += 1
data['form']= fields_form
data['tree']= fields_tree
data['name_id']= cn.replace('.','_')
if not cd.stereotype:
data['menu']= 'Unknown/'+cn.replace('.','_')
else:
data['menu']= cd.stereotype
data['name']= cn
data['name_en']= data['menu'].split('/')[-1]
data['mode'] = 'tree,form'
if 'date' in cols:
data['mode']='tree,form,calendar'
result = """
<!-- VISTA FORM: %(menu)s -->
<record model="ir.ui.view" id="view_%(name_id)s_form">
<field name="name">%(name)s.form</field>
<field name="model">%(name)s</field>
<field name="type">form</field>
<field name="arch" type="xml">
<form string="%(name)s">
<group col="4" colspan="2">
%(form)s
</group>
</form>
</field>
</record>
<!-- FIN VISTA FORM: %(menu)s -->
<!-- VISTA TREE: %(menu)s -->
<record model="ir.ui.view" id="view_%(name_id)s_tree">
<field name="name">%(name)s.tree</field>
<field name="model">%(name)s</field>
<field name="type">tree</field>
<field name="arch" type="xml">
<tree string="%(name)s">
%(tree)s
</tree>
</field>
</record>
<!-- FIN VISTA TREE: %(menu)s -->
<!-- MODELO: %(name_en)s -->
<record model="ir.actions.act_window" id="action_%(name_id)s">
<field name="name">%(name_en)s</field>
<field name="res_model">%(name)s</field>
<field name="view_type">form</field>
<field name="view_mode">%(mode)s</field>
</record>
<!-- FIN MODELO: %(name_en)s -->
<!-- MENÚ SECUNDARIO: %(menu)s -->
<menuitem name="%(menu)s" id="menu_%(name_id)s" action="action_%(name_id)s" parent="men_sec"/>
""" % data
return result
def view_get(self):
result = """<?xml version="1.0"?>
<odoo>
<data>
"""
for sk in self.klass_names:
result += self.view_class_get(sk, self.klasses[sk])
result += """
<!-- MENÚ PRINCIPAL -->
<menuitem name="%(module)s" id="men_pri"/>
<!-- Coloque aqui los menú secundarios que se crean en cada clase -->
</data>
</odoo>"""
return result
def init_model_get(self):
return """# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# Generated by the Odoo plugin for Dia !\n#\n\nimport %(module)s""" % self.data_get()
def code_get(self):
result = """# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# Generated by the Odoo plugin for Dia !
from odoo import api, fields, models
"""
for sk in self.klass_names:
cname = sk.replace('.','_')
result += "class %s(models.Model):\n" % (cname,)
if self.klasses[sk].comment:
result += " "+'"""'+self.klasses[sk].comment+'"""\n'
result += " _name = '%s'\n" % (sk,)
parents = self.klasses[sk].parents
if parents:
result += " _inherit = '"+parents[0]+"'\n"
templates = self.klasses[sk].templates
if templates:
result += " _inherits = {'"+templates[0]+"':'"+templates[0]+"'}\n"
result += " #_rec_name = ''\n"
default = {}
#result += " _columns = {\n"
for sa,attr in self.klasses[sk].attributes :
value = attr[2]
if attr[3]:
value += ", help='%s'" % (attr[3].replace("'"," "),)
attr_type = attr[0]
result += " %s = fields.%s(%s)\n" % (sa, attr_type, value)
#result += " }\n"
if default:
result += ' _defaults = {'
for d in default:
result += " '%s':lambda *args: '%s'\n" % (d, default[d])
result += ' }'
for so, op in self.klasses[sk].operations :
pars = "self, cr, uid, ids"
for p in op[2] :
pars = pars + ", " + p[0]
result+=" def %s(%s) :\n" % (so, pars)
if op[4]: result+=" \"\"\" %s \"\"\"\n" % op[4]
result+=" # returns %s\n" % (op[0], )
#result += cname+"()\n\n"
result += "\n\n"
return result
def end_render(self) :
module = self.data_get()['module']
zip = zipfile.ZipFile(self.filename, 'w')
filewrite = {
'__init__.py':self.init_get(),
'__manifest__.py':self.terp_get(),
'models/__init__.py':self.init_model_get(),
'models/'+module+'.py': self.code_get(),
'views/'+module+'_view.xml': self.view_get(),
'security/ir.model.access.csv': self.security_get(),
'static/description/index.html': self.html_get(),
'static/src/less/'+module+'.less': self.less_get()
}
for name,datastr in filewrite.items():
info = zipfile.ZipInfo(module+'/'+name)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 2175008768
zip.writestr(info, datastr)
zip.close()
ObjRenderer.end_render(self)
# dia-python keeps a reference to the renderer class and uses it on demand
dia.register_export ("PyDia Generador de Código (Odoo)", "zip", OpenERPRenderer())
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: