Salome HOME
bos #24412 Add missing failback for UpdateView() method
[modules/kernel.git] / src / KERNEL_PY / salome_study.py
index 6855fe7f6d0d9b7e8697157f950219886657b634..c8fab2542b9bcece546963276dd4be76e91c5c91 100644 (file)
@@ -1,77 +1,80 @@
-#  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-#  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
-# 
-#  This library is free software; you can redistribute it and/or 
-#  modify it under the terms of the GNU Lesser General Public 
-#  License as published by the Free Software Foundation; either 
-#  version 2.1 of the License. 
-# 
-#  This library is distributed in the hope that it will be useful, 
-#  but WITHOUT ANY WARRANTY; without even the implied warranty of 
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
-#  Lesser General Public License for more details. 
-# 
-#  You should have received a copy of the GNU Lesser General Public 
-#  License along with this library; if not, write to the Free Software 
-#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
-# 
-#  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
+#  -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
 #
+# Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
 #
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
 #
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
 #  File   : salome_study.py
 #  Author : Paul RASCLE, EDF
 #  Module : SALOME
 #  $Header$
-
+#
 import salome_kernel
 import SALOMEDS
 import salome_iapp
+from launchConfigureParser import verbose
+
+myStudy = None
+myStudyName = None
 
 #--------------------------------------------------------------------------
 
-def DumpComponent(Study, SO, offset):
-    it = Study.NewChildIterator(SO)
-    Builder = Study.NewBuilder()
-    while it.More():
-        CSO = it.Value()
-        it.Next()
-        anAttr = Builder.FindOrCreateAttribute(CSO, "AttributeName")
-        AtName = anAttr._narrow(SALOMEDS.AttributeName)
-        t_name = AtName.Value()
-        if t_name[0] == 1:
-            ofs = 1
-            a = ""
-            while ofs <= offset:
-                a = a + "--"
-                ofs = ofs +1
-            MESSAGE( a + ">" + str(CSO.GetID()) + " " + str(t_name[1]) )
-        t_RefSO = CSO.ReferencedObject()
-        if t_RefSO[0] == 1:
-            RefSO = t_RefSO[1]
-            ofs = 1
-            a = ""
-            while ofs <= offset:
-                a = a + "  "
-                ofs = ofs +1
-            MESSAGE( a + ">" + str(RefSO.GetID()) )
-        DumpComponent(Study, CSO, offset+2)
+def DumpComponent(SO, Builder,offset):
+  global myStudy
+  it = myStudy.NewChildIterator(SO)
+  while it.More():
+    CSO = it.Value()
+    a=offset*"--" + ">" + CSO.GetID()
+    find,AtName = Builder.FindAttribute(CSO, "AttributeName")
+    if find:
+      a=a+":"+AtName.Value()
+    find,AtIOR = Builder.FindAttribute(CSO, "AttributeIOR")
+    if find:
+      a=a+":"+AtIOR.Value()
+    find,RefSO = CSO.ReferencedObject()
+    if find:
+      a=a+":"+RefSO.GetID()
+    print(a)
+    DumpComponent(CSO, Builder,offset+2)
+    it.Next()
 
-    #--------------------------------------------------------------------------
+#--------------------------------------------------------------------------
 
-def DumpStudy(Study):
-    itcomp = Study.NewComponentIterator()
+def DumpStudy():
+    """
+    Dump a study, given the ior
+    """
+    global myStudy
+    itcomp = myStudy.NewComponentIterator()
+    Builder = myStudy.NewBuilder()
     while itcomp.More():
-        SC = itcomp.Value()
-        itcomp.Next()
-        name = SC.ComponentDataType()
-        MESSAGE( "-> ComponentDataType is " + name )
-        DumpComponent(Study, SC, 1)
-        
+      SC = itcomp.Value()
+      name = SC.ComponentDataType()
+      print("-> ComponentDataType is " + name)
+      DumpComponent(SC,Builder, 1)
+      itcomp.Next()
 
-    #--------------------------------------------------------------------------
+#--------------------------------------------------------------------------
 
 def IDToObject(id):
+    global myStudy
     myObj = None
     mySO = myStudy.FindObjectID(id);
     if mySO is not None:
@@ -83,6 +86,7 @@ def IDToObject(id):
     return myObj
 
 def ObjectToSObject(obj):
+    global myStudy
     mySO = None
     if obj is not None:
         ior =  orb.object_to_string(obj)
@@ -97,14 +101,15 @@ def ObjectToID(obj):
     return ""
 
 def IDToSObject(id):
+    global myStudy
     mySO = myStudy.FindObjectID(id);
     return mySO
 
     #--------------------------------------------------------------------------
 
 def generateName(prefix = None):
-    import whrandom;
-    int = whrandom.randint(1,1000);
+    import random;
+    int = random.randint(1,1000);
     if prefix is None:
         return "Study" + str(int)
     else :
