Salome HOME
To avoid compilation pb on RedHat 8.0.
[modules/kernel.git] / src / KERNEL_PY / salome_study.py
1 #  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
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 #  File   : salome_study.py
23 #  Author : Paul RASCLE, EDF
24 #  Module : SALOME
25 #  $Header$
26
27 import salome_kernel
28 import SALOMEDS
29 import salome_iapp
30 from launchConfigureParser import verbose
31
32 #--------------------------------------------------------------------------
33
34 def DumpComponent(Study, SO, offset):
35     it = Study.NewChildIterator(SO)
36     Builder = Study.NewBuilder()
37     while it.More():
38         CSO = it.Value()
39         it.Next()
40         anAttr = Builder.FindOrCreateAttribute(CSO, "AttributeName")
41         AtName = anAttr._narrow(SALOMEDS.AttributeName)
42         t_name = AtName.Value()
43         if t_name[0] == 1:
44             ofs = 1
45             a = ""
46             while ofs <= offset:
47                 a = a + "--"
48                 ofs = ofs +1
49             MESSAGE( a + ">" + str(CSO.GetID()) + " " + str(t_name[1]) )
50         t_RefSO = CSO.ReferencedObject()
51         if t_RefSO[0] == 1:
52             RefSO = t_RefSO[1]
53             ofs = 1
54             a = ""
55             while ofs <= offset:
56                 a = a + "  "
57                 ofs = ofs +1
58             MESSAGE( a + ">" + str(RefSO.GetID()) )
59         DumpComponent(Study, CSO, offset+2)
60
61     #--------------------------------------------------------------------------
62
63 def DumpStudy(Study):
64     itcomp = Study.NewComponentIterator()
65     while itcomp.More():
66         SC = itcomp.Value()
67         itcomp.Next()
68         name = SC.ComponentDataType()
69         MESSAGE( "-> ComponentDataType is " + name )
70         DumpComponent(Study, SC, 1)
71         
72
73     #--------------------------------------------------------------------------
74
75 def IDToObject(id):
76     myObj = None
77     mySO = myStudy.FindObjectID(id);
78     if mySO is not None:
79         ok, anAttr = mySO.FindAttribute("AttributeIOR")
80         if ok:
81             AtIOR = anAttr._narrow(SALOMEDS.AttributeIOR)
82             if AtIOR.Value() != "":
83                 myObj = orb.string_to_object(AtIOR.Value())
84     return myObj
85
86 def ObjectToSObject(obj):
87     mySO = None
88     if obj is not None:
89         ior =  orb.object_to_string(obj)
90         if ior != "":
91             mySO = myStudy.FindObjectIOR(ior)
92     return mySO
93
94 def ObjectToID(obj):
95     mySO = ObjectToSObject(obj)
96     if mySO:
97         return mySO.GetID()
98     return ""
99
100 def IDToSObject(id):
101     mySO = myStudy.FindObjectID(id);
102     return mySO
103
104     #--------------------------------------------------------------------------
105
106 def generateName(prefix = None):
107     import whrandom;
108     int = whrandom.randint(1,1000);
109     if prefix is None:
110         return "Study" + str(int)
111     else :
112         return prefix + str(int)
113
114     #--------------------------------------------------------------------------
115
116 def PersistentPresentation(theStudy, theSO, theWithID):
117     # put the sobject's content (with subchildren) to the string
118     aResult = ""
119     attrs = theSO.GetAllAttributes()
120     aLen = len(attrs)
121     anUncopied = 0
122     for a in range(0,aLen):
123         attr = attrs[a]
124         if isinstance(attr,SALOMEDS._objref_AttributeTreeNode):
125             anUncopied += 1
126         elif isinstance(attr,SALOMEDS._objref_AttributeTarget):
127             anUncopied += 1
128         elif isinstance(attr,SALOMEDS._objref_AttributeReal) or \
129              isinstance(attr,SALOMEDS._objref_AttributeInteger) or \
130              isinstance(attr,SALOMEDS._objref_AttributeName) or \
131              isinstance(attr,SALOMEDS._objref_AttributeComment) or \
132              isinstance(attr,SALOMEDS._objref_AttributePersistentRef) or \
133              isinstance(attr,SALOMEDS._objref_AttributeLocalID) or \
134              isinstance(attr,SALOMEDS._objref_AttributeUserID):
135             aResult += " attribute value: " + str(attr.Value())
136         elif isinstance(attr,SALOMEDS._objref_AttributeIOR):
137             aResult += " attribute: IOR"
138         elif isinstance(attr,SALOMEDS._objref_AttributeSequenceOfReal) or \
139              isinstance(attr,SALOMEDS._objref_AttributeSequenceOfInteger):
140             aResult += " Sequence: " + str(attr.CorbaSequence())
141         elif isinstance(attr,SALOMEDS._objref_AttributeDrawable):
142             aResult += " Drawable: " + str(attr.IsDrawable())
143         elif isinstance(attr,SALOMEDS._objref_AttributeSelectable):
144             aResult += " Selectable: " + str(attr.IsSelectable())
145         elif isinstance(attr,SALOMEDS._objref_AttributeExpandable):
146             aResult += " Expandable: " + str(attr.IsExpandable())
147         elif isinstance(attr,SALOMEDS._objref_AttributeOpened):
148             aResult += " Opened: " + str(attr.IsOpened())
149         elif isinstance(attr,SALOMEDS._objref_AttributeTextColor):
150             aResult += " TextColor: " + str(attr.TextColor())
151         elif isinstance(attr,SALOMEDS._objref_AttributeTextHighlightColor):
152             aResult += " TextHighlightColor: " + str(attr.TextHighlightColor())
153         elif isinstance(attr,SALOMEDS._objref_AttributePixMap):
154             aResult += " PixMap: " + str(attr.GetPixMap())
155         elif isinstance(attr,SALOMEDS._objref_AttributeTableOfInteger) or \
156              isinstance(attr,SALOMEDS._objref_AttributeTableOfReal):
157             aResult += " Table with title: " + attr.GetTitle()
158         elif isinstance(attr,SALOMEDS._objref_AttributePythonObject):
159             aResult += " PythonObject: " + attr.GetObject()
160
161     if theWithID:
162         aResult = "sobject: " + theSO.GetID() + " nbattrs: " + str(aLen - anUncopied) + aResult + '\n'
163     else:
164         aResult = " nbattrs: " + str(aLen - anUncopied) + aResult + '\n'
165     anIter = theStudy.NewChildIterator(theSO)
166     while anIter.More():
167         aResult += PersistentPresentation(theStudy, anIter.Value(), theWithID)
168         anIter.Next()
169     return aResult
170
171     #--------------------------------------------------------------------------
172
173 def GetTree(theSO):
174     # returns the document list tree (as list)
175     aResult = [theSO.GetID()]
176     anIter = myStudy.NewChildIterator(theSO)
177     while anIter.More():
178         aResult += GetTree(anIter.Value())
179         anIter.Next()
180     return aResult
181
182     #--------------------------------------------------------------------------
183
184 def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
185     aRoot = theSO
186     while aRoot.GetID() != "0:":
187         aRoot = aRoot.GetFather()
188     aTree = GetTree(aRoot)
189     aStudyPersist = PersistentPresentation(myStudy, aRoot, 1)
190
191     if not myStudyManager.CanCopy(theSO):
192         raise RuntimeError, "<CanCopy> for "+theInfo+" returns false"
193     
194     if not myStudyManager.Copy(theSO):
195         raise RuntimeError, "<Copy> for "+theInfo+" returns false"
196
197     
198     if not myStudyManager.CanPaste(theSO):
199         raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
200
201     # check: before paste study is not changed check
202     if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
203         raise RuntimeError, "Study is changed before Paste calling for "+theInfo
204     
205     aSObj = theSO
206     if theComponentPaste:
207         aSObj = theSO.GetFatherComponent()
208         theInfo = theInfo + "(paste for component)"
209     if myStudyManager.Paste(aSObj) == None:
210         raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
211     aNewTree = GetTree(aRoot)
212     aLen = len(aTree)
213     for a in range(0,aLen):
214         if aTree[a] != aNewTree[a]:
215             return myStudy.FindObjectID(aNewTree[a])
216         
217     if aLen < len(aNewTree):
218         return myStudy.FindObjectID(aNewTree[aLen])
219     
220     raise RuntimeError, "After Copy calling the tree is not changed"
221     
222     #--------------------------------------------------------------------------
223
224 def FindFileInDataDir(filename):
225     import os
226     datadir = os.getenv("DATA_DIR")
227     if datadir is not None:
228         import string
229         dirs = string.split(datadir, ":")
230         for dir in dirs:
231             file = dir + "/" + filename
232             if os.path.exists(file):
233                 return file;
234     datadir = os.getenv("KERNEL_ROOT_DIR") + "/examples/"
235     file = datadir + filename
236     if os.path.exists(file):
237         return file;
238
239     return None
240
241     #--------------------------------------------------------------------------
242
243 salome_study_ID = -1
244
245 def getActiveStudy(theStudyId=0):
246     global salome_study_ID
247     
248     if verbose(): print "getActiveStudy"
249     if salome_study_ID == -1:
250         if salome_iapp.hasDesktop():
251             if verbose(): print "---in gui"
252             salome_study_ID = salome_iapp.sg.getActiveStudyId()
253         else:
254             if verbose(): print "---outside gui"
255             if theStudyId:
256                 aStudy=myStudyManager.GetStudyByID(theStudyId)
257                 if aStudy:
258                     if verbose(): print "connection to existing study ", theStudyId
259                     salome_study_ID = theStudyId
260             if salome_study_ID == -1:
261                 salome_study_ID = createNewStudy()
262             if verbose(): print"--- Study Id ", salome_study_ID
263     return salome_study_ID
264     
265     #--------------------------------------------------------------------------
266
267 def createNewStudy():
268     print "createNewStudy"
269     i=1
270     aStudyName = "noName"
271     nameAlreadyInUse = 1
272     listOfOpenStudies = myStudyManager.GetOpenStudies()
273     print listOfOpenStudies
274     while nameAlreadyInUse:
275         aStudyName = "extStudy_%d"%i
276         if aStudyName not in listOfOpenStudies:
277             nameAlreadyInUse=0
278         else:
279             i = i+1
280
281     theStudy = myStudyManager.NewStudy(aStudyName)
282     theStudyId = theStudy._get_StudyId()
283     print aStudyName, theStudyId
284     return theStudyId
285
286     #--------------------------------------------------------------------------
287
288 salome_study_initial = 1
289
290 def salome_study_init(theStudyId=0):
291     """
292     Performs only once study creation or connection.
293     optional argument : theStudyId
294       When in embedded interpreter inside IAPP, theStudyId is not used
295       When used without GUI (external interpreter)
296         0      : create a new study (default).
297         n (>0) : try connection to study with Id = n, or create a new one
298                  if study not found.
299     """
300     
301     global salome_study_initial
302     global myStudyManager, myStudyId, myStudy, myStudyName
303     global orb, lcc, naming_service, cm
304     
305     if salome_study_initial:
306         salome_study_initial = 0
307         
308         orb, lcc, naming_service, cm = salome_kernel.salome_kernel_init()
309         
310         # get Study Manager reference
311         if verbose(): print "looking for studyManager ..."
312         obj = naming_service.Resolve('myStudyManager')
313         myStudyManager = obj._narrow(SALOMEDS.StudyManager)
314         if verbose(): print "studyManager found"
315
316         # get active study Id, ref and name
317         myStudyId = getActiveStudy(theStudyId)
318         if verbose(): print "myStudyId",myStudyId
319         myStudy = myStudyManager.GetStudyByID(myStudyId)
320         myStudyName = myStudy._get_Name()
321
322     return myStudyManager, myStudyId, myStudy, myStudyName
323