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