@@ -112,7 +117,8 @@ def generateName(prefix = None):
 
     #--------------------------------------------------------------------------
 
-def PersistentPresentation(theStudy, theSO, theWithID):
+def PersistentPresentation(theSO, theWithID):
+    global myStudy
     # put the sobject's content (with subchildren) to the string
     aResult = ""
     attrs = theSO.GetAllAttributes()
@@ -161,9 +167,9 @@ def PersistentPresentation(theStudy, theSO, theWithID):
         aResult = "sobject: " + theSO.GetID() + " nbattrs: " + str(aLen - anUncopied) + aResult + '\n'
     else:
         aResult = " nbattrs: " + str(aLen - anUncopied) + aResult + '\n'
-    anIter = theStudy.NewChildIterator(theSO)
+    anIter = myStudy.NewChildIterator(theSO)
     while anIter.More():
-        aResult += PersistentPresentation(theStudy, anIter.Value(), theWithID)
+        aResult += PersistentPresentation(anIter.Value(), theWithID)
         anIter.Next()
     return aResult
 
@@ -171,6 +177,7 @@ def PersistentPresentation(theStudy, theSO, theWithID):
 
 def GetTree(theSO):
     # returns the document list tree (as list)
+    global myStudy
     aResult = [theSO.GetID()]
     anIter = myStudy.NewChildIterator(theSO)
     while anIter.More():
@@ -181,32 +188,34 @@ def GetTree(theSO):
     #--------------------------------------------------------------------------
 
 def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
+    global myStudy
+
     aRoot = theSO
     while aRoot.GetID() != "0:":
         aRoot = aRoot.GetFather()
     aTree = GetTree(aRoot)
-    aStudyPersist = PersistentPresentation(myStudy, aRoot, 1)
+    aStudyPersist = PersistentPresentation(aRoot, 1)
 
-    if not myStudyManager.CanCopy(theSO):
-        raise RuntimeError, "<CanCopy> for "+theInfo+" returns false"
+    if not myStudy.CanCopy(theSO):
+        raise RuntimeError("<CanCopy> for "+theInfo+" returns false")
     
-    if not myStudyManager.Copy(theSO):
-        raise RuntimeError, "<Copy> for "+theInfo+" returns false"
+    if not myStudy.Copy(theSO):
+        raise RuntimeError("<Copy> for "+theInfo+" returns false")
 
     
-    if not myStudyManager.CanPaste(theSO):
-        raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
+    if not myStudy.CanPaste(theSO):
+        raise RuntimeError("<CanPaste> for "+theInfo+" returns false")
 
     # check: before paste study is not changed check
-    if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
-        raise RuntimeError, "Study is changed before Paste calling for "+theInfo
+    if aStudyPersist != PersistentPresentation(aRoot, 1):
+        raise RuntimeError("Study is changed before Paste calling for "+theInfo)
     
     aSObj = theSO
     if theComponentPaste:
         aSObj = theSO.GetFatherComponent()
         theInfo = theInfo + "(paste for component)"
-    if myStudyManager.Paste(aSObj) == None:
-        raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
+    if myStudy.Paste(aSObj) == None:
+        raise RuntimeError("<Paste> for "+theInfo+" returns None object")
     aNewTree = GetTree(aRoot)
     aLen = len(aTree)
     for a in range(0,aLen):
@@ -216,7 +225,29 @@ def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
     if aLen < len(aNewTree):
         return myStudy.FindObjectID(aNewTree[aLen])
     
-    raise RuntimeError, "After Copy calling the tree is not changed"
+    raise RuntimeError("After Copy calling the tree is not changed")
+    
+    #--------------------------------------------------------------------------
+
+def GetComponentVersion(theComponent, all_versions = False):
+    # returns the document list tree (as list)
+    global myStudy
+    props = myStudy.GetProperties()
+    stored_components = props.GetStoredComponents()
+    version = "no component data" # vsr: better raise an exception in this case?
+    if theComponent in stored_components:
+      if all_versions:
+        version = props.GetComponentVersions(theComponent)
+        for i in range(len(version)):
+          if not version[i]: version[i] = "unknown"
+          pass
+        pass
+      else:
+        version = props.GetComponentVersion(theComponent)
+        if not version: version = "unknown"
+        pass
+      pass
+    return version
     
     #--------------------------------------------------------------------------
 
@@ -239,84 +270,86 @@ def FindFileInDataDir(filename):
 
     #--------------------------------------------------------------------------
 
-salome_study_ID = -1
+def openStudy(theStudyPath):
+    if verbose(): print("openStudy (begin)")
+    global myStudy, myStudyName
+    myStudy.Open(theStudyPath)
+    myStudyName = myStudy._get_Name()
+    if verbose(): print("openStudy (end):", theStudyPath, myStudy._get_Name())
 
