Salome HOME
0eb259c5767c917dbac1a982a0fc94d038afe11f
[tools/eficas.git] / Noyau / asojb.py
1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2013   EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 """
22    Description des OJB jeveux
23 """
24 from basetype import Type
25 from asnom import SDNom
26 from ascheckers import CheckLog
27 import traceback,sys
28
29 # pour utilisation dans eficas
30 try:
31    import aster
32    from Utilitai.Utmess import UTMESS
33 except:
34    pass
35
36 # -----------------------------------------------------------------------------
37 class AsBase(Type):
38     nomj = SDNom()
39     optional = False
40
41     def __init__(self, nomj=None, *args, **kwargs ):
42         super(AsBase,self).__init__( nomj, *args, **kwargs )
43         assert self.nomj is not self.__class__.nomj
44         if isinstance( nomj, str ):
45             self.nomj.nomj = nomj
46         elif isinstance( nomj, SDNom ):
47             self.nomj.update( nomj.__getstate__() )
48
49     def set_name(self, nomj):
50         """Positionne le nomj de self
51         """
52         assert isinstance( self.nomj.nomj, str ), "uniquement pour les concepts"
53         self.nomj.nomj = nomj
54
55     def check(self, checker=None):
56         if checker is None:
57             checker = CheckLog()
58
59         # vérif déjà faite ? (en tenant compte du type)
60         if checker.checkedAsBase(self):
61             return checker
62         checker.visitAsBase( self )
63
64         # vérifie les enfants :
65         optional = checker.optional
66         checker.optional = checker.optional or self.optional
67         for name in self._subtypes:
68             v = getattr(self, name)
69             if isinstance( v, (OJB,AsBase) ):
70                 v.check(checker)
71         for name in dir(self):
72             if name.startswith( 'check_' ):
73                 v = getattr(self, name)
74                 if callable(v):
75                     try :
76                         v( checker )
77                     except :
78                         mess=60*'-'+'\n'
79                         mess=mess+'Erreur SDVERI (Attention : vérification incomplète)'+'\n'
80                         mess=mess.join(traceback.format_tb(sys.exc_traceback))
81                         checker.err(self,mess)
82
83         checker.optional = optional
84         return checker
85
86     def members( self ):
87         pass
88
89     def dump(self, indent=""):
90         import pydoc
91         l = []
92         checkers = []
93         nomj = self.nomj()
94         if self.optional:
95             f = "(f)"
96         else:
97             f = "(o)"
98         l.append( f+" "+nomj )
99         #l.append( '-'*(len(nomj)+3) )
100         for name in self._subtypes:
101             obj = getattr(self, name)
102             if isinstance(obj,(AsBase,OJB)):
103                 l.append( obj.dump(indent) )
104         for name in dir(self):
105             if name.startswith( 'check_' ):
106                 obj = getattr(self, name)
107                 if callable(obj) and name.startswith("check_"):
108                     checkers.append( obj )
109
110         indent = " "*len(nomj)
111         for checker in checkers:
112             doc = pydoc.text.document( checker )
113             for line in doc.splitlines():
114                 l.append( indent + line )
115         return "\n".join( l )
116
117     def short_repr(self):
118         return "<%s(%x,%r)>" % (self.__class__.__name__, id(self), self.nomj() )
119
120     def long_repr(self):
121         if not hasattr(self, "accessible") or not self.accessible():
122            # hors Aster ou en par_lot='oui'
123            return self.short_repr()
124         else:
125            from Cata.cata import IMPR_CO, _F
126            IMPR_CO(CONCEPT=_F(NOM=self.nom), UNITE=6)
127            return ''
128
129     def __repr__(self):
130         # par défaut, on fait court !
131         return self.short_repr()
132
133
134 # -----------------------------------------------------------------------------
135 class JeveuxAttr(object):
136     """Un attribut jeveux"""
137     def __init__(self, name):
138         self.name = name
139
140     def __get__(self, obj, klass):
141         raise NotImplementedError
142
143     def check(self, attrname, obj, log ):
144         checker = getattr(obj, "_"+attrname, None )
145         if checker is None:
146             return True
147         val = self.__get__( obj, obj.__class__ )
148         if callable( checker ):
149             return checker( obj, attrname, val, log )
150         else:
151             test = val == checker
152             if not test:
153                 log.err( obj, "Attribut incorrect %s %r!=%r" % (self.name, val, checker ) )
154             return test
155
156 # -----------------------------------------------------------------------------
157 class JeveuxExists(JeveuxAttr):
158     def __init__(self):
159         pass
160
161     def __get__(self, obj, klass):
162         if obj is None:
163             return self
164         nomj = obj.nomj()
165         if len(nomj)!=24:
166             raise AssertionError(repr(nomj))
167         return aster.jeveux_exists( nomj.ljust(24) )
168
169 # -----------------------------------------------------------------------------
170 class JeveuxIntAttr(JeveuxAttr):
171     def __get__(self, obj, klass):
172         if obj is None:
173             return self
174         nomj = obj.nomj()
175         if aster.jeveux_exists( nomj ):
176             return aster.jeveux_getattr( nomj, self.name )[0]
177         else :
178             return None
179
180 # -----------------------------------------------------------------------------
181 class JeveuxStrAttr(JeveuxAttr):
182     def __get__(self, obj, klass):
183         if obj is None:
184             return self
185         nomj = obj.nomj()
186         if aster.jeveux_exists( nomj ):
187             return aster.jeveux_getattr( nomj, self.name )[1].strip()
188         else :
189             return None
190
191 # -----------------------------------------------------------------------------
192 class OJB(AsBase):
193     _clas = None
194     _genr = None
195     _type = None
196     _ltyp = None
197     _xous = None
198     _docu = None
199     _exists = True
200
201     clas = JeveuxStrAttr("CLAS")
202     genr = JeveuxStrAttr("GENR")
203     type = JeveuxStrAttr("TYPE")
204     ltyp = JeveuxIntAttr("LTYP")
205     xous = JeveuxStrAttr("XOUS")
206     docu = JeveuxStrAttr("DOCU")
207     exists = JeveuxExists()
208     #optional = False
209     nomj = SDNom()
210
211     def __init__(self, nomj=None, **attrs):
212         super(OJB,self).__init__( nomj, **attrs )
213         self.foreachattr( self.setattribute, attrs )
214         self.optional = attrs.get('optional', False)
215
216     def setattribute( self, name, prop, attrs ):
217         _name = "_"+name
218         if name in attrs:
219             setattr( self, _name, attrs[name] )
220
221     def get(self):
222         nomj = self.nomj()
223         if aster.jeveux_exists( nomj ):
224             obj_simple = aster.jeveux_getattr( nomj, 'XOUS')[1].strip() == 'S'
225             if obj_simple :
226                 return aster.getvectjev( nomj )
227             else :
228                 return aster.getcolljev( nomj )
229         else:
230             return None
231
232     def get_stripped(self):
233         """Fonction utilitaire, renvoie une liste de chaines 'strippées'"""
234         data = self.get()
235         if data is not None:
236             return [ x.strip() for x in data ]
237         else:
238             return []
239
240     def foreachattr(self, callback, *args, **kwargs):
241         klass = self.__class__
242         for k in dir(klass):
243             v = getattr( klass, k )
244             if isinstance(v, JeveuxAttr):
245                 callback( k, v, *args, **kwargs )
246
247     def check(self, checker=None):
248         if checker is None:
249             checker = CheckLog()
250         # l'objet a déjà été vérifié, on ne fait rien
251         if checker.checkedOJB(self):
252            return checker
253         checker.visitOJB( self )
254         if self.exists:
255             self.foreachattr( lambda k,v,obj,c: v.check(k, obj, c),
256                               self, checker )
257         else:
258             if not self.optional and not checker.optional :
259                 checker.err( self, "n'existe pas (%r)" %self._parent )
260         return checker
261
262     def dump(self, indent=""):
263         if self.optional:
264             f = "(f)"
265         else:
266             f = "(o)"
267         return f +" "+ self.nomj() +" "+ str(self.exists)
268
269 # -----------------------------------------------------------------------------
270 def Facultatif( ojb ):
271     ojb.optional = True
272     return ojb
273
274 # -----------------------------------------------------------------------------
275 class OJBVect(OJB):
276     lonmax = JeveuxIntAttr("LONMAX")
277     lonuti = JeveuxIntAttr("LONUTI")
278     _xous = "S"
279     _genr = "V"
280
281 # -----------------------------------------------------------------------------
282 class OJBPtnom(OJB):
283     nommax = JeveuxIntAttr("NOMMAX")
284     nomuti = JeveuxIntAttr("NOMUTI")
285     _xous = "S"
286     _genr = "N"
287     _type = "K"
288
289 # -----------------------------------------------------------------------------
290 class OJBCollec(OJB):
291     stockage = JeveuxStrAttr("STOCKAGE")
292     nutioc = JeveuxIntAttr( "NUTIOC" )
293     acces = JeveuxStrAttr( "ACCES" )
294     modelong = JeveuxStrAttr( "MODELONG" )
295     nmaxoc = JeveuxIntAttr( "NMAXOC" )
296
297 # -----------------------------------------------------------------------------
298 class AsVI(OJBVect):
299     _type = "I"
300
301 # -----------------------------------------------------------------------------
302 class AsVS(OJBVect):
303     _type = "S"
304
305 # -----------------------------------------------------------------------------
306 class AsVR(OJBVect):
307     _type = "R"
308
309 # -----------------------------------------------------------------------------
310 class AsVC(OJBVect):
311     _type = "C"
312
313 # -----------------------------------------------------------------------------
314 class AsVL(OJBVect):
315     _type = "L"
316
317 # -----------------------------------------------------------------------------
318 class AsVK8(OJBVect):
319     _type = "K"
320     _ltyp = 8
321
322 # -----------------------------------------------------------------------------
323 class AsVK16(OJBVect):
324     _type = "K"
325     _ltyp = 16
326
327 # -----------------------------------------------------------------------------
328 class AsVK24(OJBVect):
329     _type = "K"
330     _ltyp = 24
331
332 # -----------------------------------------------------------------------------
333 class AsVK32(OJBVect):
334     _type = "K"
335     _ltyp = 32
336
337 # -----------------------------------------------------------------------------
338 class AsVK80(OJBVect):
339     _type = "K"
340     _ltyp = 80
341
342 # Pour compatibilite
343 AsObject = OJB
344 AsColl   = OJBCollec
345 AsPn     = OJBPtnom
346 AsVect   = OJBVect