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