-def getActiveStudy(theStudyId=0):
-    global salome_study_ID
-    
-    print "getActiveStudy"
-    if salome_study_ID == -1:
-        if salome_iapp.hasDesktop():
-            print "---in gui"
-            salome_study_ID = salome_iapp.sg.getActiveStudyId()
-        else:
-            print "---outside gui"
-            if theStudyId:
-                aStudy=myStudyManager.GetStudyByID(theStudyId)
-                if aStudy:
-                    print "connection to existing study ", theStudyId
-                    salome_study_ID = theStudyId
-            if salome_study_ID == -1:
-                salome_study_ID = createNewStudy()
-            print"--- Study Id ", salome_study_ID
-    return salome_study_ID
-    
     #--------------------------------------------------------------------------
 
-def createNewStudy():
-    print "createNewStudy"
-    i=1
-    aStudyName = "noName"
-    nameAlreadyInUse = 1
-    listOfOpenStudies = myStudyManager.GetOpenStudies()
-    print listOfOpenStudies
-    while nameAlreadyInUse:
-        aStudyName = "extStudy_%d"%i
-        if aStudyName not in listOfOpenStudies:
-            nameAlreadyInUse=0
-        else:
-            i = i+1
-
-    theStudy = myStudyManager.NewStudy(aStudyName)
-    theStudyId = theStudy._get_StudyId()
-    print aStudyName, theStudyId
-    return theStudyId
+def salome_study_init_without_session(theStudyPath=None):
+    """
+    Performs only once study creation or connection.
+    optional argument : theStudyPath
+        None        : attach to the currently active single study;
+                      create new empty study if there is active study
+        <URL> (str) : open study with the given file name
+    """
+    global myStudy, myStudyName
+    global orb, lcc, naming_service, cm
 
-    #--------------------------------------------------------------------------
+    if verbose(): print("theStudyPath:", theStudyPath)
+    if not myStudy:
+        import CORBA
+        orb = CORBA.ORB_init([''])
+
+        # get Study reference
+        if verbose(): print("looking for study...")
+        import KernelDS
+        myStudy = KernelDS.myStudy()
+        if verbose(): print("Study found")
+        pass
+
+    import types
+    if theStudyPath and isinstance(theStudyPath, (str, bytes)):
+        if isinstance(theStudyPath, bytes):
+            theStudyPath = str(theStudyPath, 'UTF8')
+        openStudy(theStudyPath)
+    else:
+        myStudy.Init()
 
-salome_study_initial = 1
+    myStudyName = myStudy._get_Name()
 
-def salome_study_init(theStudyId=0):
+    return myStudy, myStudyName
+
+    #--------------------------------------------------------------------------
+
+def salome_study_init(theStudyPath=None):
     """
     Performs only once study creation or connection.
-    optional argument : theStudyId
-      When in embedded interpreter inside IAPP, theStudyId is not used
-      When used without GUI (external interpreter)
-        0      : create a new study (default).
-        n (>0) : try connection to study with Id = n, or create a new one
-                 if study not found.
+    optional argument : theStudyPath
+        None        : attach to the currently active single study;
+                      create new empty study if there is active study
+        <URL> (str) : open study with the given file name
     """
-    
-    global salome_study_initial
-    global myStudyManager, myStudyId, myStudy, myStudyName
+    global myStudy, myStudyName
     global orb, lcc, naming_service, cm
-    
-    if salome_study_initial:
-        salome_study_initial = 0
-        
-        orb, lcc, naming_service, cm = salome_kernel.salome_kernel_init()
-        
-        # get Study Manager reference
-        print "looking for studyManager ..."
-        obj = naming_service.Resolve('myStudyManager')
-        myStudyManager = obj._narrow(SALOMEDS.StudyManager)
-        print "studyManager found"
 
-        # get active study Id, ref and name
-        myStudyId = getActiveStudy(theStudyId)
-        print "myStudyId",myStudyId
-        myStudy = myStudyManager.GetStudyByID(myStudyId)
-        myStudyName = myStudy._get_Name()
+    if verbose(): print("theStudyPath:", theStudyPath)
+    if not myStudy:
+        orb, lcc, naming_service, cm, _, _, _ = salome_kernel.salome_kernel_init()
+
+        # get Study reference
+        if verbose(): print("looking for study...")
+        obj = naming_service.Resolve('/Study')
+        myStudy = obj._narrow(SALOMEDS.Study)
+        if verbose(): print("Study found")
+        pass
+
+    import types
+    if theStudyPath and isinstance(theStudyPath, (str, bytes)):
+        if isinstance(theStudyPath, bytes):
+            theStudyPath = str(theStudyPath, 'UTF8')
+        openStudy(theStudyPath)
+    else:
+        myStudy.Init()
+
+    myStudyName = myStudy._get_Name()
 
-    return myStudyManager, myStudyId, myStudy, myStudyName
+    return myStudy, myStudyName
 
+def salome_study_close():
+  global myStudy, myStudyName
+  myStudy, myStudyName = None, None