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