Salome HOME
41537220256d47f0b407f340c9e1ac729f059601
[modules/kernel.git] / src / KERNEL_PY / salome_study.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2023  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 myStudy = None
35 myStudyName = None
36
37 #--------------------------------------------------------------------------
38
39 def DumpComponent(SO, Builder,offset):
40   global myStudy
41   it = myStudy.NewChildIterator(SO)
42   while it.More():
43     CSO = it.Value()
44     a=offset*"--" + ">" + CSO.GetID()
45     find,AtName = Builder.FindAttribute(CSO, "AttributeName")
46     if find:
47       a=a+":"+AtName.Value()
48     find,AtIOR = Builder.FindAttribute(CSO, "AttributeIOR")
49     if find:
50       a=a+":"+AtIOR.Value()
51     find,RefSO = CSO.ReferencedObject()
52     if find:
53       a=a+":"+RefSO.GetID()
54     print(a)
55     DumpComponent(CSO, Builder,offset+2)
56     it.Next()
57
58 #--------------------------------------------------------------------------
59
60 def DumpStudy():
61     """
62     Dump a study, given the ior
63     """
64     global myStudy
65     itcomp = myStudy.NewComponentIterator()
66     Builder = myStudy.NewBuilder()
67     while itcomp.More():
68       SC = itcomp.Value()
69       name = SC.ComponentDataType()
70       print("-> ComponentDataType is " + name)
71       DumpComponent(SC,Builder, 1)
72       itcomp.Next()
73
74 #--------------------------------------------------------------------------
75
76 def IDToObject(id):
77     global myStudy
78     myObj = None
79     mySO = myStudy.FindObjectID(id);
80     if mySO is not None:
81         ok, anAttr = mySO.FindAttribute("AttributeIOR")
82         if ok:
83             AtIOR = anAttr._narrow(SALOMEDS.AttributeIOR)
84             if AtIOR.Value() != "":
85                 myObj = orb.string_to_object(AtIOR.Value())
86     return myObj
87
88 def ObjectToSObject(obj):
89     global myStudy
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     global myStudy
105     mySO = myStudy.FindObjectID(id);
106     return mySO
107
108     #--------------------------------------------------------------------------
109
110 def generateName(prefix = None):
111     import random;
112     int = random.randint(1,1000);
113     if prefix is None:
114         return "Study" + str(int)
115     else :
116         return prefix + str(int)
117
118     #--------------------------------------------------------------------------
119
120 def PersistentPresentation(theSO, theWithID):
121     global myStudy
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 = myStudy.NewChildIterator(theSO)
171     while anIter.More():
172         aResult += PersistentPresentation(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     global myStudy
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     global myStudy
192
193     aRoot = theSO
194     while aRoot.GetID() != "0:":
195         aRoot = aRoot.GetFather()
196     aTree = GetTree(aRoot)
197     aStudyPersist = PersistentPresentation(aRoot, 1)
198
199     if not myStudy.CanCopy(theSO):
200         raise RuntimeError("<CanCopy> for "+theInfo+" returns false")
201     
202     if not myStudy.Copy(theSO):
203         raise RuntimeError("<Copy> for "+theInfo+" returns false")
204
205     
206     if not myStudy.CanPaste(theSO):
207         raise RuntimeError("<CanPaste> for "+theInfo+" returns false")
208
209     # check: before paste study is not changed check
210     if aStudyPersist != PersistentPresentation(aRoot, 1):
211         raise RuntimeError("Study is changed before Paste calling for "+theInfo)
212     
213     aSObj = theSO
214     if theComponentPaste:
215         aSObj = theSO.GetFatherComponent()
216         theInfo = theInfo + "(paste for component)"
217     if myStudy.Paste(aSObj) == None:
218         raise RuntimeError("<Paste> for "+theInfo+" returns None object")
219     aNewTree = GetTree(aRoot)
220     aLen = len(aTree)
221     for a in range(0,aLen):
222         if aTree[a] != aNewTree[a]:
223             return myStudy.FindObjectID(aNewTree[a])
224         
225     if aLen < len(aNewTree):
226         return myStudy.FindObjectID(aNewTree[aLen])
227     
228     raise RuntimeError("After Copy calling the tree is not changed")
229     
230     #--------------------------------------------------------------------------
231
232 def GetComponentVersion(theComponent, all_versions = False):
233     # returns the document list tree (as list)
234     global myStudy
235     props = myStudy.GetProperties()
236     stored_components = props.GetStoredComponents()
237     version = "no component data" # vsr: better raise an exception in this case?
238     if theComponent in stored_components:
239       if all_versions:
240         version = props.GetComponentVersions(theComponent)
241         for i in range(len(version)):
242           if not version[i]: version[i] = "unknown"
243           pass
244         pass
245       else:
246         version = props.GetComponentVersion(theComponent)
247         if not version: version = "unknown"
248         pass
249       pass
250     return version
251     
252     #--------------------------------------------------------------------------
253
254 def FindFileInDataDir(filename):
255     import os
256     datadir = os.getenv("DATA_DIR")
257     if datadir is not None:
258         import string
259         dirs = string.split(datadir, ":")
260         for dir in dirs:
261             file = dir + "/" + filename
262             if os.path.exists(file):
263                 return file;
264     datadir = os.getenv("KERNEL_ROOT_DIR") + "/examples/"
265     file = datadir + filename
266     if os.path.exists(file):
267         return file;
268
269     return None
270
271     #--------------------------------------------------------------------------
272
273 def openStudy(theStudyPath):
274     if verbose(): print("openStudy (begin)")
275     global myStudy, myStudyName
276     myStudy.Open(theStudyPath)
277     myStudyName = myStudy._get_Name()
278     if verbose(): print("openStudy (end):", theStudyPath, myStudy._get_Name())
279
280     #--------------------------------------------------------------------------
281
282 def salome_study_init_without_session(theStudyPath=None):
283     """
284     Performs only once study creation or connection.
285     optional argument : theStudyPath
286         None        : attach to the currently active single study;
287                       create new empty study if there is active study
288         <URL> (str) : open study with the given file name
289     """
290     global myStudy, myStudyName
291     global orb, lcc, naming_service, cm
292
293     if verbose(): print("theStudyPath:", theStudyPath)
294     if not myStudy:
295         import CORBA
296         orb = CORBA.ORB_init([''])
297
298         # get Study reference
299         if verbose(): print("looking for study...")
300         import KernelDS
301         myStudy = KernelDS.myStudy()
302         if verbose(): print("Study found")
303         pass
304
305     import types
306     if theStudyPath and isinstance(theStudyPath, (str, bytes)):
307         if isinstance(theStudyPath, bytes):
308             theStudyPath = str(theStudyPath, 'UTF8')
309         openStudy(theStudyPath)
310     else:
311         myStudy.Init()
312
313     myStudyName = myStudy._get_Name()
314
315     return myStudy, myStudyName
316
317     #--------------------------------------------------------------------------
318
319 def salome_study_init(theStudyPath=None):
320     """
321     Performs only once study creation or connection.
322     optional argument : theStudyPath
323         None        : attach to the currently active single study;
324                       create new empty study if there is active study
325         <URL> (str) : open study with the given file name
326     """
327     global myStudy, myStudyName
328     global orb, lcc, naming_service, cm
329
330     if verbose(): print("theStudyPath:", theStudyPath)
331     if not myStudy:
332         orb, lcc, naming_service, cm, _, _, _ = salome_kernel.salome_kernel_init()
333
334         # get Study reference
335         if verbose(): print("looking for study...")
336         obj = naming_service.Resolve('/Study')
337         myStudy = obj._narrow(SALOMEDS.Study)
338         if verbose(): print("Study found")
339         pass
340
341     import types
342     if theStudyPath and isinstance(theStudyPath, (str, bytes)):
343         if isinstance(theStudyPath, bytes):
344             theStudyPath = str(theStudyPath, 'UTF8')
345         openStudy(theStudyPath)
346     else:
347         myStudy.Init()
348
349     myStudyName = myStudy._get_Name()
350
351     return myStudy, myStudyName
352
353 def salome_study_close():
354   global myStudy, myStudyName
355   myStudy, myStudyName = None, None