Salome HOME
Merge branch V7_3_1_BR
[modules/kernel.git] / src / KERNEL_PY / salome_study.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
5 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 #
21 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 #
23
24 #  File   : salome_study.py
25 #  Author : Paul RASCLE, EDF
26 #  Module : SALOME
27 #  $Header$
28 #
29 import salome_kernel
30 import SALOMEDS
31 import salome_iapp
32 from launchConfigureParser import verbose
33
34 #--------------------------------------------------------------------------
35
36 def DumpComponent(Study, SO, Builder,offset):
37   it = Study.NewChildIterator(SO)
38   while it.More():
39     CSO = it.Value()
40     a=offset*"--" + ">" + CSO.GetID()
41     find,AtName = Builder.FindAttribute(CSO, "AttributeName")
42     if find:
43       a=a+":"+AtName.Value()
44     find,AtIOR = Builder.FindAttribute(CSO, "AttributeIOR")
45     if find:
46       a=a+":"+AtIOR.Value()
47     find,RefSO = CSO.ReferencedObject()
48     if find:
49       a=a+":"+RefSO.GetID()
50     print a
51     DumpComponent(Study, CSO, Builder,offset+2)
52     it.Next()
53
54 #--------------------------------------------------------------------------
55
56 def DumpStudy(Study):
57     """
58     Dump a study, given the ior
59     """
60     itcomp = Study.NewComponentIterator()
61     Builder = Study.NewBuilder()
62     while itcomp.More():
63       SC = itcomp.Value()
64       name = SC.ComponentDataType()
65       print "-> ComponentDataType is " + name
66       DumpComponent(Study, SC,Builder, 1)
67       itcomp.Next()
68
69 def DumpStudies():
70   """
71     Dump all studies in a StudyManager
72   """
73   for name in myStudyManager.GetOpenStudies():
74     s=myStudyManager.GetStudyByName(name)
75     print "study:",name, s._get_StudyId()
76     DumpStudy(s)
77
78
79 #--------------------------------------------------------------------------
80
81 def IDToObject(id):
82     myObj = None
83     mySO = myStudy.FindObjectID(id);
84     if mySO is not None:
85         ok, anAttr = mySO.FindAttribute("AttributeIOR")
86         if ok:
87             AtIOR = anAttr._narrow(SALOMEDS.AttributeIOR)
88             if AtIOR.Value() != "":
89                 myObj = orb.string_to_object(AtIOR.Value())
90     return myObj
91
92 def ObjectToSObject(obj):
93     mySO = None
94     if obj is not None:
95         ior =  orb.object_to_string(obj)
96         if ior != "":
97             mySO = myStudy.FindObjectIOR(ior)
98     return mySO
99
100 def ObjectToID(obj):
101     mySO = ObjectToSObject(obj)
102     if mySO:
103         return mySO.GetID()
104     return ""
105
106 def IDToSObject(id):
107     mySO = myStudy.FindObjectID(id);
108     return mySO
109
110     #--------------------------------------------------------------------------
111
112 def generateName(prefix = None):
113     import random;
114     int = random.randint(1,1000);
115     if prefix is None:
116         return "Study" + str(int)
117     else :
118         return prefix + str(int)
119
120     #--------------------------------------------------------------------------
121
122 def PersistentPresentation(theStudy, theSO, theWithID):
123     # put the sobject's content (with subchildren) to the string
124     aResult = ""
125     attrs = theSO.GetAllAttributes()
126     aLen = len(attrs)
127     anUncopied = 0
128     for a in range(0,aLen):
129         attr = attrs[a]
130         if isinstance(attr,SALOMEDS._objref_AttributeTreeNode):
131             anUncopied += 1
132         elif isinstance(attr,SALOMEDS._objref_AttributeTarget):
133             anUncopied += 1
134         elif isinstance(attr,SALOMEDS._objref_AttributeReal) or \
135              isinstance(attr,SALOMEDS._objref_AttributeInteger) or \
136              isinstance(attr,SALOMEDS._objref_AttributeName) or \
137              isinstance(attr,SALOMEDS._objref_AttributeComment) or \
138              isinstance(attr,SALOMEDS._objref_AttributePersistentRef) or \
139              isinstance(attr,SALOMEDS._objref_AttributeLocalID) or \
140              isinstance(attr,SALOMEDS._objref_AttributeUserID):
141             aResult += " attribute value: " + str(attr.Value())
142         elif isinstance(attr,SALOMEDS._objref_AttributeIOR):
143             aResult += " attribute: IOR"
144         elif isinstance(attr,SALOMEDS._objref_AttributeSequenceOfReal) or \
145              isinstance(attr,SALOMEDS._objref_AttributeSequenceOfInteger):
146             aResult += " Sequence: " + str(attr.CorbaSequence())
147         elif isinstance(attr,SALOMEDS._objref_AttributeDrawable):
148             aResult += " Drawable: " + str(attr.IsDrawable())
149         elif isinstance(attr,SALOMEDS._objref_AttributeSelectable):
150             aResult += " Selectable: " + str(attr.IsSelectable())
151         elif isinstance(attr,SALOMEDS._objref_AttributeExpandable):
152             aResult += " Expandable: " + str(attr.IsExpandable())
153         elif isinstance(attr,SALOMEDS._objref_AttributeOpened):
154             aResult += " Opened: " + str(attr.IsOpened())
155         elif isinstance(attr,SALOMEDS._objref_AttributeTextColor):
156             aResult += " TextColor: " + str(attr.TextColor())
157         elif isinstance(attr,SALOMEDS._objref_AttributeTextHighlightColor):
158             aResult += " TextHighlightColor: " + str(attr.TextHighlightColor())
159         elif isinstance(attr,SALOMEDS._objref_AttributePixMap):
160             aResult += " PixMap: " + str(attr.GetPixMap())
161         elif isinstance(attr,SALOMEDS._objref_AttributeTableOfInteger) or \
162              isinstance(attr,SALOMEDS._objref_AttributeTableOfReal):
163             aResult += " Table with title: " + attr.GetTitle()
164         elif isinstance(attr,SALOMEDS._objref_AttributePythonObject):
165             aResult += " PythonObject: " + attr.GetObject()
166
167     if theWithID:
168         aResult = "sobject: " + theSO.GetID() + " nbattrs: " + str(aLen - anUncopied) + aResult + '\n'
169     else:
170         aResult = " nbattrs: " + str(aLen - anUncopied) + aResult + '\n'
171     anIter = theStudy.NewChildIterator(theSO)
172     while anIter.More():
173         aResult += PersistentPresentation(theStudy, anIter.Value(), theWithID)
174         anIter.Next()
175     return aResult
176
177     #--------------------------------------------------------------------------
178
179 def GetTree(theSO):
180     # returns the document list tree (as list)
181     aResult = [theSO.GetID()]
182     anIter = myStudy.NewChildIterator(theSO)
183     while anIter.More():
184         aResult += GetTree(anIter.Value())
185         anIter.Next()
186     return aResult
187
188     #--------------------------------------------------------------------------
189
190 def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
191     aRoot = theSO
192     while aRoot.GetID() != "0:":
193         aRoot = aRoot.GetFather()
194     aTree = GetTree(aRoot)
195     aStudyPersist = PersistentPresentation(myStudy, aRoot, 1)
196
197     if not myStudyManager.CanCopy(theSO):
198         raise RuntimeError, "<CanCopy> for "+theInfo+" returns false"
199     
200     if not myStudyManager.Copy(theSO):
201         raise RuntimeError, "<Copy> for "+theInfo+" returns false"
202
203     
204     if not myStudyManager.CanPaste(theSO):
205         raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
206
207     # check: before paste study is not changed check
208     if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
209         raise RuntimeError, "Study is changed before Paste calling for "+theInfo
210     
211     aSObj = theSO
212     if theComponentPaste:
213         aSObj = theSO.GetFatherComponent()
214         theInfo = theInfo + "(paste for component)"
215     if myStudyManager.Paste(aSObj) == None:
216         raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
217     aNewTree = GetTree(aRoot)
218     aLen = len(aTree)
219     for a in range(0,aLen):
220         if aTree[a] != aNewTree[a]:
221             return myStudy.FindObjectID(aNewTree[a])
222         
223     if aLen < len(aNewTree):
224         return myStudy.FindObjectID(aNewTree[aLen])
225     
226     raise RuntimeError, "After Copy calling the tree is not changed"
227     
228     #--------------------------------------------------------------------------
229
230 def GetComponentVersion(theComponent, all_versions = False):
231     # returns the document list tree (as list)
232     props = myStudy.GetProperties()
233     stored_components = props.GetStoredComponents()
234     version = "no component data" # vsr: better raise an exception in this case?
235     if theComponent in stored_components:
236       if all_versions:
237         version = props.GetComponentVersions(theComponent)
238         for i in range(len(version)):
239           if not version[i]: version[i] = "unknown"
240           pass
241         pass
242       else:
243         version = props.GetComponentVersion(theComponent)
244         if not version: version = "unknown"
245         pass
246       pass
247     return version
248     
249     #--------------------------------------------------------------------------
250
251 def FindFileInDataDir(filename):
252     import os
253     datadir = os.getenv("DATA_DIR")
254     if datadir is not None:
255         import string
256         dirs = string.split(datadir, ":")
257         for dir in dirs:
258             file = dir + "/" + filename
259             if os.path.exists(file):
260                 return file;
261     datadir = os.getenv("KERNEL_ROOT_DIR") + "/examples/"
262     file = datadir + filename
263     if os.path.exists(file):
264         return file;
265
266     return None
267
268     #--------------------------------------------------------------------------
269
270 salome_study_ID = -1
271
272 def getActiveStudy():
273     global salome_study_ID
274
275     if verbose(): print "getActiveStudy"
276     if salome_study_ID == -1:
277         if salome_iapp.hasDesktop():
278             if verbose(): print "---in gui"
279             salome_study_ID = salome_iapp.sg.getActiveStudyId()
280         else:
281             if verbose(): print "---outside gui"
282             if salome_study_ID == -1:
283               listOpenStudies = myStudyManager.GetOpenStudies()
284               if len(listOpenStudies) == 0:
285                 salome_study_ID = createNewStudy()
286               else:
287                 s = myStudyManager.GetStudyByName(listOpenStudies[0])
288                 salome_study_ID = s._get_StudyId()
289             else:
290               pass
291             #if theStudyId:
292                 #aStudy=myStudyManager.GetStudyByID(theStudyId)
293                 #if aStudy:
294                     #if verbose(): print "connection to existing study ", theStudyId
295                     #salome_study_ID = theStudyId
296             if verbose(): print"--- Study Id ", salome_study_ID
297     return salome_study_ID
298
299     #--------------------------------------------------------------------------
300
301 def setCurrentStudy(theStudy):
302     """
303     Change current study : an existing one given by a study object.
304
305     :param theStudy: the study CORBA object to set as current study
306     """
307     global myStudyId, myStudy, myStudyName
308     global salome_study_ID
309     myStudy=theStudy
310     myStudyId=theStudy._get_StudyId()
311     myStudyName=theStudy._get_Name()
312     return myStudyId, myStudy, myStudyName
313
314     #--------------------------------------------------------------------------
315
316 def setCurrentStudyId(theStudyId=0):
317     """
318     Change current study : an existing or new one.
319     optional argument : theStudyId
320         0      : create a new study (default).
321         n (>0) : try connection to study with Id = n, or create a new one
322                  if study not found.
323     """
324     global myStudyId, myStudy, myStudyName
325     global salome_study_ID
326     salome_study_ID = -1
327     myStudyId = getActiveStudy(theStudyId)
328     if verbose(): print "myStudyId",myStudyId
329     myStudy = myStudyManager.GetStudyByID(myStudyId)
330     myStudyName = myStudy._get_Name()
331
332     return myStudyId, myStudy, myStudyName
333
334     #--------------------------------------------------------------------------
335
336 def createNewStudy():
337     print "createNewStudy"
338     i=1
339     aStudyName = "noName"
340     nameAlreadyInUse = 1
341     listOfOpenStudies = myStudyManager.GetOpenStudies()
342     if len(listOfOpenStudies) != 0:
343       raise ValueError("There is already an opened study: %s" % listOfOpenStudies[0])
344     print listOfOpenStudies
345     while nameAlreadyInUse:
346         aStudyName = "extStudy_%d"%i
347         if aStudyName not in listOfOpenStudies:
348             nameAlreadyInUse=0
349         else:
350             i = i+1
351
352     theStudy = myStudyManager.NewStudy(aStudyName)
353     theStudyId = theStudy._get_StudyId()
354     print aStudyName, theStudyId
355     return theStudyId
356
357     #--------------------------------------------------------------------------
358
359 salome_study_initial = 1
360
361 def salome_study_init():
362     """
363     Performs only once study creation or connection.
364     optional argument : theStudyId
365       When in embedded interpreter inside IAPP, theStudyId is not used
366       When used without GUI (external interpreter)
367         0      : create a new study (default).
368         n (>0) : try connection to study with Id = n, or create a new one
369                  if study not found.
370     """
371
372     global salome_study_initial
373     global myStudyManager, myStudyId, myStudy, myStudyName
374     global orb, lcc, naming_service, cm
375
376     if salome_study_initial:
377         salome_study_initial = 0
378
379         orb, lcc, naming_service, cm = salome_kernel.salome_kernel_init()
380
381         # get Study Manager reference
382         if verbose(): print "looking for studyManager ..."
383         obj = naming_service.Resolve('myStudyManager')
384         myStudyManager = obj._narrow(SALOMEDS.StudyManager)
385         if verbose(): print "studyManager found"
386
387         # get active study Id, ref and name
388         myStudyId = getActiveStudy()
389         if verbose(): print "myStudyId",myStudyId
390         myStudy = myStudyManager.GetStudyByID(myStudyId)
391         myStudyName = myStudy._get_Name()
392
393     return myStudyManager, myStudyId, myStudy, myStudyName
394