Salome HOME
version 19 mars
[tools/eficas.git] / Noyau / asojb.py
1 # coding=utf-8
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    Description des OJB jeveux
22 """
23 from basetype import Type
24 from asnom import SDNom
25 from ascheckers import CheckLog
26 import traceback
27 import 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
38
39 class AsBase(Type):
40     nomj = SDNom()
41     optional = False
42
43     def __init__(self, nomj=None, *args, **kwargs):
44         super(AsBase, self).__init__(nomj, *args, **kwargs)
45         assert self.nomj is not self.__class__.nomj
46         if isinstance(nomj, str):
47             self.nomj.nomj = nomj
48         elif isinstance(nomj, SDNom):
49             self.nomj.update(nomj.__getstate__())
50
51     def set_name(self, nomj):
52         """Positionne le nomj de self
53         """
54         assert isinstance(self.nomj.nomj, str), "uniquement pour les concepts"
55         self.nomj.nomj = nomj
56
57     def check(self, checker=None):
58         if checker is None:
59             checker = CheckLog()
60
61         # vérif déjà faite ? (en tenant compte du type)
62         if checker.checkedAsBase(self):
63             return checker
64         checker.visitAsBase(self)
65
66         # vérifie les enfants :
67         optional = checker.optional
68         checker.optional = checker.optional or self.optional
69         for name in self._subtypes:
70             v = getattr(self, name)
71             if isinstance(v, (OJB, AsBase)):
72                 v.check(checker)
73         for name in dir(self):
74             if name.startswith('check_'):
75                 v = getattr(self, name)
76                 if callable(v):
77                     try:
78                         v(checker)
79                     except:
80                         mess = 60 * '-' + '\n'
81                         mess = mess + \
82                             'Erreur SDVERI (Attention : vérification incomplète)' + \
83                             '\n'
84                         mess = mess.join(
85                             traceback.format_tb(sys.exc_traceback))
86                         checker.err(self, mess)
87
88         checker.optional = optional
89         return checker
90
91     def dump(self, indent=""):
92         import pydoc
93         l = []
94         checkers = []
95         nomj = self.nomj()
96         if self.optional:
97             f = "(f)"
98         else:
99             f = "(o)"
100         l.append(f + " " + nomj)
101         for name in self._subtypes:
102             obj = getattr(self, name)
103             if isinstance(obj, (AsBase, OJB)):
104                 l.append(obj.dump(indent))
105         for name in dir(self):
106             if name.startswith('check_'):
107                 obj = getattr(self, name)
108                 if callable(obj) and name.startswith("check_"):
109                     checkers.append(obj)
110
111         indent = " " * len(nomj)
112         for checker in checkers:
113             doc = pydoc.text.document(checker)
114             for line in doc.splitlines():
115                 l.append(indent + line)
116         return "\n".join(l)
117
118     def short_repr(self):
119         return "<%s(%x,%r)>" % (self.__class__.__name__, id(self), self.nomj())
120
121     def long_repr(self):
122         if not hasattr(self, "accessible") or not self.accessible():
123             # hors Aster ou en par_lot='oui'
124             return self.short_repr()
125         else:
126             from Cata.cata import IMPR_CO, _F
127             IMPR_CO(CONCEPT=_F(NOM=self.nom), UNITE=6)
128             return ''
129
130     def __repr__(self):
131         # par défaut, on fait court !
132         return self.short_repr()
133
134
135 # -----------------------------------------------------------------------------
136 class JeveuxAttr(object):
137
138     """Un attribut jeveux"""
139
140     def __init__(self, name):
141         self.name = name
142
143     def __get__(self, obj, klass):
144         raise NotImplementedError
145
146     def check(self, attrname, obj, log):
147         checker = getattr(obj, "_" + attrname, None)
148         if checker is None:
149             return True
150         val = self.__get__(obj, obj.__class__)
151         if callable(checker):
152             return checker(obj, attrname, val, log)
153         elif val == checker:
154             return True
155         else:
156             log.err(obj, "Attribut incorrect %s %r!=%r" %
157                     (self.name, val, checker))
158             return False
159
160 # -----------------------------------------------------------------------------
161
162
163 class JeveuxExists(JeveuxAttr):
164
165     def __init__(self):
166         pass
167
168     def __get__(self, obj, klass):
169         if obj is None:
170             return self
171         nomj = obj.nomj()
172         if len(nomj) != 24:
173             raise AssertionError(repr(nomj))
174         return aster.jeveux_exists(nomj.ljust(24))
175
176 # -----------------------------------------------------------------------------
177
178
179 class JeveuxIntAttr(JeveuxAttr):
180
181     def __get__(self, obj, klass):
182         if obj is None:
183             return self
184         nomj = obj.nomj()
185         if aster.jeveux_exists(nomj):
186             return aster.jeveux_getattr(nomj, self.name)[0]
187         else:
188             return None
189
190 # -----------------------------------------------------------------------------
191
192
193 class JeveuxStrAttr(JeveuxAttr):
194
195     def __get__(self, obj, klass):
196         if obj is None:
197             return self
198         nomj = obj.nomj()
199         if aster.jeveux_exists(nomj):
200             return aster.jeveux_getattr(nomj, self.name)[1].strip()
201         else:
202             return None
203
204 # -----------------------------------------------------------------------------
205
206
207 class OJB(AsBase):
208     _clas = None
209     _genr = None
210     _type = None
211     _ltyp = None
212     _xous = None
213     _docu = None
214     _exists = True
215
216     clas = JeveuxStrAttr("CLAS")
217     genr = JeveuxStrAttr("GENR")
218     type = JeveuxStrAttr("TYPE")
219     ltyp = JeveuxIntAttr("LTYP")
220     xous = JeveuxStrAttr("XOUS")
221     docu = JeveuxStrAttr("DOCU")
222     exists = JeveuxExists()
223     nomj = SDNom()
224
225     def __init__(self, nomj=None, **attrs):
226         super(OJB, self).__init__(nomj, **attrs)
227         self.foreachattr(self.setattribute, attrs)
228         self.optional = attrs.get('optional', False)
229
230     def setattribute(self, name, prop, attrs):
231         _name = "_" + name
232         if name in attrs:
233             setattr(self, _name, attrs[name])
234
235     def get(self):
236         nomj = self.nomj()
237         if aster.jeveux_exists(nomj):
238             obj_simple = aster.jeveux_getattr(nomj, 'XOUS')[1].strip() == 'S'
239             if obj_simple:
240                 return aster.getvectjev(nomj)
241             else:
242                 return aster.getcolljev(nomj)
243         else:
244             return None
245
246     def get_stripped(self):
247         """Fonction utilitaire, renvoie une liste de chaines 'strippées'"""
248         data = self.get()
249         if data is not None:
250             return [x.strip() for x in data]
251         else:
252             return []
253
254     def foreachattr(self, callback, *args, **kwargs):
255         klass = self.__class__
256         for k in dir(klass):
257             v = getattr(klass, k)
258             if isinstance(v, JeveuxAttr):
259                 callback(k, v, *args, **kwargs)
260
261     def check(self, checker=None):
262         if checker is None:
263             checker = CheckLog()
264         # l'objet a déjà été vérifié, on ne fait rien
265         if checker.checkedOJB(self):
266             return checker
267         checker.visitOJB(self)
268         if self.exists:
269             self.foreachattr(lambda k, v, obj, c: v.check(k, obj, c),
270                              self, checker)
271         else:
272             if not self.optional and not checker.optional:
273                 checker.err(self, "n'existe pas (%r)" % self._parent)
274         return checker
275
276     def dump(self, indent=""):
277         if self.optional:
278             f = "(f)"
279         else:
280             f = "(o)"
281         return f + " " + self.nomj() + " " + str(self.exists)
282
283 # -----------------------------------------------------------------------------
284
285
286 def Facultatif(ojb):
287     ojb.optional = True
288     return ojb
289
290 # -----------------------------------------------------------------------------
291
292
293 class OJBVect(OJB):
294     lonmax = JeveuxIntAttr("LONMAX")
295     lonuti = JeveuxIntAttr("LONUTI")
296     _xous = "S"
297     _genr = "V"
298
299 # -----------------------------------------------------------------------------
300
301
302 class OJBPtnom(OJB):
303     nommax = JeveuxIntAttr("NOMMAX")
304     nomuti = JeveuxIntAttr("NOMUTI")
305     _xous = "S"
306     _genr = "N"
307     _type = "K"
308
309 # -----------------------------------------------------------------------------
310
311
312 class OJBCollec(OJB):
313     stockage = JeveuxStrAttr("STOCKAGE")
314     nutioc = JeveuxIntAttr("NUTIOC")
315     acces = JeveuxStrAttr("ACCES")
316     modelong = JeveuxStrAttr("MODELONG")
317     nmaxoc = JeveuxIntAttr("NMAXOC")
318
319 # -----------------------------------------------------------------------------
320
321
322 class AsVI(OJBVect):
323     _type = "I"
324
325 # -----------------------------------------------------------------------------
326
327
328 class AsVS(OJBVect):
329     _type = "S"
330
331 # -----------------------------------------------------------------------------
332
333
334 class AsVR(OJBVect):
335     _type = "R"
336
337 # -----------------------------------------------------------------------------
338
339
340 class AsVC(OJBVect):
341     _type = "C"
342
343 # -----------------------------------------------------------------------------
344
345
346 class AsVL(OJBVect):
347     _type = "L"
348
349 # -----------------------------------------------------------------------------
350
351
352 class AsVK8(OJBVect):
353     _type = "K"
354     _ltyp = 8
355
356 # -----------------------------------------------------------------------------
357
358
359 class AsVK16(OJBVect):
360     _type = "K"
361     _ltyp = 16
362
363 # -----------------------------------------------------------------------------
364
365
366 class AsVK24(OJBVect):
367     _type = "K"
368     _ltyp = 24
369
370 # -----------------------------------------------------------------------------
371
372
373 class AsVK32(OJBVect):
374     _type = "K"
375     _ltyp = 32
376
377 # -----------------------------------------------------------------------------
378
379
380 class AsVK80(OJBVect):
381     _type = "K"
382     _ltyp = 80
383
384 # Pour compatibilite
385 AsObject = OJB
386 AsColl = OJBCollec
387 AsPn = OJBPtnom
388 AsVect = OJBVect