From: Ovidiu Mircescu
Date: Tue, 19 Jun 2018 08:48:24 +0000 (+0200)
Subject: Merge branch 'omu/Launcher9'
X-Git-Tag: SHAPER_V9_1_0RC1~15
X-Git-Url: http://git.salome-platform.org/gitweb/?a=commitdiff_plain;h=dc4b16b9dd53dd42139fd22ef26556861db58989;hp=e5d5042cbf33962846b30506cb452b4cfb4aa892;p=modules%2Fkernel.git
Merge branch 'omu/Launcher9'
Use the single thread policy for Launcher Server.
Add launcher_proxy with a reload job feature.
---
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 2fe5bece3..6822747e5 100755
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -34,7 +34,7 @@ SET(${PROJECT_NAME_UC}_MINOR_VERSION 5)
SET(${PROJECT_NAME_UC}_PATCH_VERSION 0)
SET(${PROJECT_NAME_UC}_VERSION
${${PROJECT_NAME_UC}_MAJOR_VERSION}.${${PROJECT_NAME_UC}_MINOR_VERSION}.${${PROJECT_NAME_UC}_PATCH_VERSION})
-SET(${PROJECT_NAME_UC}_VERSION_DEV 0)
+SET(${PROJECT_NAME_UC}_VERSION_DEV 1)
# Common CMake macros
# ===================
diff --git a/bin/NSparam.py b/bin/NSparam.py
index 3cb3cf9cd..612a0cff1 100755
--- a/bin/NSparam.py
+++ b/bin/NSparam.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -56,12 +56,12 @@ if __name__ == "__main__":
if sys.argv[1]=='host':
my_host = getNSparams('host')
# keep print, stdout used in shell
- print my_host
+ print(my_host)
pass
elif sys.argv[1]=='port':
my_port = getNSparams('port')
# keep print, stdout used in shell
- print my_port
+ print(my_port)
pass
else:
my_host, my_port = getNSparams()
@@ -70,7 +70,7 @@ if __name__ == "__main__":
else:
getNSparams()
# keep print, stdout used in shell
- print my_host, my_port
+ print(my_host, my_port)
pass
pass
#
diff --git a/bin/ORBConfigFile.py b/bin/ORBConfigFile.py
index 19a9647f4..c9447f8fa 100644
--- a/bin/ORBConfigFile.py
+++ b/bin/ORBConfigFile.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -64,6 +64,7 @@ def writeORBConfigFile(path, host, port, kwargs={}):
orbdata.append("%sgiopMaxMsgSize = %s # 2 GBytes"%(prefix,GIOP_MaxMsgSize))
orbdata.append("%straceLevel = 0 # critical errors only"%(prefix))
orbdata.append("%smaxGIOPConnectionPerServer = 500 # to allow containers parallel launch"%(prefix))
+ orbdata.append("%snativeCharCodeSet = UTF-8"%(prefix))
orbdata.append("")
with open(omniorb_config, "w") as f:
@@ -98,4 +99,4 @@ if __name__ == "__main__":
# RETURN_VALUE_2=$(echo ${RETURN_VALUES} | cut -d' ' -f2)
# ...
# IMPORTANT NOTE: this print call MUST BE the first one!!
- print filename, msgSize
+ print(filename, msgSize)
diff --git a/bin/PortManager.py b/bin/PortManager.py
index ced2ad296..c842c7e71 100644
--- a/bin/PortManager.py
+++ b/bin/PortManager.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2017 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -111,14 +111,14 @@ def __isNetworkConnectionActiveOnPort(port):
p = Popen(cmd, stdout=PIPE, stderr=STDOUT)
out, err = p.communicate()
except:
- print "Error when trying to access active network connections."
- if err: print err
+ print("Error when trying to access active network connections.")
+ if err: print(err)
import traceback
traceback.print_exc()
return False
- import StringIO
- buf = StringIO.StringIO(out)
+ from io import StringIO
+ buf = StringIO(out.decode())
ports = buf.readlines()
# search for TCP - LISTEN connections
import re
@@ -137,7 +137,7 @@ def getPort(preferedPort=None):
config_file, lock_file = _getConfigurationFilename()
oldmask = os.umask(0)
- with open(lock_file, 'w') as lock:
+ with open(lock_file, 'wb') as lock:
# acquire lock
__acquire_lock(lock)
@@ -145,7 +145,7 @@ def getPort(preferedPort=None):
config = {}
logger.debug("read configuration file")
try:
- with open(config_file, 'r') as f:
+ with open(config_file, 'rb') as f:
config = pickle.load(f)
except:
logger.info("Problem loading PortManager file: %s"%config_file)
@@ -167,7 +167,7 @@ def getPort(preferedPort=None):
msg = "\n"
msg += "Can't find a free port to launch omniNames\n"
msg += "Try to kill the running servers and then launch SALOME again.\n"
- raise RuntimeError, msg
+ raise RuntimeError(msg)
logger.debug("Port %s seems to be busy"%str(port))
port = port + 1
logger.debug("found free port: %s"%str(port))
@@ -176,8 +176,8 @@ def getPort(preferedPort=None):
# write config
logger.debug("write config: %s"%str(config))
try:
- with open(config_file, 'w') as f:
- pickle.dump(config, f)
+ with open(config_file, 'wb') as f:
+ pickle.dump(config, f, protocol=0)
except IOError:
pass
@@ -196,7 +196,7 @@ def releasePort(port):
config_file, lock_file = _getConfigurationFilename()
oldmask = os.umask(0)
- with open(lock_file, 'w') as lock:
+ with open(lock_file, 'wb') as lock:
# acquire lock
__acquire_lock(lock)
@@ -204,7 +204,7 @@ def releasePort(port):
config = {}
logger.debug("read configuration file")
try:
- with open(config_file, 'r') as f:
+ with open(config_file, 'rb') as f:
config = pickle.load(f)
except IOError: # empty file
pass
@@ -223,8 +223,8 @@ def releasePort(port):
# write config
logger.debug("write config: %s"%str(config))
try:
- with open(config_file, 'w') as f:
- pickle.dump(config, f)
+ with open(config_file, 'wb') as f:
+ pickle.dump(config, f, protocol=0)
except IOError:
pass
@@ -239,7 +239,7 @@ def releasePort(port):
def getBusyPorts():
config_file, lock_file = _getConfigurationFilename()
oldmask = os.umask(0)
- with open(lock_file, 'w') as lock:
+ with open(lock_file, 'wb') as lock:
# acquire lock
__acquire_lock(lock)
@@ -247,7 +247,7 @@ def getBusyPorts():
config = {}
logger.debug("read configuration file")
try:
- with open(config_file, 'r') as f:
+ with open(config_file, 'rb') as f:
config = pickle.load(f)
except IOError: # empty file
pass
diff --git a/bin/addToKillList.py b/bin/addToKillList.py
index ca2abd934..d9b580d8f 100755
--- a/bin/addToKillList.py
+++ b/bin/addToKillList.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -34,7 +34,7 @@ def findFileDict():
"""
from salome_utils import getPortNumber
port = getPortNumber()
- if verbose(): print "myport = ", port
+ if verbose(): print("myport = ", port)
return port
def addToKillList(command_pid, command, port=None):
@@ -50,9 +50,10 @@ def addToKillList(command_pid, command, port=None):
from killSalomeWithPort import getPiDict
if port is None: port=findFileDict()
filedict = getPiDict(port)
+ #filedict = getPiDict(port).encode()
try:
- with open(filedict, 'r') as fpid:
+ with open(filedict, 'rb') as fpid:
process_ids=pickle.load(fpid)
except:
process_ids=[]
@@ -60,7 +61,7 @@ def addToKillList(command_pid, command, port=None):
# check if PID is already in dictionary
already_in=False
for process_id in process_ids:
- for pid in process_id.keys():
+ for pid in process_id:
if int(pid) == int(command_pid):
already_in=True
break
@@ -71,17 +72,17 @@ def addToKillList(command_pid, command, port=None):
# add process to the dictionary
if not already_in:
import types
- if type(command) == types.ListType: command=" ".join([str(c) for c in command])
+ if isinstance(command, list): command=" ".join([str(c) for c in command])
command=command.split()[0]
try:
- if verbose(): print "addToKillList: %s : %s" % ( str(command_pid), command )
+ if verbose(): print("addToKillList: %s : %s" % ( str(command_pid), command ))
process_ids.append({int(command_pid): [command]})
dir = os.path.dirname(filedict)
- if not os.path.exists(dir): os.makedirs(dir, 0777)
- with open(filedict,'w') as fpid:
+ if not os.path.exists(dir): os.makedirs(dir, 0o777)
+ with open(filedict,'wb') as fpid:
pickle.dump(process_ids, fpid)
except:
- if verbose(): print "addToKillList: can not add command %s : %s to the kill list" % ( str(command_pid), command )
+ if verbose(): print("addToKillList: can not add command %s : %s to the kill list" % ( str(command_pid), command ))
pass
pass
pass
@@ -102,19 +103,19 @@ def killList(port=None):
if not os.path.exists(filedict): filedict = getPiDict(port, hidden=False)
try:
- with open(filedict, 'r') as fpid:
+ with open(filedict, 'rb') as fpid:
process_ids=pickle.load(fpid)
except:
process_ids=[]
pass
# kill processes
for process_id in process_ids:
- #print process_id
- for pid, cmd in process_id.items():
+ # print(process_id)
+ for pid, cmd in list(process_id.items()):
try:
os.kill(int(pid),signal.SIGKILL)
except:
- print " ------------------ process %s : %s inexistant"% (pid, cmd[0])
+ print(" ------------------ process %s : %s inexistant"% (pid, cmd[0]))
pass
pass
pass
@@ -123,6 +124,6 @@ def killList(port=None):
pass
if __name__ == "__main__":
- if verbose(): print sys.argv
+ if verbose(): print(sys.argv)
addToKillList(sys.argv[1], sys.argv[2])
pass
diff --git a/bin/appli_gen.py b/bin/appli_gen.py
index 0dbab540b..47d3a0714 100755
--- a/bin/appli_gen.py
+++ b/bin/appli_gen.py
@@ -1,5 +1,4 @@
-#! /usr/bin/env python
-# -*- coding: iso-8859-1 -*-
+#! /usr/bin/env python3
# Copyright (C) 2007-2017 CEA/DEN, EDF R&D, OPEN CASCADE
#
# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
@@ -65,7 +64,7 @@ gui_att = "gui"
class xml_parser:
def __init__(self, fileName ):
- print "Configure parser: processing %s ..." % fileName
+ print("Configure parser: processing %s ..." % fileName)
self.space = []
self.config = {}
self.config["modules"] = []
@@ -191,22 +190,21 @@ def install(prefix, config_file, verbose=0):
try:
parser = xml_parser(filename)
_config = parser.config
- except xml.sax.SAXParseException, inst:
- print inst.getMessage()
- print "Configure parser: parse error in configuration file %s" % filename
+ except xml.sax.SAXParseException as inst:
+ print(inst.getMessage())
+ print("Configure parser: parse error in configuration file %s" % filename)
pass
- except xml.sax.SAXException, inst:
- print inst.args
- print "Configure parser: error in configuration file %s" % filename
+ except xml.sax.SAXException as inst:
+ print(inst.args)
+ print("Configure parser: error in configuration file %s" % filename)
pass
- except Exception as e:
- print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
- print(e)
+ except:
+ print("Configure parser: Error : can not read configuration file %s, check existence and rights" % filename)
pass
if verbose:
for cle,val in _config.items():
- print cle, val
+ print(cle, val)
pass
# Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
@@ -217,8 +215,8 @@ def install(prefix, config_file, verbose=0):
pass
for module in _config.get("modules", []):
- if _config.has_key(module):
- print "--- add module ", module, _config[module]
+ if module in _config:
+ print("--- add module ", module, _config[module])
options = params()
options.verbose = verbose
options.clear = 0
@@ -230,8 +228,8 @@ def install(prefix, config_file, verbose=0):
pass
for extra_test in _config.get("extra_tests", []):
- if _config.has_key(extra_test):
- print "--- add extra test ", extra_test, _config[extra_test]
+ if extra_test in _config:
+ print("--- add extra test ", extra_test, _config[extra_test])
options = params()
options.verbose = verbose
options.clear = 0
@@ -273,7 +271,7 @@ def install(prefix, config_file, verbose=0):
os.remove(salome_file)
except:
pass
- env_modules = [m.encode('utf8') for m in _config.get('env_modules', [])]
+ env_modules = _config.get('env_modules', [])
with open(salome_file, 'w') as fd:
fd.write(salome_script.replace('MODULES = []', 'MODULES = {}'.format(env_modules)))
os.chmod(salome_file, 0o755)
@@ -287,31 +285,31 @@ def install(prefix, config_file, verbose=0):
# Creation of env.d directory
virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
- if _config.has_key("prereq_path") and os.path.isfile(_config["prereq_path"]):
+ if "prereq_path" in _config and os.path.isfile(_config["prereq_path"]):
shutil.copyfile(_config["prereq_path"],
os.path.join(home_dir, 'env.d', 'envProducts.sh'))
pass
else:
- print "WARNING: prerequisite file does not exist"
+ print("WARNING: prerequisite file does not exist")
pass
- if _config.has_key("context_path") and os.path.isfile(_config["context_path"]):
+ if "context_path" in _config and os.path.isfile(_config["context_path"]):
shutil.copyfile(_config["context_path"],
os.path.join(home_dir, 'env.d', 'envProducts.cfg'))
pass
else:
- print "WARNING: context file does not exist"
+ print("WARNING: context file does not exist")
pass
- if _config.has_key("sha1_collect_path") and os.path.isfile(_config["sha1_collect_path"]):
+ if "sha1_collect_path" in _config and os.path.isfile(_config["sha1_collect_path"]):
shutil.copyfile(_config["sha1_collect_path"],
os.path.join(home_dir, 'sha1_collections.txt'))
pass
else:
- print "WARNING: sha1 collections file does not exist"
+ print("WARNING: sha1 collections file does not exist")
pass
- if _config.has_key("system_conf_path") and os.path.isfile(_config["system_conf_path"]):
+ if "system_conf_path" in _config and os.path.isfile(_config["system_conf_path"]):
shutil.copyfile(_config["system_conf_path"],
os.path.join(home_dir, 'env.d', 'envConfSystem.sh'))
pass
@@ -322,11 +320,11 @@ def install(prefix, config_file, verbose=0):
command = 'export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
f.write(command)
pass
- if _config.has_key("samples_path"):
+ if "samples_path" in _config:
command = 'export DATA_DIR=' + _config["samples_path"] +'\n'
f.write(command)
pass
- if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
+ if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
command = 'export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
f.write(command)
@@ -338,11 +336,11 @@ def install(prefix, config_file, verbose=0):
command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
f.write(command)
pass
- if _config.has_key("samples_path"):
+ if "samples_path" in _config:
command = 'DATA_DIR=' + _config["samples_path"] +'\n'
f.write(command)
pass
- if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
+ if "resources_path" in _config and os.path.isfile(_config["resources_path"]):
command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
f.write(command)
@@ -399,7 +397,7 @@ MMGT_REENTRANT=1
#Add USERS directory with 777 permission to store users configuration files
users_dir = os.path.join(home_dir,'USERS')
makedirs(users_dir)
- os.chmod(users_dir, 0777)
+ os.chmod(users_dir, 0o777)
def main():
parser = optparse.OptionParser(usage=usage)
@@ -415,7 +413,7 @@ def main():
options, args = parser.parse_args()
if not os.path.exists(options.config):
- print "ERROR: config file %s does not exist. It is mandatory." % options.config
+ print("ERROR: config file %s does not exist. It is mandatory." % options.config)
sys.exit(1)
install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
diff --git a/bin/appliskel/.salome_run b/bin/appliskel/.salome_run
index 171036b0e..1eaeb9541 100755
--- a/bin/appliskel/.salome_run
+++ b/bin/appliskel/.salome_run
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
# Copyright (C) 2013-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -23,51 +23,50 @@ import os
import sys
def main(args):
- # Identify application path then locate configuration files
- currentPath = os.path.realpath(os.path.dirname(os.path.abspath(__file__)))
- launcherFile = os.path.basename(__file__)
- from salome_starter import initialize
- initialize(currentPath, launcherFile)
-
- if len(args) == 1 and args[0] in ['--help', 'help', '-h', '--h']:
- from salomeContext import usage
- usage()
- sys.exit(0)
-
- from salomeContextUtils import getConfigFileNames
- configFileNames, args, unexisting = getConfigFileNames(args, checkExistence=True)
-
- if len(unexisting) > 0:
- print "ERROR: unexisting configuration/environment file(s): " + ', '.join(unexisting)
- sys.exit(1)
-
- # Create a SalomeContext which parses configFileNames to initialize environment
- from salomeContextUtils import SalomeContextException
- try:
- from salomeContext import SalomeContext
- context = SalomeContext(configFileNames)
-
- # Here set specific variables, if needed
- # context.addToPath('mypath')
- # context.addToLdLibraryPath('myldlibrarypath')
- # context.addToPythonPath('mypythonpath')
- # context.setVariable('myvarname', 'value')
-
- # Start SALOME, parsing command line arguments
- out, err, returncode = context.runSalome(args)
- if out:
- sys.stdout.write(out)
- if err:
- sys.stderr.write(err)
- #print 'Thank you for using SALOME!'
- sys.exit(returncode)
- except SalomeContextException, e:
- import logging
- logging.getLogger("salome").error(e)
- sys.exit(1)
+ # Identify application path then locate configuration files
+ currentPath = os.path.realpath(os.path.dirname(os.path.abspath(__file__)))
+ launcherFile = os.path.basename(__file__)
+ from salome_starter import initialize
+ initialize(currentPath, launcherFile)
+
+ if len(args) == 1 and args[0] in ['--help', 'help', '-h', '--h']:
+ from salomeContext import usage
+ usage()
+ sys.exit(0)
+
+ from salomeContextUtils import getConfigFileNames
+ configFileNames, args, unexisting = getConfigFileNames(args, checkExistence=True)
+
+ if len(unexisting) > 0:
+ print("ERROR: unexisting configuration/environment file(s): " + ', '.join(unexisting))
+ sys.exit(1)
+
+ # Create a SalomeContext which parses configFileNames to initialize environment
+ from salomeContextUtils import SalomeContextException
+ try:
+ from salomeContext import SalomeContext
+ context = SalomeContext(configFileNames)
+
+ # Here set specific variables, if needed
+ # context.addToPath('mypath')
+ # context.addToLdLibraryPath('myldlibrarypath')
+ # context.addToPythonPath('mypythonpath')
+ # context.setVariable('myvarname', 'value')
+
+ # Start SALOME, parsing command line arguments
+ out, err, returncode = context.runSalome(args)
+ if out:
+ sys.stdout.write(out)
+ if err:
+ sys.stderr.write(err)
+ #print('Thank you for using SALOME!')
+ sys.exit(returncode)
+ except SalomeContextException as e:
+ import logging
+ logging.getLogger("salome").error(e)
+ sys.exit(1)
#
if __name__ == "__main__":
- args = sys.argv[1:]
- main(args)
-#
+ args = sys.argv[1:]
+ main(args)
diff --git a/bin/appliskel/getAppliPath.py b/bin/appliskel/getAppliPath.py
index b17367163..460f5c592 100755
--- a/bin/appliskel/getAppliPath.py
+++ b/bin/appliskel/getAppliPath.py
@@ -36,7 +36,7 @@ def relpath(target, base):
"""
target=target.split(os.path.sep)
base=base.split(os.path.sep)
- for i in xrange(len(base)):
+ for i in range(len(base)):
if base[i] != target[i]:
i=i-1
#not in base
@@ -61,5 +61,5 @@ if __name__ == "__main__":
applipath = relpath(os.path.realpath(os.path.dirname(__file__)),os.path.realpath(os.getenv('HOME')))
else:
applipath = get_appli_path()
- print applipath
+ print(applipath)
#
diff --git a/bin/appliskel/kill_remote_containers.py b/bin/appliskel/kill_remote_containers.py
index 06bcffb4a..39bb93397 100755
--- a/bin/appliskel/kill_remote_containers.py
+++ b/bin/appliskel/kill_remote_containers.py
@@ -25,14 +25,14 @@
"""
"""
import sys,os,shutil,glob,socket
-import optparse
+import argparse
from salome_utils import getUserName
import getAppliPath
appli_local=os.path.realpath(os.path.dirname(__file__))
APPLI=getAppliPath.relpath(appli_local,os.path.realpath(os.getenv('HOME')))
-usage="""usage: %prog [options]
+usage="""%(prog)s [options]
This procedure kill all containers that have been launched in a SALOME session on remote machines.
A SALOME session is identified by a machine name and a port number.
@@ -110,15 +110,14 @@ class Resource:
return appliPath
def main():
- parser = optparse.OptionParser(usage=usage)
- parser.add_option('-p','--port', dest="port",
- help="The SALOME session port (default NSPORT or 2810)")
+ parser = argparse.ArgumentParser(usage=usage)
+ parser.add_argument('-p','--port', dest="port",
+ help="The SALOME session port (default NSPORT or 2810)")
-
- options, args = parser.parse_args()
+ args = parser.parse_args()
if not os.path.exists(catalog_file):
- print "ERROR: the catalog file %s is mandatory" % catalog_file_base
+ print("ERROR: the catalog file %s is mandatory" % catalog_file)
sys.exit(1)
#Parse CatalogResource.xml
@@ -142,13 +141,14 @@ def main():
if resource.get_host() in local_names:continue
command=resource.get_rsh() +" -l "+resource.get_user()+" "+resource.get_host()
command=command+ " " + os.path.join(resource.get_appliPath(),"runRemote.sh")
- if options.port:
- port=options.port
+ if args.port:
+ port=args.port
else:
port=os.getenv("NSPORT") or "2810"
command=command+ " " + get_hostname() + " " + port +" killSalomeWithPort.py " + port
- print command
- os.system(command)
+ print(command)
+ return subprocess.call(command, shell=True)
+
if __name__ == '__main__':
main()
diff --git a/bin/appliskel/salome b/bin/appliskel/salome
index 37430157e..3bd95d620 100755
--- a/bin/appliskel/salome
+++ b/bin/appliskel/salome
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
import os
import subprocess
@@ -15,8 +15,8 @@ def main(args):
env_modules_option = "--with-env-modules="
env_modules_l = [x for x in args if x.startswith(env_modules_option)]
if env_modules_l:
- env_modules += env_modules_l[-1][len(env_modules_option):].split(',')
- args = [x for x in args if not x.startswith(env_modules_option)]
+ env_modules += env_modules_l[-1][len(env_modules_option):].split(',')
+ args = [x for x in args if not x.startswith(env_modules_option)]
env_modules_option += "%s" % ','.join(env_modules)
args.append(env_modules_option)
@@ -27,5 +27,3 @@ def main(args):
if __name__ == "__main__":
main(sys.argv[1:])
-#
-
diff --git a/bin/appliskel/salome_starter.py b/bin/appliskel/salome_starter.py
index 795803d40..737b4c15d 100644
--- a/bin/appliskel/salome_starter.py
+++ b/bin/appliskel/salome_starter.py
@@ -53,7 +53,7 @@ def initialize(launcherPath, launcherFile):
appliPath = __detectAppliPath(launcherPath, launcherFile)
if appliPath is None:
- print "ERROR: Unable to find application folder"
+ print("ERROR: Unable to find application folder")
sys.exit(1)
appliPath = os.path.relpath(appliPath, homePath)
@@ -68,7 +68,7 @@ def initialize(launcherPath, launcherFile):
try:
from salomeContextUtils import setOmniOrbUserPath
setOmniOrbUserPath()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
sys.exit(1)
# End of preliminary work
diff --git a/bin/appliskel/salome_tester/salome_instance.py b/bin/appliskel/salome_tester/salome_instance.py
index 23bb9c397..3653d14a9 100644
--- a/bin/appliskel/salome_tester/salome_instance.py
+++ b/bin/appliskel/salome_tester/salome_instance.py
@@ -103,11 +103,11 @@ class SalomeInstance(object):
#
if __name__ == "__main__":
- print "##### Start instance..."
+ print("##### Start instance...")
salome_instance = SalomeInstance.start()
port = salome_instance.get_port()
- print "##### ...instance started on port %s"%port
+ print("##### ...instance started on port %s"%port)
- print "##### Terminate instance running on port %s"%port
+ print("##### Terminate instance running on port %s"%port)
salome_instance.stop()
#
diff --git a/bin/appliskel/salome_tester/salome_test_driver.py b/bin/appliskel/salome_tester/salome_test_driver.py
index c167e97f6..6bc8b9771 100644
--- a/bin/appliskel/salome_tester/salome_test_driver.py
+++ b/bin/appliskel/salome_tester/salome_test_driver.py
@@ -26,6 +26,32 @@ import os
import subprocess
import signal
+# Run test
+def runTest(command):
+ print("Running:", " ".join(command))
+ p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ out, err = p.communicate()
+ res = p.returncode
+ # About res value:
+ # A negative value -N indicates that the child was terminated by signal N (Unix only).
+ # On Unix, the value 11 generally corresponds to a segmentation fault.
+ return res, out, err
+#
+
+# Display output and errors
+def processResult(res, out, err):
+ if out:
+ print(out)
+ pass
+ if err:
+ print(" ** Detected error **")
+ print("Error code: ", res)
+ print(err, end=' ')
+ print(" ** end of message **")
+ pass
+ return res
+#
+
# Timeout management
class TimeoutException(Exception):
"""Exception raised when test timeout is reached."""
@@ -41,7 +67,7 @@ if __name__ == "__main__":
# Add explicit call to python executable if a Python script is passed as
# first argument
if not args:
- print "Invalid arguments for salome_test_driver.py. No command defined."
+ print("Invalid arguments for salome_test_driver.py. No command defined.")
sys.exit(1)
_, ext = os.path.splitext(args[0])
if ext == ".py":
@@ -54,7 +80,7 @@ if __name__ == "__main__":
setOmniOrbUserPath()
# Set timeout handler
- print "Test timeout explicitly set to: %s seconds"%timeout_delay
+ print("Test timeout explicitly set to: %s seconds"%timeout_delay)
timeout_sec = abs(int(timeout_delay)-10)
if sys.platform == 'win32':
from threading import Timer
@@ -70,17 +96,10 @@ if __name__ == "__main__":
try:
salome_instance = SalomeInstance.start(shutdown_servers=True)
port = salome_instance.get_port()
- # Run the test
- print "Running:", " ".join(test_and_args)
- p = subprocess.Popen(test_and_args)
- pid = p.pid
- p.communicate()
- res = p.returncode
- # About res value:
- # A negative value -N indicates that the child was terminated by signal N (Unix only).
- # On Unix, the value 11 generally corresponds to a segmentation fault.
+ res, out, err = runTest(test_and_args)
+ res = processResult(res, out, err)
except TimeoutException:
- print "FAILED : timeout(%s) is reached"%timeout_delay
+ print("FAILED : timeout(%s) is reached"%timeout_delay)
except:
import traceback
traceback.print_exc()
@@ -92,6 +111,6 @@ if __name__ == "__main__":
pass
if sys.platform == 'win32':
timer.cancel()
- print "Exit test with status code:", res
+ print("Exit test with status code:", res)
sys.exit(res)
#
diff --git a/bin/appliskel/salome_tester/salome_test_driver_gui.py b/bin/appliskel/salome_tester/salome_test_driver_gui.py
index 1e99d312d..9d4940d95 100644
--- a/bin/appliskel/salome_tester/salome_test_driver_gui.py
+++ b/bin/appliskel/salome_tester/salome_test_driver_gui.py
@@ -41,7 +41,7 @@ if __name__ == "__main__":
# Add explicit call to python executable if a Python script is passed as
# first argument
if not args:
- print "Invalid arguments for salome_test_driver_gui.py. No command defined."
+ print("Invalid arguments for salome_test_driver_gui.py. No command defined.")
sys.exit(1)
_, ext = os.path.splitext(args[0])
test_and_args = args
@@ -51,7 +51,7 @@ if __name__ == "__main__":
setOmniOrbUserPath()
# Set timeout handler
- print "Test timeout explicitly set to: %s seconds"%timeout_delay
+ print("Test timeout explicitly set to: %s seconds"%timeout_delay)
timeout_sec = abs(int(timeout_delay)-10)
if sys.platform == 'win32':
from threading import Timer
@@ -66,7 +66,7 @@ if __name__ == "__main__":
try:
salome_instance = SalomeInstance.start(with_gui=True, args=test_and_args)
except TimeoutException:
- print "FAILED : timeout(%s) is reached"%timeout_delay
+ print("FAILED : timeout(%s) is reached"%timeout_delay)
except:
import traceback
traceback.print_exc()
@@ -77,6 +77,6 @@ if __name__ == "__main__":
pass
if sys.platform == 'win32':
timer.cancel()
-# print "Exit test with status code:", res
+# print("Exit test with status code:", res)
# sys.exit(res)
#
diff --git a/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py b/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py
index 110a5d52f..59ff65c80 100644
--- a/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py
+++ b/bin/appliskel/tests/concurrentSession/TestConcurrentSession.py
@@ -23,14 +23,14 @@ import tempfile
import os
import sys
import imp
-from cStringIO import StringIO
+from io import StringIO
import multiprocessing
import logging
def new_instance(running_instances):
from salome_instance import SalomeInstance
instance = SalomeInstance.start()
- print "Instance created and now running on port", instance.get_port()
+ print("Instance created and now running on port", instance.get_port())
running_instances.put(instance)
#
@@ -46,7 +46,7 @@ class TestConcurrentLaunch(unittest.TestCase):
def __terminateInstances(self, running_instances):
while not running_instances.empty():
instance = running_instances.get()
- print "Terminate instance running on port", instance.get_port()
+ print("Terminate instance running on port", instance.get_port())
instance.stop()
#
@@ -59,7 +59,7 @@ class TestConcurrentLaunch(unittest.TestCase):
setenv.main(True, exeName="salome start")
import runSalome
runSalome.runSalome()
- except SystemExit, e:
+ except SystemExit as e:
if str(e) != '0':
logging.error(e)
pass
@@ -73,17 +73,17 @@ class TestConcurrentLaunch(unittest.TestCase):
import runSession
params, args = runSession.configureSession(args, exe="salome shell")
return runSession.runSession(params, args)
- except SystemExit, e:
+ except SystemExit as e:
if str(e) != '0':
logging.error(e)
pass
#
def test01_SingleSession(self):
- print "** Testing single session **"
+ print("** Testing single session **")
self.session(["hello.py"])
#
def test02_MultiSession(self):
- print "** Testing multi sessions **"
+ print("** Testing multi sessions **")
jobs = []
for i in range(9):
p = multiprocessing.Process(target=self.session, args=(["hello.py"],))
@@ -94,7 +94,7 @@ class TestConcurrentLaunch(unittest.TestCase):
j.join()
#
def test03_SingleAppli(self):
- print "** Testing single appli **"
+ print("** Testing single appli **")
running_instances, processes = self.__createInstances(1)
for p in processes:
p.start()
@@ -107,7 +107,7 @@ class TestConcurrentLaunch(unittest.TestCase):
self.__terminateInstances(running_instances)
#
def test04_MultiAppli(self):
- print "** Testing multi appli **"
+ print("** Testing multi appli **")
running_instances, processes = self.__createInstances(9)
for p in processes:
p.start()
diff --git a/bin/appliskel/tests/concurrentSession/TestMinimalExample.py b/bin/appliskel/tests/concurrentSession/TestMinimalExample.py
index 4498d6934..9771f9a27 100644
--- a/bin/appliskel/tests/concurrentSession/TestMinimalExample.py
+++ b/bin/appliskel/tests/concurrentSession/TestMinimalExample.py
@@ -30,7 +30,7 @@ def port_reservation(obtained_ports, prefered=None, test=None, expected=None):
port = getPort(prefered)
else:
port = getPort()
- print "obtained port = %s"%port
+ print("obtained port = %s"%port)
obtained_ports.put(port)
@@ -41,8 +41,8 @@ def port_reservation(obtained_ports, prefered=None, test=None, expected=None):
class TestMinimalExample(unittest.TestCase):
def testSequential(self):
from PortManager import releasePort, getBusyPorts
- print "\nBEGIN testSequential"
- print "Busy ports", getBusyPorts()
+ print("\nBEGIN testSequential")
+ print("Busy ports", getBusyPorts())
obtained_ports = multiprocessing.Queue()
processes = [
@@ -56,7 +56,7 @@ class TestMinimalExample(unittest.TestCase):
for p in processes:
p.join()
- print "Busy ports", getBusyPorts()
+ print("Busy ports", getBusyPorts())
# Try to get specific port number
p = multiprocessing.Process(target=port_reservation, args=(obtained_ports, 2872, self, 2872,))
p.start()
@@ -73,7 +73,7 @@ class TestMinimalExample(unittest.TestCase):
p.join()
# Release port
- print "release port 2899"
+ print ("release port 2899")
p = multiprocessing.Process(target=releasePort, args=(2899,))
p.start()
p.join()
@@ -84,21 +84,21 @@ class TestMinimalExample(unittest.TestCase):
p.join()
# Release ports
- print "Busy ports", getBusyPorts()
+ print("Busy ports", getBusyPorts())
while not obtained_ports.empty():
port = obtained_ports.get()
- print "release port", port
+ print("release port", port)
p = multiprocessing.Process(target=releasePort, args=(port,))
p.start()
p.join()
- print "END testSequential"
+ print("END testSequential")
#
def testConcurrent(self):
from PortManager import releasePort, getBusyPorts
- print "\nBEGIN testConcurrent"
- print "Busy ports", getBusyPorts()
+ print("\nBEGIN testConcurrent")
+ print("Busy ports", getBusyPorts())
obtained_ports = multiprocessing.Queue()
processes = [
multiprocessing.Process(target=port_reservation, args=(obtained_ports,))
@@ -125,15 +125,15 @@ class TestMinimalExample(unittest.TestCase):
p.join()
# Release ports
- print "Busy ports", getBusyPorts()
+ print("Busy ports", getBusyPorts())
while not obtained_ports.empty():
port = obtained_ports.get()
- print "release port", port
+ print("release port", port)
p = multiprocessing.Process(target=releasePort, args=(port,))
p.start()
p.join()
- print "END testConcurrent"
+ print("END testConcurrent")
#
#
diff --git a/bin/appliskel/tests/concurrentSession/hello.py b/bin/appliskel/tests/concurrentSession/hello.py
index 54ec0a01f..12d363950 100644
--- a/bin/appliskel/tests/concurrentSession/hello.py
+++ b/bin/appliskel/tests/concurrentSession/hello.py
@@ -1 +1 @@
-print 'Hello!'
+print('Hello!')
diff --git a/bin/appliskel/tests/concurrentSession/usecase_concurrent.sh b/bin/appliskel/tests/concurrentSession/usecase_concurrent.sh
index a078fa166..b3a03180c 100755
--- a/bin/appliskel/tests/concurrentSession/usecase_concurrent.sh
+++ b/bin/appliskel/tests/concurrentSession/usecase_concurrent.sh
@@ -64,7 +64,7 @@ run_command() {
# make hello.py
echo "
#!/usr/bin/env python
-print 'Hello\!'
+print('Hello\!')
" > ${BASE_DIR}/hello.py
# Build output folders
diff --git a/bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py b/bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py
index d6cd97541..4a9f365a0 100644
--- a/bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py
+++ b/bin/appliskel/tests/salomeCommand/TestLauncherSessionArgs.py
@@ -22,7 +22,7 @@ import unittest
import os
import sys
import imp
-from cStringIO import StringIO
+from io import StringIO
import logging
logger = logging.getLogger("TestLauncherLogger")
@@ -71,7 +71,7 @@ class TestSessionArgs(unittest.TestCase):
import runSession
params, args = runSession.configureSession(args, exe="salome shell")
return runSession.runSession(params, args)
- except SystemExit, e:
+ except SystemExit as e:
if str(e) != '0':
logger.error(e)
import traceback
diff --git a/bin/appliskel/tests/salomeCommand/TestLauncherSimple.py b/bin/appliskel/tests/salomeCommand/TestLauncherSimple.py
index f235a0a1e..a684a6cdd 100644
--- a/bin/appliskel/tests/salomeCommand/TestLauncherSimple.py
+++ b/bin/appliskel/tests/salomeCommand/TestLauncherSimple.py
@@ -25,11 +25,11 @@ class TestLauncher(unittest.TestCase):
def setUp(self):
from salome_instance import SalomeInstance
self.instance = SalomeInstance.start()
- print "Instance created and now running on port", self.instance.get_port()
+ print("Instance created and now running on port", self.instance.get_port())
#
def tearDown(self):
- print "Terminate instance running on port", self.instance.get_port()
+ print("Terminate instance running on port", self.instance.get_port())
self.instance.stop()
#
@@ -41,7 +41,7 @@ class TestLauncher(unittest.TestCase):
args = ["hello.py"]
params, args = runSession.configureSession(args, exe="salome shell")
return runSession.runSession(params, args)
- except SystemExit, e:
+ except SystemExit as e:
if str(e) != '0':
logging.error(e)
#
diff --git a/bin/appliskel/tests/salomeInstance/instances.py b/bin/appliskel/tests/salomeInstance/instances.py
index 818467736..02a52cc2e 100644
--- a/bin/appliskel/tests/salomeInstance/instances.py
+++ b/bin/appliskel/tests/salomeInstance/instances.py
@@ -23,7 +23,7 @@ import multiprocessing
def new_instance(running_instances):
from salome_instance import SalomeInstance
instance = SalomeInstance.start()
- print "Instance created and now running on port", instance.get_port()
+ print("Instance created and now running on port", instance.get_port())
running_instances.put(instance)
#
@@ -41,7 +41,7 @@ class TestLauncher(unittest.TestCase):
def __terminateInstances(self, running_instances):
while not running_instances.empty():
instance = running_instances.get()
- print "Terminate instance running on port", instance.get_port()
+ print("Terminate instance running on port", instance.get_port())
instance.stop()
#
@@ -91,19 +91,19 @@ class TestLauncher(unittest.TestCase):
# Connect to one instance
import runConsole
- port = all_instances[len(all_instances)/2].get_port()
- print "Connect to instance running on port", port
+ port = all_instances[len(all_instances)//2].get_port()
+ print("Connect to instance running on port", port)
self.__connectToInstance(port)
# Connect to another instance
import runConsole
- port = all_instances[len(all_instances)/4].get_port()
- print "Connect to instance running on port", port
+ port = all_instances[len(all_instances)//4].get_port()
+ print("Connect to instance running on port", port)
self.__connectToInstance(port)
# Terminate instances
for instance in all_instances:
- print "Terminate instance running on port", instance.get_port()
+ print("Terminate instance running on port", instance.get_port())
instance.stop()
#
diff --git a/bin/appliskel/update_catalogs.py b/bin/appliskel/update_catalogs.py
index 82fce4834..e9981d662 100644
--- a/bin/appliskel/update_catalogs.py
+++ b/bin/appliskel/update_catalogs.py
@@ -25,14 +25,14 @@
"""
"""
import sys,os,shutil,glob,socket
-import optparse
+import argparse
from salome_utils import getUserName
import getAppliPath
appli_local=os.path.realpath(os.path.dirname(__file__))
APPLI=getAppliPath.relpath(appli_local,os.path.realpath(os.getenv('HOME')))
-usage="""usage: %prog [options]
+usage="""%(prog)s [options]
Typical use is:
python update_catalogs.py
@@ -155,11 +155,11 @@ class Resource:
os.mkdir(resource_dir)
cata_path=os.path.join(appliPath,"share","salome","resources","*Catalog.xml")
cmd="cp %s %s" % (cata_path,resource_dir)
- print cmd
+ print(cmd)
os.system(cmd)
cata_path=os.path.join(appliPath,"share","salome","resources","*","*Catalog.xml")
cmd="cp %s %s" % (cata_path,resource_dir)
- print cmd
+ print(cmd)
os.system(cmd)
else:
#remote machine, use rcopy
@@ -167,12 +167,12 @@ class Resource:
cata_path=os.path.join(appliPath,"share","salome","resources","*Catalog.xml")
cmd="%s %s@%s:%s %s"
cmd= cmd%(rcopy,userName,hostname,cata_path,resource_dir)
- print cmd
+ print(cmd)
os.system(cmd)
cata_path=os.path.join(appliPath,"share","salome","resources","*","*Catalog.xml")
cmd="%s %s@%s:%s %s"
cmd= cmd%(rcopy,userName,hostname,cata_path,resource_dir)
- print cmd
+ print(cmd)
os.system(cmd)
schema_cata=os.path.join(resource_dir,"*SchemaCatalog.xml")
@@ -207,12 +207,11 @@ class Resource:
def main():
- parser = optparse.OptionParser(usage=usage)
-
- options, args = parser.parse_args()
+ parser = argparse.ArgumentParser(usage=usage)
+ args = parser.parse_args()
if not os.path.exists(catalog_file_base):
- print "ERROR: the base catalog file %s is mandatory" % catalog_file_base
+ print("ERROR: the base catalog file %s is mandatory" % catalog_file_base)
sys.exit(1)
#Parse CatalogResource.xml
@@ -251,12 +250,11 @@ def main():
mach.update()
#dump new CatalogResources.xml
- f=open(catalog_file,'w')
- f.write('\n')
- doc.write(f)
- f.write('\n')
- f.close()
- print "%s updated" % catalog_file
+ with open(catalog_file,'w') as f:
+ f.write('\n')
+ doc.write(f)
+ f.write('\n')
+ print("%s updated" % catalog_file)
#update configRemote.sh in env.d directory (environment variable SALOME_CATALOGS_PATH)
path=[]
@@ -264,9 +262,8 @@ def main():
if mach.resource_dir:
path.append(mach.resource_dir)
- f=open(os.path.join(appli_local,"env.d","configRemote.sh"),'w')
- f.write("export SALOME_CATALOGS_PATH=%s\n" % SEP.join(path))
- f.close()
+ with open(os.path.join(appli_local,"env.d","configRemote.sh"),'w') as f:
+ f.write("export SALOME_CATALOGS_PATH=%s\n" % SEP.join(path))
if __name__ == '__main__':
diff --git a/bin/envSalome.py b/bin/envSalome.py
index 38d530438..adfddac2e 100755
--- a/bin/envSalome.py
+++ b/bin/envSalome.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
diff --git a/bin/killSalome.py b/bin/killSalome.py
index 2ea384b63..c8ce783f5 100755
--- a/bin/killSalome.py
+++ b/bin/killSalome.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -82,9 +82,9 @@ def killAllPorts():
pass
# kill other processes
if sys.platform != 'win32':
- import commands
+ import subprocess
cmd = "ps -fea | grep '%s' | grep 'ghs3d' | grep 'f /tmp/GHS3D_' | grep -v 'grep' | awk '{print $2}'" % user
- prc = commands.getoutput(cmd)
+ prc = subprocess.getoutput(cmd)
for field in prc.split():
try:
os.kill(int(field), signal.SIGKILL)
@@ -94,7 +94,7 @@ def killAllPorts():
pass
# kill ompi-server needed for MPI containers coupling
cmd = "ps -fea | grep '%s' | grep 'ompi-server' | grep -v 'grep' | awk '{print $2}'" % user
- prc = commands.getoutput(cmd)
+ prc = subprocess.getoutput(cmd)
for field in prc.split():
try:
os.kill(int(field), signal.SIGKILL)
@@ -111,8 +111,8 @@ if __name__ == "__main__":
try:
from salomeContextUtils import setOmniOrbUserPath
setOmniOrbUserPath()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
sys.exit(1)
killAllPorts()
pass
diff --git a/bin/killSalomeWithPort.py b/bin/killSalomeWithPort.py
index 01d1eb39a..fec9e4aa3 100755
--- a/bin/killSalomeWithPort.py
+++ b/bin/killSalomeWithPort.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2017 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -31,7 +31,7 @@
# \endcode
#
-import os, sys, pickle, signal, commands,glob
+import os, sys, pickle, signal, subprocess,glob
import subprocess
import shlex
from salome_utils import verbose
@@ -96,7 +96,7 @@ def appliCleanOmniOrbConfig(port):
the last is removed only if the link points to the first file.
"""
if verbose():
- print "clean OmniOrb config for port %s"%port
+ print("clean OmniOrb config for port %s"%port)
from salome_utils import generateFileName, getUserName
omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
@@ -202,7 +202,7 @@ def shutdownMyPort(port, cleanup=True):
# shutdown all
orb = CORBA.ORB_init([''], CORBA.ORB_ID)
lcc = LifeCycleCORBA(orb) # see (1)
- print "Terminating SALOME on port %s..."%(port)
+ print("Terminating SALOME on port %s..."%(port))
lcc.shutdownServers()
# give some time to shutdown to complete
time.sleep(1)
@@ -228,22 +228,22 @@ def __killMyPort(port, filedict):
port = int(port)
try:
- with open(filedict, 'r') as fpid:
+ with open(filedict, 'rb') as fpid:
process_ids=pickle.load(fpid)
for process_id in process_ids:
- for pid, cmd in process_id.items():
- if verbose(): print "stop process %s : %s"% (pid, cmd[0])
+ for pid, cmd in list(process_id.items()):
+ if verbose(): print("stop process %s : %s"% (pid, cmd[0]))
try:
from salome_utils import killpid
killpid(int(pid))
except:
- if verbose(): print " ------------------ process %s : %s not found"% (pid, cmd[0])
+ if verbose(): print(" ------------------ process %s : %s not found"% (pid, cmd[0]))
pass
pass # for pid ...
pass # for process_id ...
# end with
except:
- print "Cannot find or open SALOME PIDs file for port", port
+ print("Cannot find or open SALOME PIDs file for port", port)
pass
os.remove(filedict)
pass
@@ -276,7 +276,7 @@ def __guessPiDictFilename(port):
log_msg += " ... not found\n"
if verbose():
- print log_msg
+ print(log_msg)
return filedict
#
@@ -296,12 +296,12 @@ def killMyPort(port):
filedict = getPiDict(port)
if not os.path.isfile(filedict): # removed by previous call, see (1)
if verbose():
- print "SALOME on port %s: already removed by previous call"%port
+ print("SALOME on port %s: already removed by previous call"%port)
# Remove port from PortManager config file
try:
from PortManager import releasePort
if verbose():
- print "Removing port from PortManager configuration file"
+ print("Removing port from PortManager configuration file")
releasePort(port)
except ImportError:
pass
@@ -391,10 +391,10 @@ def killMyPortSpy(pid, port):
if __name__ == "__main__":
if len(sys.argv) < 2:
- print "Usage: "
- print " %s " % os.path.basename(sys.argv[0])
- print
- print "Kills SALOME session running on specified ."
+ print("Usage: ")
+ print(" %s " % os.path.basename(sys.argv[0]))
+ print()
+ print("Kills SALOME session running on specified .")
sys.exit(1)
pass
if sys.argv[1] == "--spy":
@@ -408,8 +408,8 @@ if __name__ == "__main__":
try:
from salomeContextUtils import setOmniOrbUserPath #@UnresolvedImport
setOmniOrbUserPath()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
sys.exit(1)
for port in sys.argv[1:]:
killMyPort(port)
diff --git a/bin/launchConfigureParser.py b/bin/launchConfigureParser.py
index bde0a996e..e52313342 100755
--- a/bin/launchConfigureParser.py
+++ b/bin/launchConfigureParser.py
@@ -21,13 +21,16 @@
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import os, glob, string, sys, re
+import argparse
+import glob
+import os
+import re
+import sys
import xml.sax
-import optparse
-import types
from salome_utils import verbose, getPortNumber, getHomeDir
+
# names of tags in XML configuration file
doc_tag = "document"
sec_tag = "section"
@@ -108,8 +111,9 @@ def version():
if root_dir and os.path.exists( version_file ):
filename = version_file
if filename:
- str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
- match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
+ with open(filename, "r") as f:
+ v = f.readline() # v = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
+ match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', v )
if match :
return match.group( 1 )
except:
@@ -213,7 +217,7 @@ def userFile(appname, cfgname):
files += glob.glob(os.path.join(getHomeDir(), filetmpl2.format(appname)))
pass
- # ... loop through all files and find most appopriate file (with closest id)
+ # ... loop through all files and find most appropriate file (with closest id)
appr_id = -1
appr_file = ""
for f in files:
@@ -241,14 +245,14 @@ def userFile(appname, cfgname):
def process_containers_params( standalone, embedded ):
# 1. filter inappropriate containers names
if standalone is not None:
- standalone = filter( lambda x: x in standalone_choices, standalone )
+ standalone = [x for x in standalone if x in standalone_choices]
if embedded is not None:
- embedded = filter( lambda x: x in embedded_choices, embedded )
+ embedded = [x for x in embedded if x in embedded_choices]
# 2. remove containers appearing in 'standalone' parameter from the 'embedded'
# parameter --> i.e. 'standalone' parameter has higher priority
if standalone is not None and embedded is not None:
- embedded = filter( lambda x: x not in standalone, embedded )
+ embedded = [x for x in embedded if x not in standalone]
# 3. return corrected parameters values
return standalone, embedded
@@ -264,7 +268,7 @@ section_to_skip = ""
class xml_parser:
def __init__(self, fileName, _opts, _importHistory):
#warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call
- if verbose(): print "Configure parser: processing %s ..." % fileName
+ if verbose(): print("Configure parser: processing %s ..." % fileName)
self.fileName = os.path.abspath(fileName)
self.importHistory = _importHistory
self.importHistory.append(self.fileName)
@@ -282,39 +286,42 @@ class xml_parser:
self.opts[ embedded_nam ] = embedded
pass
- def boolValue( self, str ):
- strloc = str
- if isinstance(strloc, types.UnicodeType):
+ def boolValue( self, item):
+ strloc = item
+ if isinstance(strloc, str):
strloc = strloc.encode().strip()
- if isinstance(strloc, types.StringType):
- strlow = strloc.lower()
- if strlow in ("1", "yes", "y", "on", "true", "ok"):
+ if isinstance(strloc, bytes):
+ strlow = strloc.decode().lower()
+ if strlow in ("1", "yes", "y", "on", "true", "ok"):
return True
elif strlow in ("0", "no", "n", "off", "false", "cancel"):
return False
return strloc
pass
- def intValue( self, str ):
- strloc = str
- if isinstance(strloc, types.UnicodeType):
+ def intValue( self, item):
+ strloc = item
+ if isinstance(strloc, str):
strloc = strloc.encode().strip()
- if isinstance(strloc, types.StringType):
- strlow = strloc.lower()
- if strlow in ("1", "yes", "y", "on", "true", "ok"):
+ if isinstance(strloc, bytes):
+ strlow = strloc.decode().lower()
+ if strlow in ("1", "yes", "y", "on", "true", "ok"):
return 1
elif strlow in ("0", "no", "n", "off", "false", "cancel"):
return 0
else:
- return string.atoi(strloc)
+ return int(strloc.decode())
return strloc
pass
- def strValue( self, str ):
- strloc = str
+ def strValue( self, item):
+ strloc = item
try:
- if isinstance(strloc, types.UnicodeType): strloc = strloc.encode().strip()
- else: strloc = strloc.strip()
+ if isinstance( strloc, str):
+ strloc = strloc.strip()
+ else:
+ if isinstance( strloc, bytes):
+ strloc = strloc.decode().strip()
except:
pass
return strloc
@@ -333,7 +340,7 @@ class xml_parser:
section_name = attrs.getValue( nam_att )
if section_name in [lanch_nam, lang_nam]:
self.section = section_name # launch section
- elif self.opts.has_key( modules_nam ) and \
+ elif modules_nam in self.opts and \
section_name in self.opts[ modules_nam ]:
self.section = section_name # section
else:
@@ -401,12 +408,12 @@ class xml_parser:
if os.path.exists(absfname + ext) :
absfname += ext
if absfname in self.importHistory :
- if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
+ if verbose(): print("Configure parser: Warning : file %s is already imported" % absfname)
return # already imported
break
pass
else:
- if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
+ if verbose(): print("Configure parser: Error : file %s does not exist" % absfname)
return
# importing file
@@ -417,438 +424,380 @@ class xml_parser:
# import file
imp = xml_parser(absfname, opts, self.importHistory)
# merge results
- for key in imp.opts.keys():
- if not self.opts.has_key(key):
+ for key in imp.opts:
+ if key not in self.opts:
self.opts[key] = imp.opts[key]
pass
pass
pass
except:
- if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
+ if verbose(): print("Configure parser: Error : can not read configuration file %s" % absfname)
pass
# -----------------------------------------------------------------------------
-booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True,
- '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
+booleans = {'1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok' : True,
+ '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False}
-boolean_choices = booleans.keys()
+boolean_choices = list(booleans.keys())
-def check_embedded(option, opt, value, parser):
- from optparse import OptionValueError
- assert value is not None
- if parser.values.embedded:
- embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
- else:
- embedded = []
- if parser.values.standalone:
- standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
- else:
- standalone = []
- vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
- for v in vals:
- if v not in embedded_choices:
- raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
- if v not in embedded:
- embedded.append( v )
- if v in standalone:
- del standalone[ standalone.index( v ) ]
- pass
- parser.values.embedded = ",".join( embedded )
- parser.values.standalone = ",".join( standalone )
- pass
-def check_standalone(option, opt, value, parser):
- from optparse import OptionValueError
- assert value is not None
- if parser.values.embedded:
- embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
- else:
- embedded = []
- if parser.values.standalone:
- standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
- else:
- standalone = []
- vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
- for v in vals:
- if v not in standalone_choices:
- raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
- if v not in standalone:
- standalone.append( v )
- if v in embedded:
- del embedded[ embedded.index( v ) ]
- pass
- parser.values.embedded = ",".join( embedded )
- parser.values.standalone = ",".join( standalone )
- pass
+class CheckEmbeddedAction(argparse.Action):
+ def __call__(self, parser, namespace, value, option_string=None):
+ assert value is not None
+ if namespace.embedded:
+ embedded = [a for a in re.split("[:;,]", namespace.embedded) if a.strip()]
+ else:
+ embedded = []
+ if namespace.standalone:
+ standalone = [a for a in re.split("[:;,]", namespace.standalone) if a.strip()]
+ else:
+ standalone = []
+ vals = [a for a in re.split("[:;,]", value) if a.strip()]
+ for v in vals:
+ if v not in embedded_choices:
+ raise argparse.ArgumentError("option %s: invalid choice: %r (choose from %s)"
+ % (self.dest, v, ", ".join(map(repr, embedded_choices))))
+ if v not in embedded:
+ embedded.append(v)
+ if v in standalone:
+ del standalone[standalone.index(v)]
+ pass
+ namespace.embedded = ",".join(embedded)
+ namespace.standalone = ",".join(standalone)
+ pass
+
+
+class CheckStandaloneAction(argparse.Action):
+ def __call__(self, parser, namespace, value, option_string=None):
+ assert value is not None
+ if namespace.embedded:
+ embedded = [a for a in re.split("[:;,]", namespace.embedded) if a.strip()]
+ else:
+ embedded = []
+ if namespace.standalone:
+ standalone = [a for a in re.split("[:;,]", namespace.standalone) if a.strip()]
+ else:
+ standalone = []
+ vals = [a for a in re.split("[:;,]", value) if a.strip()]
+ for v in vals:
+ if v not in standalone_choices:
+ raise argparse.ArgumentError("option %s: invalid choice: %r (choose from %s)"
+ % (self.dest, v, ", ".join(map(repr, standalone_choices))))
+ if v not in standalone:
+ standalone.append(v)
+ if v in embedded:
+ del embedded[embedded.index(v)]
+ pass
+ namespace.embedded = ",".join(embedded)
+ namespace.standalone = ",".join(standalone)
-def store_boolean (option, opt, value, parser, *args):
- if isinstance(value, types.StringType):
- try:
- value_conv = booleans[value.strip().lower()]
- for attribute in args:
- setattr(parser.values, attribute, value_conv)
- except KeyError:
- raise optparse.OptionValueError(
- "option %s: invalid boolean value: %s (choose from %s)"
- % (opt, value, boolean_choices))
- else:
- for attribute in args:
- setattr(parser.values, attribute, value)
-def CreateOptionParser (theAdditionalOptions=None, exeName=None):
- if theAdditionalOptions is None:
- theAdditionalOptions = []
+class StoreBooleanAction(argparse.Action):
+ def __call__(self, parser, namespace, value, option_string=None):
+ if isinstance(value, bytes):
+ value = value.decode()
+ if isinstance(value, str):
+ try:
+ value_conv = booleans[value.strip().lower()]
+ setattr(namespace, self.dest, value_conv)
+ except KeyError:
+ raise argparse.ArgumentError(
+ "option %s: invalid boolean value: %s (choose from %s)"
+ % (self.dest, value, boolean_choices))
+ else:
+ setattr(namespace, self.dest, value)
+
+
+def CreateOptionParser(exeName=None):
+
+ if not exeName:
+ exeName = "%(prog)s"
+
+ a_usage = """%s [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
+Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,...
+""" % exeName
+ version_str = "Salome %s" % version()
+ pars = argparse.ArgumentParser(usage=a_usage)
+
+ # Version
+ pars.add_argument('-v', '--version', action='version', version=version_str)
+
# GUI/Terminal. Default: GUI
help_str = "Launch without GUI (in the terminal mode)."
- o_t = optparse.Option("-t",
- "--terminal",
- action="store_false",
- dest="gui",
- help=help_str)
+ pars.add_argument("-t",
+ "--terminal",
+ action="store_false",
+ dest="gui",
+ help=help_str)
help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
- o_b = optparse.Option("-b",
- "--batch",
- action="store_true",
- dest="batch",
- help=help_str)
+ pars.add_argument("-b",
+ "--batch",
+ action="store_true",
+ dest="batch",
+ help=help_str)
help_str = "Launch in GUI mode [default]."
- o_g = optparse.Option("-g",
- "--gui",
- action="store_true",
- dest="gui",
- help=help_str)
+ pars.add_argument("-g",
+ "--gui",
+ action="store_true",
+ dest="gui",
+ help=help_str)
# Show Desktop (only in GUI mode). Default: True
help_str = "1 to activate GUI desktop [default], "
help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
help_str += "Ignored in the terminal mode."
- o_d = optparse.Option("-d",
- "--show-desktop",
- metavar="<1/0>",
- #type="choice", choices=boolean_choices,
- type="string",
- action="callback", callback=store_boolean, callback_args=('desktop',),
- dest="desktop",
- help=help_str)
+ pars.add_argument("-d",
+ "--show-desktop",
+ metavar="<1/0>",
+ action=StoreBooleanAction,
+ dest="desktop",
+ help=help_str)
help_str = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
help_str += "The same as --show-desktop=0."
- o_o = optparse.Option("-o",
- "--hide-desktop",
- action="store_false",
- dest="desktop",
- help=help_str)
+ pars.add_argument("-o",
+ "--hide-desktop",
+ action="store_false",
+ dest="desktop",
+ help=help_str)
# Use logger or log-file. Default: nothing.
help_str = "Redirect messages to the CORBA collector."
- #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
- o_l = optparse.Option("-l",
- "--logger",
- action="store_const", const="CORBA",
- dest="log_file",
- help=help_str)
+ pars.add_argument("-l",
+ "--logger",
+ action="store_const", const="CORBA",
+ dest="log_file",
+ help=help_str)
help_str = "Redirect messages to the "
- o_f = optparse.Option("-f",
- "--log-file",
- metavar="",
- type="string",
- action="store",
- dest="log_file",
- help=help_str)
+ pars.add_argument("-f",
+ "--log-file",
+ metavar="",
+ dest="log_file",
+ help=help_str)
# Configuration XML file. Default: see defaultUserFile() function
- help_str = "Parse application settings from the "
+ help_str = "Parse application settings from the "
help_str += "instead of default %s" % defaultUserFile()
- o_r = optparse.Option("-r",
- "--resources",
- metavar="",
- type="string",
- action="store",
- dest="resources",
- help=help_str)
+ pars.add_argument("-r",
+ "--resources",
+ metavar="",
+ dest="resources",
+ help=help_str)
# Use own xterm for each server. Default: False.
help_str = "Launch each SALOME server in own xterm console"
- o_x = optparse.Option("-x",
- "--xterm",
- action="store_true",
- dest="xterm",
- help=help_str)
+ pars.add_argument("-x",
+ "--xterm",
+ action="store_true",
+ dest="xterm",
+ help=help_str)
# Modules. Default: Like in configuration files.
help_str = "SALOME modules list (where , are the names "
help_str += "of SALOME modules which should be available in the SALOME session)"
- o_m = optparse.Option("-m",
- "--modules",
- metavar="",
- type="string",
- action="append",
- dest="modules",
- help=help_str)
+ pars.add_argument("-m",
+ "--modules",
+ metavar="",
+ action="append",
+ dest="modules",
+ help=help_str)
# Embedded servers. Default: Like in configuration files.
help_str = "CORBA servers to be launched in the Session embedded mode. "
help_str += "Valid values for : %s " % ", ".join( embedded_choices )
help_str += "[by default the value from the configuration files is used]"
- o_e = optparse.Option("-e",
- "--embedded",
- metavar="",
- type="string",
- action="callback",
- dest="embedded",
- callback=check_embedded,
- help=help_str)
+ pars.add_argument("-e",
+ "--embedded",
+ metavar="",
+ action=CheckEmbeddedAction,
+ dest="embedded",
+ help=help_str)
# Standalone servers. Default: Like in configuration files.
help_str = "CORBA servers to be launched in the standalone mode (as separate processes). "
help_str += "Valid values for : %s " % ", ".join( standalone_choices )
help_str += "[by default the value from the configuration files is used]"
- o_s = optparse.Option("-s",
- "--standalone",
- metavar="",
- type="string",
- action="callback",
- dest="standalone",
- callback=check_standalone,
- help=help_str)
+ pars.add_argument("-s",
+ "--standalone",
+ metavar="",
+ action=CheckStandaloneAction,
+ dest="standalone",
+ help=help_str)
# Kill with port. Default: False.
help_str = "Kill SALOME with the current port"
- o_p = optparse.Option("-p",
- "--portkill",
- action="store_true",
- dest="portkill",
- help=help_str)
+ pars.add_argument("-p",
+ "--portkill",
+ action="store_true",
+ dest="portkill",
+ help=help_str)
# Kill all. Default: False.
help_str = "Kill all running SALOME sessions"
- o_k = optparse.Option("-k",
- "--killall",
- action="store_true",
- dest="killall",
- help=help_str)
+ pars.add_argument("-k",
+ "--killall",
+ action="store_true",
+ dest="killall",
+ help=help_str)
# Additional python interpreters. Default: 0.
help_str = "The number of additional external python interpreters to run. "
help_str += "Each additional python interpreter is run in separate "
help_str += "xterm session with properly set SALOME environment"
- o_i = optparse.Option("-i",
- "--interp",
- metavar="",
- type="int",
- action="store",
- dest="interp",
- help=help_str)
+ pars.add_argument("-i",
+ "--interp",
+ metavar="",
+ type=int,
+ dest="interp",
+ help=help_str)
# Splash. Default: True.
help_str = "1 to display splash screen [default], "
help_str += "0 to disable splash screen. "
help_str += "This option is ignored in the terminal mode. "
help_str += "It is also ignored if --show-desktop=0 option is used."
- o_z = optparse.Option("-z",
- "--splash",
- metavar="<1/0>",
- #type="choice", choices=boolean_choices,
- type="string",
- action="callback", callback=store_boolean, callback_args=('splash',),
- dest="splash",
- help=help_str)
+ pars.add_argument("-z",
+ "--splash",
+ metavar="<1/0>",
+ action=StoreBooleanAction,
+ dest="splash",
+ help=help_str)
# Catch exceptions. Default: True.
help_str = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
- o_c = optparse.Option("-c",
- "--catch-exceptions",
- metavar="<1/0>",
- #type="choice", choices=boolean_choices,
- type="string",
- action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
- dest="catch_exceptions",
- help=help_str)
+ pars.add_argument("-c",
+ "--catch-exceptions",
+ metavar="<1/0>",
+ action=StoreBooleanAction,
+ dest="catch_exceptions",
+ help=help_str)
# Print free port and exit
help_str = "Print free port and exit"
- o_a = optparse.Option("--print-port",
- action="store_true",
- dest="print_port", default=False,
- help=help_str)
+ pars.add_argument("--print-port",
+ action="store_true",
+ dest="print_port",
+ help=help_str)
# Do not relink ${HOME}/.omniORB_last.cfg
help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
- o_n = optparse.Option("--nosave-config",
- action="store_false",
- dest="save_config", default=True,
- help=help_str)
+ pars.add_argument("--nosave-config",
+ action="store_false",
+ dest="save_config",
+ help=help_str)
# Launch with interactive python console. Default: False.
help_str = "Launch with interactive python console."
- o_pi = optparse.Option("--pinter",
- action="store_true",
- dest="pinter",
- help=help_str)
+ pars.add_argument("--pinter",
+ action="store_true",
+ dest="pinter",
+ help=help_str)
# Print Naming service port into a user file. Default: False.
help_str = "Print Naming Service Port into a user file."
- o_nspl = optparse.Option("--ns-port-log",
- metavar="",
- type="string",
- action="store",
- dest="ns_port_log_file",
- help=help_str)
+ pars.add_argument("--ns-port-log",
+ metavar="",
+ dest="ns_port_log_file",
+ help=help_str)
# Write/read test script file with help of TestRecorder. Default: False.
help_str = "Write/read test script file with help of TestRecorder."
- o_test = optparse.Option("--test",
- metavar="",
- type="string",
- action="store",
- dest="test_script_file",
- help=help_str)
+ pars.add_argument("--test",
+ metavar="",
+ dest="test_script_file",
+ help=help_str)
# Reproducing test script with help of TestRecorder. Default: False.
help_str = "Reproducing test script with help of TestRecorder."
- o_play = optparse.Option("--play",
- metavar="",
- type="string",
- action="store",
- dest="play_script_file",
- help=help_str)
+ pars.add_argument("--play",
+ metavar="",
+ dest="play_script_file",
+ help=help_str)
# gdb session
help_str = "Launch session with gdb"
- o_gdb = optparse.Option("--gdb-session",
- action="store_true",
- dest="gdb_session", default=False,
- help=help_str)
+ pars.add_argument("--gdb-session",
+ action="store_true",
+ dest="gdb_session",
+ help=help_str)
# ddd session
help_str = "Launch session with ddd"
- o_ddd = optparse.Option("--ddd-session",
- action="store_true",
- dest="ddd_session", default=False,
- help=help_str)
+ pars.add_argument("--ddd-session",
+ action="store_true",
+ dest="ddd_session",
+ help=help_str)
# valgrind session
help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
- o_valgrind = optparse.Option("--valgrind-session",
- action="store_true",
- dest="valgrind_session", default=False,
- help=help_str)
+ pars.add_argument("--valgrind-session",
+ action="store_true",
+ dest="valgrind_session",
+ help=help_str)
# shutdown-servers. Default: False.
help_str = "1 to shutdown standalone servers when leaving python interpreter, "
help_str += "0 to keep the standalone servers as daemon [default]. "
help_str += "This option is only useful in batchmode "
help_str += "(terminal mode or without showing desktop)."
- o_shutdown = optparse.Option("-w",
- "--shutdown-servers",
- metavar="<1/0>",
- #type="choice", choices=boolean_choices,
- type="string",
- action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
- dest="shutdown_servers",
- help=help_str)
+ pars.add_argument("-w",
+ "--shutdown-servers",
+ metavar="<1/0>",
+ action=StoreBooleanAction,
+ dest="shutdown_servers",
+ help=help_str)
# foreground. Default: True.
help_str = "0 and runSalome exits after have launched the gui, "
help_str += "1 to launch runSalome in foreground mode [default]."
- o_foreground = optparse.Option("--foreground",
- metavar="<1/0>",
- #type="choice", choices=boolean_choices,
- type="string",
- action="callback", callback=store_boolean, callback_args=('foreground',),
- dest="foreground",
- help=help_str)
+ pars.add_argument("--foreground",
+ metavar="<1/0>",
+ action=StoreBooleanAction,
+ dest="foreground",
+ help=help_str)
# wake up session
help_str = "Wake up a previously closed session. "
help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
help_str += "If this variable is not set, the last configuration is taken. "
- o_wake_up = optparse.Option("--wake-up-session",
- action="store_true",
- dest="wake_up_session", default=False,
- help=help_str)
+ pars.add_argument("--wake-up-session",
+ action="store_true",
+ dest="wake_up_session", default=False,
+ help=help_str)
# server launch mode
help_str = "Mode used to launch server processes (daemon or fork)."
- o_slm = optparse.Option("--server-launch-mode",
- metavar="",
- type="choice",
- choices=["daemon","fork"],
- action="store",
- dest="server_launch_mode",
- help=help_str)
+ pars.add_argument("--server-launch-mode",
+ metavar="",
+ choices=["daemon", "fork"],
+ dest="server_launch_mode",
+ help=help_str)
# use port
help_str = "Preferable port SALOME to be started on. "
help_str += "If specified port is not busy, SALOME session will start on it; "
help_str += "otherwise, any available port will be searched and used."
- o_port = optparse.Option("--port",
- metavar="",
- type="int",
- action="store",
- dest="use_port",
- help=help_str)
+ pars.add_argument("--port",
+ metavar="",
+ type=int,
+ dest="use_port",
+ help=help_str)
+ # Language
help_str = "Force application language. By default, a language specified in "
help_str += "the user's preferences is used."
- o_lang = optparse.Option("-a",
- "--language",
- action="store",
- dest="language",
- help=help_str)
-
- # All options
- opt_list = [o_t,o_g, # GUI/Terminal
- o_d,o_o, # Desktop
- o_b, # Batch
- o_l,o_f, # Use logger or log-file
- o_r, # Configuration XML file
- o_x, # xterm
- o_m, # Modules
- o_e, # Embedded servers
- o_s, # Standalone servers
- o_p, # Kill with port
- o_k, # Kill all
- o_i, # Additional python interpreters
- o_z, # Splash
- o_c, # Catch exceptions
- o_a, # Print free port and exit
- o_n, # --nosave-config
- o_pi, # Interactive python console
- o_nspl,
- o_test, # Write/read test script file with help of TestRecorder
- o_play, # Reproducing test script with help of TestRecorder
- o_gdb,
- o_ddd,
- o_valgrind,
- o_shutdown,
- o_foreground,
- o_wake_up,
- o_slm, # Server launch mode
- o_port, # Use port
- o_lang, # Language
- ]
-
- #std_options = ["gui", "desktop", "log_file", "resources",
- # "xterm", "modules", "embedded", "standalone",
- # "portkill", "killall", "interp", "splash",
- # "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
-
- opt_list += theAdditionalOptions
-
- if not exeName:
- exeName = "%prog"
+ pars.add_argument("-a",
+ "--language",
+ dest="language",
+ help=help_str)
- a_usage = """%s [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
-Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,...
-"""%exeName
- version_str = "Salome %s" % version()
- pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
+ # Positional arguments (hdf file, python file)
+ pars.add_argument("arguments", nargs=argparse.REMAINDER)
return pars
@@ -862,7 +811,7 @@ Python file arguments, if any, must be comma-separated (without blank characters
args = {}
#def get_env():
#args = []
-def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgname, exeName=None):
+def get_env(appname=salomeappname, cfgname=salomecfgname, exeName=None):
###
# Collect launch configuration files:
# - The environment variable "Config" (SalomeAppConfig) which can
@@ -885,32 +834,29 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
# specified in configuration file(s)
###
- if theAdditionalOptions is None:
- theAdditionalOptions = []
-
global args
config_var = appname+'Config'
# check KERNEL_ROOT_DIR
kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
if kernel_root_dir is None:
- print """
+ print("""
For each SALOME module, the environment variable _ROOT_DIR must be set.
KERNEL_ROOT_DIR is mandatory.
- """
+ """)
sys.exit(1)
############################
# parse command line options
- pars = CreateOptionParser(theAdditionalOptions, exeName=exeName)
- (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
+ pars = CreateOptionParser(exeName=exeName)
+ cmd_opts = pars.parse_args(sys.argv[1:])
############################
# Process --print-port option
if cmd_opts.print_port:
from searchFreePort import searchFreePort
searchFreePort({})
- print "port:%s"%(os.environ['NSPORT'])
+ print("port:%s"%(os.environ['NSPORT']))
try:
import PortManager
@@ -932,7 +878,7 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
gui_available = False
if os.getenv("GUI_ROOT_DIR"):
gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui')
- if os.path.isdir( gui_resources_dir ):
+ if os.path.isdir(gui_resources_dir):
gui_available = True
dirs.append(gui_resources_dir)
pass
@@ -953,16 +899,16 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
_opts = {} # associative array of options to be filled
# parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
- for dir in dirs:
- filename = os.path.join(dir, appname+'.xml')
+ for directory in dirs:
+ filename = os.path.join(directory, appname + '.xml')
if not os.path.exists(filename):
- if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
+ if verbose(): print("Configure parser: Warning : can not find configuration file %s" % filename)
else:
try:
p = xml_parser(filename, _opts, [])
_opts = p.opts
except:
- if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
+ if verbose(): print("Configure parser: Error : can not read configuration file %s" % filename)
pass
# parse user configuration file
@@ -972,33 +918,33 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
user_config = cmd_opts.resources
if not user_config:
user_config = userFile(appname, cfgname)
- if verbose(): print "Configure parser: user configuration file is", user_config
+ if verbose(): print("Configure parser: user configuration file is", user_config)
if not user_config or not os.path.exists(user_config):
- if verbose(): print "Configure parser: Warning : can not find user configuration file"
+ if verbose(): print("Configure parser: Warning : can not find user configuration file")
else:
try:
p = xml_parser(user_config, _opts, [])
_opts = p.opts
except:
- if verbose(): print 'Configure parser: Error : can not read user configuration file'
+ if verbose(): print('Configure parser: Error : can not read user configuration file')
user_config = ""
args = _opts
args['user_config'] = user_config
- #print "User Configuration file: ", args['user_config']
+ # print("User Configuration file: ", args['user_config'])
# set default values for options which are NOT set in config files
for aKey in listKeys:
- if not args.has_key( aKey ):
+ if aKey not in args:
args[aKey] = []
for aKey in boolKeys:
- if not args.has_key( aKey ):
+ if aKey not in args:
args[aKey] = 0
if args[file_nam]:
- afile=args[file_nam]
+ afile = args[file_nam]
args[file_nam] = [afile]
args[appname_nam] = appname
@@ -1050,26 +996,28 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
# Naming Service port log file
if cmd_opts.ns_port_log_file is not None:
- args["ns_port_log_file"] = cmd_opts.ns_port_log_file
+ args["ns_port_log_file"] = cmd_opts.ns_port_log_file
# Study files
- for arg in cmd_args:
- if arg[-4:] == ".hdf" and not args["study_hdf"]:
+ for arg in cmd_opts.arguments:
+ file_extension = os.path.splitext(arg)[-1]
+ if file_extension == ".hdf" and not args["study_hdf"]:
args["study_hdf"] = arg
# Python scripts
from salomeContextUtils import getScriptsAndArgs, ScriptAndArgs
- args[script_nam] = getScriptsAndArgs(cmd_args)
+ args[script_nam] = getScriptsAndArgs(cmd_opts.arguments)
if args[gui_nam] and args["session_gui"]:
new_args = []
- for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects
+ for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects
script = re.sub(r'^python.*\s+', r'', sa_obj.script)
new_args.append(ScriptAndArgs(script=script, args=sa_obj.args, out=sa_obj.out))
#
args[script_nam] = new_args
# xterm
- if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
+ if cmd_opts.xterm is not None:
+ args[xterm_nam] = cmd_opts.xterm
# Modules
if cmd_opts.modules is not None:
@@ -1086,11 +1034,11 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
# Embedded
if cmd_opts.embedded is not None:
- args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
+ args[embedded_nam] = [a for a in re.split( "[:;,]", cmd_opts.embedded ) if a.strip()]
# Standalone
if cmd_opts.standalone is not None:
- args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
+ args[standalone_nam] = [a for a in re.split( "[:;,]", cmd_opts.standalone ) if a.strip()]
# Normalize the '--standalone' and '--embedded' parameters
standalone, embedded = process_containers_params( args.get( standalone_nam ),
@@ -1150,13 +1098,6 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
if cmd_opts.wake_up_session is not None:
args[wake_up_session_nam] = cmd_opts.wake_up_session
- ####################################################
- # Add values to args
- for add_opt in theAdditionalOptions:
- cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest)
- exec(cmd)
- ####################################################
-
# disable signals handling
if args[except_nam] == 1:
os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
@@ -1179,7 +1120,7 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
elif os.path.exists( os.path.join(d2,"{0}.xml".format(salomeappname)) ):
dirs.append( d2 )
else:
- #print "* '"+m+"' should be deleted from ",args[modules_nam]
+ # print("* '"+m+"' should be deleted from ",args[modules_nam])
pass
# Test
@@ -1202,19 +1143,19 @@ def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgn
if cmd_opts.use_port is not None:
min_port = 2810
max_port = min_port + 100
- if cmd_opts.use_port not in xrange(min_port, max_port+1):
- print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
+ if cmd_opts.use_port not in range(min_port, max_port+1):
+ print("Error: port number should be in range [%d, %d])" % (min_port, max_port))
sys.exit(1)
args[useport_nam] = cmd_opts.use_port
if cmd_opts.language is not None:
langs = args["language_languages"] if "language_languages" in args else []
if cmd_opts.language not in langs:
- print "Error: unsupported language: %s" % cmd_opts.language
+ print("Error: unsupported language: %s" % cmd_opts.language)
sys.exit(1)
args[lang_nam] = cmd_opts.language
# return arguments
os.environ[config_var] = os.pathsep.join(dirs)
- #print "Args: ", args
+ # print("Args: ", args)
return args
diff --git a/bin/nameserver.py b/bin/nameserver.py
index 37061547d..19fde8e96 100755
--- a/bin/nameserver.py
+++ b/bin/nameserver.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -42,16 +42,16 @@ class NamingServer(Server):
from salome_utils import getLogDir
upath = getLogDir()
try:
- os.makedirs(upath, mode=0777)
+ os.makedirs(upath, mode=0o777)
except:
pass
- if verbose(): print "Name Service... "
+ if verbose(): print("Name Service... ", end =' ')
hname = getHostName()
with open(os.environ["OMNIORB_CONFIG"]) as f:
ss = re.findall("NameService=corbaname::" + hname + ":\d+", f.read())
- if verbose(): print "ss = ", ss,
+ if verbose(): print("ss = ", ss, end=' ')
sl = ss[0]
ll = sl.split(':')
aPort = ll[-1]
@@ -68,7 +68,7 @@ class NamingServer(Server):
try:
os.mkdir(upath)
except:
- #print "Can't create " + upath
+ # print("Can't create " + upath)
pass
#os.system("touch " + upath + "/dummy")
@@ -80,11 +80,11 @@ class NamingServer(Server):
#os.system("rm -f " + upath + "/omninames* " + upath + "/dummy " + upath + "/*.log")
#aSedCommand="s/.*NameService=corbaname::" + hname + ":\([[:digit:]]*\)/\1/"
- #print "sed command = ", aSedCommand
+ # print("sed command = ", aSedCommand)
#aPort = commands.getoutput("sed -e\"" + aSedCommand + "\"" + os.environ["OMNIORB_CONFIG"])
- #print "port=", aPort
+ # print("port=", aPort)
if sys.platform == "win32":
- #print "start omniNames -start " + aPort + " -logdir " + upath
+ # print("start omniNames -start " + aPort + " -logdir " + upath)
self.CMD = ['omniNames', '-start' , aPort , '-nohostname', '-logdir' , os.path.realpath(upath), '-errlog', os.path.realpath(os.path.join(upath,'omniNameErrors.log'))]
#os.system("start omniNames -start " + aPort + " -logdir " + upath)
else:
@@ -92,8 +92,8 @@ class NamingServer(Server):
self.CMD = ['omniNames','-start' , aPort, '-logdir' , upath, '-errlog', upath+'/omniNameErrors.log']
#os.system("omniNames -start " + aPort + " -logdir " + upath + " &")
- if verbose(): print "... ok"
- if verbose(): print "to list contexts and objects bound into the context with the specified name : showNS "
+ if verbose(): print("... ok")
+ if verbose(): print("to list contexts and objects bound into the context with the specified name : showNS ")
def initArgs(self):
diff --git a/bin/orbmodule.py b/bin/orbmodule.py
index 223a91a56..81043ac11 100755
--- a/bin/orbmodule.py
+++ b/bin/orbmodule.py
@@ -56,7 +56,7 @@ class client:
return
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
self.rootContext = None
- if verbose(): print "Launch Naming Service++",
+ if verbose(): print("Launch Naming Service++", end=' ')
# On lance le Naming Server (doit etre dans le PATH)
test = True
@@ -66,7 +66,7 @@ class client:
if test:
NamingServer(args).run()
pass
- print "Searching Naming Service ",
+ print("Searching Naming Service ", end=' ')
ncount=0
delta=0.1
while(ncount < 100):
@@ -82,25 +82,25 @@ class client:
time.sleep(delta)
if self.rootContext is None:
- print "Failed to narrow the root naming context"
+ print("Failed to narrow the root naming context")
sys.exit(1)
- print " found in %s seconds " % ((ncount-1)*delta)
+ print(" found in %s seconds " % ((ncount-1)*delta))
# --------------------------------------------------------------------------
def showNScontext(self,context,dec=''):
if not context:
- print "[NS] No context"
+ print("[NS] No context")
return
else:
- print context
+ print(context)
_,bi = context.list(0)
if bi is not None:
ok,b = bi.next_one()
while(ok):
for s in b.binding_name :
- print "%s%s.%s" %(dec,s.id,s.kind)
+ print("%s%s.%s" %(dec,s.id,s.kind))
if s.kind == "dir":
obj = context.resolve([s])
scontext = obj._narrow(CosNaming.NamingContext)
@@ -116,7 +116,7 @@ class client:
# --------------------------------------------------------------------------
def Resolve(self, Path):
- resolve_path = string.split(Path,'/')
+ resolve_path = Path.split('/')
if resolve_path[0] == '': del resolve_path[0]
dir_path = resolve_path[:-1]
context_name = []
@@ -126,11 +126,11 @@ class client:
try:
obj = self.rootContext.resolve(context_name)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
obj = None
- except CosNaming.NamingContext.InvalidName, ex:
+ except CosNaming.NamingContext.InvalidName as ex:
obj = None
- except CosNaming.NamingContext.CannotProceed, ex:
+ except CosNaming.NamingContext.CannotProceed as ex:
obj = None
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
obj = None
@@ -141,13 +141,13 @@ class client:
def waitNS(self,name,typobj=None,maxcount=240):
count = 0
delta = 0.5
- print "Searching %s in Naming Service " % name,
+ print("Searching %s in Naming Service " % name, end=' ')
while(1):
count += 1
- if count > maxcount : raise RuntimeError, "Impossible de trouver %s" % name
+ if count > maxcount : raise RuntimeError("Impossible de trouver %s" % name)
obj = self.Resolve(name)
if obj :
- print " found in %s seconds " % ((count-1)*delta)
+ print(" found in %s seconds " % ((count-1)*delta))
break
else:
sys.stdout.write('+')
@@ -158,7 +158,7 @@ class client:
nobj = obj._narrow(typobj)
if nobj is None:
- print "%s exists but is not a %s" % (name,typobj)
+ print("%s exists but is not a %s" % (name,typobj))
return nobj
if sys.platform != "win32":
@@ -166,16 +166,16 @@ class client:
aCount = 0
aDelta = 0.5
anObj = None
- print "Searching %s in Naming Service " % theName,
+ print("Searching %s in Naming Service " % theName, end=' ')
while(1):
try:
os.kill(thePID,0)
except:
- raise RuntimeError, "Process %d for %s not found" % (thePID,theName)
+ raise RuntimeError("Process %d for %s not found" % (thePID,theName))
aCount += 1
anObj = self.Resolve(theName)
if anObj:
- print " found in %s seconds " % ((aCount-1)*aDelta)
+ print(" found in %s seconds " % ((aCount-1)*aDelta))
break
else:
sys.stdout.write('+')
@@ -189,7 +189,7 @@ class client:
anObject = anObj._narrow(theTypObj)
if anObject is None:
- print "%s exists but is not a %s" % (theName,theTypObj)
+ print("%s exists but is not a %s" % (theName,theTypObj))
return anObject
@@ -201,11 +201,11 @@ class client:
try:
obj = self.rootContext.resolve(context_name)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
obj = None
- except CosNaming.NamingContext.InvalidName, ex:
+ except CosNaming.NamingContext.InvalidName as ex:
obj = None
- except CosNaming.NamingContext.CannotProceed, ex:
+ except CosNaming.NamingContext.CannotProceed as ex:
obj = None
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
obj = None
@@ -216,13 +216,13 @@ class client:
def waitLogger(self,name,typobj=None,maxcount=40):
count = 0
delta = 0.5
- print "Searching %s in Naming Service " % name,
+ print("Searching %s in Naming Service " % name, end=' ')
while(1):
count += 1
- if count > maxcount : raise RuntimeError, "Impossible de trouver %s" % name
+ if count > maxcount : raise RuntimeError("Impossible de trouver %s" % name)
obj = self.ResolveLogger(name)
if obj :
- print " found in %s seconds " % ((count-1)*delta)
+ print(" found in %s seconds " % ((count-1)*delta))
break
else:
sys.stdout.write('+')
@@ -233,5 +233,5 @@ class client:
nobj = obj._narrow(typobj)
if nobj is None:
- print "%s exists but is not a %s" % (name,typobj)
+ print("%s exists but is not a %s" % (name,typobj))
return nobj
diff --git a/bin/parseConfigFile.py b/bin/parseConfigFile.py
index 77e6350df..63d0c92cc 100644
--- a/bin/parseConfigFile.py
+++ b/bin/parseConfigFile.py
@@ -17,7 +17,7 @@
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import ConfigParser
+import configparser
import os
import logging
import re
@@ -44,9 +44,9 @@ def _expandSystemVariables(key, val):
#
# :TRICKY: So ugly solution...
-class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
+class MultiOptSafeConfigParser(configparser.SafeConfigParser):
def __init__(self):
- ConfigParser.SafeConfigParser.__init__(self)
+ configparser.SafeConfigParser.__init__(self)
# copied from python 2.6.8 Lib.ConfigParser.py
# modified (see code comments) to handle duplicate keys
@@ -88,7 +88,7 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
sectname = mo.group('header')
if sectname in self._sections:
cursect = self._sections[sectname]
- elif sectname == ConfigParser.DEFAULTSECT:
+ elif sectname == configparser.DEFAULTSECT:
cursect = self._defaults
else:
cursect = self._dict()
@@ -98,7 +98,7 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
optname = None
# no section header in the file?
elif cursect is None:
- raise ConfigParser.MissingSectionHeaderError(fpname, lineno, line)
+ raise configparser.MissingSectionHeaderError(fpname, lineno, line)
# an option line?
else:
mo = self.OPTCRE.match(line)
@@ -143,7 +143,7 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
# raised at the end of the file and will contain a
# list of all bogus lines
if not e:
- e = ConfigParser.ParsingError(fpname)
+ e = configparser.ParsingError(fpname)
e.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception
if e:
@@ -151,9 +151,9 @@ class MultiOptSafeConfigParser(ConfigParser.SafeConfigParser):
# join the multi-line values collected while reading
all_sections = [self._defaults]
- all_sections.extend(self._sections.values())
+ all_sections.extend(list(self._sections.values()))
for options in all_sections:
- for name, val in options.items():
+ for name, val in list(options.items()):
if isinstance(val, list):
options[name] = '\n'.join(val)
#
@@ -174,13 +174,13 @@ def parseConfigFile(filename, reserved = None):
# Read config file
try:
config.read(filename)
- except ConfigParser.MissingSectionHeaderError:
+ except configparser.MissingSectionHeaderError:
logConfigParser.error("No section found in file: %s"%(filename))
return []
try:
return __processConfigFile(config, reserved, filename)
- except ConfigParser.InterpolationMissingOptionError, e:
+ except configparser.InterpolationMissingOptionError as e:
msg = "A variable may be undefined in SALOME context file: %s\nParser error is: %s\n"%(filename, e)
raise SalomeContextException(msg)
#
diff --git a/bin/runConsole.py b/bin/runConsole.py
index 9639291f7..78e12ee2e 100644
--- a/bin/runConsole.py
+++ b/bin/runConsole.py
@@ -24,7 +24,6 @@
from optparse import OptionParser
import os
import sys
-import user
import pickle
# Use to display newlines (\n) in epilog
@@ -47,7 +46,7 @@ ask user to select a port from list of available SALOME instances.\n
The -c option can be used to specify the command to execute in the interpreter.
A script can also be used.
For example:
- salome connect -p 2810 -c 'print "Hello"'
+ salome connect -p 2810 -c 'print("Hello")'
salome connect -p 2810 hello.py
"""
parser = MyParser(usage=usage, epilog=epilog)
@@ -60,31 +59,31 @@ For example:
)
try:
(options, args) = parser.parse_args(args)
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
return {}, []
return options, args
#
def __show_running_instances(list_of_instances):
- print '-'*10
- print "Running instances:"
+ print('-'*10)
+ print("Running instances:")
for i in range(len(list_of_instances)):
host, port, _ = list_of_instances[i]
- print " [%d] %s:%s"%(i+1, host, port)
- print '-'*10
+ print(" [%d] %s:%s"%(i+1, host, port))
+ print('-'*10)
#
def __choose_in(choices):
__show_running_instances(choices)
- rep = raw_input("Please enter the number of instance to use (0 to cancel): ")
+ rep = input("Please enter the number of instance to use (0 to cancel): ")
if rep == '0':
return None, None, None
elif rep in [str(i) for i in range(1, len(choices)+1)]:
return choices[int(rep)-1]
else:
- print "*** Invalid number! ***"
+ print("*** Invalid number! ***")
return __choose_in(choices)
#
@@ -102,36 +101,36 @@ def __get_running_session(requested_port=None, lastInstanceByDefault=False):
host, port, filename = None, None, None
if requested_port:
- print "Search for running instance on port %s..."%requested_port
+ print("Search for running instance on port %s..."%requested_port)
found = [(h,p,f) for h,p,f in available_connexions if int(p) == int(requested_port)]
if not found:
- print " ...no running instance found"
+ print(" ...no running instance found")
elif len(found) == 1:
host, port, filename = found[0]
- print " ...found unique instance: %s:%s"%(host,port)
+ print(" ...found unique instance: %s:%s"%(host,port))
else:
- print " ...multiple instances found ; please choose one in the following:"
+ print(" ...multiple instances found ; please choose one in the following:")
host, port, filename = __choose_in(found)
else: # no requested port
if not available_connexions:
- print "No running instance found"
+ print("No running instance found")
elif len(available_connexions) == 1:
host, port, filename = available_connexions[0]
- print "Found unique instance: %s:%s"%(host,port)
+ print("Found unique instance: %s:%s"%(host,port))
else:
- print "Multiple instances found ; please choose one in the following:"
+ print("Multiple instances found ; please choose one in the following:")
host, port, filename = __choose_in(available_connexions)
pass
if port:
- print "Selected instance: %s:%s"%(host, port)
+ print("Selected instance: %s:%s"%(host, port))
else:
- print "Cancel."
+ print("Cancel.")
return host, port, filename
#
-from omniORB import CORBA
+import CORBA
import CosNaming
import orbmodule
@@ -143,7 +142,7 @@ class client(orbmodule.client):
self.rootContext = obj._narrow(CosNaming.NamingContext)
return
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
- print "It's not a valid naming service"
+ print("It's not a valid naming service")
self.rootContext = None
sys.stdout.flush()
raise
@@ -162,12 +161,12 @@ def start_client():
if session_server:
session = clt.waitNS("/Kernel/Session")
catalog = clt.waitNS("/Kernel/ModulCatalog")
- studyMgr = clt.waitNS("/myStudyManager")
+ study = clt.waitNS("/Study")
import salome
salome.salome_init()
from salome import lcc
- print "--> now connected to SALOME"
+ print("--> now connected to SALOME")
#
def _prompt(environment=None, commands=None, message="Connecting to SALOME"):
@@ -183,10 +182,10 @@ def _prompt(environment=None, commands=None, message="Connecting to SALOME"):
readline.set_completer(rlcompleter.Completer(environment).complete)
readline.parse_and_bind("tab: complete")
# calling this with globals ensures we can see the environment
- print message
+ print(message)
shell = code.InteractiveConsole(environment)
for cmd in commands:
- print "Execute command:", cmd
+ print("Execute command:", cmd)
shell.push(cmd)
pass
shell.interact()
@@ -208,22 +207,27 @@ def connect(args=None, env=None):
cmd.append(options.command)
if args: # unprocessed: may be scripts
for arg in args:
- cmd.append("execfile('%s')"%os.path.abspath(os.path.expanduser(arg)))
+ filename = os.path.abspath(os.path.expanduser(arg))
+ pythonLine = "exec(compile(open(%s, \"rb\").read(), %s, 'exec'))"%(filename, filename)
+ cmd.append(pythonLine)
if port:
import subprocess
absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
env_copy = os.environ.copy()
- proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","runConsole.py"), pickle.dumps(cmd)], shell=False, close_fds=True, env=env_copy)
+ cmdDump = pickle.dumps(cmd, protocol=0)
+ cmdString = cmdDump.decode()
+ proc = subprocess.Popen(['python3', os.path.join(absoluteAppliPath,"bin","salome","runConsole.py"), cmdString], shell=False, close_fds=True, env=env_copy)
proc.communicate()
return proc.returncode
#
if __name__ == "__main__":
if len(sys.argv) == 2:
- cmd = pickle.loads(sys.argv[1])
+ cmdBytes = sys.argv[1].encode()
+ cmd = pickle.loads(cmdBytes)
sys.argv = []
_prompt(commands=cmd)
else:
- print "runConsole.py: incorrect usage!"
+ print("runConsole.py: incorrect usage!")
#
diff --git a/bin/runIDLparser b/bin/runIDLparser
index c13e39b12..f3c8df9f1 100644
--- a/bin/runIDLparser
+++ b/bin/runIDLparser
@@ -43,7 +43,7 @@ if test "$hh" = "1" ; then
echo ""
echo " to run IDLparser:"
echo ""
- echo " $0 -Wbcatalog=[,icon=][,version=][,author=][,name=][,multistudy=][,remove=component_name] "
+ echo " $0 -Wbcatalog=[,icon=][,version=][,author=][,name=][,remove=component_name] "
echo ""
echo " to have omniidl help:"
echo ""
diff --git a/bin/runSalome.py b/bin/runSalome.py
index e6e797639..63eb62f16 100755
--- a/bin/runSalome.py
+++ b/bin/runSalome.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -50,7 +50,7 @@ def killLocalPort():
try:
killMyPort(my_port)
except:
- print "problem in killLocalPort()"
+ print("problem in killLocalPort()")
pass
pass
@@ -65,7 +65,7 @@ def givenPortKill(port):
try:
killMyPort(my_port)
except:
- print "problem in LocalPortKill(), killMyPort(%s)"%port
+ print("problem in LocalPortKill(), killMyPort(%s)"%port)
pass
pass
@@ -101,7 +101,7 @@ class InterpServer(Server):
def run(self):
global process_id
command = self.CMD
- print "INTERPSERVER::command = ", command
+ print("INTERPSERVER::command = ", command)
import subprocess
pid = subprocess.Popen(command).pid
process_id[pid]=self.CMD
@@ -116,7 +116,7 @@ def get_cata_path(list_modules,modules_root_dir):
cata_path=[]
for module in list_modules:
- if modules_root_dir.has_key(module):
+ if module in modules_root_dir:
module_root_dir=modules_root_dir[module]
module_cata=module+"Catalog.xml"
cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
@@ -134,7 +134,7 @@ def get_cata_path(list_modules,modules_root_dir):
if os.path.exists(path):
for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
module_name= os.path.basename(cata_file)[:-11]
- if not modules_cata.has_key(module_name):
+ if module_name not in modules_cata:
cata_path.append(cata_file)
modules_cata[module_name]=cata_file
@@ -160,7 +160,7 @@ class CatalogServer(Server):
cata_path=get_cata_path(list_modules,modules_root_dir)
- self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+ self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
# ---
@@ -215,10 +215,10 @@ class LoggerServer(Server):
with_username=True,
with_hostname=True,
with_port=True)
- print "==========================================================="
- print "Logger server: put log to the file:"
- print logfile
- print "==========================================================="
+ print("===========================================================")
+ print("Logger server: put log to the file:")
+ print(logfile)
+ print("===========================================================")
self.CMD=['SALOME_Logger_Server', logfile]
pass
pass # end of LoggerServer class
@@ -256,7 +256,7 @@ class SessionServer(Server):
raise Exception('Python containers no longer supported')
if self.args['gui']:
session_gui = True
- if self.args.has_key('session_gui'):
+ if 'session_gui' in self.args:
session_gui = self.args['session_gui']
if session_gui:
self.SCMD2+=['GUI']
@@ -267,7 +267,7 @@ class SessionServer(Server):
self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
pass
pass
- if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
+ if 'pyscript' in self.args and len(self.args['pyscript']) > 0:
msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
self.SCMD2+=['--pyscript=%s'%(msg)]
pass
@@ -275,9 +275,9 @@ class SessionServer(Server):
pass
if self.args['noexcepthandler']:
self.SCMD2+=['noexcepthandler']
- if self.args.has_key('user_config'):
+ if 'user_config' in self.args:
self.SCMD2+=['--resources=%s'%self.args['user_config']]
- if self.args.has_key('modules'):
+ if 'modules' in self.args:
list_modules = []
#keep only modules with GUI
for m in modules_list:
@@ -291,7 +291,7 @@ class SessionServer(Server):
list_modules.reverse()
self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
pass
- if self.args.has_key('language'):
+ if 'language' in self.args:
self.SCMD2+=['--language=%s' % self.args['language']]
pass
@@ -305,14 +305,14 @@ class SessionServer(Server):
cata_path=get_cata_path(list_modules,modules_root_dir)
- if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
+ if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
#Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
- self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+ self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
else:
self.CMD=self.SCMD1 + self.SCMD2
- if self.args.has_key('test'):
+ if 'test' in self.args:
self.CMD+=['-test'] + self.args['test']
- elif self.args.has_key('play'):
+ elif 'play' in self.args:
self.CMD+=['-play'] + self.args['play']
if self.args["gdb_session"] or self.args["ddd_session"]:
@@ -371,9 +371,9 @@ class LauncherServer(Server):
cata_path=get_cata_path(list_modules,modules_root_dir)
- if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
+ if ("gui" in self.args) & ('moduleCatalog' in self.args['embedded']):
#Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
- self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
+ self.CMD=self.SCMD1 + ['"' + '"::"'.join(cata_path) + '"'] + self.SCMD2
else:
self.CMD=self.SCMD1 + self.SCMD2
#
@@ -395,12 +395,12 @@ def startSalome(args, modules_list, modules_root_dir):
"""Launch all SALOME servers requested by args"""
init_time = os.times()
- if verbose(): print "startSalome ", args
+ if verbose(): print("startSalome ", args)
#
# Set server launch command
#
- if args.has_key('server_launch_mode'):
+ if 'server_launch_mode' in args:
Server.set_server_launch_mode(args['server_launch_mode'])
#
@@ -509,15 +509,15 @@ def startSalome(args, modules_list, modules_root_dir):
# and wait until it is registered in naming service
#
- #print "ARGS = ",args
+ # print("ARGS = ",args)
if ('study' not in args['embedded']) | (args["gui"] == 0):
- print "RunStudy"
+ print("RunStudy")
myServer=SalomeDSServer(args)
myServer.run()
if sys.platform == "win32":
- clt.waitNS("/myStudyManager")
+ clt.waitNS("/Study")
else:
- clt.waitNSPID("/myStudyManager",myServer.PID)
+ clt.waitNSPID("/Study",myServer.PID)
#
# Launch LauncherServer
@@ -578,9 +578,9 @@ def startSalome(args, modules_list, modules_root_dir):
session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
args["session_object"] = session
end_time = os.times()
- if verbose(): print
- print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
- - init_time[4])
+ if verbose(): print()
+ print("Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
+ - init_time[4]))
# ASV start GUI without Loader
#if args['gui']:
@@ -597,14 +597,14 @@ def startSalome(args, modules_list, modules_root_dir):
except:
import traceback
traceback.print_exc()
- print "-------------------------------------------------------------"
- print "-- to get an external python interpreter:runSalome --interp=1"
- print "-------------------------------------------------------------"
+ print("-------------------------------------------------------------")
+ print("-- to get an external python interpreter:runSalome --interp=1")
+ print("-------------------------------------------------------------")
- if verbose(): print "additional external python interpreters: ", nbaddi
+ if verbose(): print("additional external python interpreters: ", nbaddi)
if nbaddi:
for i in range(nbaddi):
- print "i=",i
+ print("i=",i)
anInterp=InterpServer(args)
anInterp.run()
@@ -634,21 +634,21 @@ def useSalome(args, modules_list, modules_root_dir):
except:
import traceback
traceback.print_exc()
- print
- print
- print "--- Error during Salome launch ---"
+ print()
+ print()
+ print("--- Error during Salome launch ---")
- #print process_id
+ # print(process_id)
from addToKillList import addToKillList
from killSalomeWithPort import getPiDict
filedict = getPiDict(args['port'])
- for pid, cmd in process_id.items():
+ for pid, cmd in list(process_id.items()):
addToKillList(pid, cmd, args['port'])
pass
- if verbose(): print """
+ if verbose(): print("""
Saving of the dictionary of Salome processes in %s
To kill SALOME processes from a console (kill all sessions from all ports):
python killSalome.py
@@ -660,7 +660,7 @@ def useSalome(args, modules_list, modules_root_dir):
runSalome, with --killall option, starts with killing
the processes resulting from the previous execution.
- """%filedict
+ """%filedict)
#
# Print Naming Service directory list
@@ -668,8 +668,8 @@ def useSalome(args, modules_list, modules_root_dir):
if clt != None:
if verbose():
- print
- print " --- registered objects tree in Naming Service ---"
+ print()
+ print(" --- registered objects tree in Naming Service ---")
clt.showNS()
pass
@@ -694,14 +694,14 @@ def useSalome(args, modules_list, modules_root_dir):
# run python scripts, passed as command line arguments
toimport = []
- if args.has_key('gui') and args.has_key('session_gui'):
+ if 'gui' in args and 'session_gui' in args:
if not args['gui'] or not args['session_gui']:
- if args.has_key('study_hdf'):
+ if 'study_hdf' in args:
toopen = args['study_hdf']
if toopen:
import salome
salome.salome_init(toopen)
- if args.has_key('pyscript'):
+ if 'pyscript' in args:
toimport = args['pyscript']
from salomeContextUtils import formatScriptsAndArgs
command = formatScriptsAndArgs(toimport)
@@ -714,9 +714,9 @@ def useSalome(args, modules_list, modules_root_dir):
return clt
def execScript(script_path):
- print 'executing', script_path
+ print('executing', script_path)
sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
- execfile(script_path,globals())
+ exec(compile(open(script_path).read(), script_path, 'exec'),globals())
del sys.path[0]
# -----------------------------------------------------------------------------
@@ -759,17 +759,17 @@ def main(exeName=None):
try:
from salomeContextUtils import setOmniOrbUserPath
setOmniOrbUserPath()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
sys.exit(1)
from salome_utils import getHostName
args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName)
- print "runSalome running on %s" % getHostName()
+ print("runSalome running on %s" % getHostName())
kill_salome(args)
save_config = True
- if args.has_key('save_config'):
+ if 'save_config' in args:
save_config = args['save_config']
# --
test = True
@@ -850,7 +850,6 @@ def foreGround(clt, args):
#
def runSalome():
- import user
clt,args = main()
# --
test = args['gui'] and args['session_gui']
diff --git a/bin/runSession.py b/bin/runSession.py
index bf0c5c6b7..c6676b802 100644
--- a/bin/runSession.py
+++ b/bin/runSession.py
@@ -121,8 +121,8 @@ User "myself" connects to remotemachine to run the script concatenate.py in
short_args, extra_args = getShortAndExtraArgs(args)
try:
(options, args) = parser.parse_args(short_args)
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
return None, []
port = options.port
@@ -252,7 +252,7 @@ def __copyFiles(user, machine, script, infiles, outfiles):
# copy the infile to the remote server
cmd = "scp %s %s@%s:%s" % (infile, user, machine, tmp_file)
- print "[ SCP ]", cmd
+ print("[ SCP ]", cmd)
os.system(cmd)
list_infiles.append(tmp_file)
@@ -276,7 +276,7 @@ def __copyFiles(user, machine, script, infiles, outfiles):
# copy the salome script on the remote server
cmd = "scp %s %s@%s:%s" % (tmp_script, user, machine, tmp_script)
- print "[ SCP ]", cmd
+ print("[ SCP ]", cmd)
os.system(cmd)
return list_infiles, list_outfiles, tmp_script
@@ -285,10 +285,10 @@ def __copyFiles(user, machine, script, infiles, outfiles):
# sa_obj is a ScriptAndArgs object (from salomeContextUtils)
def __runRemoteSession(sa_obj, params):
if not params.user:
- print "ERROR: The user login on remote machine MUST be given."
+ print("ERROR: The user login on remote machine MUST be given.")
return 1
if not params.directory:
- print "ERROR: The remote directory MUST be given."
+ print("ERROR: The remote directory MUST be given.")
return 1
# sa_obj.script may be 'python script.py' --> only process .py file
@@ -302,7 +302,7 @@ def __runRemoteSession(sa_obj, params):
if params.port:
command = command + "-p %s "%params.port
command = command + " %s %s args:%s"%(header, tmp_script, ",".join(tmp_in))
- print '[ SSH ] ' + command
+ print('[ SSH ] ' + command)
os.system(command)
# Get remote files and clean
@@ -312,12 +312,12 @@ def __runRemoteSession(sa_obj, params):
for outfile in (sa_obj.out or []):
remote_outfile = tmp_out.pop(0)
command = "scp %s@%s:%s %s" %(params.user, params.machine, remote_outfile, outfile)
- print "[ SCP ] " + command
+ print("[ SCP ] " + command)
os.system(command)
# clean temporary files
command = "ssh %s@%s \\rm -f %s" % (params.user, params.machine, " ".join(temp_files))
- print '[ SSH ] ' + command
+ print('[ SSH ] ' + command)
os.system(command)
os.remove(tmp_script)
diff --git a/bin/runTests.py b/bin/runTests.py
index 2ea2fce2c..31f662576 100644
--- a/bin/runTests.py
+++ b/bin/runTests.py
@@ -65,7 +65,7 @@ For complete description of available options, pleaser refer to ctest documentat
return []
if args[0] in ["-h", "--help"]:
- print usage + epilog
+ print(usage + epilog)
sys.exit(0)
return args
diff --git a/bin/salomeContext.py b/bin/salomeContext.py
index a674fff6c..8e40e820a 100644
--- a/bin/salomeContext.py
+++ b/bin/salomeContext.py
@@ -20,7 +20,7 @@
import os
import sys
import logging
-import ConfigParser
+import configparser
from parseConfigFile import parseConfigFile
@@ -68,7 +68,7 @@ Command options:
any blank characters.
'''
- print msg
+ print(msg)
#
"""
@@ -128,7 +128,9 @@ class SalomeContext:
absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
env_copy = os.environ.copy()
- proc = subprocess.Popen(['python', os.path.join(absoluteAppliPath,"bin","salome","salomeContext.py"), pickle.dumps(self), pickle.dumps(args)], shell=False, close_fds=True, env=env_copy)
+ selfBytes= pickle.dumps(self, protocol=0)
+ argsBytes= pickle.dumps(args, protocol=0)
+ proc = subprocess.Popen(['python3', os.path.join(absoluteAppliPath,"bin","salome","salomeContext.py"), selfBytes.decode(), argsBytes.decode()], shell=False, close_fds=True, env=env_copy)
out, err = proc.communicate()
return out, err, proc.returncode
#
@@ -222,7 +224,7 @@ class SalomeContext:
'car' : '_getCar',
}
- if not command in availableCommands.keys():
+ if command not in availableCommands:
command = "start"
options = args
@@ -265,14 +267,14 @@ class SalomeContext:
if ex.code != 0:
self.getLogger().error("SystemExit %s in method %s.", ex.code, command)
return ex.code
- except StandardError:
+ except SalomeContextException as e:
+ self.getLogger().error(e)
+ return 1
+ except Exception:
self.getLogger().error("Unexpected error:")
import traceback
traceback.print_exc()
return 1
- except SalomeContextException, e:
- self.getLogger().error(e)
- return 1
#
def __setContextFromConfigFile(self, filename, reserved=None):
@@ -280,7 +282,7 @@ class SalomeContext:
reserved = []
try:
unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved)
- except SalomeContextException, e:
+ except SalomeContextException as e:
msg = "%s"%e
self.getLogger().error(msg)
return 1
@@ -291,7 +293,7 @@ class SalomeContext:
# set context
for reserved in reservedDict:
- a = filter(None, reservedDict[reserved]) # remove empty elements
+ a = [_f for _f in reservedDict[reserved] if _f] # remove empty elements
a = [ os.path.realpath(x) for x in a ]
reformattedVals = os.pathsep.join(a)
if reserved in ["INCLUDE", "LIBPATH"]:
@@ -325,17 +327,17 @@ class SalomeContext:
def _setContext(self, args=None):
salome_context_set = os.getenv("SALOME_CONTEXT_SET")
if salome_context_set:
- print "***"
- print "*** SALOME context has already been set."
- print "*** Enter 'exit' (only once!) to leave SALOME context."
- print "***"
+ print("***")
+ print("*** SALOME context has already been set.")
+ print("*** Enter 'exit' (only once!) to leave SALOME context.")
+ print("***")
return 0
os.environ["SALOME_CONTEXT_SET"] = "yes"
- print "***"
- print "*** SALOME context is now set."
- print "*** Enter 'exit' (only once!) to leave SALOME context."
- print "***"
+ print("***")
+ print("*** SALOME context is now set.")
+ print("*** Enter 'exit' (only once!) to leave SALOME context.")
+ print("***")
cmd = ["/bin/bash"]
proc = subprocess.Popen(cmd, shell=False, close_fds=True)
@@ -374,7 +376,7 @@ class SalomeContext:
args = []
ports = args
if not ports:
- print "Port number(s) not provided to command: salome kill "
+ print("Port number(s) not provided to command: salome kill ")
return 1
from multiprocessing import Process
@@ -422,7 +424,7 @@ class SalomeContext:
#
def _showSoftwareVersions(self, softwares=None):
- config = ConfigParser.SafeConfigParser()
+ config = configparser.SafeConfigParser()
absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH')
filename = os.path.join(absoluteAppliPath, "sha1_collections.txt")
versions = {}
@@ -441,12 +443,12 @@ class SalomeContext:
if softwares:
for soft in softwares:
if versions.has_key(soft.upper()):
- print soft.upper().rjust(max_len), versions[soft.upper()]
+ print(soft.upper().rjust(max_len), versions[soft.upper()])
else:
import collections
od = collections.OrderedDict(sorted(versions.items()))
for name, version in od.iteritems():
- print name.rjust(max_len), versions[name]
+ print(name.rjust(max_len), versions[name])
pass
def _showInfo(self, args=None):
@@ -468,7 +470,7 @@ Available options are:
args = ["--version"]
if "-h" in args or "--help" in args:
- print usage + epilog
+ print(usage + epilog)
return 0
if "-p" in args or "--ports" in args:
@@ -477,17 +479,17 @@ Available options are:
this_ports = ports['this']
other_ports = ports['other']
if this_ports or other_ports:
- print "SALOME instances are running on the following ports:"
+ print("SALOME instances are running on the following ports:")
if this_ports:
- print " This application:", this_ports
+ print(" This application:", this_ports)
else:
- print " No SALOME instances of this application"
+ print(" No SALOME instances of this application")
if other_ports:
- print " Other applications:", other_ports
+ print(" Other applications:", other_ports)
else:
- print " No SALOME instances of other applications"
+ print(" No SALOME instances of other applications")
else:
- print "No SALOME instances are running"
+ print("No SALOME instances are running")
if "-s" in args or "--softwares" in args:
if "-s" in args:
@@ -500,7 +502,7 @@ Available options are:
self._showSoftwareVersions(softwares=args[index+1:indexEnd])
if "-v" in args or "--version" in args:
- print "Running with python", platform.python_version()
+ print("Running with python", platform.python_version())
return self._runAppli(["--version"])
return 0
@@ -512,7 +514,7 @@ Available options are:
modules = args
if not modules:
- print "Module(s) not provided to command: salome doc "
+ print("Module(s) not provided to command: salome doc ")
return 1
appliPath = os.getenv("ABSOLUTE_APPLI_PATH")
@@ -528,71 +530,71 @@ Available options are:
if os.path.isfile(docfile):
out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
else:
- print "Online documentation is not accessible for module:", module
+ print("Online documentation is not accessible for module:", module)
def _usage(self, unused=None):
usage()
#
def _makeCoffee(self, unused=None):
- print " ("
- print " ) ("
- print " ___...(-------)-....___"
- print " .-\"\" ) ( \"\"-."
- print " .-\'``\'|-._ ) _.-|"
- print " / .--.| `\"\"---...........---\"\"` |"
- print " / / | |"
- print " | | | |"
- print " \\ \\ | |"
- print " `\\ `\\ | |"
- print " `\\ `| SALOME |"
- print " _/ /\\ 4 EVER /"
- print " (__/ \\ <3 /"
- print " _..---\"\"` \\ /`\"\"---.._"
- print " .-\' \\ / \'-."
- print " : `-.__ __.-\' :"
- print " : ) \"\"---...---\"\" ( :"
- print " \'._ `\"--...___...--\"` _.\'"
- print " \\\"\"--..__ __..--\"\"/"
- print " \'._ \"\"\"----.....______.....----\"\"\" _.\'"
- print " `\"\"--..,,_____ _____,,..--\"\"`"
- print " `\"\"\"----\"\"\"`"
- print ""
- print " SALOME is working for you; what else?"
- print ""
+ print(" (")
+ print(" ) (")
+ print(" ___...(-------)-....___")
+ print(" .-\"\" ) ( \"\"-.")
+ print(" .-\'``\'|-._ ) _.-|")
+ print(" / .--.| `\"\"---...........---\"\"` |")
+ print(" / / | |")
+ print(" | | | |")
+ print(" \\ \\ | |")
+ print(" `\\ `\\ | |")
+ print(" `\\ `| SALOME |")
+ print(" _/ /\\ 4 EVER /")
+ print(" (__/ \\ <3 /")
+ print(" _..---\"\"` \\ /`\"\"---.._")
+ print(" .-\' \\ / \'-.")
+ print(" : `-.__ __.-\' :")
+ print(" : ) \"\"---...---\"\" ( :")
+ print(" \'._ `\"--...___...--\"` _.\'")
+ print(" \\\"\"--..__ __..--\"\"/")
+ print(" \'._ \"\"\"----.....______.....----\"\"\" _.\'")
+ print(" `\"\"--..,,_____ _____,,..--\"\"`")
+ print(" `\"\"\"----\"\"\"`")
+ print("")
+ print(" SALOME is working for you; what else?")
+ print("")
#
def _getCar(self, unused=None):
- print " _____________"
- print " ..---:::::::-----------. ::::;;."
- print " .\'\"\"\"\"\"\" ;; \\ \":."
- print " .\'\' ; \\ \"\\__."
- print " .\' ;; ; \\\\\";"
- print " .\' ; _____; \\\\/"
- print " .\' :; ;\" \\ ___:\'."
- print " .\'--........................... : = ____:\" \\ \\"
- print " ..-\"\" \"\"\"\' o\"\"\" ; ; :"
- print " .--\"\" .----- ..----... _.- --. ..-\" ; ; ; ;"
- print " .\"\"_- \"--\"\"-----\'\"\" _-\" .-\"\" ; ; .-."
- print " .\' .\' SALOME .\" .\" ; ; /. |"
- print " /-./\' 4 EVER <3 .\" / _.. ; ; ;;;|"
- print " : ;-.______ / _________==. /_ \\ ; ; ;;;;"
- print " ; / | \"\"\"\"\"\"\"\"\"\"\".---.\"\"\"\"\"\"\" : /\" \". |; ; _; ;;;"
- print " /\"-/ | / / / / ;|; ;-\" | ;\';"
- print ":- : \"\"\"----______ / / ____. . .\"\'. ;; .-\"..T\" ."
- print "\'. \" ___ \"\": \'\"\"\"\"\"\"\"\"\"\"\"\"\"\" . ; ; ;; ;.\" .\" \'--\""
- print " \", __ \"\"\" \"\"---... :- - - - - - - - - \' \' ; ; ; ;;\" .\""
- print " /. ; \"\"\"---___ ; ; ; ;|.\"\""
- print " : \": \"\"\"----. .-------. ; ; ; ;:"
- print " \\ \'--__ \\ \\ \\ / | ; ;;"
- print " \'-.. \"\"\"\"---___ : .______..\\ __/..-\"\"| ; ; ;"
- print " \"\"--.. \"\"\"--\" m l s . \". . ;"
- print " \"\"------... ..--\"\" \" :"
- print " \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \\ /"
- print " \"------\""
- print ""
- print " Drive your simulation properly with SALOME!"
- print ""
+ print(" _____________")
+ print(" ..---:::::::-----------. ::::;;.")
+ print(" .\'\"\"\"\"\"\" ;; \\ \":.")
+ print(" .\'\' ; \\ \"\\__.")
+ print(" .\' ;; ; \\\\\";")
+ print(" .\' ; _____; \\\\/")
+ print(" .\' :; ;\" \\ ___:\'.")
+ print(" .\'--........................... : = ____:\" \\ \\")
+ print(" ..-\"\" \"\"\"\' o\"\"\" ; ; :")
+ print(" .--\"\" .----- ..----... _.- --. ..-\" ; ; ; ;")
+ print(" .\"\"_- \"--\"\"-----\'\"\" _-\" .-\"\" ; ; .-.")
+ print(" .\' .\' SALOME .\" .\" ; ; /. |")
+ print(" /-./\' 4 EVER <3 .\" / _.. ; ; ;;;|")
+ print(" : ;-.______ / _________==. /_ \\ ; ; ;;;;")
+ print(" ; / | \"\"\"\"\"\"\"\"\"\"\".---.\"\"\"\"\"\"\" : /\" \". |; ; _; ;;;")
+ print(" /\"-/ | / / / / ;|; ;-\" | ;\';")
+ print(":- : \"\"\"----______ / / ____. . .\"\'. ;; .-\"..T\" .")
+ print("\'. \" ___ \"\": \'\"\"\"\"\"\"\"\"\"\"\"\"\"\" . ; ; ;; ;.\" .\" \'--\"")
+ print(" \", __ \"\"\" \"\"---... :- - - - - - - - - \' \' ; ; ; ;;\" .\"")
+ print(" /. ; \"\"\"---___ ; ; ; ;|.\"\"")
+ print(" : \": \"\"\"----. .-------. ; ; ; ;:")
+ print(" \\ \'--__ \\ \\ \\ / | ; ;;")
+ print(" \'-.. \"\"\"\"---___ : .______..\\ __/..-\"\"| ; ; ;")
+ print(" \"\"--.. \"\"\"--\" m l s . \". . ;")
+ print(" \"\"------... ..--\"\" \" :")
+ print(" \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \\ /")
+ print(" \"------\"")
+ print("")
+ print(" Drive your simulation properly with SALOME!")
+ print("")
#
# Add the following two methods since logger is not pickable
@@ -618,8 +620,8 @@ Available options are:
if __name__ == "__main__":
if len(sys.argv) == 3:
- context = pickle.loads(sys.argv[1])
- args = pickle.loads(sys.argv[2])
+ context = pickle.loads(sys.argv[1].encode())
+ args = pickle.loads(sys.argv[2].encode())
status = context._startSalome(args)
sys.exit(status)
diff --git a/bin/salomeContextUtils.py.in b/bin/salomeContextUtils.py.in
index c078c96fe..4835bcd25 100644
--- a/bin/salomeContextUtils.py.in
+++ b/bin/salomeContextUtils.py.in
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
# Copyright (C) 2013-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -188,8 +188,8 @@ def getScriptsAndArgs(args=None, searchPathList=None):
extracted_args = []
x = elt.split(",")
# x is ['[file1', 'file2]', 'val1', 'done', '[1', '2', '3]', '[True', 'False]', 'ok']
- list_begin_indices = [i for i in xrange(len(x)) if x[i].startswith('[')] # [0, 4, 7]
- list_end_indices = [i for i in xrange(len(x)) if x[i].endswith(']')] # [1, 6, 8]
+ list_begin_indices = [i for i in range(len(x)) if x[i].startswith('[')] # [0, 4, 7]
+ list_end_indices = [i for i in range(len(x)) if x[i].endswith(']')] # [1, 6, 8]
start = 0
for lbeg, lend in zip(list_begin_indices,list_end_indices): # [(0, 1), (4, 6), (7, 8)]
if lbeg > start:
@@ -221,17 +221,18 @@ def getScriptsAndArgs(args=None, searchPathList=None):
callPython = True
afterArgs = False
else:
+ file_extension = os.path.splitext(elt)[-1]
if not os.path.isfile(elt) and not os.path.isfile(elt+".py"):
eltInSearchPath = __getScriptPath(elt, searchPathList)
if eltInSearchPath is None or (not os.path.isfile(eltInSearchPath) and not os.path.isfile(eltInSearchPath+".py")):
- if elt[-3:] == ".py":
+ if file_extension == ".py":
raise SalomeContextException("Script not found: %s"%elt)
scriptArgs.append(ScriptAndArgs(script=elt))
continue
elt = eltInSearchPath
- if elt[-4:] != ".hdf":
- if elt[-3:] == ".py" or isDriver:
+ if file_extension != ".hdf":
+ if file_extension == ".py" or isDriver:
currentScript = os.path.abspath(elt)
elif os.path.isfile(elt+".py"):
currentScript = os.path.abspath(elt+".py")
@@ -244,6 +245,7 @@ def getScriptsAndArgs(args=None, searchPathList=None):
scriptArgs.append(ScriptAndArgs(script=currentKey))
callPython = False
elif currentScript:
+ script_extension = os.path.splitext(currentScript)[-1]
if isDriver:
currentKey = currentScript
scriptArgs.append(ScriptAndArgs(script=currentKey))
@@ -255,7 +257,7 @@ def getScriptsAndArgs(args=None, searchPathList=None):
ispython = False
try:
fn = open(currentScript)
- for i in xrange(10): # read only 10 first lines
+ for i in range(10): # read only 10 first lines
ln = fn.readline()
if re.search("#!.*python"):
ispython = True
@@ -264,7 +266,7 @@ def getScriptsAndArgs(args=None, searchPathList=None):
fn.close()
except:
pass
- if not ispython and currentScript[-3:] == ".py":
+ if not ispython and script_extension == ".py":
currentKey = "@PYTHONBIN@ "+currentScript
else:
currentKey = currentScript
diff --git a/bin/salome_utils.py b/bin/salome_utils.py
index 4f4936f97..5c2297330 100644
--- a/bin/salome_utils.py
+++ b/bin/salome_utils.py
@@ -56,10 +56,9 @@ def _try_bool( arg ):
are supported.
If does not represent a boolean, an exception is raised.
"""
- import types
- if type( arg ) == types.BooleanType :
+ if isinstance(arg, bool) :
return arg
- elif type( arg ) == types.StringType :
+ elif isinstance(arg, (str, bytes)):
v = str( arg ).lower()
if v in [ "yes", "y", "true" ]: return True
elif v in [ "no", "n", "false" ]: return False
@@ -294,7 +293,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None,
### check unsupported parameters
for kw in kwargs:
if kw not in supported and verbose():
- print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
+ print('Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw)
pass
pass
### process supported keywords
@@ -375,7 +374,7 @@ def generateFileName( dir, prefix = None, suffix = None, extension = None,
# ---
-def makeTmpDir( path, mode=0777 ):
+def makeTmpDir( path, mode=0o777 ):
"""
Make temporary directory with the specified path.
If the directory exists then clear its contents.
@@ -510,12 +509,12 @@ def killpid(pid, sig = 9):
if not pid: return
import os, sys
if sig != 0:
- if verbose(): print "######## killpid pid = ", pid
+ if verbose(): print("######## killpid pid = ", pid)
try:
if sys.platform == "win32":
import ctypes
if sig == 0:
- # PROCESS_QUERY_INFORMATION (0x0400) Required to retrieve certain information about a process
+ # PROCESS_QUERY_INFORMATION (0x0400) Required to retrieve certain information about a process
handle = ctypes.windll.kernel32.OpenProcess(0x0400, False, int(pid))
if handle:
ret = 1
@@ -523,7 +522,7 @@ def killpid(pid, sig = 9):
else:
ret = 0
if sig == 9:
- # PROCESS_TERMINATE (0x0001) Required to terminate a process using TerminateProcess.
+ # PROCESS_TERMINATE (0x0001) Required to terminate a process using TerminateProcess.
handle = ctypes.windll.kernel32.OpenProcess(0x0001, False, int(pid))
ret = ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
@@ -535,7 +534,7 @@ def killpid(pid, sig = 9):
ret = 1
pass
pass
- except OSError, e:
+ except OSError as e:
# errno.ESRCH == 3 is 'No such process'
if e.errno == 3:
ret = 0
diff --git a/bin/searchFreePort.py b/bin/searchFreePort.py
index cdf304eba..85eee9bbb 100755
--- a/bin/searchFreePort.py
+++ b/bin/searchFreePort.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -69,27 +69,27 @@ def searchFreePort_withPortManager(queue, args={}, save_config=1, use_port=None)
port = getPort(use_port)
if use_port:
- print "Check if port can be used: %d" % use_port,
+ print("Check if port can be used: %d" % use_port, end=' ')
if port == use_port and port != -1:
- print "- OK"
+ print("- OK")
__setup_config(use_port, args, save_config)
queue.put([os.environ['OMNIORB_CONFIG'],
os.environ['NSPORT'],
os.environ['NSHOST']])
return
else:
- print "- KO: port is busy"
+ print("- KO: port is busy")
pass
#
- print "Searching for a free port for naming service:",
+ print("Searching for a free port for naming service:", end=' ')
if port == -1: # try again
port = getPort(use_port)
if port != -1:
- print "%s - OK"%(port)
+ print("%s - OK"%(port))
__setup_config(port, args, save_config)
else:
- print "Unable to obtain port"
+ print("Unable to obtain port")
queue.put([os.environ['OMNIORB_CONFIG'],
os.environ['NSPORT'],
@@ -99,7 +99,7 @@ def searchFreePort_withPortManager(queue, args={}, save_config=1, use_port=None)
def __savePortToFile(args):
# Save Naming service port name into
# the file args["ns_port_log_file"]
- if args.has_key('ns_port_log_file'):
+ if 'ns_port_log_file' in args:
omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
file_name = os.path.join(omniorbUserPath, args["ns_port_log_file"])
with open(file_name, "w") as f:
diff --git a/bin/server.py b/bin/server.py
index 75b6b16e0..2712c880e 100755
--- a/bin/server.py
+++ b/bin/server.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -71,7 +71,7 @@ class Server:
+ os.getenv("LD_LIBRARY_PATH")]
myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
command = myargs + self.CMD
- #print "command = ", command
+ # print("command = ", command)
if sys.platform == "win32":
import subprocess
pid = subprocess.Popen(command).pid
@@ -121,12 +121,13 @@ class Server:
pid = os.fork()
if pid > 0:
#send real pid to parent
- os.write(c2pwrite,"%d" % pid)
+ pid_str = "%d" % pid
+ os.write(c2pwrite,pid_str.encode())
os.close(c2pwrite)
# exit from second parent
os._exit(0)
- except OSError, e:
- print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
+ except OSError as e:
+ print("fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
os.write(c2pwrite,"-1")
os.close(c2pwrite)
sys.exit(1)
@@ -136,6 +137,6 @@ class Server:
os.open("/dev/null", os.O_RDWR) # redirect standard input (0) to /dev/null
try:
os.execvp(args[0], args)
- except OSError, e:
- print >>sys.stderr, "(%s) launch failed: %d (%s)" % (args[0],e.errno, e.strerror)
+ except OSError as e:
+ print("(%s) launch failed: %d (%s)" % (args[0],e.errno, e.strerror), file=sys.stderr)
os._exit(127)
diff --git a/bin/setenv.py b/bin/setenv.py
index 242f492cd..e36481da8 100755
--- a/bin/setenv.py
+++ b/bin/setenv.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -43,7 +43,7 @@ def add_path(directory, variable_name):
splitsym = ";"
else:
splitsym = ":"
- if not os.environ.has_key(variable_name):
+ if variable_name not in os.environ:
os.environ[variable_name] = ""
pass
if os.path.exists(directory):
@@ -59,9 +59,8 @@ def add_path(directory, variable_name):
if os.path.abspath(_dir) != os.path.abspath(directory):
newpath.append(_dir)
pass
- import string
newpath[:0] = [ directory ]
- newpath = string.join(newpath, splitsym)
+ newpath = splitsym.join(newpath)
os.environ[variable_name] = newpath
if variable_name == "PYTHONPATH":
sys.path[:0] = [os.path.realpath(directory)]
@@ -89,23 +88,16 @@ def get_config(silent=False, exeName=None):
# read args from launch configure xml file and command line options
- #*** Test additional option
- #*** import optparse
- #*** help_str = "Test options addition."
- #*** o_j = optparse.Option("-j", "--join", action="store_true", dest="join", help=help_str)
import launchConfigureParser
args = launchConfigureParser.get_env(exeName=exeName)
- #*** Test additional option
- #*** args = launchConfigureParser.get_env([o_j])
- #*** if args.has_key("join"): print args["join"]
# Check variables _ROOT_DIR
# and set list of used modules (without KERNEL)
modules_list = []
- if args.has_key("modules"):
+ if "modules" in args:
modules_list += [a for a in args["modules"] if a.strip()]
# KERNEL must be last in the list to locate it at the first place in PATH
if args["gui"] :
@@ -118,14 +110,14 @@ def get_config(silent=False, exeName=None):
to_remove_list=[]
for module in modules_list :
module_variable=module+"_ROOT_DIR"
- if not os.environ.has_key(module_variable):
+ if module_variable not in os.environ:
if not silent:
- print "*******************************************************"
- print "*"
- print "* Environment variable",module_variable,"must be set"
- print "* Module", module, "will be not available"
- print "*"
- print "********************************************************"
+ print("*******************************************************")
+ print("*")
+ print("* Environment variable",module_variable,"must be set")
+ print("* Module", module, "will be not available")
+ print("*")
+ print("********************************************************")
pass
to_remove_list.append(module)
continue
@@ -170,7 +162,7 @@ def set_env(args, modules_list, modules_root_dir, silent=False):
modules_list = modules_list[:] + ["GUI"]
modules_list = modules_list[:] + ["KERNEL"]
for module in modules_list :
- if modules_root_dir.has_key(module):
+ if module in modules_root_dir:
module_root_dir = modules_root_dir[module]
if module_root_dir not in modules_root_dir_list:
modules_root_dir_list[:0] = [module_root_dir]
@@ -185,7 +177,7 @@ def set_env(args, modules_list, modules_root_dir, silent=False):
"LD_LIBRARY_PATH")
add_path(os.path.join(module_root_dir,"bin",salome_subdir),
"PATH")
- if os.path.exists(module_root_dir + "/examples") :
+ if os.path.exists(os.path.join(module_root_dir, "examples")):
add_path(os.path.join(module_root_dir,"examples"),
"PYTHONPATH")
pass
@@ -230,7 +222,7 @@ def set_env(args, modules_list, modules_root_dir, silent=False):
# set trace environment variable
- if not os.environ.has_key("SALOME_trace"):
+ if "SALOME_trace" not in os.environ:
os.environ["SALOME_trace"]="local"
if args['file']:
os.environ["SALOME_trace"]="file:"+args['file'][0]
diff --git a/bin/showNS.py b/bin/showNS.py
index ca54dfcc6..e3b807a25 100755
--- a/bin/showNS.py
+++ b/bin/showNS.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
diff --git a/bin/virtual_salome.py b/bin/virtual_salome.py
index 3d7fbc0f9..120228c4d 100755
--- a/bin/virtual_salome.py
+++ b/bin/virtual_salome.py
@@ -1,4 +1,3 @@
-# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
@@ -20,7 +19,6 @@
#
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-
"""Create a virtual Salome installation
Based on a script created by Ian Bicking.
@@ -32,7 +30,9 @@ Typical use::
install module KERNEL in the current directory
"""
-import sys, os, optparse, shutil,glob,fnmatch
+import sys, os, optparse, shutil, glob, fnmatch
+
+
py_version = 'python%s.%s' % (sys.version_info[0], sys.version_info[1])
verbose=0
@@ -43,11 +43,11 @@ def mkdir(path):
"""Create a directory and all the intermediate directories if path does not exist"""
if not os.path.exists(path):
if verbose:
- print 'Creating %s' % path
+ print('Creating %s' % path)
os.makedirs(path)
else:
if verbose:
- print 'Directory %s already exists' % path
+ print('Directory %s already exists' % path)
pass
pass
@@ -57,15 +57,15 @@ def symlink(src, dest):
"""Create a link if it does not exist"""
if not os.path.exists(dest):
if os.path.lexists(dest):
- print "Do not create symlink %s. It already exists but it's broken" % dest
+ print("Do not create symlink %s. It already exists but it's broken" % dest)
return
if verbose:
- print 'Creating symlink %s' % dest
+ print('Creating symlink %s' % dest)
pass
os.symlink(src, dest)
else:
if verbose:
- print 'Symlink %s already exists' % dest
+ print('Symlink %s already exists' % dest)
pass
pass
@@ -74,11 +74,11 @@ def symlink(src, dest):
def rmtree(dir):
"""Remove (recursive) a directory if it exists"""
if os.path.exists(dir):
- print 'Deleting tree %s' % dir
+ print('Deleting tree %s' % dir)
shutil.rmtree(dir)
else:
if verbose:
- print 'Do not need to delete %s; already gone' % dir
+ print('Do not need to delete %s; already gone' % dir)
pass
pass
pass
@@ -99,12 +99,12 @@ def link_module(options):
global verbose
if not options.module_path:
- print "Option module is mandatory"
+ print("Option module is mandatory")
return
module_dir=os.path.abspath(options.module_path)
if not os.path.exists(module_dir):
- print "Module %s does not exist" % module_dir
+ print("Module %s does not exist" % module_dir)
return
verbose = options.verbose
@@ -127,7 +127,7 @@ def link_module(options):
pyversio=versio
else:
#incompatible python versions
- print "incompatible python versions : application has version %s and module %s has not" % (versio,module_dir)
+ print("incompatible python versions : application has version %s and module %s has not" % (versio,module_dir))
return
module_bin_dir=os.path.join(module_dir,'bin','salome')
@@ -188,20 +188,21 @@ def link_module(options):
pass
else:
if verbose:
- print module_bin_dir, " doesn't exist"
+ print(module_bin_dir, " doesn't exist")
pass
#directory bin/salome/test : create it and link content
if os.path.exists(module_test_dir):
# link /bin/salome/test/ to /bin/salome/test
- print "link %s --> %s"%(os.path.join(test_dir, options.module_name), module_test_dir)
+ print("link %s --> %s"%(os.path.join(test_dir, options.module_name), module_test_dir))
symlink(module_test_dir, os.path.join(test_dir, options.module_name))
# register module for testing in CTestTestfile.cmake
with open(os.path.join(test_dir, "CTestTestfile.cmake"), "ab") as f:
- f.write("SUBDIRS(%s)\n"%options.module_name)
+ aStr = "SUBDIRS(%s)\n"%options.module_name
+ f.write(aStr.encode())
else:
if verbose:
- print module_test_dir, " doesn't exist"
+ print(module_test_dir, " doesn't exist")
pass
#directory idl/salome : create it and link content
@@ -211,7 +212,7 @@ def link_module(options):
symlink(os.path.join(module_idl_dir, fn), os.path.join(idl_dir, fn))
else:
if verbose:
- print module_idl_dir, " doesn't exist"
+ print(module_idl_dir, " doesn't exist")
#directory lib/salome : create it and link content
if os.path.exists(module_lib_dir):
@@ -222,7 +223,7 @@ def link_module(options):
pass
else:
if verbose:
- print module_lib_dir, " doesn't exist"
+ print(module_lib_dir, " doesn't exist")
pass
#directory lib/paraview : create it and link content
@@ -234,12 +235,12 @@ def link_module(options):
pass
else:
if verbose:
- print module_pvlib_dir, " doesn't exist"
+ print(module_pvlib_dir, " doesn't exist")
pass
#directory lib/pyversio/site-packages/salome : create it and link content
if not os.path.exists(module_lib_py_dir):
- print "Python directory %s does not exist" % module_lib_py_dir
+ print("Python directory %s does not exist" % module_lib_py_dir)
else:
# Specific action for the package salome
module_lib_pypkg_dir=os.path.join(module_lib_py_dir,"salome")
@@ -262,7 +263,7 @@ def link_module(options):
pass
else:
if verbose:
- print module_lib_py_shared_dir, " doesn't exist"
+ print(module_lib_py_shared_dir, " doesn't exist")
pass
#directory share/doc/salome (KERNEL doc) : create it and link content
@@ -322,7 +323,7 @@ def link_module(options):
#other directories (not resources)
symlink(os.path.join(module_share_dir, fn), os.path.join(share_dir, fn))
else:
- print "share/salome directory %s does not exist" % module_share_dir
+ print("share/salome directory %s does not exist" % module_share_dir)
pass
#html files in doc/salome directory
@@ -355,12 +356,12 @@ def link_extra_test(options):
global verbose
if not options.extra_test_path:
- print "Option extra_test is mandatory"
+ print("Option extra_test is mandatory")
return
extra_test_dir=os.path.abspath(options.extra_test_path)
if not os.path.exists(extra_test_dir):
- print "Test %s does not exist" % extra_test_dir
+ print("Test %s does not exist" % extra_test_dir)
return
verbose = options.verbose
@@ -375,14 +376,15 @@ def link_extra_test(options):
#directory bin/salome/test : create it and link content
if os.path.exists(extra_test_dir):
# link /bin/salome/test/ to /bin/salome/test
- print "link %s --> %s"%(os.path.join(test_dir, options.extra_test_name), extra_test_dir)
+ print("link %s --> %s"%(os.path.join(test_dir, options.extra_test_name), extra_test_dir))
symlink(extra_test_dir, os.path.join(test_dir, options.extra_test_name))
# register extra_test for testing in CTestTestfile.cmake
with open(os.path.join(test_dir, "CTestTestfile.cmake"), "ab") as f:
- f.write("SUBDIRS(%s)\n"%options.extra_test_name)
+ aStr = "SUBDIRS(%s)\n" % options.extra_test_name
+ f.write(aStr.encode())
else:
if verbose:
- print extra_test_dir, " doesn't exist"
+ print(extra_test_dir, " doesn't exist")
pass
# -----------------------------------------------------------------------------
diff --git a/bin/waitContainers.py b/bin/waitContainers.py
index 6bc37fa43..8b2e655b5 100755
--- a/bin/waitContainers.py
+++ b/bin/waitContainers.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
@@ -43,11 +43,11 @@ while(1):
try:
ccontext = rootContext.resolve(cname)
break
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
time.sleep(1)
- except CosNaming.NamingContext.InvalidName, ex:
+ except CosNaming.NamingContext.InvalidName as ex:
time.sleep(1)
- except CosNaming.NamingContext.CannotProceed, ex:
+ except CosNaming.NamingContext.CannotProceed as ex:
time.sleep(1)
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
time.sleep(1)
@@ -68,7 +68,7 @@ def waitContainer(mycont):
while(ok):
for s in bb.binding_name :
if s.id == mycont:
- print s.id
+ print(s.id)
return
ok,bb=bii.next_one()
ok,b=bi.next_one()
diff --git a/bin/waitNS.py b/bin/waitNS.py
index 1c386b511..4005f6714 100755
--- a/bin/waitNS.py
+++ b/bin/waitNS.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
diff --git a/doc/salome/examples/example1 b/doc/salome/examples/example1
index eae882cae..9300f476e 100644
--- a/doc/salome/examples/example1
+++ b/doc/salome/examples/example1
@@ -19,10 +19,10 @@ file = str+"/test.hdf"
#file = "/tmp/ggg.hdf"
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy=batchmode_geompy.myStudyManager.Open(file)
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy=batchmode_geompy.myStudy.Open(file)
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
diff --git a/doc/salome/examples/example10 b/doc/salome/examples/example10
index 756e4a3f1..3c2345d9c 100644
--- a/doc/salome/examples/example10
+++ b/doc/salome/examples/example10
@@ -22,8 +22,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy = batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy = batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
diff --git a/doc/salome/examples/example11 b/doc/salome/examples/example11
index 4cfd732fd..99dac3761 100644
--- a/doc/salome/examples/example11
+++ b/doc/salome/examples/example11
@@ -22,8 +22,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy=batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy=batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
diff --git a/doc/salome/examples/example12 b/doc/salome/examples/example12
index 760587736..3394d8b86 100644
--- a/doc/salome/examples/example12
+++ b/doc/salome/examples/example12
@@ -19,7 +19,7 @@ A.SetTextColor(color)
c = A.TextColor();
if c.R != 234 or c.G != 345 or c.B != 231:
- print "Error: wrong value of AttributeTextColor"
+ print("Error: wrong value of AttributeTextColor")
# save / restore study
#============================================================
@@ -28,8 +28,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy = batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy = batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -53,5 +53,5 @@ if A == None :
c = A.TextColor();
if c.R != 234 or c.G != 345 or c.B != 231:
- print "Error: wrong value of AttributeTextColor"
+ print("Error: wrong value of AttributeTextColor")
diff --git a/doc/salome/examples/example13 b/doc/salome/examples/example13
index c05aaff52..6c16c96f0 100644
--- a/doc/salome/examples/example13
+++ b/doc/salome/examples/example13
@@ -19,7 +19,7 @@ A.SetTextHighlightColor(highlightcolor)
c = A.TextHighlightColor();
if c.R != 256 or c.G != 256 or c.B != 256:
- print "Error: wrong value of AttributeTextHighlightColor"
+ print("Error: wrong value of AttributeTextHighlightColor")
# save / restore study
@@ -29,8 +29,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy=batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy=batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -44,7 +44,7 @@ if father is None:
#============================================================
res, A = father.FindAttribute("AttributeTextHighlightColor")
-print res, A
+print(res, A)
if res == 0 or A == None:
raise RuntimeError, "Error: not found AttributeTextHighlightColor"
@@ -56,5 +56,5 @@ if A == None :
c = A.TextHighlightColor();
if c.R != 256 or c.G != 256 or c.B != 256:
- print "Error: wrong value of AttributeTextTextHighlightColor"
+ print("Error: wrong value of AttributeTextTextHighlightColor")
diff --git a/doc/salome/examples/example14 b/doc/salome/examples/example14
index a0acf346d..643891394 100644
--- a/doc/salome/examples/example14
+++ b/doc/salome/examples/example14
@@ -9,7 +9,7 @@ aPixmap = A._narrow(SALOMEDS.AttributePixMap);
aPixmap.SetPixMap( "ICON_OBJBROWSER_Geometry" );
if aPixmap.GetPixMap() != "ICON_OBJBROWSER_Geometry":
- print "Error: wrong value of AttributePixMap"
+ print("Error: wrong value of AttributePixMap")
# save / restore study
@@ -19,8 +19,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy = batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy = batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -43,5 +43,5 @@ if A == None :
raise RuntimeError, "Can't create AttributePixMap attribute"
if A.GetPixMap() != "ICON_OBJBROWSER_Geometry":
- print "Error: wrong value of AttributePixMap"
+ print("Error: wrong value of AttributePixMap")
diff --git a/doc/salome/examples/example15 b/doc/salome/examples/example15
index 42493fe01..6494b849d 100644
--- a/doc/salome/examples/example15
+++ b/doc/salome/examples/example15
@@ -9,7 +9,7 @@ A = A._narrow(SALOMEDS.AttributeLocalID)
A.SetValue(763242882)
if A.Value() != 763242882:
- print "Error: wrong value of AttributeLocalID"
+ print("Error: wrong value of AttributeLocalID")
# save / restore study
#=================================
@@ -18,8 +18,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy = batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy = batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -39,5 +39,5 @@ if res == 0 or A == None:
A = A._narrow(SALOMEDS.AttributeLocalID)
if A.Value() != 763242882:
- print "Error: wrong value of AttributeLocalID"
+ print("Error: wrong value of AttributeLocalID")
diff --git a/doc/salome/examples/example16 b/doc/salome/examples/example16
index 3be50d9b6..b5694d661 100644
--- a/doc/salome/examples/example16
+++ b/doc/salome/examples/example16
@@ -21,7 +21,7 @@ A.Add(300)
A.Add(500)
A.Add(400)
A.Add(700)
-print "First transaction goes on : HasOpenCommand() = ", batchmode_geompy.myBuilder.HasOpenCommand()
+print("First transaction goes on : HasOpenCommand() = ", batchmode_geompy.myBuilder.HasOpenCommand())
batchmode_geompy.myBuilder.CommitCommand() #--------------
# 2nd transaction ------------------------------------------
@@ -34,12 +34,12 @@ if batchmode_geompy.myBuilder.GetAvailableUndos() == 0:
raise RuntimeError, "GetAvailableUndos() = 0 but must not !"
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 500:
raise RuntimeError, "Wrong value of AttributeSequenceOfInteger"
file1 = dir + "/test1.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file1, batchmode_geompy.myStudy)
+batchmode_geompy.myStudy.SaveAs(file1)
# 1st Undo ---------------------------------------
batchmode_geompy.myBuilder.Undo()
@@ -47,13 +47,13 @@ res, A = batchmode_geompy.myBuilder.FindAttribute(batchmode_geompy.father, "Attr
if A is None:
raise RuntimeError, "After first 'undo' can't find AttributeSequenceOfInteger"
if A.Length() != 5:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 500 or A.Value(4) != 400 or A.Value(5) != 700:
- print A.Value(1), A.Value(2), A.Value(3), A.Value(4), A.Value(5)
+ print( A.Value(1), A.Value(2), A.Value(3), A.Value(4), A.Value(5))
raise RuntimeError, "Wrong value of AttributeSequenceOfInteger after the first 'undo'!"
# save
file2 = dir + "/test2.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file2, batchmode_geompy.myStudy)
+batchmode_geompy.myStudy.SaveAs(file2)
#-------------------------------------------------
# 2nd Undo ---------------------------------------
batchmode_geompy.myBuilder.Undo()
@@ -61,7 +61,7 @@ res, attr = batchmode_geompy.myBuilder.FindAttribute(batchmode_geompy.father, "A
if res !=0 or attr != None :
raise RuntimeError, "After the second 'undo' AttributeSequenceOfInteger exists but must not!"
file3 = dir + "/test3.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file3, batchmode_geompy.myStudy)
+batchmode_geompy.myStudy.SaveAs(file3)
#-------------------------------------------------
#make redo twice ---------------------------------
@@ -73,13 +73,13 @@ res, A = batchmode_geompy.myBuilder.FindAttribute(batchmode_geompy.father, "Attr
if res ==0 or A== None :
raise RuntimeError, "AttributeSequenceOfInteger is not found but must be!"
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 500:
raise RuntimeError, "Wrong value of AttributeSequenceOfInteger"
#----------------------------------------------------------------------
-openedStudy=batchmode_geompy.myStudyManager.Open(file1);
+openedStudy=batchmode_geompy.myStudy.Open(file1);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -100,11 +100,11 @@ if res == 0 or A == None:
A = A._narrow(SALOMEDS.AttributeSequenceOfInteger)
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 500:
- print "Wrong value of AttributeSequenceOfInteger"
+ print("Wrong value of AttributeSequenceOfInteger")
#----------------------------------------------------------------------
-openedStudy=batchmode_geompy.myStudyManager.Open(file2);
+openedStudy=batchmode_geompy.myStudy.Open(file2);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -125,12 +125,12 @@ if res == 0 or A == None:
A = A._narrow(SALOMEDS.AttributeSequenceOfInteger)
if A.Length() != 5:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 500 or A.Value(4) != 400 or A.Value(5) != 700:
raise RuntimeError, "Wrong value of AttributeSequenceOfInteger after the first 'undo'!"
#----------------------------------------------------------------------
-openedStudy=batchmode_geompy.myStudyManager.Open(file3);
+openedStudy=batchmode_geompy.myStudy.Open(file3);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
diff --git a/doc/salome/examples/example17 b/doc/salome/examples/example17
index 2c3e6b819..2ffd4ee03 100644
--- a/doc/salome/examples/example17
+++ b/doc/salome/examples/example17
@@ -51,7 +51,7 @@ if A == None :
A.SetValue("AttributesTesting")
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
batchmode_geompy.myBuilder.CommitCommand()
@@ -130,11 +130,11 @@ batchmode_geompy.myBuilder.CommitCommand()
#===========================================================
res, A = batchmode_geompy.myBuilder.FindAttribute(child, "AttributeComment")
-print "res = ", res
+print("res = ", res)
if A != None :
- print " AttributeComment was found"
+ print(" AttributeComment was found")
else:
- print " AttributeComment is not found. It's correct"
+ print(" AttributeComment is not found. It's correct")
attributes=[]
@@ -142,12 +142,12 @@ attributes = child.GetAllAttributes()
length = len(attributes)
-print "Attributes number = ", length
-print attributes
+print("Attributes number = ", length)
+print(attributes)
for i in range(0, length) :
attr = attributes[i]
if attr is None :
- print i,"None item of object attributes list"
+ print(i,"None item of object attributes list")
if length != 5 :
raise RuntimeError, "Wrong number of attributes"
diff --git a/doc/salome/examples/example18 b/doc/salome/examples/example18
index 477f8b2b6..b2423ab89 100644
--- a/doc/salome/examples/example18
+++ b/doc/salome/examples/example18
@@ -135,29 +135,29 @@ N32.SetFather(N3)
N32.Prepend(N31)
N33.InsertAfter(N32)
N33.Append(N34)
-print "------------- ", N1, " ------------- "
-print "N1.Label() = ", N1.Label() , "IsRoot() = ", N1.IsRoot(), "Depth() = ", N1.Depth()
-print "N11.Label() = ", N11.Label() , "IsRoot() = ", N11.IsRoot(), "Depth() = ", N11.Depth()
-print "N111.Label() = ", N111.Label() , "IsRoot() = ", N111.IsRoot(), "Depth() = ", N111.Depth()
-print "N2.Label() = ", N2.Label() , "IsRoot() = ", N2.IsRoot(), "Depth() = ", N2.Depth()
-print "N3.Label() = ", N3.Label() , "IsRoot() = ", N3.IsRoot(), "Depth() = ", N3.Depth()
-print "N31.Label() = ", N31.Label() , "IsRoot() = ", N31.IsRoot(), "Depth() = ", N31.Depth()
-print "N32.Label() = ", N32.Label() , "IsRoot() = ", N32.IsRoot(), "Depth() = ", N32.Depth()
-print "N321.Label() = ", N321.Label() , "IsRoot() = ", N321.IsRoot(), "Depth() = ", N321.Depth()
-print "N33.Label() = ", N33.Label() , "IsRoot() = ", N33.IsRoot(), "Depth() = ", N33.Depth()
-print "N34.Label() = ", N34.Label() , "IsRoot() = ", N34.IsRoot(), "Depth() = ", N34.Depth()
-print "N1.IsRoot()=", N1.IsRoot()
-
-print "N1.HasNext() = ",N1.HasNext()
+print("------------- ", N1, " ------------- ")
+print("N1.Label() = ", N1.Label() , "IsRoot() = ", N1.IsRoot(), "Depth() = ", N1.Depth())
+print("N11.Label() = ", N11.Label() , "IsRoot() = ", N11.IsRoot(), "Depth() = ", N11.Depth())
+print("N111.Label() = ", N111.Label() , "IsRoot() = ", N111.IsRoot(), "Depth() = ", N111.Depth())
+print("N2.Label() = ", N2.Label() , "IsRoot() = ", N2.IsRoot(), "Depth() = ", N2.Depth())
+print("N3.Label() = ", N3.Label() , "IsRoot() = ", N3.IsRoot(), "Depth() = ", N3.Depth())
+print("N31.Label() = ", N31.Label() , "IsRoot() = ", N31.IsRoot(), "Depth() = ", N31.Depth())
+print("N32.Label() = ", N32.Label() , "IsRoot() = ", N32.IsRoot(), "Depth() = ", N32.Depth())
+print("N321.Label() = ", N321.Label() , "IsRoot() = ", N321.IsRoot(), "Depth() = ", N321.Depth())
+print("N33.Label() = ", N33.Label() , "IsRoot() = ", N33.IsRoot(), "Depth() = ", N33.Depth())
+print("N34.Label() = ", N34.Label() , "IsRoot() = ", N34.IsRoot(), "Depth() = ", N34.Depth())
+print("N1.IsRoot()=", N1.IsRoot())
+
+print("N1.HasNext() = ",N1.HasNext())
if N1.HasNext():
- print N1.Next().Label()
+ print(N1.Next().Label())
-print "N32.HasPrevious() = ",N32.HasPrevious()
+print("N32.HasPrevious() = ",N32.HasPrevious())
if N32.HasPrevious():
- print N32.GetPrevious().Label()
+ print(N32.GetPrevious().Label())
-print "N111.HasFirst()=",N111.HasFirst()
-print "N111.HasFather()=",N111.HasFather()
+print("N111.HasFirst()=",N111.HasFirst())
+print("N111.HasFather()=",N111.HasFather())
if N111.HasFather() :
- print "N111.GetFather().Label()=",N111.GetFather().Label()
+ print("N111.GetFather().Label()=",N111.GetFather().Label())
diff --git a/doc/salome/examples/example19 b/doc/salome/examples/example19
index 19bd49ec0..45785ad4c 100644
--- a/doc/salome/examples/example19
+++ b/doc/salome/examples/example19
@@ -36,7 +36,7 @@ ShapeType = batchmode_smesh.ShapeType
subShapeList = batchmode_geompy.SubShapeAll(box,ShapeType["Face"])
face=subShapeList[0]
name = "box_face"
-print name
+print(name)
idface= batchmode_geompy.addToStudyInFather(box,face,name)
# ---- add shell from box in study
@@ -44,7 +44,7 @@ idface= batchmode_geompy.addToStudyInFather(box,face,name)
subShellList= batchmode_geompy.SubShapeAll(box,ShapeType["Shell"])
shell = subShellList[0]
name = "box_shell"
-print name
+print(name)
idshell= batchmode_geompy.addToStudyInFather(box,shell,name)
# ---- add first edge of face in study
@@ -52,7 +52,7 @@ idshell= batchmode_geompy.addToStudyInFather(box,shell,name)
edgeList = batchmode_geompy.SubShapeAll(face,ShapeType["Edge"])
edge=edgeList[0];
name = "face_edge"
-print name
+print(name)
idedge= batchmode_geompy.addToStudyInFather(face,edge,name)
# ---- launch SMESH, init a Mesh with the box
@@ -60,7 +60,7 @@ idedge= batchmode_geompy.addToStudyInFather(face,edge,name)
smesh = batchmode_smesh.smesh
# -- Init --
shape = batchmode_geompy.IDToObject(idbox)
-mesh=smesh.Init(geom, batchmode_geompy.myStudyId, shape)
+mesh=smesh.Init(geom, shape)
orb = batchmode_geompy.orb
@@ -70,73 +70,73 @@ batchmode_smesh.SetShape(idbox, idmesh);
# ---- create Hypothesis
-print "-------------------------- create Hypothesis ----------------------"
-print "-------------------------- LocalLength"
-hyp1 = smesh.CreateHypothesis("LocalLength", batchmode_geompy.myStudyId )
+print("-------------------------- create Hypothesis ----------------------")
+print("-------------------------- LocalLength")
+hyp1 = smesh.CreateHypothesis("LocalLength")
hypLen1 = hyp1._narrow(SMESH.SMESH_LocalLength)
hypLen1.SetLength(100)
-print hypLen1.GetName()
-print hypLen1.GetId()
-print hypLen1.GetLength()
+print(hypLen1.GetName())
+print(hypLen1.GetId())
+print(hypLen1.GetLength())
idlength = batchmode_smesh.AddNewHypothesis( orb.object_to_string(hypLen1) );
batchmode_smesh.SetName(idlength, "Local_Length_100");
-print "-------------------------- NumberOfSegments"
-hyp2 = smesh.CreateHypothesis("NumberOfSegments", batchmode_geompy.myStudyId )
+print("-------------------------- NumberOfSegments")
+hyp2 = smesh.CreateHypothesis("NumberOfSegments")
hypNbSeg1=hyp2._narrow(SMESH.SMESH_NumberOfSegments)
hypNbSeg1.SetNumberOfSegments(7)
-print hypNbSeg1.GetName()
-print hypNbSeg1.GetId()
-print hypNbSeg1.GetNumberOfSegments()
+print(hypNbSeg1.GetName())
+print(hypNbSeg1.GetId())
+print(hypNbSeg1.GetNumberOfSegments())
idseg = batchmode_smesh.AddNewHypothesis( orb.object_to_string(hypNbSeg1) );
batchmode_smesh.SetName(idseg, "NumberOfSegments_7");
-print "-------------------------- MaxElementArea"
-hyp3 = smesh.CreateHypothesis("MaxElementArea", batchmode_geompy.myStudyId)
+print("-------------------------- MaxElementArea")
+hyp3 = smesh.CreateHypothesis("MaxElementArea")
hypArea1=hyp3._narrow(SMESH.SMESH_MaxElementArea)
hypArea1.SetMaxElementArea(2500)
-print hypArea1.GetName()
-print hypArea1.GetId()
-print hypArea1.GetMaxElementArea()
+print(hypArea1.GetName())
+print(hypArea1.GetId())
+print(hypArea1.GetMaxElementArea())
idarea1 = batchmode_smesh.AddNewHypothesis( orb.object_to_string(hypArea1) );
batchmode_smesh.SetName(idarea1, "MaxElementArea_2500");
-print "-------------------------- MaxElementArea"
-hyp3 = smesh.CreateHypothesis("MaxElementArea", batchmode_geompy.myStudyId)
+print("-------------------------- MaxElementArea")
+hyp3 = smesh.CreateHypothesis("MaxElementArea")
hypArea2 = hyp3._narrow(SMESH.SMESH_MaxElementArea)
hypArea2.SetMaxElementArea(500)
-print hypArea2.GetName()
-print hypArea2.GetId()
-print hypArea2.GetMaxElementArea()
+print(hypArea2.GetName())
+print(hypArea2.GetId())
+print(hypArea2.GetMaxElementArea())
idarea2 = batchmode_smesh.AddNewHypothesis( orb.object_to_string(hypArea2) );
batchmode_smesh.SetName(idarea2, "MaxElementArea_500");
-print "-------------------------- Regular_1D"
-alg1 = smesh.CreateHypothesis("Regular_1D", batchmode_geompy.myStudyId)
+print("-------------------------- Regular_1D")
+alg1 = smesh.CreateHypothesis("Regular_1D")
algo1 = alg1._narrow(SMESH.SMESH_Algo)
listHyp = algo1.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
+ print(hyp)
algoReg=alg1._narrow(SMESH.SMESH_Regular_1D)
-print algoReg.GetName()
-print algoReg.GetId()
+print(algoReg.GetName())
+print(algoReg.GetId())
idreg = batchmode_smesh.AddNewAlgorithms( orb.object_to_string(algoReg) );
batchmode_smesh.SetName(idreg, "Regular_1D");
-print "-------------------------- MEFISTO_2D"
-alg2 = smesh.CreateHypothesis("MEFISTO_2D", batchmode_geompy.myStudyId)
+print("-------------------------- MEFISTO_2D")
+alg2 = smesh.CreateHypothesis("MEFISTO_2D")
algo2 = alg2._narrow(SMESH.SMESH_Algo)
listHyp=algo2.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
+ print(hyp)
algoMef=alg2._narrow(SMESH.SMESH_MEFISTO_2D)
-print algoMef.GetName()
-print algoMef.GetId()
+print(algoMef.GetName())
+print(algoMef.GetId())
idmef = batchmode_smesh.AddNewAlgorithms( orb.object_to_string(algoMef) );
batchmode_smesh.SetName(idmef, "MEFISTO_2D");
@@ -144,13 +144,13 @@ batchmode_smesh.SetName(idmef, "MEFISTO_2D");
# ---- add hypothesis to edge
-print "-------------------------- add hypothesis to edge"
+print("-------------------------- add hypothesis to edge")
edge = batchmode_geompy.IDToObject(idedge)
submesh = mesh.GetElementsOnShape(edge)
ret = mesh.AddHypothesis(edge,algoReg)
-print ret
+print(ret)
ret=mesh.AddHypothesis(edge,hypLen1)
-print ret
+print(ret)
idsm1 = batchmode_smesh.AddSubMeshOnShape( idmesh,
idedge,
@@ -160,11 +160,11 @@ batchmode_smesh.SetName(idsm1, "SubMeshEdge")
batchmode_smesh.SetAlgorithms( idsm1, idreg );
batchmode_smesh.SetHypothesis( idsm1, idlength );
-print "-------------------------- add hypothesis to face"
+print("-------------------------- add hypothesis to face")
face=batchmode_geompy.IDToObject(idface)
submesh=mesh.GetElementsOnShape(face)
ret=mesh.AddHypothesis(face,hypArea2)
-print ret
+print(ret)
idsm2 = batchmode_smesh.AddSubMeshOnShape( idmesh,
idface,
@@ -175,17 +175,17 @@ batchmode_smesh.SetHypothesis( idsm2, idarea2 );
# ---- add hypothesis to box
-print "-------------------------- add hypothesis to box"
+print("-------------------------- add hypothesis to box")
box=batchmode_geompy.IDToObject(idbox)
submesh=mesh.GetElementsOnShape(box)
ret=mesh.AddHypothesis(box,algoReg)
-print ret
+print(ret)
ret=mesh.AddHypothesis(box,hypNbSeg1)
-print ret
+print(ret)
ret=mesh.AddHypothesis(box,algoMef)
-print ret
+print(ret)
ret=mesh.AddHypothesis(box,hypArea1)
-print ret
+print(ret)
batchmode_smesh.SetAlgorithms( idmesh, idreg );
batchmode_smesh.SetHypothesis( idmesh, idseg );
@@ -194,12 +194,12 @@ batchmode_smesh.SetHypothesis( idmesh, idarea1 );
# ---- compute box
-print "-------------------------- compute box"
+print("-------------------------- compute box")
ret=smesh.Compute(mesh,box)
-print ret
+print(ret)
log=mesh.GetLog(0); # no erase trace
for linelog in log:
- print linelog
+ print(linelog)
#=======================================================
@@ -212,12 +212,12 @@ dir= os.getenv("SUPERV_ROOT_DIR")
if dir == None:
raise RuntimeError, "SUPERV_ROOT_DIR is not defined"
xmlfile = dir +"/examples/GraphEssai.xml"
-print "--------------\n"+xmlfile+"\n--------------\n"
+print("--------------\n"+xmlfile+"\n--------------\n")
myGraph = Graph ( xmlfile )
# This DataFlow is "valid" : no loop, correct links between Nodes etc...
-print myGraph.IsValid()
+print(myGraph.IsValid())
# Get Nodes
myGraph.PrintNodes()
@@ -235,61 +235,61 @@ Mulz = Mul.Port('z')
Divz = Div.Port('z')
# This DataFlow is "executable" : all pending Ports are defined with Datas
-print myGraph.IsExecutable()
+print(myGraph.IsExecutable())
# Starts only execution of that DataFlow and gets control immediately
-print myGraph.Run()
+print(myGraph.Run())
# That DataFlow is running ==> 0 (false)
-print myGraph.IsDone()
+print(myGraph.IsDone())
# Events of execution :
aStatus,aNode,anEvent,aState = myGraph.Event()
while aStatus :
- print aNode.Thread(),aNode.SubGraph(),aNode.Name(),anEvent,aState
+ print(aNode.Thread(),aNode.SubGraph(),aNode.Name(),anEvent,aState)
aStatus,aNode,anEvent,aState = myGraph.Event()
-print myGraph.IsDone()
+print(myGraph.IsDone())
# Wait for Completion (but it is already done after event loop ...)
-print "Done : ",myGraph.DoneW()
+print("Done : ",myGraph.DoneW())
# Get result
-print "Result : ",Divz.ToString()
+print("Result : ",Divz.ToString())
# Intermediate results :
-print "Intermediate Result Add\z : ",Addz.ToString()
-print "Intermediate Result Sub\z : ",Subz.ToString()
-print "Intermediate Result Mul\z : ",Mulz.ToString()
+print("Intermediate Result Add\z : ",Addz.ToString())
+print("Intermediate Result Sub\z : ",Subz.ToString())
+print("Intermediate Result Mul\z : ",Mulz.ToString())
-print " "
-#print "Type : print myGraph.IsDone()"
-#print " If execution is finished ==> 1 (true)"
+print(" ")
+#print("Type : print(myGraph.IsDone()")
+#print(" If execution is finished ==> 1 (true)")
res=myGraph.IsDone()
if res != 1:
raise RuntimeError, "myGraph.Run() is not done"
-print " "
-print "Type : print Divz.ToString()"
-print " You will get the result"
+print(" ")
+print("Type : print(Divz.ToString()")
+print(" You will get the result")
Divz.ToString()
-print " "
-print "Type : myGraph.PrintPorts()"
-print " to see input and output values of the graph"
+print(" ")
+print("Type : myGraph.PrintPorts()")
+print(" to see input and output values of the graph")
myGraph.PrintPorts()
-print " "
-print "Type : Add.PrintPorts()"
+print(" ")
+print("Type : Add.PrintPorts()")
Add.PrintPorts()
-print "Type : Sub.PrintPorts()"
+print("Type : Sub.PrintPorts()")
Sub.PrintPorts()
-print "Type : Mul.PrintPorts()"
+print("Type : Mul.PrintPorts()")
Mul.PrintPorts()
-print "Type : Div.PrintPorts()"
-print " to see input and output values of nodes"
+print("Type : Div.PrintPorts()")
+print(" to see input and output values of nodes")
Div.PrintPorts()
# Export will create newsupervisionexample.xml and the corresponding .py file
@@ -297,21 +297,21 @@ tmpdir=os.getenv("TmpDir")
if tmpdir is None:
tmpdir="/tmp"
file = tmpdir + "/newsupervisionexample"
-print "--------------\n"+file+"\n--------------\n"
+print("--------------\n"+file+"\n--------------\n")
myGraph.Export(file)
ior = batchmode_geompy.orb.object_to_string(myGraph.G)
addStudy(ior)
GraphName = myGraph.Name()
-print "Before save ",
+print("Before save ",)
nodes = myGraph.Nodes()
length_bs = len(nodes)
-print "ListOfNodes length = ", length_bs
+print("ListOfNodes length = ", length_bs)
names=[]
for node in nodes:
names.append(node.Name())
-print names
+print(names)
#=================================
@@ -326,26 +326,26 @@ file = str+"/test.hdf"
#==================================================
#1. SaveAs
#==================================================
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-batchmode_geompy.myStudyManager.Close(batchmode_geompy.myStudy)
+batchmode_geompy.myStudy.SaveAs(file)
+batchmode_geompy.myStudy.Clear()
#rename the file and try to reread it again
os.mkdir(str + "/test_dir")
#2.==================================================
-print " ------- We rename the file as " + str + "/test_dir/test_new.hdf"
+print(" ------- We rename the file as " + str + "/test_dir/test_new.hdf")
os.rename(file, str+"/test_dir/test_new.hdf")
#==================================================
#3. Open
#==================================================
-print " ------- We try to open " + str + "/test_dir/test_new.hdf"
+print(" ------- We try to open " + str + "/test_dir/test_new.hdf")
try:
- openedStudy=batchmode_geompy.myStudyManager.Open(str+"/test_dir/test_new.hdf")
+ openedStudy=batchmode_geompy.myStudy.Open(str+"/test_dir/test_new.hdf")
except Exception:
raise RuntimeError, "Can't open saved study!"
@@ -417,7 +417,7 @@ aChildIterator = openedStudy.NewChildIterator(father)
#while aChildIterator.More():
anSObject = aChildIterator.Value()
-#print "iterate: ", anSObject.GetID()
+#print("iterate: ", anSObject.GetID())
res, anAttr=anSObject.FindAttribute("AttributeIOR")
if res :
anAttr=anAttr._narrow(SALOMEDS.AttributeIOR)
@@ -425,7 +425,7 @@ if res :
Graph=SuperV.getGraph(ior)
ListOfNodes=Graph.Nodes()
length_as= len(ListOfNodes)
- print "ListOfNodes length = ", length_as
+ print("ListOfNodes length = ", length_as)
if length_as != length_bs:
raise RuntimeErrror, "different length of nodes after study open"
#aChildIterator.Next()
@@ -441,13 +441,13 @@ if names != Names :
#==================================================
#4. Save
#==================================================
-batchmode_geompy.myStudyManager.Save(openedStudy)
-batchmode_geompy.myStudyManager.Close(openedStudy)
+batchmode_geompy.myStudy.Save()
+batchmode_geompy.myStudy.Clear()
#==================================================
#5. Open
#==================================================
try:
- openedStudy = batchmode_geompy.myStudyManager.Open(str+"/test_dir/test_new.hdf")
+ openedStudy = batchmode_geompy.myStudy.Open(str+"/test_dir/test_new.hdf")
except Exception:
raise RuntimeError, "Can't open saved study!"
@@ -525,7 +525,7 @@ if res :
Graph=SuperV.getGraph(ior)
ListOfNodes=Graph.Nodes()
length_as= len(ListOfNodes)
- print "ListOfNodes length = ", length_as
+ print("ListOfNodes length = ", length_as)
if length_as != length_bs:
raise RuntimeErrror, "different length of nodes after study open"
#aChildIterator.Next()
diff --git a/doc/salome/examples/example20 b/doc/salome/examples/example20
index 9326da115..6b7731d99 100644
--- a/doc/salome/examples/example20
+++ b/doc/salome/examples/example20
@@ -20,22 +20,22 @@ if A == None :
A = A._narrow(SALOMEDS.AttributeStudyProperties)
batchmode_geompy.myBuilder.NewCommand();
-print "A.GetUserName()= ", A.GetUserName()
+print("A.GetUserName()= ", A.GetUserName())
res,mm,hh,dd,mnth,yy=A.GetCreationDate()
-print "A.GetCreationDate() = ", mm,hh,dd,mnth,yy
-print "A.GetCreationMode() = ", A.GetCreationMode()
-print "A.IsModified() = ", A.IsModified()
-print "A.IsLocked() = ", A.IsLocked()
+print("A.GetCreationDate() = ", mm,hh,dd,mnth,yy)
+print("A.GetCreationMode() = ", A.GetCreationMode())
+print("A.IsModified() = ", A.IsModified())
+print("A.IsLocked() = ", A.IsLocked())
if A.IsLocked() == 0 :
- A.SetUserName("tester"); print 'A.SetUserName("tester"), A.GetUserName() = ', A.GetUserName()
- A.SetCreationDate(11,11,11,11,2002); print 'A.SetCreationDate(11,11,11,11,2002), A.GetCreationDate() =', A.GetCreationDate()
- print "A.IsModified() = ", A.IsModified()
+ A.SetUserName("tester"); print('A.SetUserName("tester"), A.GetUserName() = ', A.GetUserName())
+ A.SetCreationDate(11,11,11,11,2002); print('A.SetCreationDate(11,11,11,11,2002), A.GetCreationDate() =', A.GetCreationDate())
+ print("A.IsModified() = ", A.IsModified())
A.SetLocked(1)
#check the transaction result
batchmode_geompy.myBuilder.CommitCommand()
if A.GetUserName() != "tester":
- print 'Control after transaction close : A.GetUserName() = ', A.GetUserName()
+ print('Control after transaction close : A.GetUserName() = ', A.GetUserName())
raise RuntimeError, "Field 'UserName' was not modified but had to!"
# try to make some changes wrapped by transaction
@@ -63,9 +63,9 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
+batchmode_geompy.myStudy.SaveAs(file)
#--------------------------------------------------------------------------#
@@ -74,7 +74,7 @@ batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
print" -------------- Open " + file + "-------------- "
-openedStudy = batchmode_geompy.myStudyManager.Open(file)
+openedStudy = batchmode_geompy.myStudy.Open(file)
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -135,17 +135,17 @@ myBuilder.CommitCommand()
#4.
myBuilder.NewCommand()
A.SetLocked(0);
-print "A.GetUserName()= ", A.GetUserName()
-print "A.GetCreationDate() = ", A.GetCreationDate()
-print "A.GetCreationMode() = ", A.GetCreationMode()
-print "A.IsModified() = ", A.IsModified()
+print("A.GetUserName()= ", A.GetUserName())
+print("A.GetCreationDate() = ", A.GetCreationDate())
+print("A.GetCreationMode() = ", A.GetCreationMode())
+print("A.IsModified() = ", A.IsModified())
myBuilder.CommitCommand()
#5.
myBuilder.NewCommand()
A.SetUserName("tester1")
myBuilder.CommitCommand()
-print "A.GetUserName()= ", A.GetUserName()
+print("A.GetUserName()= ", A.GetUserName())
#remove the document file
os.remove(file)
diff --git a/doc/salome/examples/example21 b/doc/salome/examples/example21
index 33526d956..7ff5b0ec2 100644
--- a/doc/salome/examples/example21
+++ b/doc/salome/examples/example21
@@ -29,10 +29,10 @@ a=[836,3425,342]
A.SetColumn(3,a)
# change attribute values
-print "A.GetValue(2,2) = ", A.GetValue(2,2)
-print "A.PutValue(2,2,625323)"
+print("A.GetValue(2,2) = ", A.GetValue(2,2))
+print("A.PutValue(2,2,625323)")
A.PutValue(625323,2,2)
-print "A.GetValue(2,2) = ", A.GetValue(2,2)
+print("A.GetValue(2,2) = ", A.GetValue(2,2))
#set Titles
@@ -48,18 +48,18 @@ A.SetColumnTitle(3,"TC")
#check the table
-print "Common title : ",A.GetTitle()
-print "Rows titles : ", A.GetRowTitles()
+print("Common title : ",A.GetTitle())
+print("Rows titles : ", A.GetRowTitles())
rnb = A.GetNbRows()
for i in range(1, rnb):
b=A.GetRow(i)
- print b
+ print(b)
cnb = A.GetNbColumns()
-print "Columns title : ", A.GetColumnTitles()
+print("Columns title : ", A.GetColumnTitles())
for i in range(1, cnb):
b=A.GetColumn(i)
- print b
+ print(b)
# set titles
#titles=["11","12","13"]
@@ -77,9 +77,9 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
+batchmode_geompy.myStudy.SaveAs(file)
#--------------------------------------------------------------------------#
#---------------------------- Open file -----------------------------------#
@@ -87,7 +87,7 @@ batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
print" -------------- Open " + file + "-------------- "
-openedStudy=batchmode_geompy.myStudyManager.Open(file)
+openedStudy=batchmode_geompy.myStudy.Open(file)
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -104,24 +104,24 @@ if res == 0 or A == None:
A = A._narrow(SALOMEDS.AttributeTableOfInteger)
#check the table
-print "Common title : ",A.GetTitle()
-print "Rows titles : ", A.GetRowTitles()
+print("Common title : ",A.GetTitle())
+print("Rows titles : ", A.GetRowTitles())
rnb = A.GetNbRows()
for i in range(1, rnb):
b=A.GetRow(i)
- print b
+ print(b)
cnb = A.GetNbColumns()
-print "Columns title : ", A.GetColumnTitles()
+print("Columns title : ", A.GetColumnTitles())
for i in range(1, cnb):
b=A.GetColumn(i)
- print b
+ print(b)
titles=["ff","ss","tt"]
A.SetRowTitles(titles)
-print "Rows titles : ", A.GetRowTitles()
+print("Rows titles : ", A.GetRowTitles())
titles=["ww","zz","cc"]
A.SetColumnTitles(titles)
-print "Column titles : ", A.GetColumnTitles()
+print("Column titles : ", A.GetColumnTitles())
diff --git a/doc/salome/examples/example22 b/doc/salome/examples/example22
index bba273be6..157bd3631 100644
--- a/doc/salome/examples/example22
+++ b/doc/salome/examples/example22
@@ -29,10 +29,10 @@ a=[836,3425,342]
A.SetColumn(3,a)
# change attribute values
-print "A.GetValue(2,2) = ", A.GetValue(2,2)
-print "A.PutValue(2,2,625323)"
+print("A.GetValue(2,2) = ", A.GetValue(2,2))
+print("A.PutValue(2,2,625323)")
A.PutValue(625323,2,2)
-print "A.GetValue(2,2) = ", A.GetValue(2,2)
+print("A.GetValue(2,2) = ", A.GetValue(2,2))
#set Titles
@@ -48,18 +48,18 @@ A.SetColumnTitle(3,"TC")
#check the table
-print "Common title : ",A.GetTitle()
-print "Rows titles : ", A.GetRowTitles()
+print("Common title : ",A.GetTitle())
+print("Rows titles : ", A.GetRowTitles())
rnb = A.GetNbRows() + 1
for i in range(1, rnb):
b=A.GetRow(i)
- print b
+ print(b)
cnb = A.GetNbColumns() + 1
-print "Columns title : ", A.GetColumnTitles()
+print("Columns title : ", A.GetColumnTitles())
for i in range(1, cnb):
b=A.GetColumn(i)
- print b
+ print(b)
# set titles
#titles=["11","12","13"]
@@ -78,9 +78,9 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-print " ------- We will save to", file, "-----------"
+print(" ------- We will save to", file, "-----------")
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
+batchmode_geompy.myStudy.SaveAs(file)
#--------------------------------------------------------------------------#
#---------------------------- Open file -----------------------------------#
@@ -88,7 +88,7 @@ batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
print" -------------- Open " + file + "-------------- "
-openedStudy = batchmode_geompy.myStudyManager.Open(file)
+openedStudy = batchmode_geompy.myStudy.Open(file)
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -105,24 +105,24 @@ if res == 0 or A == None:
A = A._narrow(SALOMEDS.AttributeTableOfReal)
#check the table
-print "Common title : ",A.GetTitle()
-print "Rows titles : ", A.GetRowTitles()
+print("Common title : ",A.GetTitle())
+print("Rows titles : ", A.GetRowTitles())
rnb = A.GetNbRows() + 1
for i in range(1, rnb):
b=A.GetRow(i)
- print b
+ print(b)
cnb = A.GetNbColumns() + 1
-print "Columns title : ", A.GetColumnTitles()
+print("Columns title : ", A.GetColumnTitles())
for i in range(1, cnb):
b=A.GetColumn(i)
- print b
+ print(b)
titles=["ff","ss","tt"]
A.SetRowTitles(titles)
-print "Rows titles : ", A.GetRowTitles()
+print("Rows titles : ", A.GetRowTitles())
titles=["ww","zz","cc"]
A.SetColumnTitles(titles)
-print "Column titles : ", A.GetColumnTitles()
+print("Column titles : ", A.GetColumnTitles())
diff --git a/doc/salome/examples/example23 b/doc/salome/examples/example23
index da60ce0e9..b613c47c7 100644
--- a/doc/salome/examples/example23
+++ b/doc/salome/examples/example23
@@ -12,19 +12,3 @@ anAttrName = anAttr._narrow(SALOMEDS.AttributeName)
anAttrName.SetValue("User data")
-#Add a new case 'Case1' to the component 'User data'
-aBuilder.AddDirectory("/User data/Case1")
-
-#Set a study context to '/User data/Case1'
-aStudy.SetContext("/User data/Case1")
-
-#Print the current study context
-print aStudy.GetContext()
-
-#Add a sub directory 'aSubCase' to 'Case1' (under the current context)
-aBuilder.AddDirectory("aSubCase")
-
-
-#Add a new case 'Case2' to component 'User data'
-aBuilder.AddDirectory("/User data/Case2")
-
diff --git a/doc/salome/examples/example3 b/doc/salome/examples/example3
index 95e18e8e7..a374b98fb 100644
--- a/doc/salome/examples/example3
+++ b/doc/salome/examples/example3
@@ -13,16 +13,16 @@ A.Add(625.1e+2)
A.Add(0.928e+100)
A.Add(83.287)
-print "initial values ",A.Value(1), A.Value(2), A.Value(3), A.Value(4)
+print("initial values ",A.Value(1), A.Value(2), A.Value(3), A.Value(4))
A.Remove(3)
-print "after remove ", A.Value(1), A.Value(2), A.Value(3)
+print("after remove ", A.Value(1), A.Value(2), A.Value(3))
A.ChangeValue(2,76.265)
-print "after second item change", A.Value(1), A.Value(2), A.Value(3)
+print("after second item change", A.Value(1), A.Value(2), A.Value(3))
if A.Length() != 3:
- print "Error : wrong length of SequenceOfReal"
+ print("Error : wrong length of SequenceOfReal")
if A.Value(1) != 0.0293 or A.Value(2) != 76.265 or A.Value(3) != 83.287:
- print "Error : wrong value of AttributeSequenceOfReal"
+ print("Error : wrong value of AttributeSequenceOfReal")
# save / restore study
#=================================
@@ -31,8 +31,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy=batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy=batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -53,8 +53,8 @@ if res == 0 or A == None:
A = A._narrow(SALOMEDS.AttributeSequenceOfReal)
if A.Length() != 3:
- print "Error : wrong length of SequenceOfReal"
+ print("Error : wrong length of SequenceOfReal")
if A.Value(1) != 0.0293 or A.Value(2) != 76.265 or A.Value(3) != 83.287:
- print "Error : wrong value of AttributeSequenceOfReal"
-print "after restoring ", A.Value(1), A.Value(2), A.Value(3)
+ print("Error : wrong value of AttributeSequenceOfReal")
+print("after restoring ", A.Value(1), A.Value(2), A.Value(3))
diff --git a/doc/salome/examples/example4 b/doc/salome/examples/example4
index 2dd1966db..fa0ad0e0c 100644
--- a/doc/salome/examples/example4
+++ b/doc/salome/examples/example4
@@ -19,9 +19,9 @@ A.ChangeValue(4,500)
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 700:
- print "Wrong value of AttributeSequenceOfInteger"
+ print("Wrong value of AttributeSequenceOfInteger")
# save / restore study
@@ -30,8 +30,8 @@ str= os.getenv("TmpDir")
if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy=batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy=batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -52,7 +52,7 @@ if res == 0 or A == None:
A = A._narrow(SALOMEDS.AttributeSequenceOfInteger)
if A.Length() != 4:
- print "Wrong length of SequenceOfInteger"
+ print("Wrong length of SequenceOfInteger")
if A.Value(1) != 100 or A.Value(2) != 300 or A.Value(3) != 400 or A.Value(4) != 700:
- print "Wrong value of AttributeSequenceOfInteger"
+ print("Wrong value of AttributeSequenceOfInteger")
diff --git a/doc/salome/examples/example5 b/doc/salome/examples/example5
index 59e3bc6a0..c6f6ea217 100644
--- a/doc/salome/examples/example5
+++ b/doc/salome/examples/example5
@@ -11,7 +11,7 @@ if A == None :
A.SetValue("AttributesTesting")
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
# save / restore study
@@ -21,8 +21,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy = batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy = batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
@@ -46,5 +46,5 @@ if A == None :
raise RuntimeError, "Can't create AttributeName attribute"
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
diff --git a/doc/salome/examples/example6 b/doc/salome/examples/example6
index 71a5859e7..4685f2b7a 100644
--- a/doc/salome/examples/example6
+++ b/doc/salome/examples/example6
@@ -19,8 +19,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy = batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy = batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
diff --git a/doc/salome/examples/example7 b/doc/salome/examples/example7
index 8ddf8bb2b..2477a3e07 100644
--- a/doc/salome/examples/example7
+++ b/doc/salome/examples/example7
@@ -18,8 +18,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy = batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy = batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
diff --git a/doc/salome/examples/example8 b/doc/salome/examples/example8
index eadb13feb..3d79cab44 100644
--- a/doc/salome/examples/example8
+++ b/doc/salome/examples/example8
@@ -26,8 +26,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy=batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy=batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
diff --git a/doc/salome/examples/example9 b/doc/salome/examples/example9
index d29c9bab7..68d9394d3 100644
--- a/doc/salome/examples/example9
+++ b/doc/salome/examples/example9
@@ -22,8 +22,8 @@ if str == None:
str = "/tmp"
file = str+"/test.hdf"
-batchmode_geompy.myStudyManager.SaveAs(file, batchmode_geompy.myStudy)
-openedStudy = batchmode_geompy.myStudyManager.Open(file);
+batchmode_geompy.myStudy.SaveAs(file)
+openedStudy = batchmode_geompy.myStudy.Open(file);
if openedStudy == None:
raise RuntimeError, "Can't open saved study!"
diff --git a/doc/salome/kernel_salome.dox b/doc/salome/kernel_salome.dox
index 75deb2960..735396a86 100644
--- a/doc/salome/kernel_salome.dox
+++ b/doc/salome/kernel_salome.dox
@@ -72,46 +72,6 @@ geom = salome.lcc.FindOrLoadComponent('FactoryServer', 'GEOM')
\b Note, that in the above example, \e "FactoryServer" is a name of the
SALOME container, where Geometry module engine should be loaded.
-\li \b myStudyManager Reference to the study manager
-
-SALOMEDS Study manager is used to manipulate with the studies: create,
-open, save, close. It also can be used to find the study by its
-numerical ID or name. The code below demonstrates main
-functionalities of a study manager:
-\code
-# create new study with the name "MyStudy"
-new_study = salome.myStudyManager.NewStudy("MyStudy")
-
-# open study from file /home/user/MyStudy.hdf
-study = salome.myStudyManager.OpenStudy("/home/user/MyStudy.hdf")
-
-# save study
-salome.myStudyManager.Save(study, False) # not using multifile save mode
-
-# save study in ASCII format
-salome.myStudyManager.SaveASCII(study, True) # using multifile save mode
-
-# save study with the new file path
-salome.myStudyManager.SaveAs("/home/user/MyStudy.hdf", study, False)
-
-# save study with the new file path in ASCII format
-salome.myStudyManager.SaveAsASCII("/home/user/MyStudy.hdf", study, False)
-
-# close study
-salome.myStudyManager.Close(study)
-
-# get list of all opened studies
-studies = salome.myStudyManager.GetOpenStudies()
-
-# find study by its numerical ID (integer value starting from 1)
-study = salome.myStudyManager.GetStudyByID(studyID)
-
-# find study by its name
-study = salome.myStudyManager.GetStudyByName("/home/user/MyStudy.hdf")
-
-# ...
-\endcode
-
\anchor salome_myStudy
\li \b myStudy Reference to the current (active) study
@@ -136,8 +96,26 @@ documentation.
# get study name
studyName = salome.myStudy._get_Name()
-# get study numerical ID
-studyID = salome.myStudy._get_StudyId()
+# open study from file /home/user/MyStudy.hdf
+salome.myStudy.Open("/home/user/MyStudy.hdf")
+
+# save study
+salome.myStudy.Save(False, False) # not using multifile save mode
+
+# save study in ASCII format
+salome.myStudy.Save(True, True) # using multifile save mode
+
+# save study with the new file path
+salome.myStudy.SaveAs("/home/user/MyStudy.hdf", False, False)
+
+# save study with the new file path in ASCII format
+salome.myStudy.SaveAs("/home/user/MyStudy.hdf", False, True)
+
+# clear study
+salome.myStudy.Clear()
+
+# init study
+salome.myStudy.Init()
# find SALOMEDS component by its type
scomponent = FindComponent("MyComponent")
@@ -185,19 +163,13 @@ iter = salome.myStudy.NewChildIterator(comp) # initialize from the component
iter.InitEx(True) # init recursive mode
while iter.More():
c = iter.Value()
- print c.GetID()
+ print(c.GetID())
iter.Next()
pass
# ...
\endcode
-\li \b myStudyId Identifier of the current (active) study
-
-This variable contains the numerical identifier of the current
-(active) study. It is an equivalent of \c
-salome.myStudy._get_StudyId() code.
-
\li \b myStudyName Name of the current (active) study
This variable contains the name of the current (active) study. It is
@@ -210,7 +182,7 @@ window. The output for each object includes its entry ID, name, IOR
(if there is one) and referenced object ID (for references). I.e.
this is the same data the user can see in the Object Browser columns.
\code
-salome.DumpStudy(salome.myStudy)
+salome.DumpStudy()
\endcode
\li \b IDToSObject() Get SALOMEDS object by its entry ID.
@@ -279,15 +251,6 @@ else:
entry = ""
\endcode
-\li \b createNewStudy() Create new study
-
-This function can be used to create new SALOME study. Returns an ID of
-the created study.
-\code
-studyId = salome.createNewStudy()
-study = salome.myStudyManager.GetStudyByID(s)
-\endcode
-
\li \b generateName() Generate unique name
This function adds random numerical suffix to the passed string
diff --git a/doc/salome/kernel_services.dox b/doc/salome/kernel_services.dox
index 71933b791..19b96a54d 100644
--- a/doc/salome/kernel_services.dox
+++ b/doc/salome/kernel_services.dox
@@ -135,7 +135,6 @@ Study.dir
extStudy_1.object
extStudy_2.object
extStudy_3.object
-myStudyManager.object
SalomeAppEngine.object
\endcode
diff --git a/doc/salome/python_doc_compl.dox b/doc/salome/python_doc_compl.dox
index eca7301eb..fa29dcab3 100644
--- a/doc/salome/python_doc_compl.dox
+++ b/doc/salome/python_doc_compl.dox
@@ -120,7 +120,7 @@ def extend_path(pname):
# WARN: This may still add duplicate entries to path on
# case-insensitive filesystems
if os.path.isdir(subdir) and subdir not in __path__:
- print "INFO - The directory %s is appended to sys.path" % subdir
+ print("INFO - The directory %s is appended to sys.path" % subdir)
__path__.append(subdir)
extend_path(ROOT_PYTHONPACKAGE_NAME)
diff --git a/doc/salome/salome_command.dox b/doc/salome/salome_command.dox
index bf3c2e6ea..1ec93a046 100644
--- a/doc/salome/salome_command.dox
+++ b/doc/salome/salome_command.dox
@@ -97,7 +97,7 @@ From a Python script, use a SalomeInstance object:
\code
from salome_instance import SalomeInstance
instance = SalomeInstance.start()
-print "Instance created and now running on port", instance.get_port()
+print("Instance created and now running on port", instance.get_port())
...
instance.stop()
\endcode
diff --git a/doc/salome/tui/pythfilter.py b/doc/salome/tui/pythfilter.py
index 4f9439e83..cb665591f 100644
--- a/doc/salome/tui/pythfilter.py
+++ b/doc/salome/tui/pythfilter.py
@@ -337,7 +337,7 @@ def tok_eater(type, tok, spos, epos, line):
s = 'static '
if params[0] == 'cls':
param = string.join(params[1:], ",")
- s = s+name+"("+param+");\n"
+ s = s+name+"("+param+");\n"
if len(name) > 1 \
and name[0:2] == '__' \
and name[len(name)-2:len(name)] != '__' \
@@ -345,7 +345,7 @@ def tok_eater(type, tok, spos, epos, line):
private_member = True
output(" private:\n",(def_spos[0]+2,def_spos[1]))
else:
- s = name+"("+param+");\n"
+ s = name+"("+param+");\n"
if (doc_string!=""): comment_block.append(doc_string)
print_comment(def_spos)
output(s,def_spos)
@@ -427,12 +427,12 @@ def filterFile(filename, out=sys.stdout):
root,ext = os.path.splitext(filename)
if ext==".py":
- filter(filename)
+ list(filter(filename))
else:
dump(filename)
sys.stderr.write("OK\n")
- except IOError,e:
+ except IOError as e:
sys.stderr.write(e[1]+"\n")
@@ -478,7 +478,7 @@ def convert(srcpath, destpath):
namespace=namespace+"::"+os.path.split(srcpath)[1]
else:
namespace=os.path.split(srcpath)[1]
- print "It's a package:",namespace
+ print("It's a package:",namespace)
sp = os.path.join(srcpath,"*")
sfiles = glob.glob(sp)
dp = os.path.join(destpath,"*")
@@ -507,7 +507,7 @@ def convert(srcpath, destpath):
destfile = os.path.join(destpath,basename)
if destfile==srcfile:
- print "WARNING: Input and output names are identical!"
+ print("WARNING: Input and output names are identical!")
sys.exit(1)
count+=1
@@ -527,12 +527,12 @@ def convert(srcpath, destpath):
try:
shutil.rmtree(dname)
except:
- print "Can't remove obsolete directory '%s'"%dname
+ print("Can't remove obsolete directory '%s'"%dname)
else:
try:
os.remove(dname)
except:
- print "Can't remove obsolete file '%s'"%dname
+ print("Can't remove obsolete file '%s'"%dname)
return count
@@ -545,8 +545,8 @@ filter_file = False
try:
opts, args = getopt.getopt(sys.argv[1:], "hf", ["help"])
-except getopt.GetoptError,e:
- print e
+except getopt.GetoptError as e:
+ print(e)
sys.exit(1)
for o,a in opts:
@@ -564,6 +564,6 @@ else:
sys.exit(1)
# Filter an entire Python source tree
- print '"%s" -> "%s"\n'%(args[0],args[1])
+ print('"%s" -> "%s"\n'%(args[0],args[1]))
c=convert(args[0],args[1])
- print "%d files"%(c)
+ print("%d files"%(c))
diff --git a/idl/SALOMEDS.idl b/idl/SALOMEDS.idl
index 8e8f4f218..e063ff7ad 100644
--- a/idl/SALOMEDS.idl
+++ b/idl/SALOMEDS.idl
@@ -41,7 +41,7 @@ module SALOMEDS
{
/*! \brief Name of the file in which the %Study is saved.
*/
- typedef string URL;
+ typedef wstring URLPath;
/*! \brief Main identifier of an object in %SALOME application
*/
@@ -55,12 +55,6 @@ module SALOMEDS
*/
typedef string SalomeReference;
-/*! \brief List of the names of studies which are currently open in this %SALOME session.
-
-Since %SALOME is a multi-study application, it allows to open a lot of studies
-during each working session.
-*/
- typedef sequence ListOfOpenStudies;
//! List of file names
typedef sequence ListOfFileNames;
//! List of modification dates of a study
@@ -81,7 +75,6 @@ during each working session.
interface GenericAttribute;
interface Study;
- interface StudyManager;
interface StudyBuilder;
interface SObject;
interface SComponent;
@@ -105,899 +98,752 @@ during each working session.
//! Exception indicating that this feature hasn't been implemented in %SALOME application.
exception NotImplemented {};
+ //==========================================================================
+/*! \brief %Study Builder Interface
- //===========================================================================
- /*! \brief %Study Interface
-
- The purpose of the %Study is to manage the data produced by various components of %SALOME platform.
- Most of the %Study operations are handled by the StudyManager and the StudyBuilder.
- What is left in the %Study interface are elementary inquiries.
- (Incidentally, we recall that a CORBA attribute is implemented as a pair of get
- and set methods.) A %Study is explored by a set of tools, mainly iterators
- , which are described further. Nevertheless, the %Study
- interface allows the search of an object by name or by ID.
- \note
-
The Path of an object in %SALOME application is much alike a standard path of a file.
- In general it's a string of names of directories divided by a slash '/'.
-
The Context is the current directory of an object.
+ The purpose of the Builder is to add and/or remove objects and attributes.
+ A %StudyBuilder is linked to a %Study. A
+ command management is provided for the undo/redo functionalities.
+ \note
+
The Tag of an item in %SALOME application is a symbolic description of
+ item's position in the tree-type structure of the browser. In general it has the following
+ form: 0:2:1:1
*/
+ //==========================================================================
- interface Study
+ interface StudyBuilder
{
+/*! \brief %LockProtection Exception
-//! Invalid study reference
- exception StudyInvalidReference {};
-//! Invalid study context
- exception StudyInvalidContext {};
-//! Invalid study component
- exception StudyInvalidComponent {};
-//! Invalid directory of the %study exception
- exception StudyInvalidDirectory {};
-//! Exception pointing that this name of the study has already been used.
- exception StudyNameAlreadyUsed {};
-//! study object already exists
- exception StudyObjectAlreadyExists {};
-//! Invalid name of the %study exception
- exception StudyNameError {};
-//! Invalid study comment
- exception StudyCommentError {};
-
-/*! \brief The name of the %Study
-
- This is equivalent to the methods setName() & getName()
+ This exception is raised while attempting to modify a locked %study.
*/
- attribute string Name; // equivalent to setName() & getName()
-/*! \brief The ID of the %Study
+ exception LockProtection {};
+/*! \brief Creation of a new %SComponent.
- This is equivalent to the methods setID() & getID()
-*/
- attribute short StudyId;
-//! Sequence containing %SObjects
- typedef sequence ListOfSObject;
-//! Get the persistent reference to the %Study.
- PersistentReference GetPersistentReference() raises(StudyInvalidReference);
-//! Get a transient reference to the %Study.
- SalomeReference GetTransientReference() raises(StudyInvalidReference);
+ Creates a new %SComponent
+ \param ComponentDataType Data type of the %SComponent which will be created.
-/*! \brief indicate whether the %Study is empty
+See \ref example17 for an example of this method usage in batchmode of %SALOME application.
- \return True if the %Study is empty
*/
- boolean IsEmpty() raises(StudyInvalidReference);
-/*! \brief Find a %SComponent by its name.
-
- \param aComponentName It's a string value in the Comment Attribute of the Component,
- which is looked for, defining the data type of this Component.
+ SComponent NewComponent(in string ComponentDataType) raises(LockProtection);
-See \ref example1 for an example of this method usage in batchmode of %SALOME application.
+/*! \brief Definition of the instance to the %SComponent
+ Defines the instance to the %SComponent.
*/
- SComponent FindComponent (in string aComponentName) raises(StudyInvalidReference);
+ void DefineComponentInstance (in SComponent aComponent,in Object ComponentIOR) raises(LockProtection);
-/*! \brief Find a %SComponent by ID of the according %SObject
+/*! \brief Deletion of a %SComponent
+
+ Removes a %SComponent.
*/
- SComponent FindComponentID(in ID aComponentID) raises(StudyInvalidReference);
-/*! \brief Find a %SObject by the Name Attribute of this %SObject
+ void RemoveComponent(in SComponent aComponent) raises(LockProtection);
- \param anObjectName String parameter defining the name of the object
- \return The obtained %SObject
+/*! \brief Creation of a new %SObject
-See \ref example19 for an example of this method usage in batchmode of %SALOME application.
-*/
- SObject FindObject (in string anObjectName) raises(StudyInvalidReference);
-/*! \brief Find a %SObject by its ID
+ Creates a new %SObject under a definite father %SObject.
- \param aObjectID This parameter defines the ID of the required object
- \return The obtained %SObject
-*/
- SObject FindObjectID (in ID aObjectID) raises(StudyInvalidReference);
-/*! \brief Create a %SObject by its ID
+ \param theFatherObject The father %SObject under which this one should be created.
+ \return New %SObject
- \param aObjectID This parameter defines the ID of the required object
- \return The created %SObject
-*/
- SObject CreateObjectID (in ID aObjectID) raises(StudyInvalidReference);
-/*! \brief Find a %SObject by IOR of the object belonging to this %SObject.
+See \ref example18 for an example of this method usage in batchmode of %SALOME application.
- \param anObjectName This parameter defines the IOR of the object
- \return The obtained %SObject
*/
- SObject FindObjectIOR (in ID aObjectIOR) raises(StudyInvalidReference);
-/*! \brief Find in the study all %SObjects produced by a given %Component.
- \param anObjectName The Name Attribute of the searched %SObjects should correspond to anObjectName.
- \param aComponentName The name of the component, which objects are searched for.
-*/
- ListOfSObject FindObjectByName(in string anObjectName, in string aComponentName) raises(StudyInvalidReference);
-/*! \brief Find a %SObject by the path to it.
+ SObject NewObject (in SObject theFatherObject) raises(LockProtection);
- \param thePath The path to the required %SObject.
- \return The obtained %SObject.
-*/
- SObject FindObjectByPath(in string thePath) raises(StudyInvalidReference);
-/*! \brief Get the path to the %SObject.
-*/
- string GetObjectPath(in Object theObject) raises(StudyInvalidReference);
+/*! \brief Creation of a new %SObject with a definite %tag
-/*! \brief Set the context of the %Study.
+ Creates a new %SObject with a definite %tag.
- \param thePath String parameter defining the context of the study.
+ \param atag Long value corresponding to the tag of the new %SObject.
+ \return New %SObject
-See \ref example23 for an example of this method usage in batchmode of %SALOME application.
*/
- void SetContext(in string thePath) raises (StudyInvalidReference, StudyInvalidContext);
-/*! \brief Get the context of the %Study.
+ SObject NewObjectToTag (in SObject theFatherObject, in long atag) raises(LockProtection);
+/*! \brief Deletion of the %SObject
-See \ref example23 for an example of this method usage in batchmode of %SALOME application.
-*/
- string GetContext() raises (StudyInvalidReference, StudyInvalidContext);
-/*! \brief Get a list of names of objects corresponding to the context.
+ Removes a %SObject from the %StudyBuilder.
- \note If the parameter theContext is empty, then the current context will be used.
+ \param anObject The %SObject to be deleted.
*/
- ListOfStrings GetObjectNames(in string theContext) raises (StudyInvalidReference, StudyInvalidContext);
-/*! \brief Get a list of names of directories and subdirectories corresponding to the context.
+ void RemoveObject (in SObject anObject) raises(LockProtection);
+/*! \brief Deletion of the %SObject with all his child objects.
- \note If the parameter theContext is empty, then the current context will be used.
-*/
- ListOfStrings GetDirectoryNames(in string theContext) raises (StudyInvalidReference, StudyInvalidContext);
-/*! \brief Get a list of names of Files corresponding to the context.
+ Removes the %SObject with all his child objects.
- \note If the parameter theContext is empty, then the current context will be used.
+ \param anObject The %SObject to be deleted with all child objects.
*/
- ListOfStrings GetFileNames(in string theContext) raises (StudyInvalidReference, StudyInvalidContext);
-/*! \brief Get a list of names of Components corresponding to the context.
+ void RemoveObjectWithChildren(in SObject anObject) raises(LockProtection);
- \note If the parameter theContext is empty, then the current context will be used.
-*/
- ListOfStrings GetComponentNames(in string theContext) raises(StudyInvalidReference);
-/*! \brief Create a new iterator of child levels of the given %SObject.
+/*!
+ Loads a %SComponent.
- \param aSO The given %SObject
- \return A new iterator of child levels of the given %SObject.
-*/
- ChildIterator NewChildIterator(in SObject aSO) raises(StudyInvalidReference);
+See \ref example19 for an example of this method usage in batchmode of %SALOME application.
-/*! \brief Create a new iterator of the %SComponents.
+*/
+ void LoadWith (in SComponent sco, in Driver Engine) raises (SALOME::SALOME_Exception);
+/*!
+ Loads a %SObject.
- \return A new iterator of the %SComponents.
+ \param sco %SObject to be loaded.
*/
- SComponentIterator NewComponentIterator() raises(StudyInvalidReference);
+ void Load (in SObject sco);
-/*! \brief Create a new %StudyBuilder to add or modify an object in the study.
+/*! \brief Looking for or creating an attribute assigned to the %SObject
- \return A new %StudyBuilder.
+ Allows to find or create an attribute of a specific type which is assigned to the object.
+ \param anObject The %SObject corresponding to the attribute which is looked for.
+ \param aTypeOfAttribute Type of the attribute.
-See \ref example20 for an example of this method usage in batchmode of %SALOME application.
+See \ref example1 for an example of this method usage in batchmode of %SALOME application.
*/
- StudyBuilder NewBuilder() raises(StudyInvalidReference);
-/*! \brief Labels dependency
- Updates the map with IOR attribute. It's an inner method used for optimization.
-*/
- void UpdateIORLabelMap(in string anIOR, in string anEntry) raises(StudyInvalidReference);
+ GenericAttribute FindOrCreateAttribute(in SObject anObject,
+ in string aTypeOfAttribute) raises(LockProtection);
-/*! \brief Getting properties of the study
+/*! \brief Looking for an attribute assigned to a %SObject
- Returns the attribute, which contains the properties of this study.
+ Allows to find an attribute of a specific type which is assigned to the object.
+ \param anObject The %SObject corresponding to the attribute which is looked for.
+ \param aTypeOfAttribute Type of the attribute.
+ \param anAttribute Where the attribute is placed if it's found.
+ \return True if it finds an attribute.
+ */
-See \ref example20 for an example of this method usage in batchmode of %SALOME application.
+ boolean FindAttribute(in SObject anObject,
+ out GenericAttribute anAttribute,
+ in string aTypeOfAttribute);
+/*! \brief Deleting the attribute assigned to the %SObject
-*/
- AttributeStudyProperties GetProperties() raises(StudyInvalidReference);
-/*! \brief Indicate whether the %study has been saved
-*/
- attribute boolean IsSaved;
-/*! \brief Indicate whether the %study has been modified and not saved.
+ Removes the attribute of a specific type which is assigned to the object.
+ \param anObject The %SObject corresponding to the attribute.
+ \param aTypeOfAttribute Type of the attribute.
- Returns True if the %study has been modified and not saved.
+See \ref example17 for an example of this method usage in batchmode of %SALOME application.
*/
- boolean IsModified() raises(StudyInvalidReference);
-
-/*! \brief Mark the %study as being modified and not saved.
+ void RemoveAttribute(in SObject anObject,
+ in string aTypeOfAttribute) raises(LockProtection);
+/*!
+ Adds a reference between %anObject and %theReferencedObject.
+ \param anObject The %SObject which will get a reference
+ \param theReferencedObject The %SObject having a reference
*/
- void Modified() raises(StudyInvalidReference);
-/*! \brief Indicate the file where the %study has been saved
+ void Addreference(in SObject anObject,
+ in SObject theReferencedObject) ;
+
+/*!
+ Removes a reference from %anObject to another object.
+ \param anObject The %SObject which contains a reference
*/
- attribute string URL;
-/*! \brief List of %SObjects
+ void RemoveReference(in SObject anObject) ;
- Returns the list of %SObjects which refers to %anObject.
-*/
- ListOfSObject FindDependances(in SObject anObject) raises(StudyInvalidReference);
+/*! \brief Identification of the %SObject's substructure.
-/*! \brief The date of the last saving of the study
+ Identification of the %SObject's substructure by GUID.
- Returns the date of the last saving of study with format: "DD/MM/YYYY HH:MM"
-*/
- string GetLastModificationDate() raises(StudyInvalidReference);
-/*! \brief The list of modification dates of the study
- Returns the list of modification dates (without creation date) with format "DD/MM/YYYY HH:MM".
- Note : the first modification begins the list.
+ \param anObject The %SObject which will be identified
+ \param theGUID GUID has the following format "00000000-0000-0000-0000-000000000000"
*/
- ListOfDates GetModificationsDate() raises(StudyInvalidReference);
-/*! \brief Object conversion.
+ void SetGUID(in SObject anObject, in string theGUID) raises(LockProtection);
+/*!
+Searches for a definite %SObject with a definite GUID and returns True if it finds it.
- Converts an object into IOR.
- \return IOR
+\param anObject A definite %SObject which will be identified
+\param theGUID GUID has the following format "00000000-0000-0000-0000-000000000000"
*/
- string ConvertObjectToIOR(in Object theObject);
-/*! \brief Object conversion.
+ boolean IsGUID(in SObject anObject, in string theGUID);
- Converts IOR into an object.
- \return An object
-*/
- Object ConvertIORToObject(in string theIOR);
+/*! \brief Creation of a new command
-/*! \brief Get a new %UseCaseBuilder.
-*/
- UseCaseBuilder GetUseCaseBuilder() raises(StudyInvalidReference);
+ Creates a new command which can contain several different actions.
-/*! \brief Close the components in the study, remove itself from the %StudyManager.
-*/
- void Close() raises(StudyInvalidReference);
+See \ref example3 for an example of this method usage in batchmode of %SALOME application.
-/*! \brief Enable (if isEnabled = True)/disable automatic addition of new %SObjects to the use case.
*/
- void EnableUseCaseAutoFilling(in boolean isEnabled) raises(StudyInvalidReference);
+ void NewCommand(); // command management
+/*! \brief Execution of the command
-/*!
- Functions for internal usage only
-*/
- void AddPostponed(in string theIOR) raises(StudyInvalidReference);
+ Commits all actions declared within this command.
- void AddCreatedPostponed(in string theIOR) raises(StudyInvalidReference);
+ \exception LockProtection This exception is raised, when trying to perform this command a study, which is protected for modifications.
- void RemovePostponed(in long theUndoLimit) raises(StudyInvalidReference);
+See \ref example16 for an example of this method usage in batchmode of %SALOME application.
- void UndoPostponed(in long theWay) raises(StudyInvalidReference);
-
- boolean DumpStudy(in string thePath,
- in string theBaseName,
- in boolean isPublished,
- in boolean isMultiFile) raises(StudyInvalidReference);
-
-/*! \brief Get an AttributeParameter used to store common parameters for given %theSavePoint.
-
- \param theID identifies a common parameters set (Example: "Interface Applicative")
- \param theSavePoint is number of a set of parameters as there can be several sets
-*/
- AttributeParameter GetCommonParameters(in string theID, in long theSavePoint) raises(StudyInvalidReference);
-
-/*! \brief Get an AttributeParameter used to store parameters for given %theModuleName.
-
- \param theID identifies a common parameters set (Example: "Interface Applicative")
- \param theModuleName is a name of the module (Example: "Geometry")
- \param theSavePoint is number of a set of parameters as there can be several sets
*/
- AttributeParameter GetModuleParameters(in string theID, in string theModuleName, in long theSavePoint) raises(StudyInvalidReference);
-
-
-/*! \brief Get a default Python script to restore visual parameters for given %theModuleName.
-
- \param theModuleName is a name of the module (Example: "Geometry")
- \param indent is a string to use for script indentation
-*/
- string GetDefaultScript(in string theModuleName, in string indent) raises(StudyInvalidReference);
-
+ void CommitCommand() raises(LockProtection); // command management
/*!
- Private method, returns an implementation of this Study.
- \param theHostname is a hostname of the caller
- \param thePID is a process ID of the caller
- \param isLocal is set True if the Study is launched locally with the caller
-*/
- long long GetLocalImpl(in string theHostname, in long thePID, out boolean isLocal);
-
-
-/*! \brief Mark this Study as being locked by the given locker.
-
- The lock status can be checked by method IsStudyLocked
- \param theLockerID identifies a locker of the study can be for ex. IOR of the engine that locks the study.
-*/
- void SetStudyLock(in string theLockerID) raises(StudyInvalidReference);
-
-/*! \brief Indicate if the Study is locked
-
- Returns True if the Study was marked locked.
+ Returns True if at this moment there is a command under execution.
*/
- boolean IsStudyLocked() raises(StudyInvalidReference);
+ boolean HasOpenCommand();
+/*! \brief Cancellation of the command
-/*! \brief Mark this Study as being unlocked by the given locker.
+ Cancels all actions declared within the command.
- The lock status can be checked by method IsStudyLocked
- \param theLockerID identifies a locker of the study can be for ex. IOR of the engine that unlocks the study.
+See \ref example17 for an example of this method usage in batchmode of %SALOME application.
*/
- void UnLockStudy(in string theLockerID) raises(StudyInvalidReference);
+ void AbortCommand(); // command management
+/*! \brief Undolimit
-/*! \brief Get the list of IDs of the Study's lockers.
+ The number of actions which can be undone
*/
- ListOfStrings GetLockerID() raises(StudyInvalidReference);
+ attribute long UndoLimit;
+/*! \brief Undo method
-/*! \brief Create real variable with Name theVarName and value theValue
+ Cancels all actions of the last command.
- (or set if variable value into theValue already exists)
- \param theVarName is a name of the variable
- \param theVarName is a value of the variable.
-*/
- void SetReal( in string theVarName, in double theValue ) raises(StudyInvalidReference);
+ \exception LockProtection This exception is raised, when trying to perform this command a study, which is protected for modifications.
-/*! \brief Create integer variable with Name theVarName and value theValue
+See \ref example16 for an example of this method usage in batchmode of %SALOME application.
- (or set if variable value into theValue already exists)
- \param theVarName is a name of the variable
- \param theVarName is a value of the variable.
*/
- void SetInteger( in string theVarName, in long theValue ) raises(StudyInvalidReference);
-/*! \brief Create boolean variable with Name theVarName and value theValue
+ void Undo() raises (LockProtection);
+/*! \brief Redo method
- (or set if variable value into theValue already exists)
- \param theVarName is a name of the variable
- \param theVarName is a value of the variable.
-*/
- void SetBoolean( in string theVarName, in boolean theValue ) raises(StudyInvalidReference);
+ Redoes all actions of the last command.
-/*! \brief Create string variable with Name theVarName and value theValue
+\exception LockProtection This exception is raised, when trying to perform this command a study, which is protected for modifications.
- (or set if variable value into theValue already exists)
- \param theVarName is a name of the variable
- \param theVarName is a value of the variable.
-*/
- void SetString( in string theVarName, in string theValue ) raises(StudyInvalidReference);
+See \ref example16 for an example of this method usage in batchmode of %SALOME application.
-/*! \brief Set current value as double for string variable
*/
- void SetStringAsDouble( in string theVarName, in double theValue ) raises(StudyInvalidReference);
+ void Redo() raises (LockProtection);
+/*!
+ Returns True if at this moment there are any actions which can be canceled.
-/*! \brief Get value of a real variable
+See \ref example16 for an example of this method usage in batchmode of %SALOME application.
- \param theVarName is a name of the variable.
*/
- double GetReal( in string theVarName ) raises(StudyInvalidReference);
+ boolean GetAvailableUndos();
+/*!
+ Returns True if at this moment there are any actions which can be redone.
-/*! \brief Get value of an integer variable
+See \ref example3 for an example of this method usage in batchmode of %SALOME application.
- \param theVarName is a name of the variable.
*/
- long GetInteger( in string theVarName ) raises(StudyInvalidReference);
-
-/*! \brief Get value of a boolean variable
+ boolean GetAvailableRedos();
+/*!
+ Puts name attribute with the given string value to the given %SObject
- \param theVarName is a name of the variable.
+ \param theSO Existing SObject to set name attribute.
+ \param theValue The value to be set to the name attribute.
*/
- boolean GetBoolean( in string theVarName ) raises(StudyInvalidReference);
+ void SetName(in SObject theSO, in string theValue) raises (LockProtection);
-/*! \brief Get value of a string variable
+/*!
+ Puts comment attribute with the given string value to the given %SObject
- \param theVarName is a name of the variable.
+ \param theSO Existing SObject to set comment attribute.
+ \param theValue The value to be set to the comment attribute.
*/
- string GetString( in string theVarName ) raises(StudyInvalidReference);
-
+ void SetComment(in SObject theSO, in string theValue) raises (LockProtection);
-/*! \brief Indicate if a variable is real
+/*!
+ Puts IOR attribute with the given string value to the given %SObject
- Return true if variable is real otherwise return false.
- \param theVarName is a name of the variable.
+ \param theSO Existing SObject to set IOR attribute.
+ \param theValue The value to be set to the IOR attribute.
*/
- boolean IsReal( in string theVarName ) raises(StudyInvalidReference);
+ void SetIOR(in SObject theSO, in string theValue) raises (LockProtection);
+ };
-/*! \brief Indicate if a variable is integer
+ //===========================================================================
+ /*! \brief %Study Interface
- Return true if variable is integer otherwise return false.
- \param theVarName is a name of the variable.
+ The purpose of the %Study is to manage the data produced by various components of %SALOME platform.
+ Most of the %Study operations are handled by the StudyBuilder.
+ What is left in the %Study interface are elementary inquiries.
+ (Incidentally, we recall that a CORBA attribute is implemented as a pair of get
+ and set methods.) A %Study is explored by a set of tools, mainly iterators
+ , which are described further. Nevertheless, the %Study
+ interface allows the search of an object by name or by ID.
+ \note
+
The Path of an object in %SALOME application is much alike a standard path of a file.
+ In general it's a string of names of directories divided by a slash '/'.
+
The Context is the current directory of an object.
*/
- boolean IsInteger( in string theVarName ) raises(StudyInvalidReference);
-/*! \brief Indicate if a variable is boolean
+ interface Study
+ {
- Return true if variable is boolean otherwise return false.
- \param theVarName is a name of the variable.
+//! Invalid study reference
+ exception StudyInvalidReference {};
+//! Invalid study component
+ exception StudyInvalidComponent {};
+//! Invalid directory of the %study exception
+ exception StudyInvalidDirectory {};
+//! Exception pointing that this name of the study has already been used.
+ exception StudyNameAlreadyUsed {};
+//! study object already exists
+ exception StudyObjectAlreadyExists {};
+//! Invalid name of the %study exception
+ exception StudyNameError {};
+//! Invalid study comment
+ exception StudyCommentError {};
+
+/*!
+ Determines whether the server has already been loaded or not.
*/
- boolean IsBoolean( in string theVarName ) raises(StudyInvalidReference);
-
-/*! \brief Indicate if a variable is string
+ void ping();
+ void Shutdown();
+/*!
+ Returns the PID of the server
+*/
+ long getPID();
- Return true if variable is string otherwise return false.
- \param theVarName is a name of the variable.
+/*!
+ Shutdown the Study process.
*/
- boolean IsString( in string theVarName ) raises(StudyInvalidReference);
+ oneway void ShutdownWithExit();
-/*! \brief Indicate if a variable exists in the study
+/*! \brief The name of the %Study
- Return true if variable exists in the study,
- otherwise return false.
- \param theVarName is a name of the variable.
+ This is equivalent to the methods setName() & getName()
*/
- boolean IsVariable( in string theVarName ) raises(StudyInvalidReference);
+ attribute wstring Name; // equivalent to getName()
-/*! \brief Get names of all variables from the study.
+/*! \brief Indicate the file where the %study has been saved
*/
- ListOfStrings GetVariableNames() raises(StudyInvalidReference);
-/*! \brief Remove a variable
+//! Sequence containing %SObjects
+ typedef sequence ListOfSObject;
+//! Get the persistent reference to the %Study.
+ PersistentReference GetPersistentReference() raises(StudyInvalidReference);
- Remove variable with the specified name from the study with substitution of its value.
+/*! \brief indicate whether the %Study is empty
- \param theVarName Name of the variable.
- \return Status of operation.
+ \return True if the %Study is empty
*/
- boolean RemoveVariable( in string theVarName ) raises(StudyInvalidReference);
+ boolean IsEmpty() raises(StudyInvalidReference);
+/*! \brief Find a %SComponent by its name.
-/*! \brief Rename a variable
+ \param aComponentName It's a string value in the Comment Attribute of the Component,
+ which is looked for, defining the data type of this Component.
- Rename variable with the specified name within the study.
+See \ref example1 for an example of this method usage in batchmode of %SALOME application.
- \param theVarName Name of the variable.
- \param theNewVarName New name for the variable.
- \return Status of operation.
*/
- boolean RenameVariable( in string theVarName, in string theNewVarName ) raises(StudyInvalidReference);
-
-/*! \brief Indicate whether variable is used
-
- Check that variable is used in the study.
+ SComponent FindComponent (in string aComponentName) raises(StudyInvalidReference);
- \param theVarName Name of the variable.
- \return Variable usage.
+/*! \brief Find a %SComponent by ID of the according %SObject
*/
- boolean IsVariableUsed( in string theVarName ) raises(StudyInvalidReference);
+ SComponent FindComponentID(in ID aComponentID) raises(StudyInvalidReference);
+/*! \brief Find a %SObject by the Name Attribute of this %SObject
-/*! \brief Parse variables used for object creation
+ \param anObjectName String parameter defining the name of the object
+ \return The obtained %SObject
- \param string with variables, separated by special symbol.
- \return Variables list.
+See \ref example19 for an example of this method usage in batchmode of %SALOME application.
*/
- ListOfListOfStrings ParseVariables( in string theVars ) raises(StudyInvalidReference);
-
-/*!
- Attach an observer to the Study
+ SObject FindObject (in string anObjectName) raises(StudyInvalidReference);
+/*! \brief Find a %SObject by its ID
- \param theObserver observer being attached
- \param modify when \c true, observer receives any object's modification events;
- otherwise observer receives object's creation events only
+ \param aObjectID This parameter defines the ID of the required object
+ \return The obtained %SObject
*/
- void attach(in SALOMEDS::Observer theObserver, in boolean modify);
-/*!
- Detach an observer from the Study
+ SObject FindObjectID (in ID aObjectID) raises(StudyInvalidReference);
+/*! \brief Create a %SObject by its ID
- \param theObserver observer to be detached
+ \param aObjectID This parameter defines the ID of the required object
+ \return The created %SObject
*/
- void detach(in SALOMEDS::Observer theObserver);
- };
-
- //==========================================================================
-/*! \brief %Study Builder Interface
+ SObject CreateObjectID (in ID aObjectID) raises(StudyInvalidReference);
+/*! \brief Find a %SObject by IOR of the object belonging to this %SObject.
- The purpose of the Builder is to add and/or remove objects and attributes.
- A %StudyBuilder is linked to a %Study. A
- command management is provided for the undo/redo functionalities.
- \note
-
The Tag of an item in %SALOME application is a symbolic description of
- item's position in the tree-type structure of the browser. In general it has the following
- form: 0:2:1:1
+ \param anObjectName This parameter defines the IOR of the object
+ \return The obtained %SObject
*/
- //==========================================================================
-
- interface StudyBuilder
- {
-/*! \brief %LockProtection Exception
+ SObject FindObjectIOR (in ID aObjectIOR) raises(StudyInvalidReference);
+/*! \brief Find in the study all %SObjects produced by a given %Component.
- This exception is raised while attempting to modify a locked %study.
+ \param anObjectName The Name Attribute of the searched %SObjects should correspond to anObjectName.
+ \param aComponentName The name of the component, which objects are searched for.
*/
- exception LockProtection {};
-/*! \brief Creation of a new %SComponent.
-
- Creates a new %SComponent
- \param ComponentDataType Data type of the %SComponent which will be created.
-
-See \ref example17 for an example of this method usage in batchmode of %SALOME application.
+ ListOfSObject FindObjectByName(in string anObjectName, in string aComponentName) raises(StudyInvalidReference);
+/*! \brief Find a %SObject by the path to it.
+ \param thePath The path to the required %SObject.
+ \return The obtained %SObject.
*/
- SComponent NewComponent(in string ComponentDataType) raises(LockProtection);
-/*! \brief Definition of the instance to the %SComponent
-
- Defines the instance to the %SComponent.
+ SObject FindObjectByPath(in string thePath) raises(StudyInvalidReference);
+/*! \brief Get the path to the %SObject.
*/
- void DefineComponentInstance (in SComponent aComponent,in Object ComponentIOR) raises(LockProtection);
+ string GetObjectPath(in Object theObject) raises(StudyInvalidReference);
-/*! \brief Deletion of a %SComponent
+/*! \brief Create a new iterator of child levels of the given %SObject.
- Removes a %SComponent.
+ \param aSO The given %SObject
+ \return A new iterator of child levels of the given %SObject.
*/
- void RemoveComponent(in SComponent aComponent) raises(LockProtection);
+ ChildIterator NewChildIterator(in SObject aSO) raises(StudyInvalidReference);
-/*! \brief Creation of a new %SObject
+/*! \brief Create a new iterator of the %SComponents.
- Creates a new %SObject under a definite father %SObject.
+ \return A new iterator of the %SComponents.
+*/
+ SComponentIterator NewComponentIterator() raises(StudyInvalidReference);
- \param theFatherObject The father %SObject under which this one should be created.
- \return New %SObject
+/*! \brief Create a new %StudyBuilder to add or modify an object in the study.
-See \ref example18 for an example of this method usage in batchmode of %SALOME application.
+ \return A new %StudyBuilder.
+See \ref example20 for an example of this method usage in batchmode of %SALOME application.
*/
+ StudyBuilder NewBuilder() raises(StudyInvalidReference);
+/*! \brief Labels dependency
- SObject NewObject (in SObject theFatherObject) raises(LockProtection);
+ Updates the map with IOR attribute. It's an inner method used for optimization.
+*/
+ void UpdateIORLabelMap(in string anIOR, in string anEntry) raises(StudyInvalidReference);
-/*! \brief Creation of a new %SObject with a definite %tag
+/*! \brief Getting properties of the study
- Creates a new %SObject with a definite %tag.
+ Returns the attribute, which contains the properties of this study.
- \param atag Long value corresponding to the tag of the new %SObject.
- \return New %SObject
+See \ref example20 for an example of this method usage in batchmode of %SALOME application.
*/
- SObject NewObjectToTag (in SObject theFatherObject, in long atag) raises(LockProtection);
-/*! \brief Deletion of the %SObject
-
- Removes a %SObject from the %StudyBuilder.
-
- \param anObject The %SObject to be deleted.
+ AttributeStudyProperties GetProperties() raises(StudyInvalidReference);
+/*! \brief Indicate whether the %study has been saved
*/
- void RemoveObject (in SObject anObject) raises(LockProtection);
-/*! \brief Deletion of the %SObject with all his child objects.
-
- Removes the %SObject with all his child objects.
+ attribute boolean IsSaved;
+/*! \brief Indicate whether the %study has been modified and not saved.
- \param anObject The %SObject to be deleted with all child objects.
+ Returns True if the %study has been modified and not saved.
*/
- void RemoveObjectWithChildren(in SObject anObject) raises(LockProtection);
-
-/*!
- Loads a %SComponent.
-
-See \ref example19 for an example of this method usage in batchmode of %SALOME application.
+ boolean IsModified() raises(StudyInvalidReference);
+/*! \brief Mark the %study as being modified and not saved.
*/
- void LoadWith (in SComponent sco, in Driver Engine) raises (SALOME::SALOME_Exception);
-/*!
- Loads a %SObject.
+ void Modified() raises(StudyInvalidReference);
- \param sco %SObject to be loaded.
+/*! \brief Indicate the file where the %study has been saved
*/
- void Load (in SObject sco);
-
-/*! \brief Looking for or creating an attribute assigned to the %SObject
+ attribute wstring URL;
- Allows to find or create an attribute of a specific type which is assigned to the object.
- \param anObject The %SObject corresponding to the attribute which is looked for.
- \param aTypeOfAttribute Type of the attribute.
+/*! \brief List of %SObjects
-See \ref example1 for an example of this method usage in batchmode of %SALOME application.
+ Returns the list of %SObjects which refers to %anObject.
*/
+ ListOfSObject FindDependances(in SObject anObject) raises(StudyInvalidReference);
- GenericAttribute FindOrCreateAttribute(in SObject anObject,
- in string aTypeOfAttribute) raises(LockProtection);
+/*! \brief The date of the last saving of the study
-/*! \brief Looking for an attribute assigned to a %SObject
+ Returns the date of the last saving of study with format: "DD/MM/YYYY HH:MM"
+*/
+ string GetLastModificationDate() raises(StudyInvalidReference);
+/*! \brief The list of modification dates of the study
- Allows to find an attribute of a specific type which is assigned to the object.
- \param anObject The %SObject corresponding to the attribute which is looked for.
- \param aTypeOfAttribute Type of the attribute.
- \param anAttribute Where the attribute is placed if it's found.
- \return True if it finds an attribute.
- */
+ Returns the list of modification dates (without creation date) with format "DD/MM/YYYY HH:MM".
+ Note : the first modification begins the list.
+*/
+ ListOfDates GetModificationsDate() raises(StudyInvalidReference);
+/*! \brief Object conversion.
- boolean FindAttribute(in SObject anObject,
- out GenericAttribute anAttribute,
- in string aTypeOfAttribute);
-/*! \brief Deleting the attribute assigned to the %SObject
+ Converts an object into IOR.
+ \return IOR
+*/
+ string ConvertObjectToIOR(in Object theObject);
+/*! \brief Object conversion.
- Removes the attribute of a specific type which is assigned to the object.
- \param anObject The %SObject corresponding to the attribute.
- \param aTypeOfAttribute Type of the attribute.
+ Converts IOR into an object.
+ \return An object
+*/
+ Object ConvertIORToObject(in string theIOR);
-See \ref example17 for an example of this method usage in batchmode of %SALOME application.
+/*! \brief Get a new %UseCaseBuilder.
*/
- void RemoveAttribute(in SObject anObject,
- in string aTypeOfAttribute) raises(LockProtection);
-/*!
- Adds a reference between %anObject and %theReferencedObject.
- \param anObject The %SObject which will get a reference
- \param theReferencedObject The %SObject having a reference
+ UseCaseBuilder GetUseCaseBuilder() raises(StudyInvalidReference);
+
+/*! \brief Clear a study object
*/
+ void Clear() raises(StudyInvalidReference);
- void Addreference(in SObject anObject,
- in SObject theReferencedObject) ;
-
-/*!
- Removes a reference from %anObject to another object.
- \param anObject The %SObject which contains a reference
+/*! \brief Initialization a study object
*/
+ void Init() raises(StudyInvalidReference);
+
+/*! \brief Open a study by url
- void RemoveReference(in SObject anObject) ;
-
-/*!
- Adds a directory in the %Study.
- \param theName String parameter defining the name of the directory.
-
-See \ref example23 for an example of this method usage in batchmode of %SALOME application.
-
+ Reads and activates the structure of the study %Objects.
+ \param aStudyUrl The path to the study
*/
- void AddDirectory(in string theName) raises(LockProtection);
-
-/*! \brief Identification of the %SObject's substructure.
+ boolean Open (in URLPath aStudyUrl) raises (SALOME::SALOME_Exception);
+
+/*! \brief Saving the study in a file (or files).
- Identification of the %SObject's substructure by GUID.
+ Saves a study.
+ \param theMultiFile If this parameter is True the study will be saved in several files.
+ \param theASCII If this parameter is True the study will be saved in ASCII format, otherwise in HDF format.
+*/
+ boolean Save(in boolean theMultiFile, in boolean theASCII) raises(StudyInvalidReference);
+
+/*! \brief Saving the study in a specified file (or files).
+ Saves the study in a specified file (or files).
+ \param aUrl The path to the definite file in whcih the study will be saved
+ \param theMultiFile If this parameter is True the study will be saved in several files.
+ \param theASCII If this parameter is True the study will be saved in ASCII format, otherwise in HDF format.
- \param anObject The %SObject which will be identified
- \param theGUID GUID has the following format "00000000-0000-0000-0000-000000000000"
+See \ref example1 for an example of this method usage in batchmode of %SALOME application.
*/
-
- void SetGUID(in SObject anObject, in string theGUID) raises(LockProtection);
+ boolean SaveAs(in URLPath aUrl, // if the file already exists
+ in boolean theMultiFile, // overwrite (as option)
+ in boolean theASCII)
+ raises(StudyInvalidReference);
/*!
-Searches for a definite %SObject with a definite GUID and returns True if it finds it.
-
-\param anObject A definite %SObject which will be identified
-\param theGUID GUID has the following format "00000000-0000-0000-0000-000000000000"
+ Returns True, if the given %SObject can be copied to the clipboard.
*/
- boolean IsGUID(in SObject anObject, in string theGUID);
-
-/*! \brief Creation of a new command
-
- Creates a new command which can contain several different actions.
-
-See \ref example3 for an example of this method usage in batchmode of %SALOME application.
-
+ boolean CanCopy(in SObject theObject) raises(StudyInvalidReference);
+/*!
+ Returns True, if the given %SObject is copied to the clipboard.
+ \param theObject The %SObject which will be copied
*/
- void NewCommand(); // command management
-/*! \brief Execution of the command
-
- Commits all actions declared within this command.
-
- \exception LockProtection This exception is raised, when trying to perform this command a study, which is protected for modifications.
-
-See \ref example16 for an example of this method usage in batchmode of %SALOME application.
-
+ boolean Copy(in SObject theObject) raises(StudyInvalidReference);
+/*!
+ Returns True, if the object from the clipboard can be pasted to the given %SObject.
+ \param theObject The %SObject stored in the clipboard.
*/
- void CommitCommand() raises(LockProtection); // command management
+ boolean CanPaste(in SObject theObject) raises(StudyInvalidReference);
/*!
- Returns True if at this moment there is a command under execution.
+ Returns the %SObject in which the object from the clipboard was pasted to.
+ \param theObject The %SObject which will be pasted
+ \exception SALOMEDS::StudyBuilder::LockProtection This exception is raised, when trying to paste
+ an object into a study, which is protected for modifications.
*/
- boolean HasOpenCommand();
-/*! \brief Cancellation of the command
-
- Cancels all actions declared within the command.
+ SObject Paste(in SObject theObject) raises (SALOMEDS::StudyBuilder::LockProtection);
-See \ref example17 for an example of this method usage in batchmode of %SALOME application.
+/*! \brief Enable (if isEnabled = True)/disable automatic addition of new %SObjects to the use case.
*/
- void AbortCommand(); // command management
-/*! \brief Undolimit
+ void EnableUseCaseAutoFilling(in boolean isEnabled) raises(StudyInvalidReference);
- The number of actions which can be undone
+/*!
+ Functions for internal usage only
*/
- attribute long UndoLimit;
-/*! \brief Undo method
+ void AddPostponed(in string theIOR) raises(StudyInvalidReference);
- Cancels all actions of the last command.
+ void AddCreatedPostponed(in string theIOR) raises(StudyInvalidReference);
- \exception LockProtection This exception is raised, when trying to perform this command a study, which is protected for modifications.
+ void RemovePostponed(in long theUndoLimit) raises(StudyInvalidReference);
-See \ref example16 for an example of this method usage in batchmode of %SALOME application.
+ void UndoPostponed(in long theWay) raises(StudyInvalidReference);
-*/
- void Undo() raises (LockProtection);
-/*! \brief Redo method
+ boolean DumpStudy(in string thePath,
+ in string theBaseName,
+ in boolean isPublished,
+ in boolean isMultiFile) raises(StudyInvalidReference);
- Redoes all actions of the last command.
+/*! \brief Get an AttributeParameter used to store common parameters for given %theSavePoint.
-\exception LockProtection This exception is raised, when trying to perform this command a study, which is protected for modifications.
+ \param theID identifies a common parameters set (Example: "Interface Applicative")
+ \param theSavePoint is number of a set of parameters as there can be several sets
+*/
+ AttributeParameter GetCommonParameters(in string theID, in long theSavePoint) raises(StudyInvalidReference);
-See \ref example16 for an example of this method usage in batchmode of %SALOME application.
+/*! \brief Get an AttributeParameter used to store parameters for given %theModuleName.
+ \param theID identifies a common parameters set (Example: "Interface Applicative")
+ \param theModuleName is a name of the module (Example: "Geometry")
+ \param theSavePoint is number of a set of parameters as there can be several sets
*/
- void Redo() raises (LockProtection);
-/*!
- Returns True if at this moment there are any actions which can be canceled.
+ AttributeParameter GetModuleParameters(in string theID, in string theModuleName, in long theSavePoint) raises(StudyInvalidReference);
-See \ref example16 for an example of this method usage in batchmode of %SALOME application.
+/*! \brief Get a default Python script to restore visual parameters for given %theModuleName.
+
+ \param theModuleName is a name of the module (Example: "Geometry")
+ \param indent is a string to use for script indentation
*/
- boolean GetAvailableUndos();
+ string GetDefaultScript(in string theModuleName, in string indent) raises(StudyInvalidReference);
+
/*!
- Returns True if at this moment there are any actions which can be redone.
+ Private method, returns an implementation of this Study.
+ \param theHostname is a hostname of the caller
+ \param thePID is a process ID of the caller
+ \param isLocal is set True if the Study is launched locally with the caller
+*/
+ long long GetLocalImpl(in string theHostname, in long thePID, out boolean isLocal);
-See \ref example3 for an example of this method usage in batchmode of %SALOME application.
-*/
- boolean GetAvailableRedos();
-/*!
- Puts name attribute with the given string value to the given %SObject
+/*! \brief Mark this Study as being locked by the given locker.
- \param theSO Existing SObject to set name attribute.
- \param theValue The value to be set to the name attribute.
+ The lock status can be checked by method IsStudyLocked
+ \param theLockerID identifies a locker of the study can be for ex. IOR of the engine that locks the study.
*/
- void SetName(in SObject theSO, in string theValue) raises (LockProtection);
+ void SetStudyLock(in string theLockerID) raises(StudyInvalidReference);
-/*!
- Puts comment attribute with the given string value to the given %SObject
+/*! \brief Indicate if the Study is locked
- \param theSO Existing SObject to set comment attribute.
- \param theValue The value to be set to the comment attribute.
+ Returns True if the Study was marked locked.
*/
- void SetComment(in SObject theSO, in string theValue) raises (LockProtection);
+ boolean IsStudyLocked() raises(StudyInvalidReference);
-/*!
- Puts IOR attribute with the given string value to the given %SObject
+/*! \brief Mark this Study as being unlocked by the given locker.
- \param theSO Existing SObject to set IOR attribute.
- \param theValue The value to be set to the IOR attribute.
+ The lock status can be checked by method IsStudyLocked
+ \param theLockerID identifies a locker of the study can be for ex. IOR of the engine that unlocks the study.
*/
- void SetIOR(in SObject theSO, in string theValue) raises (LockProtection);
- };
-
- //==========================================================================
-/*! \brief %Study Manager interface
+ void UnLockStudy(in string theLockerID) raises(StudyInvalidReference);
- The purpose of the Manager is to manipulate the %Studies. You will find in this
- interface the methods to create, open,
- close, and save a %Study. Since a %SALOME session is multi-document, you will
- also find the methods allowing to navigate
- through the collection of studies present in a session.
+/*! \brief Get the list of IDs of the Study's lockers.
*/
- //==========================================================================
+ ListOfStrings GetLockerID() raises(StudyInvalidReference);
- interface StudyManager
- {
-/*!
- Determines whether the server has already been loaded or not.
+/*! \brief Create real variable with Name theVarName and value theValue
+
+ (or set if variable value into theValue already exists)
+ \param theVarName is a name of the variable
+ \param theVarName is a value of the variable.
*/
- void ping();
+ void SetReal( in string theVarName, in double theValue ) raises(StudyInvalidReference);
- void Shutdown();
+/*! \brief Create integer variable with Name theVarName and value theValue
-/*!
- Returns the PID of the server
+ (or set if variable value into theValue already exists)
+ \param theVarName is a name of the variable
+ \param theVarName is a value of the variable.
*/
- long getPID();
+ void SetInteger( in string theVarName, in long theValue ) raises(StudyInvalidReference);
+/*! \brief Create boolean variable with Name theVarName and value theValue
-/*!
- Shutdown the StudyManager process.
+ (or set if variable value into theValue already exists)
+ \param theVarName is a name of the variable
+ \param theVarName is a value of the variable.
*/
- oneway void ShutdownWithExit();
+ void SetBoolean( in string theVarName, in boolean theValue ) raises(StudyInvalidReference);
-/*! \brief Creation of a new study
+/*! \brief Create string variable with Name theVarName and value theValue
- Creates a new study with a definite name.
+ (or set if variable value into theValue already exists)
+ \param theVarName is a name of the variable
+ \param theVarName is a value of the variable.
+*/
+ void SetString( in string theVarName, in string theValue ) raises(StudyInvalidReference);
- \param study_name String parameter defining the name of the study
+/*! \brief Set current value as double for string variable
+*/
+ void SetStringAsDouble( in string theVarName, in double theValue ) raises(StudyInvalidReference);
-See \ref example17 for an example of this method usage in batchmode of %SALOME application.
+/*! \brief Get value of a real variable
+ \param theVarName is a name of the variable.
*/
- Study NewStudy(in string study_name) raises (SALOME::SALOME_Exception);
-
-/*! \brief Open a study
+ double GetReal( in string theVarName ) raises(StudyInvalidReference);
- Reads and activates the structure of the study %Objects.
- \param aStudyUrl The path to the study
- \warning This method doesn't activate the corba objects. Only a component can do it.
+/*! \brief Get value of an integer variable
-See \ref example1 for an example of this method usage in batchmode of %SALOME application.
+ \param theVarName is a name of the variable.
*/
- Study Open (in URL aStudyUrl) raises (SALOME::SALOME_Exception);
+ long GetInteger( in string theVarName ) raises(StudyInvalidReference);
-/*! \brief Closing the study
+/*! \brief Get value of a boolean variable
- Closes a study.
+ \param theVarName is a name of the variable.
*/
- void Close(in Study aStudy);
-/*! \brief Saving the study in a HDF file (or files).
+ boolean GetBoolean( in string theVarName ) raises(StudyInvalidReference);
- Saves a study.
+/*! \brief Get value of a string variable
- \param theMultiFile If this parameter is True the study will be saved in several files.
+ \param theVarName is a name of the variable.
+*/
+ string GetString( in string theVarName ) raises(StudyInvalidReference);
-See \ref example19 for an example of this method usage in batchmode of %SALOME application.
-*/
- boolean Save(in Study aStudy, in boolean theMultiFile);
-/*! \brief Saving a study in a ASCII file (or files).
+/*! \brief Indicate if a variable is real
- Saves a study in an ASCII format file (or files).
- \param theMultiFile If this parameter is True the study will be saved in several files.
+ Return true if variable is real otherwise return false.
+ \param theVarName is a name of the variable.
*/
- boolean SaveASCII(in Study aStudy, in boolean theMultiFile);
-/*! \brief Saving the study in a specified HDF file (or files).
+ boolean IsReal( in string theVarName ) raises(StudyInvalidReference);
- Saves the study in a specified file (or files).
- \param aUrl The path to the definite file in which the study will be saved
- \param aStudy The study which will be saved
- \param theMultiFile If this parameter is True the study will be saved in several files.
+/*! \brief Indicate if a variable is integer
-See \ref example1 for an example of this method usage in batchmode of %SALOME application.
+ Return true if variable is integer otherwise return false.
+ \param theVarName is a name of the variable.
*/
- boolean SaveAs(in URL aUrl, // if the file already exists
- in Study aStudy,
- in boolean theMultiFile); // overwrite (as option)
-/*! \brief Saving the study in a specified ASCII file (or files).
+ boolean IsInteger( in string theVarName ) raises(StudyInvalidReference);
- Saves the study in a specified ASCII file (or files).
+/*! \brief Indicate if a variable is boolean
- \param aUrl The path to the definite file in which the study will be saved
- \param aStudy The study which will be saved
- \param theMultiFile If this parameter is True the study will be saved in several files.
+ Return true if variable is boolean otherwise return false.
+ \param theVarName is a name of the variable.
*/
- boolean SaveAsASCII(in URL aUrl, // if the file already exists
- in Study aStudy,
- in boolean theMultiFile); // overwrite (as option)
+ boolean IsBoolean( in string theVarName ) raises(StudyInvalidReference);
+/*! \brief Indicate if a variable is string
-/*! \brief List of open studies.
+ Return true if variable is string otherwise return false.
+ \param theVarName is a name of the variable.
+*/
+ boolean IsString( in string theVarName ) raises(StudyInvalidReference);
-Gets the list of open studies
+/*! \brief Indicate if a variable exists in the study
- \return A list of open studies in the current session.
+ Return true if variable exists in the study,
+ otherwise return false.
+ \param theVarName is a name of the variable.
*/
- ListOfOpenStudies GetOpenStudies();
-
-/*! \brief Getting a particular %Study picked by name
+ boolean IsVariable( in string theVarName ) raises(StudyInvalidReference);
- Activates a particular %Study
- among the session collection picking it by name.
- \param aStudyName The name of the study
+/*! \brief Get names of all variables from the study.
*/
- Study GetStudyByName (in string aStudyName);
+ ListOfStrings GetVariableNames() raises(StudyInvalidReference);
-/*! \brief Getting a particular %Study picked by ID
+/*! \brief Remove a variable
+
+ Remove variable with the specified name from the study with substitution of its value.
- Activates a particular %Study
- among the session collection picking it by ID.
- \param aStudyID The ID of the study
+ \param theVarName Name of the variable.
+ \return Status of operation.
*/
- Study GetStudyByID (in short aStudyID);
+ boolean RemoveVariable( in string theVarName ) raises(StudyInvalidReference);
- // copy/paste methods
+/*! \brief Rename a variable
-/*!
- Returns True, if the given %SObject can be copied to the clipboard.
-*/
- boolean CanCopy(in SObject theObject);
-/*!
- Returns True, if the given %SObject is copied to the clipboard.
- \param theObject The %SObject which will be copied
-*/
- boolean Copy(in SObject theObject);
-/*!
- Returns True, if the object from the clipboard can be pasted to the given %SObject.
- \param theObject The %SObject stored in the clipboard.
-*/
- boolean CanPaste(in SObject theObject);
-/*!
- Returns the %SObject in which the object from the clipboard was pasted to.
- \param theObject The %SObject which will be pasted
- \exception SALOMEDS::StudyBuilder::LockProtection This exception is raised, when trying to paste
- an object into a study, which is protected for modifications.
+ Rename variable with the specified name within the study.
+
+ \param theVarName Name of the variable.
+ \param theNewVarName New name for the variable.
+ \return Status of operation.
*/
- SObject Paste(in SObject theObject) raises (SALOMEDS::StudyBuilder::LockProtection);
+ boolean RenameVariable( in string theVarName, in string theNewVarName ) raises(StudyInvalidReference);
-/*! \brief Object conversion.
+/*! \brief Indicate whether variable is used
- Converts an object into IOR.
- \return IOR
+ Check that variable is used in the study.
+
+ \param theVarName Name of the variable.
+ \return Variable usage.
*/
- string ConvertObjectToIOR(in Object theObject);
-/*! \brief Object conversion.
+ boolean IsVariableUsed( in string theVarName ) raises(StudyInvalidReference);
- Converts IOR into an object.
- \return An object
+/*! \brief Parse variables used for object creation
+
+ \param string with variables, separated by special symbol.
+ \return Variables list.
*/
- Object ConvertIORToObject(in string theIOR);
+ ListOfListOfStrings ParseVariables( in string theVars ) raises(StudyInvalidReference);
/*!
- Private method, returns an implementation of this StudyManager.
- \param theHostname is a hostname of the caller
- \param thePID is a process ID of the caller
- \param isLocal is set True if the StudyManager is launched locally with the caller
+ Attach an observer to the Study
+
+ \param theObserver observer being attached
+ \param modify when \c true, observer receives any object's modification events;
+ otherwise observer receives object's creation events only
*/
- long long GetLocalImpl(in string theHostname, in long thePID, out boolean isLocal);
+ void attach(in SALOMEDS::Observer theObserver, in boolean modify);
+/*!
+ Detach an observer from the Study
+ \param theObserver observer to be detached
+*/
+ void detach(in SALOMEDS::Observer theObserver);
};
-
//==========================================================================
/*! \brief %SObject interface
@@ -1081,11 +927,6 @@ Gets the list of open studies
*/
ListOfAttributes GetAllAttributes();
-/*! Gets the study of a given %SObject.
- \return The study containing the given %SObject.
-*/
- Study GetStudy();
-
/*! Gets the CORBA object by its own IOR attribute.
Returns nil, if can't.
\return The CORBA object of the %SObject.
@@ -1374,7 +1215,7 @@ This class represents a common tool for all components integrated into SALOME ap
can be called by any component and which provide the following functionality:
- publishing in the study of the objects created by a definite component
-
- saving/loading of the data created by a definite component. These methods are called by the StudyManager when loading/saving a study containing the data created by a definite component.
+
- saving/loading of the data created by a definite component. These methods are called when loading/saving a study containing the data created by a definite component.
- transforming of the transient references into persistent references (or vice versa) of the SObjects when saving (or loading) a study
- copy/paste common functionality. These methods can be called by any component in order to copy/paste its object created in the study
@@ -1386,7 +1227,7 @@ can be called by any component and which provide the following functionality:
/*! \brief Saving the data produced by a definite component.
- This method is called by the StudyManager when saving a study.
+ This method is called when saving a study.
\param theComponent %SComponent corresponding to this Component
\param theURL The path to the file in which the data will be saved.
\param isMultiFile If the value of this boolean parameter is True, the data will be saved in several files.
@@ -1401,7 +1242,7 @@ can be called by any component and which provide the following functionality:
/*! \brief Saving the data in ASCII format produced by a definite component.
- This method is called by the StudyManager when saving a study in ASCII format.
+ This method is called when saving a study in ASCII format.
\param theComponent %SComponent corresponding to this Component
\param theURL The path to the file in which the data will be saved.
\param isMultiFile If the value of this boolean parameter is True, the data will be saved in several files.
@@ -1414,7 +1255,7 @@ can be called by any component and which provide the following functionality:
/*! \brief Loading the data.
- This method is called by the StudyManager when opening a study.
+ This method is called when opening a study.
\param theComponent %SComponent corresponding to this Component
\param theStream The file which contains all data saved by the component on Save method
\param isMultiFile If the value of this boolean parameter is True, the data will be loaded from several files
@@ -1425,7 +1266,7 @@ can be called by any component and which provide the following functionality:
/*! \brief Loading the data from files in ASCII format.
- This method is called by the StudyManager when opening a study.
+ This method is called when opening a study.
\param theComponent %SComponent corresponding to this Component
\param theStream The file which contains all data saved by the component on Save method
\param isMultiFile If the value of this boolean parameter is True, the data will be loaded from several files
@@ -1436,7 +1277,7 @@ can be called by any component and which provide the following functionality:
/*! \brief Closing of the study
- This method Close is called by the StudyManager when closing a study.
+ This method Close is called when closing a study.
\param aSComponent The according %SComponent
*/
@@ -1500,7 +1341,6 @@ study is open, these references are transformed into persintent IORs.
/*! \brief Publishing in the study
Publishes the given object in the %study, using the algorithm of this component.
- \param theStudy The %study in which the object is published
\param theSObject If this parameter is null the object is published for the first time. Otherwise
this parameter should contain a reference to the object published earlier
\param theObject The object which is published
@@ -1509,7 +1349,7 @@ study is open, these references are transformed into persintent IORs.
\return The published %SObject.
*/
- SObject PublishInStudy(in Study theStudy, in SObject theSObject, in Object theObject, in string theName);
+ SObject PublishInStudy(in SObject theSObject, in Object theObject, in string theName);
// copy/paste methods
diff --git a/idl/SALOME_Component.idl b/idl/SALOME_Component.idl
index f5b18d4a3..8c02315aa 100644
--- a/idl/SALOME_Component.idl
+++ b/idl/SALOME_Component.idl
@@ -90,12 +90,9 @@ module Engines
\param componentName Name of the component which will be registered
in Registry and Name Service,
(instance number suffix added to the registered name)
- \param studyId 0 if instance is not associated to a study,
- >0 otherwise (== study id)
\return a loaded component
*/
- Engines::EngineComponent create_component_instance(in string componentName,
- in long studyId);
+ Engines::EngineComponent create_component_instance(in string componentName);
//! Create a new Python servant instance of a generic service.
/*!
@@ -104,8 +101,6 @@ module Engines
Warning: no internal registration is done, so it is up to the caller to
manage the various instantiation.
\param serviceName Name of the service
-
- >0 otherwise (== study id)
\param reason in case of error (return void string) a string explaining the error
\return the IOR of the loaded service.
*/
@@ -118,25 +113,20 @@ module Engines
\param componentName Name of the component which will be registered
in Registry and Name Service,
(instance number suffix added to the registered name)
- \param studyId 0 if instance is not associated to a study,
- >0 otherwise (== study id)
\param env a dict of env variables
\param reason in case of error (return nil) a string explaining the error
\return a loaded component
*/
Engines::EngineComponent create_component_instance_env(in string componentName,
- in long studyId, in FieldsDict env,
+ in FieldsDict env,
out string reason);
//! Find a servant instance of a component
/*!
\param registeredName Name of the component in Registry or Name Service,
without instance suffix number
- \param studyId 0 if instance is not associated to a study,
- >0 otherwise (== study id)
- \return the first instance found with same studyId
+ \return the first instance found
*/
- EngineComponent find_component_instance(in string registeredName,
- in long studyId);
+ EngineComponent find_component_instance(in string registeredName);
//! Find a servant instance of a component, or create a new one.
/*!
@@ -261,15 +251,6 @@ module Engines
//! Determines whether the server has already been loaded or not.
void ping();
- //! Get study associated to component instance
- /*!
- get study associated to component instance
- \return -1: not initialised (Internal Error)
- 0: multistudy component instance
- >0: study id associated to this instance
- */
- long getStudyId();
-
//! Remove component instance from container
/*!
Deactivates the %Component.
@@ -355,8 +336,7 @@ module Engines
Returns a python script, which is being played back reproduces
the data model of component
*/
- TMPFile DumpPython(in Object theStudy,
- in boolean isPublished,
+ TMPFile DumpPython(in boolean isPublished,
in boolean isMultiFile,
out boolean isValidScript);
@@ -469,11 +449,10 @@ module Engines
It is worth using this method only if hasObjectInfo() method returns true.
\param entry object's entry.
- \param studyId study id
\return an information about the given object.
*/
- string getObjectInfo(in long studyId, in string entry);
+ string getObjectInfo(in string entry);
//! Get version of the component
/*!
diff --git a/idl/SALOME_ModuleCatalog.idl b/idl/SALOME_ModuleCatalog.idl
index 78439ffe3..9aa6c6164 100644
--- a/idl/SALOME_ModuleCatalog.idl
+++ b/idl/SALOME_ModuleCatalog.idl
@@ -166,7 +166,6 @@ a path to a component
ComponentType type;
string name;
string username;
- boolean multistudy;
ImplType implementationType;
string implname;
string icon;
@@ -269,10 +268,6 @@ a path to a component
*/
readonly attribute string componentusername;
-/*! \brief Get whether the component is multistudy or not
-*/
- readonly attribute boolean multistudy;
-
/*! \brief Get the type of the component
*/
readonly attribute ComponentType component_type ;
diff --git a/idl/SALOME_PACOExtension.idl b/idl/SALOME_PACOExtension.idl
index 855f6f73c..ecedde31a 100644
--- a/idl/SALOME_PACOExtension.idl
+++ b/idl/SALOME_PACOExtension.idl
@@ -39,8 +39,7 @@ module Engines
// Replicated Method used by the proxy to create
// a PACO Component
void create_paco_component_node_instance(in string registeredName,
- in string proxy_containerName,
- in long studyId) raises(SALOME::SALOME_Exception);
+ in string proxy_containerName) raises(SALOME::SALOME_Exception);
void updateInstanceNumber();
};
diff --git a/idl/SALOME_SDS.idl b/idl/SALOME_SDS.idl
index 1b28d5610..09401cd00 100644
--- a/idl/SALOME_SDS.idl
+++ b/idl/SALOME_SDS.idl
@@ -140,6 +140,7 @@ module SALOME
void fetchAndGetAccessOfVar(in string varName, out string access, out ByteVec data) raises (SALOME::SALOME_Exception);
Transaction createRdOnlyVarTransac(in string varName, in ByteVec constValue) raises (SALOME::SALOME_Exception);
Transaction createRdExtVarTransac(in string varName, in ByteVec constValue) raises (SALOME::SALOME_Exception);
+ Transaction createRdExtVarFreeStyleTransac(in string varName, in ByteVec constValue, in ByteVec sha1) raises (SALOME::SALOME_Exception);
Transaction createRdExtInitVarTransac(in string varName, in ByteVec constValue) raises (SALOME::SALOME_Exception);
Transaction createRdWrVarTransac(in string varName, in ByteVec constValue) raises (SALOME::SALOME_Exception);
Transaction addKeyValueInVarHard(in string varName, in ByteVec keyValue, in ByteVec constValue) raises (SALOME::SALOME_Exception);
diff --git a/idl/SALOME_Session.idl b/idl/SALOME_Session.idl
index 90509c0bb..5715977b1 100644
--- a/idl/SALOME_Session.idl
+++ b/idl/SALOME_Session.idl
@@ -51,11 +51,10 @@ module SALOME
It can be:
-# asleep : no running study
- -# running : one or more running studies
+ -# running : one running study
*/
SessionState state ;
- //! Number of running studies
- short runningStudies ;
+
//! It is True if GUI is active in the session
boolean activeGUI ;
} ;
@@ -70,8 +69,8 @@ module SALOME
{
//! This exception is raised when trying to stop the %session with active GUI
exception GUIActive {} ;
-//! This exception is raised when trying to stop the %session with a number of running studies.
- exception RunningStudies {} ;
+//! This exception is raised when trying to stop the %session with running study.
+ exception RunningStudy {} ;
//! Launches GUI in the session
void GetInterface();
@@ -80,7 +79,7 @@ module SALOME
Engines::EngineComponent GetComponent(in string theLibraryName);
//! Stops the %Session (It must be idle)
- void StopSession() raises(GUIActive, RunningStudies) ;
+ void StopSession() raises(GUIActive, RunningStudy) ;
//! Gets Session State
StatSession GetStatSession() ;
@@ -94,8 +93,6 @@ module SALOME
long getPID();
//! Returns host name
string getHostname();
-//! Get Active study ID
- long GetActiveStudyId();
//! Restores a state of the study at theSavePoint
boolean restoreVisualState(in long theSavePoint);
diff --git a/resources/KERNELCatalog.xml.in b/resources/KERNELCatalog.xml.in
index 5648c41fd..3a87aadde 100644
--- a/resources/KERNELCatalog.xml.in
+++ b/resources/KERNELCatalog.xml.in
@@ -77,7 +77,6 @@
NRI
@SALOMEKERNEL_VERSION@
GUI Neutral Context
- 1
hostname = muna
@@ -88,7 +87,6 @@
NRI
@SALOMEKERNEL_VERSION@
GUI Neutral Context
- 1
'linux' ~ OS
@@ -98,7 +96,6 @@
NRI
@SALOMEKERNEL_VERSION@
GUI Neutral Context
- 1
'linux' ~ OS
diff --git a/salome_adm/prepare_generating_doc.py b/salome_adm/prepare_generating_doc.py
index dbe0153e7..5dec70e4b 100755
--- a/salome_adm/prepare_generating_doc.py
+++ b/salome_adm/prepare_generating_doc.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
# This library is free software; you can redistribute it and/or
@@ -32,16 +32,16 @@
# Current the script does:
# 1. remove Python documentation in triple double quotes (like """some_comments""")
#
-# Usage: prepare_generating_doc.py [-o ]
+# Usage: prepare_generating_doc.py [-o ]
#
# If is not specified, it is generated in the current directory.
#
-#################################################################################
+###############################################################################
-import os, sys, re
+import os, sys
def main(input_file, output_file = None):
-
+
# open input file
try:
infile = open(input_file, 'rb')
@@ -50,7 +50,7 @@ def main(input_file, output_file = None):
pass
if not output_file: output_file = os.path.basename(input_file)
-
+
# open output file
try:
outfile = open(output_file, 'wb')
@@ -65,8 +65,8 @@ def main(input_file, output_file = None):
for line in infile.readlines():
# 1. remove comments like """some_comments"""
- n = line.find('"""')
- n1 = line[(n+2):].find('"""')
+ n = line.find(b'"""')
+ n1 = line[(n+2):].find(b'"""')
if (n > -1) and (n1 > -1):
continue
if isCom:
@@ -92,14 +92,13 @@ def main(input_file, output_file = None):
pass
if __name__ == "__main__":
- import optparse
- parser = optparse.OptionParser(usage="%prog [options] input_file")
+ import argparse
+ parser = argparse.ArgumentParser()
h = "Output file (if not specified, generated in the current directory)"
- parser.add_option("-o", "--output", dest="output",
- action="store", default=None, metavar="file",
- help=h)
- (options, args) = parser.parse_args()
-
- if len( args ) < 1: sys.exit("Input file is not specified")
- main( args[0], options.output )
+ parser.add_argument("-o", "--output", dest="output",
+ action="store", default=None, metavar="file",
+ help=h)
+ parser.add_argument('input_file')
+ args = parser.parse_args()
+ main( args.input_file, args.output )
pass
diff --git a/salome_adm/unix/config_files/check_swig.m4 b/salome_adm/unix/config_files/check_swig.m4
index 8136f11e5..4b61ca056 100644
--- a/salome_adm/unix/config_files/check_swig.m4
+++ b/salome_adm/unix/config_files/check_swig.m4
@@ -58,7 +58,7 @@ EOF
AC_MSG_RESULT($swig_ok)
fi
-numpydir=`$PYTHON -c "import numpy;print numpy.get_include()" 2>/dev/null`
+numpydir=`$PYTHON -c "import numpy;print(numpy.get_include())" 2>/dev/null`
if test -d "$numpydir"; then
numpy_ok=yes
PYTHON_INCLUDES="-I$numpydir $PYTHON_INCLUDES"
diff --git a/salome_adm/unix/config_files/pyembed.m4 b/salome_adm/unix/config_files/pyembed.m4
index 9f153147a..f40fd0282 100644
--- a/salome_adm/unix/config_files/pyembed.m4
+++ b/salome_adm/unix/config_files/pyembed.m4
@@ -32,7 +32,7 @@ AC_MSG_CHECKING(for flags used to embed python interpreter)
changequote(,)dnl
py_makefile="`$PYTHON -c '
import sys
-print \"%s/lib/python%s/config/Makefile\"%(sys.exec_prefix, sys.version[:3])'`"
+print(\"%s/lib/python%s/config/Makefile\"%(sys.exec_prefix, sys.version[:3]))'`"
changequote([,])dnl
if test ! -f "$py_makefile"; then
AC_MSG_ERROR([*** Couldn't find the python config makefile. Maybe you are
@@ -44,11 +44,11 @@ py_lib="`$PYTHON -c '
import sys
ver = sys.version[:3]
pre = sys.exec_prefix
-print \"-L%s/lib/python%s/config\" % (pre, ver),
+print(\"-L%s/lib/python%s/config\" % (pre, ver)),
if ver == \"1.4\":
- print \"-lPython -lObjects -lParser\"
+ print(\"-lPython -lObjects -lParser\")
else:
- print \"-lpython\" + ver
+ print(\"-lpython\" + ver)
changequote([,])dnl
@@ -83,7 +83,7 @@ AC_MSG_CHECKING(for config.c.in)
changequote(,)dnl
py_config_in="`$PYTHON -c '
import sys
-print \"%s/lib/python%s/config/config.c.in\"%(sys.exec_prefix, sys.version[:3])'`"
+print(\"%s/lib/python%s/config/config.c.in\"%(sys.exec_prefix, sys.version[:3]))'`"
changequote([,])dnl
if test ! -f "$py_config_in"; then
AC_MSG_ERROR([*** Couldn't find the config.c.in file. Maybe you are
diff --git a/salome_adm/unix/config_files/python.m4 b/salome_adm/unix/config_files/python.m4
index 9153ded5d..833f4c90a 100644
--- a/salome_adm/unix/config_files/python.m4
+++ b/salome_adm/unix/config_files/python.m4
@@ -37,33 +37,31 @@ dnl a `module'.
AC_DEFUN([CHECK_PYTHON],
[
+ AC_BEFORE([$0],[AM_PATH_PYTHON])
+ AC_REQUIRE([AC_LINKER_OPTIONS])dnl
+
python_ok=yes
- AC_ARG_WITH(python,
- [AC_HELP_STRING([--with-python=DIR],[root directory path of python installation])],
- [PYTHON="$withval/bin/python"
- AC_MSG_RESULT("select python distribution in $withval")
- ], [
- AC_PATH_PROG(PYTHON, python)
- ])
+ AM_PATH_PYTHON([3])
- AC_CHECKING([local Python configuration])
-
- AC_REQUIRE([AC_LINKER_OPTIONS])dnl
-
- PYTHON_PREFIX=`echo $PYTHON | sed -e "s,[[^/]]*$,,;s,/$,,;s,^$,.,"`
- PYTHON_PREFIX=`echo $PYTHON_PREFIX | sed -e "s,[[^/]]*$,,;s,/$,,;s,^$,.,"`
- PYTHONHOME=$PYTHON_PREFIX
-
- AC_SUBST(PYTHON_PREFIX)
- AC_SUBST(PYTHONHOME)
-
- changequote(<<, >>)dnl
- PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"`
- changequote([, ])dnl
- AC_SUBST(PYTHON_VERSION)
+ AC_MSG_NOTICE([local Python configuration])
+
+ AC_SUBST([python_bin],
+ [`basename ${PYTHON}`] )
+
+ AC_SUBST([PYTHON_ABIFLAGS],
+ [`${PYTHON} -c "import sys; print (sys.abiflags)"`] )
+
+ AC_SUBST([PYTHON_PREFIX],
+ [`${PYTHON} -c "import sys; print (sys.prefix)"`] )
+
+ AC_SUBST([PYTHONHOME],
+ [`${PYTHON} -c "import sys; print (sys.prefix)"`] )
PY_MAKEFILE=${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python$PYTHON_VERSION/config/Makefile
+ if test ! -f "$PY_MAKEFILE"; then
+ PY_MAKEFILE=${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python$PYTHON_VERSION/config-${PYTHON_VERSION}${PYTHON_ABIFLAGS}-${build_cpu}-${build_os}/Makefile
+ fi
if test ! -f "$PY_MAKEFILE"; then
# For Ubuntu >= 13.04
PY_MAKEFILE=${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python$PYTHON_VERSION/config-${build_cpu}-${build_os}/Makefile
@@ -92,13 +90,18 @@ AC_DEFUN([CHECK_PYTHON],
PYTHON_LIB=$PYTHON_LIBS
PYTHON_LIBA=${PYTHON_PREFIX}/lib64/python$PYTHON_VERSION/config/libpython$PYTHON_VERSION.a
fi
+ if test "$PY_MAKEFILE" = "${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python$PYTHON_VERSION/config-${PYTHON_VERSION}${PYTHON_ABIFLAGS}-${build_cpu}-${build_os}/Makefile" ; then
+ PYTHON_LIBS="-L${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python${PYTHON_VERSION}/config-${PYTHON_VERSION}${PYTHON_ABIFLAGS}-${build_cpu}-${build_os} -lpython${PYTHON_VERSION}${PYTHON_ABIFLAGS}"
+ PYTHON_LIB=$PYTHON_LIBS
+ PYTHON_LIBA=${PYTHON_PREFIX}/lib${LIB_LOCATION_SUFFIX}/python$PYTHON_VERSION/config-${PYTHON_VERSION}${PYTHON_ABIFLAGS}-${build_cpu}-${build_os}/libpython${PYTHON_VERSION}${PYTHON_ABIFLAGS}.a
+ fi
fi
dnl At times (like when building shared libraries) you may want
dnl to know which OS Python thinks this is.
AC_SUBST(PYTHON_PLATFORM)
- PYTHON_PLATFORM=`$PYTHON -c "import sys; print sys.platform"`
+ PYTHON_PLATFORM=`$PYTHON -c "import sys; print(sys.platform)"`
AC_SUBST(PYTHON_SITE)
AC_ARG_WITH(python-site,
diff --git a/src/AppQuickStart/app-quickstart.py b/src/AppQuickStart/app-quickstart.py
index 59cefd2d4..1a3fde918 100755
--- a/src/AppQuickStart/app-quickstart.py
+++ b/src/AppQuickStart/app-quickstart.py
@@ -21,55 +21,50 @@
import os
import shutil
-import optparse
+import argparse
# Options of this script
def profileQuickStartParser() :
- parser = optparse.OptionParser( usage = "usage: python app-quickstart.py [options]" )
+ parser = argparse.ArgumentParser( usage = "usage: python app-quickstart.py [options]" )
- parser.add_option('-p',
+ parser.add_argument('-p',
"--prefix",
metavar="",
- type="string",
action="store",
dest="prefix",
default='.',
help="Where the application's sources will be generated. [Default : '.']")
- parser.add_option('-m',
+ parser.add_argument('-m',
"--modules",
metavar="",
- type="string",
action="store",
dest="modules",
default='KERNEL,GUI',
help="List of the application's modules. [Default : KERNEL,GUI]")
- parser.add_option('-n',
+ parser.add_argument('-n',
"--name",
- type="string",
action="store",
dest="name",
help="Name of the application")
- parser.add_option('-v',
+ parser.add_argument('-v',
"--version",
- type="string",
action="store",
dest="version",
default='1.0',
help="Version of the application. [Default : 1.0]")
- parser.add_option('-s',
+ parser.add_argument('-s',
"--slogan",
- type="string",
action="store",
dest="slogan",
default='',
help="Slogan of the application.")
- parser.add_option('-f',
+ parser.add_argument('-f',
"--force",
action="store_true",
dest="force",
@@ -85,8 +80,14 @@ def profileGenerateSplash( resources_dir, appname, version, subtext ):
import ImageDraw
import ImageFont
- uname = unicode(appname, 'UTF-8')
- uversion = unicode(version, 'UTF-8')
+ if isinstance(appname, bytes):
+ uname = str(appname, 'UTF-8')
+ else:
+ uname = appname
+ if isinstance(version, bytes):
+ uversion = str(version, 'UTF-8')
+ else:
+ uversion = version
# fonts
fontbig = ImageFont.truetype( os.path.join( resources_dir, 'Anita semi square.ttf' ), 64)
@@ -98,7 +99,7 @@ def profileGenerateSplash( resources_dir, appname, version, subtext ):
nbcar = len(uname)
width = 600
if nbcar > 12:
- width = min( width*nbcar/12, 1024) #a little more
+ width = min( width*nbcar//12, 1024) #a little more
height = 300
borderX = 30 #50
borderY = 3 #30
@@ -143,7 +144,10 @@ def profileGenerateLogo( appname, font ):
import Image
import ImageDraw
- uname = unicode(appname, 'UTF-8')
+ if isinstance(appname, bytes):
+ uname = str(appname, 'UTF-8')
+ else:
+ uname = appname
# evaluate size before deleting draw
im = Image.new( "RGBA", (1, 1), (0, 0, 0, 0) )
@@ -157,28 +161,42 @@ def profileGenerateLogo( appname, font ):
del draw
return im
-
+
+# Check if filename is a binary file
+def is_binary(filename):
+ """ returns True if filename is a binary file
+ (from https://stackoverflow.com/a/7392391/2531279)
+ """
+ textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
+ with open(filename, 'rb') as f:
+ s = f.read(512)
+ return bool(s.translate(None, textchars))
+
+
#Replace strings in the template
-def profileReplaceStrings( src, dst, options ) :
- with open( dst, "wt" ) as fout:
- with open( src, "rt" ) as fin:
+def profileReplaceStrings( src, dst, args) :
+ if is_binary(src):
+ shutil.copyfile(src, dst)
+ else:
+ with open( dst, "w") as fout, \
+ open( src, "r") as fin:
for line in fin:
- if options.modules == '_NO_' and '[LIST_OF_MODULES]' in line:
+ if args.modules == '_NO_' and '[LIST_OF_MODULES]' in line:
line = ''
- l = line.replace( '[LIST_OF_MODULES]', options.modules )
- l = l.replace( '[VERSION]', options.version )
- l = l.replace( '[SLOGAN]', options.slogan )
- l = l.replace( '[NAME_OF_APPLICATION]', options.name.upper() )
- l = l.replace( '[Name_of_Application]', options.name )
- l = l.replace( '(name_of_application)', options.name.lower() )
+ l = line.replace( '[LIST_OF_MODULES]', args.modules )
+ l = l.replace( '[VERSION]', args.version )
+ l = l.replace( '[SLOGAN]', args.slogan )
+ l = l.replace( '[NAME_OF_APPLICATION]', args.name.upper() )
+ l = l.replace( '[Name_of_Application]', args.name )
+ l = l.replace( '(name_of_application)', args.name.lower() )
fout.write( l )
#Generation of a template profile sources
-def profileGenerateSources( options, args ) :
+def profileGenerateSources( args ) :
#Set name of several directories
- app_dir = options.prefix
+ app_dir = args.prefix
app_resources_dir = os.path.join( app_dir, "resources" )
kernel_root_dir = os.environ["KERNEL_ROOT_DIR"]
bin_salome_dir = os.path.join( kernel_root_dir, "bin", "salome" )
@@ -187,9 +205,9 @@ def profileGenerateSources( options, args ) :
#Check if the directory of the sources already exists and delete it
if os.path.exists( app_dir ) :
- if not options.force :
- print "Directory %s already exists." %app_dir
- print "Use option --force to overwrite it."
+ if not args.force :
+ print("Directory %s already exists." %app_dir)
+ print("Use option --force to overwrite it.")
return
else :
shutil.rmtree( app_dir )
@@ -201,7 +219,7 @@ def profileGenerateSources( options, args ) :
for d in dirs :
os.mkdir( os.path.join( dst_dir, d ) )
for f in files :
- profileReplaceStrings( os.path.join( root, f ), os.path.join( dst_dir, f ), options )
+ profileReplaceStrings( os.path.join( root, f ), os.path.join( dst_dir, f ), args)
#Complete source directory
contextFiles = [ "salomeContext.py", "salomeContextUtils.py", "parseConfigFile.py" ]
@@ -227,15 +245,15 @@ def profileGenerateSources( options, args ) :
font = ImageFont.truetype( os.path.join( kernel_resources_dir, "Anita semi square.ttf" ) , 18 )
#Generate and save logo
- app_logo = profileGenerateLogo( options.name, font )
+ app_logo = profileGenerateLogo( args.name, font )
app_logo.save( logo_destination, "PNG" )
#Generate and splash screen and about image
- if options.slogan :
- subtext = options.slogan
+ if args.slogan :
+ subtext = args.slogan
else :
subtext = "Powered by SALOME"
- im = profileGenerateSplash( kernel_resources_dir, options.name, options.version, subtext )
+ im = profileGenerateSplash( kernel_resources_dir, args.name, args.version, subtext )
im.save( splash_destination, "PNG" )
im.save( about_destination, "PNG" )
else :
@@ -249,22 +267,22 @@ def profileGenerateSources( options, args ) :
shutil.copy( about_name, splash_destination )
#End of script
- print "Sources of %s were generated in %s." %( options.name, app_dir )
+ print("Sources of %s were generated in %s." %( args.name, app_dir ))
# -----------------------------------------------------------------------------
if __name__ == '__main__':
- #Get options and args
- (options, args) = profileQuickStartParser().parse_args()
+ #Get optional and positional args
+ args = profileQuickStartParser().parse_args()
#Check name of the application
- if not options.name :
+ if not args.name :
raise RuntimeError( "A name must be given to the application. Please use option --name." )
#Check if the prefix's parent is a directory
- if not os.path.isdir( os.path.dirname( options.prefix ) ) :
- raise RuntimeError( "%s is not a directory." % os.path.dirname( options.prefix ) )
+ if not os.path.isdir( os.path.dirname( args.prefix ) ) :
+ raise RuntimeError( "%s is not a directory." % os.path.dirname( args.prefix ) )
#Generate sources of the profile
- profileGenerateSources( options, args )
+ profileGenerateSources( args )
diff --git a/src/AppQuickStart/app-template/src/tests/helloWorld.py b/src/AppQuickStart/app-template/src/tests/helloWorld.py
index 62c813abc..44159b395 100644
--- a/src/AppQuickStart/app-template/src/tests/helloWorld.py
+++ b/src/AppQuickStart/app-template/src/tests/helloWorld.py
@@ -1 +1 @@
-print "Hello world"
+print("Hello world")
diff --git a/src/Basics/Basics_DirUtils.cxx b/src/Basics/Basics_DirUtils.cxx
index 6a52479a1..9c33b5d5a 100644
--- a/src/Basics/Basics_DirUtils.cxx
+++ b/src/Basics/Basics_DirUtils.cxx
@@ -44,14 +44,22 @@
# define _separator_ '/'
#endif
+#define _extension_ ".hdf"
+
namespace Kernel_Utils
{
- std::string GetBaseName( const std::string& file_path )
+ std::string GetBaseName( const std::string& file_path, const bool with_extension )
{
+ std::string tmp_str = file_path;
int pos = file_path.rfind( _separator_ );
if ( pos >= 0 )
- return pos < (int)file_path.size()-1 ? file_path.substr( pos+1 ) : "";
- return file_path;
+ tmp_str = pos < (int)file_path.size()-1 ? file_path.substr( pos+1 ) : "";
+
+ pos = tmp_str.rfind( _extension_ );
+ if( !with_extension && pos >= 0 )
+ tmp_str = pos < (int)tmp_str.size()-1 ? tmp_str.substr( 0, pos ) : "";
+
+ return tmp_str;
}
std::string GetDirName( const std::string& file_path )
@@ -157,6 +165,15 @@ namespace Kernel_Utils
return aFilePath;
}
+ std::string AddExtension( const std::string& name )
+ {
+ std::string tmp_str = name;
+ int pos = tmp_str.rfind( _extension_ );
+ if( pos < 0 )
+ return tmp_str.append( _extension_ );
+ return tmp_str;
+ }
+
//============================================================================
// function : IsExists
// purpose : Returns True(False) if the path (not)exists
diff --git a/src/Basics/Basics_DirUtils.hxx b/src/Basics/Basics_DirUtils.hxx
index 5c27021f6..f4c7fa5f3 100644
--- a/src/Basics/Basics_DirUtils.hxx
+++ b/src/Basics/Basics_DirUtils.hxx
@@ -32,7 +32,7 @@
namespace Kernel_Utils
{
// Extracts and returns the base name of the specified file name.
- BASICS_EXPORT std::string GetBaseName( const std::string& file_path );
+ BASICS_EXPORT std::string GetBaseName( const std::string& file_path, bool with_extension = true );
// Extracts and returns the dir name of the specified file name.
BASICS_EXPORT std::string GetDirName( const std::string& file_path );
@@ -49,11 +49,13 @@ namespace Kernel_Utils
// /tmp/something/ for Unix or c:\something\ for WIN32
BASICS_EXPORT std::string GetTmpDir();
-
// Returns the unique temporary file name without any extension
// /tmp/something/file for Unix or c:\something\file for WIN32
BASICS_EXPORT std::string GetTmpFileName();
+ // Adds extension in the end of the specified file name.
+ BASICS_EXPORT std::string AddExtension( const std::string& name );
+
// Returns True(False) if the path (not)exists
BASICS_EXPORT bool IsExists( const std::string& path );
diff --git a/src/Basics/Basics_Utils.cxx b/src/Basics/Basics_Utils.cxx
index 0487829cb..df5d1a49c 100644
--- a/src/Basics/Basics_Utils.cxx
+++ b/src/Basics/Basics_Utils.cxx
@@ -106,6 +106,36 @@ namespace Kernel_Utils
return guid;
}
+ const wchar_t* decode(const char* encoded)
+ {
+ setlocale(LC_ALL, "");
+ size_t length = strlen(encoded) + sizeof(char);
+ wchar_t* decoded = new wchar_t[length];
+ memset( decoded, '\0', length);
+ mbstowcs(decoded, encoded, length);
+ return decoded;
+ }
+
+ const wchar_t* decode_s(std::string encoded)
+ {
+ return decode(encoded.c_str());
+ }
+
+ const char* encode(const wchar_t* decoded)
+ {
+ setlocale(LC_ALL, "");
+ size_t length = std::wcslen(decoded) + sizeof(wchar_t);
+ char* encoded = new char[length];
+ memset( encoded, '\0', length);
+ wcstombs(encoded, decoded, length);
+ return encoded;
+ }
+
+ std::string encode_s(const wchar_t* decoded)
+ {
+ return std::string(encode(decoded));
+ }
+
#ifndef WIN32
void print_traceback()
{
diff --git a/src/Basics/Basics_Utils.hxx b/src/Basics/Basics_Utils.hxx
index 868fd3f9a..3468d205e 100644
--- a/src/Basics/Basics_Utils.hxx
+++ b/src/Basics/Basics_Utils.hxx
@@ -56,6 +56,11 @@ namespace Kernel_Utils
ObjectdID //!< Global usage object identifier ID
};
+ const wchar_t* decode(const char* encoded);
+ const wchar_t* decode_s(std::string encoded);
+ const char* encode(const wchar_t* decoded);
+ std::string encode_s(const wchar_t* decoded);
+
//! Get predefined GUID
BASICS_EXPORT std::string GetGUID( GUIDtype );
#ifndef WIN32
diff --git a/src/Communication_SWIG/CMakeLists.txt b/src/Communication_SWIG/CMakeLists.txt
index 7ee54b5b8..9396baf81 100755
--- a/src/Communication_SWIG/CMakeLists.txt
+++ b/src/Communication_SWIG/CMakeLists.txt
@@ -20,7 +20,7 @@
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(libSALOME_Comm.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(libSALOME_Comm.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(libSALOME_Comm.i PROPERTIES SWIG_FLAGS "-py3")
INCLUDE_DIRECTORIES(
${PYTHON_INCLUDE_DIRS}
diff --git a/src/Container/Component_i.cxx b/src/Container/Component_i.cxx
index 6cbff9c6d..be654198a 100644
--- a/src/Container/Component_i.cxx
+++ b/src/Container/Component_i.cxx
@@ -51,7 +51,6 @@ int SIGUSR11 = 1000;
extern bool _Sleeping ;
static Engines_Component_i * theEngines_Component ;
-bool Engines_Component_i::_isMultiStudy = true;
bool Engines_Component_i::_isMultiInstance = false;
/*! \class Engines_Component_i
@@ -101,7 +100,6 @@ Engines_Component_i::Engines_Component_i(CORBA::ORB_ptr orb,
_Executed(false) ,
_graphName("") ,
_nodeName(""),
- _studyId(-1),
_id(0),
_contId(0),
_CanceledThread(false)
@@ -155,7 +153,6 @@ Engines_Component_i::Engines_Component_i(CORBA::ORB_ptr orb,
_Executed(false) ,
_graphName("") ,
_nodeName(""),
- _studyId(-1),
_id(0),
_contId(0),
_CanceledThread(false)
@@ -227,20 +224,6 @@ char* Engines_Component_i::interfaceName()
return CORBA::string_dup(_interfaceName.c_str()) ;
}
-//=============================================================================
-/*!
- * CORBA method: Get study Id
- * \return -1: not initialised (Internal Error)
- * 0: multistudy component instance
- * >0: study id associated to this instance
- */
-//=============================================================================
-
-CORBA::Long Engines_Component_i::getStudyId()
-{
- return _studyId;
-}
-
//=============================================================================
/*!
* CORBA method: Test if instance is alive and responds
@@ -606,31 +589,6 @@ Engines_Container_i *Engines_Component_i::GetContainerPtr()
return dynamic_cast(_poa->id_to_servant(contId)) ;
}
-//=============================================================================
-/*!
- * C++ method: set study Id
- * \param studyId 0 if instance is not associated to a study,
- * >0 otherwise (== study id)
- * \return true if the set of study Id is OK
- * must be set once by Container, at instance creation,
- * and cannot be changed after.
- */
-//=============================================================================
-
-CORBA::Boolean Engines_Component_i::setStudyId(CORBA::Long studyId)
-{
- ASSERT( studyId >= 0);
- CORBA::Boolean ret = false;
- if (_studyId < 0) // --- not yet initialized
- {
- _studyId = studyId;
- ret = true;
- }
- else
- if ( _studyId == studyId) ret = true;
- return ret;
-}
-
//=============================================================================
/*!
* C++ method: return CORBA instance id, the id is set in derived class
@@ -915,12 +873,11 @@ std::string Engines_Component_i::GetDynLibraryName(const char *componentName)
*/
//=============================================================================
-Engines::TMPFile* Engines_Component_i::DumpPython(CORBA::Object_ptr theStudy,
- CORBA::Boolean isPublished,
+Engines::TMPFile* Engines_Component_i::DumpPython(CORBA::Boolean isPublished,
CORBA::Boolean isMultiFile,
CORBA::Boolean& isValidScript)
{
- const char* aScript = isMultiFile ? "def RebuildData(theStudy): pass" : "";
+ const char* aScript = isMultiFile ? "def RebuildData(): pass" : "";
char* aBuffer = new char[strlen(aScript)+1];
strcpy(aBuffer, aScript);
CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
diff --git a/src/Container/Container_i.cxx b/src/Container/Container_i.cxx
index 19eb2de77..d34b36ba8 100644
--- a/src/Container/Container_i.cxx
+++ b/src/Container/Container_i.cxx
@@ -259,17 +259,17 @@ Engines_Container_i::~Engines_Container_i()
if(_NS)
delete _NS;
for(std::map::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
- {
- Engines::PyNode_var tmpVar((*it).second);
- if(!CORBA::is_nil(tmpVar))
- tmpVar->UnRegister();
- }
+ {
+ Engines::PyNode_var tmpVar((*it).second);
+ if(!CORBA::is_nil(tmpVar))
+ tmpVar->UnRegister();
+ }
for(std::map::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
- {
- Engines::PyScriptNode_var tmpVar((*it).second);
- if(!CORBA::is_nil(tmpVar))
- tmpVar->UnRegister();
- }
+ {
+ Engines::PyScriptNode_var tmpVar((*it).second);
+ if(!CORBA::is_nil(tmpVar))
+ tmpVar->UnRegister();
+ }
}
//=============================================================================
@@ -374,20 +374,20 @@ void Engines_Container_i::Shutdown()
*/
std::map::iterator itm;
for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
+ {
+ try
{
- try
- {
- itm->second->destroy();
- }
- catch(const CORBA::Exception& e)
- {
- // ignore this entry and continue
- }
- catch(...)
- {
- // ignore this entry and continue
- }
+ itm->second->destroy();
+ }
+ catch(const CORBA::Exception& e)
+ {
+ // ignore this entry and continue
}
+ catch(...)
+ {
+ // ignore this entry and continue
+ }
+ }
_listInstances_map.clear();
_NS->Destroy_FullDirectory(_containerName.c_str());
@@ -418,15 +418,15 @@ Engines_Container_i::load_component_Library(const char* componentName, CORBA::St
//=================================================================
std::string retso;
if(load_component_CppImplementation(componentName,retso))
- {
- reason=CORBA::string_dup("");
- return true;
- }
+ {
+ reason=CORBA::string_dup("");
+ return true;
+ }
else if(retso != "ImplementationNotFound")
- {
- reason=CORBA::string_dup(retso.c_str());
- return false;
- }
+ {
+ reason=CORBA::string_dup(retso.c_str());
+ return false;
+ }
retso="Component ";
retso+=componentName;
@@ -438,15 +438,15 @@ Engines_Container_i::load_component_Library(const char* componentName, CORBA::St
//=================================================================
std::string retpy;
if(load_component_PythonImplementation(componentName,retpy))
- {
- reason=CORBA::string_dup("");
- return true;
- }
+ {
+ reason=CORBA::string_dup("");
+ return true;
+ }
else if(retpy != "ImplementationNotFound")
- {
- reason=CORBA::string_dup(retpy.c_str());
- return false;
- }
+ {
+ reason=CORBA::string_dup(retpy.c_str());
+ return false;
+ }
retpy="Component ";
retpy+=componentName;
@@ -459,15 +459,15 @@ Engines_Container_i::load_component_Library(const char* componentName, CORBA::St
//=================================================================
std::string retex;
if(load_component_ExecutableImplementation(componentName,retex))
- {
- reason=CORBA::string_dup("");
- return true;
- }
+ {
+ reason=CORBA::string_dup("");
+ return true;
+ }
else if(retex != "ImplementationNotFound")
- {
- reason=CORBA::string_dup(retex.c_str());
- return false;
- }
+ {
+ reason=CORBA::string_dup(retex.c_str());
+ return false;
+ }
retex="Component ";
retex+=componentName;
@@ -508,21 +508,21 @@ Engines_Container_i::load_component_CppImplementation(const char* componentName,
// (see decInstanceCnt, finalize_removal))
if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
if (_library_map.count(impl_name) != 0)
- {
- MESSAGE("Library " << impl_name << " already loaded");
- _numInstanceMutex.unlock();
- reason="";
- return true;
- }
+ {
+ MESSAGE("Library " << impl_name << " already loaded");
+ _numInstanceMutex.unlock();
+ reason="";
+ return true;
+ }
_numInstanceMutex.unlock();
#ifndef WIN32
void* handle;
handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
if ( !handle )
- {
- //not loadable. Try to find the lib file in LD_LIBRARY_PATH
- std::string path;
+ {
+ //not loadable. Try to find the lib file in LD_LIBRARY_PATH
+ std::string path;
#ifdef __APPLE__
char* p=getenv("DYLD_LIBRARY_PATH");
#else
@@ -550,25 +550,25 @@ Engines_Container_i::load_component_CppImplementation(const char* componentName,
//continue with other implementation
reason="ImplementationNotFound";
return false;
- }
}
+ }
#else
HINSTANCE handle;
handle = LoadLibrary( impl_name.c_str() );
if ( !handle )
- {
- reason="ImplementationNotFound";
- }
+ {
+ reason="ImplementationNotFound";
+ }
#endif
if ( handle )
- {
- _numInstanceMutex.lock();
- _library_map[impl_name] = handle;
- _numInstanceMutex.unlock();
- reason="";
- return true;
- }
+ {
+ _numInstanceMutex.lock();
+ _library_map[impl_name] = handle;
+ _numInstanceMutex.unlock();
+ reason="";
+ return true;
+ }
return false;
@@ -589,11 +589,11 @@ Engines_Container_i::load_component_PythonImplementation(const char* componentNa
_numInstanceMutex.lock() ; // lock to be alone (stl container write)
if (_library_map.count(aCompName) != 0)
- {
- _numInstanceMutex.unlock() ;
- reason="";
- return true; // Python Component, already imported
- }
+ {
+ _numInstanceMutex.unlock() ;
+ reason="";
+ return true; // Python Component, already imported
+ }
_numInstanceMutex.unlock() ;
PyGILState_STATE gstate = PyGILState_Ensure();
@@ -601,30 +601,30 @@ Engines_Container_i::load_component_PythonImplementation(const char* componentNa
(char*)"import_component",
(char*)"s",componentName);
- reason=PyString_AsString(result);
+ reason=PyUnicode_AsUTF8(result);
Py_XDECREF(result);
SCRUTE(reason);
PyGILState_Release(gstate);
if (reason=="")
- {
- //Python component has been loaded (import componentName)
- _numInstanceMutex.lock() ; // lock to be alone (stl container write)
- _library_map[aCompName] = (void *)_pyCont; // any non O value OK
- _numInstanceMutex.unlock() ;
- MESSAGE("import Python: "<< aCompName <<" OK");
- return true;
- }
+ {
+ //Python component has been loaded (import componentName)
+ _numInstanceMutex.lock() ; // lock to be alone (stl container write)
+ _library_map[aCompName] = (void *)_pyCont; // any non O value OK
+ _numInstanceMutex.unlock() ;
+ MESSAGE("import Python: "<< aCompName <<" OK");
+ return true;
+ }
else if(reason=="ImplementationNotFound")
- {
- //Python implementation has not been found. Continue with other implementation
- reason="ImplementationNotFound";
- }
+ {
+ //Python implementation has not been found. Continue with other implementation
+ reason="ImplementationNotFound";
+ }
else
- {
- //Python implementation has been found but loading has failed
- std::cerr << reason << std::endl;
- }
+ {
+ //Python implementation has been found but loading has failed
+ std::cerr << reason << std::endl;
+ }
return false;
}
@@ -650,27 +650,27 @@ Engines_Container_i::load_component_ExecutableImplementation(const char* compone
if(p)path=p;
if (findpathof(path, pth, executable))
+ {
+ if(checkifexecutable(pth))
{
- if(checkifexecutable(pth))
- {
- _numInstanceMutex.lock() ; // lock to be alone (stl container write)
- _library_map[executable] = (void *)1; // any non O value OK
- _numInstanceMutex.unlock() ;
- MESSAGE("import executable: "<< pth <<" OK");
- reason="";
- return true;
- }
- reason="Component ";
- reason+=aCompName;
- reason+=": implementation found ";
- reason+=pth;
- reason+=" but it is not executable";
- std::cerr << reason << std::endl;
+ _numInstanceMutex.lock() ; // lock to be alone (stl container write)
+ _library_map[executable] = (void *)1; // any non O value OK
+ _numInstanceMutex.unlock() ;
+ MESSAGE("import executable: "<< pth <<" OK");
+ reason="";
+ return true;
}
+ reason="Component ";
+ reason+=aCompName;
+ reason+=": implementation found ";
+ reason+=pth;
+ reason+=" but it is not executable";
+ std::cerr << reason << std::endl;
+ }
else
- {
- reason="ImplementationNotFound";
- }
+ {
+ reason="ImplementationNotFound";
+ }
return false;
}
@@ -681,19 +681,16 @@ Engines_Container_i::load_component_ExecutableImplementation(const char* compone
* The servant registers itself to naming service and Registry.
* \param genericRegisterName Name of the component instance to register
* in Registry & Name Service (without _inst_n suffix)
-* \param studyId 0 for multiStudy instance,
-* study Id (>0) otherwise
* \return a loaded component
*/
//=============================================================================
Engines::EngineComponent_ptr
-Engines_Container_i::create_component_instance(const char*genericRegisterName,
- CORBA::Long studyId)
+Engines_Container_i::create_component_instance(const char*genericRegisterName)
{
Engines::FieldsDict_var env = new Engines::FieldsDict;
char* reason;
Engines::EngineComponent_ptr compo =
- create_component_instance_env(genericRegisterName, studyId, env, reason);
+ create_component_instance_env(genericRegisterName, env, reason);
CORBA::string_free(reason);
return compo;
}
@@ -705,8 +702,6 @@ Engines_Container_i::create_component_instance(const char*genericRegisterName,
* The servant registers itself to naming service and Registry.
* \param genericRegisterName Name of the component instance to register
* in Registry & Name Service (without _inst_n suffix)
-* \param studyId 0 for multiStudy instance,
-* study Id (>0) otherwise
* \param env dict of env variables
* \param reason explains error when create_component_instance_env fails
* \return a loaded component
@@ -714,44 +709,36 @@ Engines_Container_i::create_component_instance(const char*genericRegisterName,
//=============================================================================
Engines::EngineComponent_ptr
Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
- CORBA::Long studyId,
const Engines::FieldsDict& env,
CORBA::String_out reason)
{
- if (studyId < 0)
- {
- INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
- reason=CORBA::string_dup("studyId must be > 0 for mono study instance, =0 for multiStudy");
- return Engines::EngineComponent::_nil() ;
- }
-
std::string error;
if (_library_map.count(genericRegisterName) != 0)
- {
- // It's a Python component
- Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, studyId, error);
- reason=CORBA::string_dup(error.c_str());
- return compo;
- }
+ {
+ // It's a Python component
+ Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
+ reason=CORBA::string_dup(error.c_str());
+ return compo;
+ }
std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
if (_library_map.count(impl_name) != 0)
- {
- // It's a C++ component
- void* handle = _library_map[impl_name];
- Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, studyId, error);
- reason=CORBA::string_dup(error.c_str());
- return compo;
- }
+ {
+ // It's a C++ component
+ void* handle = _library_map[impl_name];
+ Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
+ reason=CORBA::string_dup(error.c_str());
+ return compo;
+ }
impl_name = std::string(genericRegisterName) + ".exe";
if (_library_map.count(impl_name) != 0)
- {
- //It's an executable component
- Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, studyId, env, error);
- reason=CORBA::string_dup(error.c_str());
- return compo;
- }
+ {
+ //It's an executable component
+ Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
+ reason=CORBA::string_dup(error.c_str());
+ return compo;
+ }
error="load_component_Library has probably not been called for component: ";
error += genericRegisterName;
@@ -764,8 +751,6 @@ Engines_Container_i::create_component_instance_env(const char*genericRegisterNam
//! Create a new component instance (Executable implementation)
/*!
* \param CompName Name of the component instance
-* \param studyId 0 for multiStudy instance,
-* study Id (>0) otherwise
* \param env dict of env variables
* \param reason explains error when creation fails
* \return a loaded component
@@ -776,7 +761,7 @@ Engines_Container_i::create_component_instance_env(const char*genericRegisterNam
*/
//=============================================================================
Engines::EngineComponent_ptr
-Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
+Engines_Container_i::createExecutableInstance(std::string CompName,
const Engines::FieldsDict& env,
std::string& reason)
{
@@ -830,35 +815,35 @@ Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
int status;
pid_t pid = fork();
if(pid == 0) // child
+ {
+ for (CORBA::ULong i=0; i < env.length(); i++)
{
- for (CORBA::ULong i=0; i < env.length(); i++)
- {
- if (env[i].value.type()->kind() == CORBA::tk_string)
- {
- const char* value;
- env[i].value >>= value;
- std::string s(env[i].key);
- s+='=';
- s+=value;
- putenv(strdup(s.c_str()));
- }
- }
-
- execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
- status=-1;
+ if (env[i].value.type()->kind() == CORBA::tk_string)
+ {
+ const char* value;
+ env[i].value >>= value;
+ std::string s(env[i].key);
+ s+='=';
+ s+=value;
+ putenv(strdup(s.c_str()));
+ }
}
+
+ execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
+ status=-1;
+ }
else if(pid < 0) // failed to fork
- {
- status=-1;
- }
+ {
+ status=-1;
+ }
else //parent
+ {
+ pid_t tpid;
+ do
{
- pid_t tpid;
- do
- {
- tpid = wait(&status);
- } while (tpid != pid);
- }
+ tpid = wait(&status);
+ } while (tpid != pid);
+ }
#else
// launch component with a system call
int status=system(command.c_str());
@@ -928,14 +913,12 @@ Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
//! Create a new component instance (Python implementation)
/*!
* \param CompName Name of the component instance
-* \param studyId 0 for multiStudy instance,
-* study Id (>0) otherwise
* \param reason explains error when creation fails
* \return a loaded component
*/
//=============================================================================
Engines::EngineComponent_ptr
-Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
+Engines_Container_i::createPythonInstance(std::string CompName,
std::string& reason)
{
Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
@@ -953,10 +936,9 @@ Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *result = PyObject_CallMethod(_pyCont,
(char*)"create_component_instance",
- (char*)"ssl",
+ (char*)"ss",
CompName.c_str(),
- instanceName.c_str(),
- studyId);
+ instanceName.c_str());
const char *ior;
const char *error;
PyArg_ParseTuple(result,"ss", &ior, &error);
@@ -966,11 +948,11 @@ Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
PyGILState_Release(gstate);
if( iors!="" )
- {
- CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
- iobject = Engines::EngineComponent::_narrow( obj ) ;
- _listInstances_map[instanceName] = iobject;
- }
+ {
+ CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
+ iobject = Engines::EngineComponent::_narrow( obj ) ;
+ _listInstances_map[instanceName] = iobject;
+ }
return iobject._retn();
}
@@ -993,10 +975,9 @@ Engines_Container_i::create_python_service_instance(const char * CompName,
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject *result = PyObject_CallMethod(_pyCont,
(char*)"create_component_instance",
- (char*)"ssl",
+ (char*)"ss",
CompName,
- instanceName.c_str(),
- 0);
+ instanceName.c_str());
const char *ior;
const char *error;
PyArg_ParseTuple(result,"ss", &ior, &error);
@@ -1017,8 +998,6 @@ Engines_Container_i::create_python_service_instance(const char * CompName,
* in Registry & Name Service,
* (without _inst_n suffix, like "COMPONENT")
* \param handle loaded library handle
-* \param studyId 0 for multiStudy instance,
-* study Id (>0) otherwise
* \param reason explains error when creation fails
* \return a loaded component
*
@@ -1034,7 +1013,6 @@ Engines_Container_i::create_python_service_instance(const char * CompName,
Engines::EngineComponent_ptr
Engines_Container_i::createInstance(std::string genericRegisterName,
void *handle,
- int studyId,
std::string& reason)
{
// --- find the factory
@@ -1088,30 +1066,23 @@ Engines_Container_i::createInstance(std::string genericRegisterName,
id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
aGenRegisterName.c_str() ) ;
if (id == NULL)
- {
- reason="Can't get ObjectId from factory";
- INFOS(reason);
- return iobject._retn();
- }
+ {
+ reason="Can't get ObjectId from factory";
+ INFOS(reason);
+ return iobject._retn();
+ }
- // --- get reference & servant from id
+ // --- get reference from id
CORBA::Object_var obj = _poa->id_to_reference(*id);
iobject = Engines::EngineComponent::_narrow( obj ) ;
- Engines_Component_i *servant =
- dynamic_cast(_poa->reference_to_servant(iobject));
- ASSERT(servant);
- //SCRUTE(servant->_refcount_value());
_numInstanceMutex.lock() ; // lock to be alone (stl container write)
_listInstances_map[instanceName] = iobject;
_cntInstances_map[aGenRegisterName] += 1;
_numInstanceMutex.unlock() ;
SCRUTE(aGenRegisterName);
SCRUTE(_cntInstances_map[aGenRegisterName]);
- servant->setStudyId(studyId);
- servant->_remove_ref(); // do not need servant any more (remove ref from reference_to_servant)
- //SCRUTE(servant->_refcount_value());
// --- register the engine under the name
// containerName(.dir)/instanceName(.object)
@@ -1133,14 +1104,11 @@ Engines_Container_i::createInstance(std::string genericRegisterName,
* CORBA method: Finds a servant instance of a component
* \param registeredName Name of the component in Registry or Name Service,
* without instance suffix number
-* \param studyId 0 if instance is not associated to a study,
-* >0 otherwise (== study id)
-* \return the first instance found with same studyId
+* \return the first found instance
*/
//=============================================================================
Engines::EngineComponent_ptr
-Engines_Container_i::find_component_instance( const char* registeredName,
- CORBA::Long studyId)
+Engines_Container_i::find_component_instance( const char* registeredName)
{
Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
std::map::iterator itm =_listInstances_map.begin();
@@ -1151,10 +1119,7 @@ Engines_Container_i::find_component_instance( const char* registeredName,
if (instance.find(registeredName) == 0)
{
anEngine = (*itm).second;
- if (studyId == anEngine->getStudyId())
- {
- return anEngine._retn();
- }
+ return anEngine._retn();
}
itm++;
}
@@ -1320,29 +1285,11 @@ Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
{
iobject = createInstance(genericRegisterName,
handle,
- 0,
- reason); // force multiStudy instance here !
+ reason);
}
else
{
iobject = Engines::EngineComponent::_narrow( obj ) ;
- Engines_Component_i *servant =
- dynamic_cast
- (_poa->reference_to_servant(iobject));
- ASSERT(servant)
- int studyId = servant->getStudyId();
- ASSERT (studyId >= 0);
- if (studyId == 0) // multiStudy instance, OK
- {
- // No ReBind !
- MESSAGE(component_registerBase.c_str()<<" already bound");
- }
- else // monoStudy instance: NOK
- {
- iobject = Engines::EngineComponent::_nil();
- INFOS("load_impl & find_component_instance methods "
- << "NOT SUITABLE for mono study components");
- }
}
}
catch (...)
@@ -1632,36 +1579,36 @@ void Engines_Container_i::copyFile(Engines::Container_ptr container, const char*
FILE* fp;
if ((fp = fopen(localFile,"wb")) == NULL)
- {
- INFOS("file " << localFile << " cannot be open for writing");
- return;
- }
+ {
+ INFOS("file " << localFile << " cannot be open for writing");
+ return;
+ }
CORBA::Long fileId = fileTransfer->open(remoteFile);
if (fileId > 0)
+ {
+ Engines::fileBlock* aBlock;
+ int toFollow = 1;
+ int ctr=0;
+ while (toFollow)
{
- Engines::fileBlock* aBlock;
- int toFollow = 1;
- int ctr=0;
- while (toFollow)
- {
- ctr++;
- //SCRUTE(ctr);
- aBlock = fileTransfer->getBlock(fileId);
- toFollow = aBlock->length();
- //SCRUTE(toFollow);
- CORBA::Octet *buf = aBlock->get_buffer();
- fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
- delete aBlock;
- }
- fclose(fp);
- MESSAGE("end of transfer");
- fileTransfer->close(fileId);
+ ctr++;
+ //SCRUTE(ctr);
+ aBlock = fileTransfer->getBlock(fileId);
+ toFollow = aBlock->length();
+ //SCRUTE(toFollow);
+ CORBA::Octet *buf = aBlock->get_buffer();
+ fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
+ delete aBlock;
}
+ fclose(fp);
+ MESSAGE("end of transfer");
+ fileTransfer->close(fileId);
+ }
else
- {
- INFOS("open reference file for copy impossible");
- }
+ {
+ INFOS("open reference file for copy impossible");
+ }
}
//=============================================================================
@@ -1673,57 +1620,57 @@ void Engines_Container_i::copyFile(Engines::Container_ptr container, const char*
//=============================================================================
Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
{
- Engines::PyNode_var node= Engines::PyNode::_nil();
+ Engines::PyNode_var node= Engines::PyNode::_nil();
- PyGILState_STATE gstate = PyGILState_Ensure();
- PyObject *res = PyObject_CallMethod(_pyCont,
- (char*)"create_pynode",
- (char*)"ss",
- nodeName,
- code);
- if(res==NULL)
- {
- //internal error
- PyErr_Print();
- PyGILState_Release(gstate);
- SALOME::ExceptionStruct es;
- es.type = SALOME::INTERNAL_ERROR;
- es.text = "can not create a python node";
- throw SALOME::SALOME_Exception(es);
- }
- long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
- PyObject* result=PyTuple_GetItem(res,1);
- std::string astr=PyString_AsString(result);
- Py_DECREF(res);
+ PyGILState_STATE gstate = PyGILState_Ensure();
+ PyObject *res = PyObject_CallMethod(_pyCont,
+ (char*)"create_pynode",
+ (char*)"ss",
+ nodeName,
+ code);
+ if(res==NULL)
+ {
+ //internal error
+ PyErr_Print();
PyGILState_Release(gstate);
- if(ierr==0)
- {
- Utils_Locker lck(&_mutexForDftPy);
- CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
- node=Engines::PyNode::_narrow(obj);
- std::map::iterator it(_dftPyNode.find(nodeName));
- if(it==_dftPyNode.end())
- {
- _dftPyNode[nodeName]=node;
- }
- else
- {
- Engines::PyNode_var oldNode((*it).second);
- if(!CORBA::is_nil(oldNode))
- oldNode->UnRegister();
- (*it).second=node;
- }
- if(!CORBA::is_nil(node))
- node->Register();
- return node._retn();
- }
+ SALOME::ExceptionStruct es;
+ es.type = SALOME::INTERNAL_ERROR;
+ es.text = "can not create a python node";
+ throw SALOME::SALOME_Exception(es);
+ }
+ long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
+ PyObject* result=PyTuple_GetItem(res,1);
+ std::string astr=PyUnicode_AsUTF8(result);
+ Py_DECREF(res);
+ PyGILState_Release(gstate);
+ if(ierr==0)
+ {
+ Utils_Locker lck(&_mutexForDftPy);
+ CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
+ node=Engines::PyNode::_narrow(obj);
+ std::map::iterator it(_dftPyNode.find(nodeName));
+ if(it==_dftPyNode.end())
+ {
+ _dftPyNode[nodeName]=node;
+ }
else
- {
- SALOME::ExceptionStruct es;
- es.type = SALOME::INTERNAL_ERROR;
- es.text = astr.c_str();
- throw SALOME::SALOME_Exception(es);
- }
+ {
+ Engines::PyNode_var oldNode((*it).second);
+ if(!CORBA::is_nil(oldNode))
+ oldNode->UnRegister();
+ (*it).second=node;
+ }
+ if(!CORBA::is_nil(node))
+ node->Register();
+ return node._retn();
+ }
+ else
+ {
+ SALOME::ExceptionStruct es;
+ es.type = SALOME::INTERNAL_ERROR;
+ es.text = astr.c_str();
+ throw SALOME::SALOME_Exception(es);
+ }
}
//=============================================================================
@@ -1738,13 +1685,13 @@ Engines::PyNode_ptr Engines_Container_i::getDefaultPyNode(const char *nodeName)
if(it==_dftPyNode.end())
return Engines::PyNode::_nil();
else
- {
- Engines::PyNode_var tmpVar((*it).second);
- if(!CORBA::is_nil(tmpVar))
- return Engines::PyNode::_duplicate(tmpVar);
- else
- return Engines::PyNode::_nil();
- }
+ {
+ Engines::PyNode_var tmpVar((*it).second);
+ if(!CORBA::is_nil(tmpVar))
+ return Engines::PyNode::_duplicate(tmpVar);
+ else
+ return Engines::PyNode::_nil();
+ }
}
//=============================================================================
@@ -1756,58 +1703,58 @@ Engines::PyNode_ptr Engines_Container_i::getDefaultPyNode(const char *nodeName)
//=============================================================================
Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
{
- Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
+ Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
- PyGILState_STATE gstate = PyGILState_Ensure();
- PyObject *res = PyObject_CallMethod(_pyCont,
- (char*)"create_pyscriptnode",
- (char*)"ss",
- nodeName,
- code);
- if(res==NULL)
- {
- //internal error
- PyErr_Print();
- PyGILState_Release(gstate);
- SALOME::ExceptionStruct es;
- es.type = SALOME::INTERNAL_ERROR;
- es.text = "can not create a python node";
- throw SALOME::SALOME_Exception(es);
- }
- long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
- PyObject* result=PyTuple_GetItem(res,1);
- std::string astr=PyString_AsString(result);
- Py_DECREF(res);
+ PyGILState_STATE gstate = PyGILState_Ensure();
+ PyObject *res = PyObject_CallMethod(_pyCont,
+ (char*)"create_pyscriptnode",
+ (char*)"ss",
+ nodeName,
+ code);
+ if(res==NULL)
+ {
+ //internal error
+ PyErr_Print();
PyGILState_Release(gstate);
+ SALOME::ExceptionStruct es;
+ es.type = SALOME::INTERNAL_ERROR;
+ es.text = "can not create a python node";
+ throw SALOME::SALOME_Exception(es);
+ }
+ long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
+ PyObject* result=PyTuple_GetItem(res,1);
+ std::string astr=PyUnicode_AsUTF8(result);
+ Py_DECREF(res);
+ PyGILState_Release(gstate);
- if(ierr==0)
- {
- Utils_Locker lck(&_mutexForDftPy);
- CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
- node=Engines::PyScriptNode::_narrow(obj);
- std::map::iterator it(_dftPyScriptNode.find(nodeName));
- if(it==_dftPyScriptNode.end())
- {
- _dftPyScriptNode[nodeName]=node;
- }
- else
- {
- Engines::PyScriptNode_var oldNode((*it).second);
- if(!CORBA::is_nil(oldNode))
- oldNode->UnRegister();
- (*it).second=node;
- }
- if(!CORBA::is_nil(node))
- node->Register();
- return node._retn();
- }
+ if(ierr==0)
+ {
+ Utils_Locker lck(&_mutexForDftPy);
+ CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
+ node=Engines::PyScriptNode::_narrow(obj);
+ std::map::iterator it(_dftPyScriptNode.find(nodeName));
+ if(it==_dftPyScriptNode.end())
+ {
+ _dftPyScriptNode[nodeName]=node;
+ }
else
- {
- SALOME::ExceptionStruct es;
- es.type = SALOME::INTERNAL_ERROR;
- es.text = astr.c_str();
- throw SALOME::SALOME_Exception(es);
- }
+ {
+ Engines::PyScriptNode_var oldNode((*it).second);
+ if(!CORBA::is_nil(oldNode))
+ oldNode->UnRegister();
+ (*it).second=node;
+ }
+ if(!CORBA::is_nil(node))
+ node->Register();
+ return node._retn();
+ }
+ else
+ {
+ SALOME::ExceptionStruct es;
+ es.type = SALOME::INTERNAL_ERROR;
+ es.text = astr.c_str();
+ throw SALOME::SALOME_Exception(es);
+ }
}
//=============================================================================
@@ -1822,13 +1769,13 @@ Engines::PyScriptNode_ptr Engines_Container_i::getDefaultPyScriptNode(const char
if(it==_dftPyScriptNode.end())
return Engines::PyScriptNode::_nil();
else
- {
- Engines::PyScriptNode_var tmpVar((*it).second);
- if(!CORBA::is_nil(tmpVar))
- return Engines::PyScriptNode::_duplicate(tmpVar);
- else
- return Engines::PyScriptNode::_nil();
- }
+ {
+ Engines::PyScriptNode_var tmpVar((*it).second);
+ if(!CORBA::is_nil(tmpVar))
+ return Engines::PyScriptNode::_duplicate(tmpVar);
+ else
+ return Engines::PyScriptNode::_nil();
+ }
}
//=============================================================================
@@ -1916,3 +1863,43 @@ void Engines_Container_i::clearTemporaryFiles()
}
_tmp_files.clear();
}
+
+/*
+std::string Engines_Container_i::AnotherMethodeToReplace_PyString_AsString(PyObject * result)
+{
+ std::string my_result = "";
+ if (PyUnicode_Check(result)) {
+ // Convert string to bytes.
+ // strdup() bytes into my_result.
+ PyObject * temp_bytes = PyUnicode_AsEncodedString(result, "ASCII", "strict"); // Owned reference
+ if (temp_bytes != NULL) {
+ my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
+ my_result = strdup(my_result);
+ Py_DECREF(temp_bytes);
+ } else {
+ // TODO PY3: Handle encoding error.
+ Py_DECREF(temp_bytes);
+ }
+
+ } else if (PyBytes_Check(result)) {
+ // strdup() bytes into my_result.
+ my_result = PyBytes_AS_STRING(result); // Borrowed pointer
+ my_result = strdup(my_result);
+ } else {
+ // Convert into your favorite string representation.
+ // Convert string to bytes if it is not already.
+ // strdup() bytes into my_result.
+ // TODO PY3: Check if only bytes is ok.
+ PyObject * temp_bytes = PyObject_Bytes(result); // Owned reference
+ if (temp_bytes != NULL) {
+ my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
+ my_result = strdup(my_result);
+ Py_DECREF(temp_bytes);
+ } else {
+ // TODO PY3: Handle error.
+ Py_DECREF(temp_bytes);
+ }
+ }
+ return my_result;
+}
+*/
diff --git a/src/Container/Container_init_python.cxx b/src/Container/Container_init_python.cxx
index dad0be21b..beaea103b 100644
--- a/src/Container/Container_init_python.cxx
+++ b/src/Container/Container_init_python.cxx
@@ -20,7 +20,8 @@
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#include
+#include
+#include
#ifndef WIN32
#include
#endif
@@ -29,6 +30,135 @@
#include "utilities.h"
#include "Container_init_python.hxx"
+#if PY_VERSION_HEX < 0x03050000
+static char*
+Py_EncodeLocale(const wchar_t *arg, size_t *size)
+{
+ return _Py_wchar2char(arg, size);
+}
+static wchar_t*
+Py_DecodeLocale(const char *arg, size_t *size)
+{
+ return _Py_char2wchar(arg, size);
+}
+#endif
+
+/*
+ The following functions are used to hook the Python
+ interpreter output.
+*/
+
+static void ContainerPyStdOut_dealloc(ContainerPyStdOut *self)
+{
+ PyObject_Del(self);
+}
+
+static PyObject*
+ContainerPyStdOut_write(ContainerPyStdOut *self, PyObject *args)
+{
+ char *c;
+ if (!PyArg_ParseTuple(args, "s",&c))
+ return NULL;
+ if(self->_cb==NULL) {
+ if ( self->_iscerr )
+ std::cerr << c ;
+ else
+ std::cout << c ;
+ }
+ else {
+ self->_cb(self->_data,c);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyObject*
+ContainerPyStdOut_flush(ContainerPyStdOut *self)
+{
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+static PyMethodDef ContainerPyStdOut_methods[] = {
+ {"write", (PyCFunction)ContainerPyStdOut_write, METH_VARARGS, PyDoc_STR("write(string) -> None")},
+ {"flush", (PyCFunction)ContainerPyStdOut_flush, METH_NOARGS, PyDoc_STR("flush() -> None")},
+ {NULL, NULL} /* sentinel */
+};
+
+static PyMemberDef ContainerPyStdOut_memberlist[] = {
+ {(char*)"softspace", T_INT, offsetof(ContainerPyStdOut, softspace), 0,
+ (char*)"flag indicating that a space needs to be printed; used by print"},
+ {NULL} /* Sentinel */
+};
+
+static PyTypeObject ContainerPyStdOut_Type = {
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /*0,*/ /*ob_size*/
+ "PyOut", /*tp_name*/
+ sizeof(ContainerPyStdOut), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)ContainerPyStdOut_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ /* softspace is writable: we must supply tp_setattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ ContainerPyStdOut_methods, /*tp_methods*/
+ ContainerPyStdOut_memberlist, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
+ 0, /*tp_bases*/
+ 0, /*tp_mro*/
+ 0, /*tp_cache*/
+ 0, /*tp_subclasses*/
+ 0, /*tp_weaklist*/
+ 0, /*tp_del*/
+ 0, /*tp_version_tag*/
+ 0, /*tp_finalize*/
+};
+
+static ContainerPyStdOut* ContainerNewPyStdOut( bool iscerr )
+{
+ ContainerPyStdOut *self;
+ self = PyObject_New(ContainerPyStdOut, &ContainerPyStdOut_Type);
+ if (self == NULL)
+ return NULL;
+ self->softspace = 0;
+ self->_cb = NULL;
+ self->_iscerr = iscerr;
+ return self;
+}
+
void KERNEL_PYTHON::init_python(int argc, char **argv)
{
if (Py_IsInitialized())
@@ -41,11 +171,25 @@ void KERNEL_PYTHON::init_python(int argc, char **argv)
MESSAGE("=================================================================");
// set stdout to line buffering (aka C++ std::cout)
setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
- char* salome_python=getenv("SALOME_PYTHON");
- if(salome_python != 0)
- Py_SetProgramName(salome_python);
+ wchar_t* salome_python;
+ char* env_python=getenv("SALOME_PYTHON");
+ if(env_python != 0)
+ {
+ wchar_t* salome_python = Py_DecodeLocale(env_python, NULL);
+ Py_SetProgramName(salome_python);
+ }
Py_Initialize(); // Initialize the interpreter
- PySys_SetArgv(argc, argv);
+ if (Py_IsInitialized())
+ {
+ MESSAGE("Python initialized eh eh eh");
+ }
+ wchar_t **changed_argv = new wchar_t*[argc]; // Setting arguments
+ for (int i = 0; i < argc; i++)
+ {
+ changed_argv[i] = Py_DecodeLocale(argv[i], NULL);
+ }
+ PySys_SetArgv(argc, changed_argv);
+
PyRun_SimpleString("import threading\n");
// VSR (22/09/2016): This is a workaround to prevent invoking qFatal() from PyQt5
// causing application aborting
@@ -61,7 +205,14 @@ void KERNEL_PYTHON::init_python(int argc, char **argv)
int res = PyRun_SimpleString(script.c_str());
// VSR (22/09/2016): end of workaround
PyEval_InitThreads(); // Create (and acquire) the interpreter lock
+
+ // Create python objects to capture stdout and stderr
+ PyObject* _vout=(PyObject*)ContainerNewPyStdOut( false ); // stdout
+ PyObject* _verr=(PyObject*)ContainerNewPyStdOut( true ); // stderr
+ PySys_SetObject((char*)"stderr",_verr);
+ PySys_SetObject((char*)"stdout",_vout);
+
PyThreadState *pts = PyGILState_GetThisThreadState();
- PyEval_ReleaseThread(pts);
+ PyEval_ReleaseThread(pts);
+ //delete[] changed_argv;
}
-
diff --git a/src/Container/Container_init_python.hxx b/src/Container/Container_init_python.hxx
index 75e484524..e14475eac 100644
--- a/src/Container/Container_init_python.hxx
+++ b/src/Container/Container_init_python.hxx
@@ -58,6 +58,16 @@
#define Py_RELEASE_NEW_THREAD \
PyGILState_Release(gil_state);
+typedef void ContainerPyOutChanged(void* data,char * c);
+
+typedef struct {
+ PyObject_HEAD
+ int softspace;
+ ContainerPyOutChanged* _cb;
+ void* _data;
+ bool _iscerr;
+} ContainerPyStdOut;
+
struct CONTAINER_EXPORT KERNEL_PYTHON
{
static void init_python(int argc, char **argv);
diff --git a/src/Container/SALOME_ComponentPy.py b/src/Container/SALOME_ComponentPy.py
index a9ce718b8..b7c08321f 100755
--- a/src/Container/SALOME_ComponentPy.py
+++ b/src/Container/SALOME_ComponentPy.py
@@ -46,7 +46,7 @@ from libNOTIFICATION import *
from SALOME_utilities import *
-from thread import *
+from _thread import *
#=============================================================================
@@ -59,7 +59,6 @@ class SALOME_ComponentPy_i (Engines__POA.EngineComponent):
_orb = None
_poa = None
_fieldsDict = []
- _studyId = -1
#-------------------------------------------------------------------------
@@ -173,7 +172,7 @@ class SALOME_ComponentPy_i (Engines__POA.EngineComponent):
self._StartUsed = self.CpuUsed_impl()
self._ThreadCpuUsed = 0
self._Executed = 1
- print "beginService for ",serviceName," Component instance : ",self._instanceName
+ print("beginService for ",serviceName," Component instance : ",self._instanceName)
MESSAGE( "SALOME_ComponentPy_i::beginService _StartUsed " + str( self._ThreadId ) + " " + str( self._StartUsed ) )
for e in self._fieldsDict:
key=e.key
@@ -187,7 +186,7 @@ class SALOME_ComponentPy_i (Engines__POA.EngineComponent):
def endService(self , serviceName ):
MESSAGE( "Send EndService notification for " + str( self._ThreadId ) + " " + str(serviceName) + " for graph/node " + str(self._graphName) + " " + str(self._nodeName) + " CpuUsed " + str( self.CpuUsed_impl() ) )
MESSAGE( "Component instance : " + str(self._instanceName) )
- print "endService for",serviceName,"Component instance :",self._instanceName,"Cpu Used:",self.CpuUsed_impl()," (s) "
+ print("endService for",serviceName,"Component instance :",self._instanceName,"Cpu Used:",self.CpuUsed_impl()," (s) ")
#-------------------------------------------------------------------------
@@ -293,25 +292,20 @@ class SALOME_ComponentPy_i (Engines__POA.EngineComponent):
#-------------------------------------------------------------------------
- def DumpPython(self, theStudy, isPublished, isMultiFile):
+ def DumpPython(self, isPublished, isMultiFile):
aBuffer = "\0"
if isMultiFile :
- aBuffer = "def RebuildData(theStudy): pass\n\0"
+ aBuffer = "def RebuildData(): pass\n\0"
return (aBuffer, 1)
#-------------------------------------------------------------------------
- def getStudyId(self):
- return self._studyId
-
- #-------------------------------------------------------------------------
-
def hasObjectInfo(self):
return 0
#-------------------------------------------------------------------------
- def getObjectInfo(self, studyId, entry):
+ def getObjectInfo(self, entry):
return ""
#-------------------------------------------------------------------------
diff --git a/src/Container/SALOME_Component_i.hxx b/src/Container/SALOME_Component_i.hxx
index 4315da8b3..4235f5048 100644
--- a/src/Container/SALOME_Component_i.hxx
+++ b/src/Container/SALOME_Component_i.hxx
@@ -81,7 +81,6 @@ public:
void ping();
void destroy();
- CORBA::Long getStudyId();
Engines::Container_ptr GetContainerRef();
void setProperties(const Engines::FieldsDict& dico);
@@ -97,8 +96,7 @@ public:
bool Resume_impl();
CORBA::Long CpuUsed_impl() ;
- virtual Engines::TMPFile* DumpPython(CORBA::Object_ptr theStudy,
- CORBA::Boolean isPublished,
+ virtual Engines::TMPFile* DumpPython(CORBA::Boolean isPublished,
CORBA::Boolean isMultiFile,
CORBA::Boolean& isValidScript);
@@ -118,7 +116,7 @@ public:
// Object information
virtual bool hasObjectInfo() { return false; }
- virtual char* getObjectInfo(CORBA::Long studyId, const char* entry) { return CORBA::string_dup(""); }
+ virtual char* getObjectInfo(const char* entry) { return CORBA::string_dup(""); }
// Version information
virtual char* getVersion();
@@ -130,8 +128,6 @@ public:
std::string getContainerName();
void setContainerName();
- virtual bool setStudyId(CORBA::Long studyId);
- static bool isMultiStudy();
static bool isMultiInstance();
static std::string GetDynLibraryName(const char *componentName);
@@ -150,8 +146,6 @@ public:
Salome_file_i * file);
protected:
- int _studyId; // -1: not initialised; 0: multiStudy; >0: study
- static bool _isMultiStudy;
static bool _isMultiInstance;
std::string _instanceName ;
diff --git a/src/Container/SALOME_Container.py b/src/Container/SALOME_Container.py
index 2d6ee3b75..901f678a0 100644
--- a/src/Container/SALOME_Container.py
+++ b/src/Container/SALOME_Container.py
@@ -34,7 +34,6 @@
import os
import sys
-import string
import traceback
import imp
from omniORB import CORBA, PortableServer
@@ -65,7 +64,7 @@ class SALOME_Container_i:
self._orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
self._poa = self._orb.resolve_initial_references("RootPOA")
self._containerName = containerName
- if verbose(): print "SALOME_Container.SALOME_Container_i : _containerName ",self._containerName
+ if verbose(): print("SALOME_Container.SALOME_Container_i : _containerName ",self._containerName)
#self._naming_service = SALOME_NamingServicePy_i(self._orb)
self._container = self._orb.string_to_object(containerIORStr)
@@ -75,10 +74,10 @@ class SALOME_Container_i:
MESSAGE( "SALOME_Container_i::import_component" )
ret=""
try:
- if verbose(): print "try import ",componentName
+ if verbose(): print("try import ",componentName)
__import__(componentName)
- if verbose(): print "import ",componentName," successful"
- except ImportError,e:
+ if verbose(): print("import ",componentName," successful")
+ except ImportError as e:
#can't import python module componentName
#try to find it in python path
try:
@@ -87,22 +86,22 @@ class SALOME_Container_i:
#module file found in path
ret="Component "+componentName+": Python implementation found but it can't be loaded\n"
ret=ret+traceback.format_exc(10)
- except ImportError,ee:
+ except ImportError as ee:
ret="ImplementationNotFound"
except:
- if verbose():print "error when calling find_module"
+ if verbose():print("error when calling find_module")
ret="ImplementationNotFound"
except:
ret="Component "+componentName+": Python implementation found but it can't be loaded\n"
ret=ret+traceback.format_exc(10)
if verbose():
traceback.print_exc()
- print "import ",componentName," not possible"
+ print("import ",componentName," not possible")
return ret
#-------------------------------------------------------------------------
- def create_component_instance(self, componentName, instanceName, studyId):
+ def create_component_instance(self, componentName, instanceName):
MESSAGE( "SALOME_Container_i::create_component_instance" )
comp_iors=""
ret=""
diff --git a/src/Container/SALOME_ContainerPy.py b/src/Container/SALOME_ContainerPy.py
index ac5f03894..e3cff84ab 100755
--- a/src/Container/SALOME_ContainerPy.py
+++ b/src/Container/SALOME_ContainerPy.py
@@ -61,7 +61,7 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
myMachine=getShortHostName()
Container_path = "/Containers/" + myMachine + "/" + containerName
self._containerName = Container_path
- if verbose(): print "container name ",self._containerName
+ if verbose(): print("container name ",self._containerName)
naming_service = SALOME_NamingServicePy_i(self._orb)
self._naming_service = naming_service
@@ -138,7 +138,7 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
def instance(self, nameToRegister, componentName):
MESSAGE( "SALOME_ContainerPy_i::instance " + str(nameToRegister) + ' ' + str(componentName) )
self._numInstance = self._numInstance +1
- instanceName = nameToRegister + "_inst_" + `self._numInstance`
+ instanceName = nameToRegister + "_inst_" + repr(self._numInstance)
component=__import__(componentName)
factory=getattr(component,componentName)
@@ -154,13 +154,13 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
def load_impl(self, nameToRegister, componentName):
MESSAGE( "SALOME_ContainerPy_i::load_impl " + str(nameToRegister) + ' ' + str(componentName) )
self._numInstance = self._numInstance +1
- instanceName = nameToRegister + "_inst_" + `self._numInstance`
+ instanceName = nameToRegister + "_inst_" + repr(self._numInstance)
interfaceName = nameToRegister
the_command = "import " + nameToRegister + "\n"
the_command = the_command + "comp_i = " + nameToRegister + "." + nameToRegister
the_command = the_command + "(self._orb, self._poa, self._this(), self._containerName, instanceName, interfaceName)\n"
MESSAGE( "SALOME_ContainerPy_i::load_impl :" + str (the_command) )
- exec the_command
+ exec(the_command)
comp_o = comp_i._this()
return comp_o
@@ -170,19 +170,19 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
MESSAGE( "SALOME_Container_i::import_component" )
reason = ""
try:
- if verbose(): print "try import %s" % componentName
+ if verbose(): print("try import %s" % componentName)
# try import component
module=__import__(componentName)
- if verbose(): print "import %s is done successfully" % componentName
+ if verbose(): print("import %s is done successfully" % componentName)
# if import successfully, check that component is loadable
if not hasattr(module, componentName):
reason = "module %s is not loadable" % componentName
- print reason
+ print(reason)
pass
pass
except:
import traceback
- print "cannot import %s" % componentName
+ print("cannot import %s" % componentName)
traceback.print_exc()
reason = "cannot import %s" % componentName
return reason
@@ -192,64 +192,55 @@ class SALOME_ContainerPy_i (Engines__POA.Container):
def load_component_Library(self, componentName):
MESSAGE( "SALOME_ContainerPy_i::load_component_Library " + str(componentName) )
ret = 0
- instanceName = componentName + "_inst_" + `self._numInstance`
+ instanceName = componentName + "_inst_" + repr(self._numInstance)
interfaceName = componentName
reason = self.import_component(componentName)
return reason == "", reason
#-------------------------------------------------------------------------
- def create_component_instance_env(self, componentName, studyId, env):
- return self.create_component_instance(componentName, studyId), ""
+ def create_component_instance_env(self, componentName, env):
+ return self.create_component_instance(componentName), ""
- def create_component_instance(self, componentName, studyId):
- MESSAGE( "SALOME_ContainerPy_i::create_component_instance ==> " + str(componentName) + ' ' + str(studyId) )
- if studyId < 0:
- MESSAGE( "Study ID is lower than 0!" )
- return None
- else:
- self._numInstance = self._numInstance +1
- instanceName = componentName + "_inst_" + `self._numInstance`
- comp_iors=""
- try:
- component=__import__(componentName)
- factory=getattr(component,componentName)
- comp_i=factory(self._orb,
- self._poa,
- self._this(),
- self._containerName,
- instanceName,
- componentName)
-
- MESSAGE( "SALOME_Container_i::create_component_instance : OK")
- comp_o = comp_i._this()
- self._listInstances_map[instanceName] = comp_i
- except:
- import traceback
- traceback.print_exc()
- MESSAGE( "SALOME_Container_i::create_component_instance : NOT OK")
- return comp_o
+ def create_component_instance(self, componentName):
+ MESSAGE( "SALOME_ContainerPy_i::create_component_instance ==> " + str(componentName) )
+ self._numInstance = self._numInstance +1
+ instanceName = componentName + "_inst_" + repr(self._numInstance)
+ comp_iors=""
+ try:
+ component=__import__(componentName)
+ factory=getattr(component,componentName)
+ comp_i=factory(self._orb,
+ self._poa,
+ self._this(),
+ self._containerName,
+ instanceName,
+ componentName)
+
+ MESSAGE( "SALOME_Container_i::create_component_instance : OK")
+ comp_o = comp_i._this()
+ self._listInstances_map[instanceName] = comp_i
+ except:
+ import traceback
+ traceback.print_exc()
+ MESSAGE( "SALOME_Container_i::create_component_instance : NOT OK")
+ return comp_o
#-------------------------------------------------------------------------
- def find_component_instance(self, registeredName, studyId):
+ def find_component_instance(self, registeredName):
anEngine = None
- keysList = self._listInstances_map.keys()
- i = 0
- while i < len(keysList):
- instance = keysList[i]
+ for instance in self._listInstances_map:
if find(instance,registeredName) == 0:
anEngine = self._listInstances_map[instance]
- if studyId == anEngine.getStudyId():
- return anEngine._this()
- i = i + 1
- return anEngine._this()
+ return anEngine._this()
+ return anEngine
#-------------------------------------------------------------------------
def create_python_service_instance(self, CompName):
- return self.create_component_instance(CompName, 0)
+ return self.create_component_instance(CompName)
#-------------------------------------------------------------------------
@@ -319,19 +310,19 @@ if __name__ == "__main__":
# change the stdout buffering to line buffering (same as C++ cout buffering)
sys.stdout=os.fdopen(1,"w",1)
#initialise the ORB and find the root POA
- if verbose():print "Starting ",sys.argv[1]
+ if verbose():print("Starting ",sys.argv[1])
orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
poa = orb.resolve_initial_references("RootPOA")
- if verbose():print "ORB and POA initialized"
+ if verbose():print("ORB and POA initialized")
#create an instance of SALOME_ContainerPy_i and a Container reference
#containerName = "FactoryServerPy"
MESSAGE( str(sys.argv) )
containerName = sys.argv[1]
cpy_i = SALOME_ContainerPy_i(orb, poa, containerName)
- if verbose():print "SALOME_ContainerPy_i instance created ",cpy_i
+ if verbose():print("SALOME_ContainerPy_i instance created ",cpy_i)
cpy_o = cpy_i._this()
- if verbose():print "SALOME_ContainerPy_i instance activated ",cpy_o
+ if verbose():print("SALOME_ContainerPy_i instance activated ",cpy_o)
sys.stdout.flush()
sys.stderr.flush()
@@ -341,4 +332,4 @@ if __name__ == "__main__":
#Block for ever
orb.run()
- if verbose():print "SALOME_ContainerPy_i shutdown"
+ if verbose():print("SALOME_ContainerPy_i shutdown")
diff --git a/src/Container/SALOME_Container_i.hxx b/src/Container/SALOME_Container_i.hxx
index 197d0def9..1193ec379 100644
--- a/src/Container/SALOME_Container_i.hxx
+++ b/src/Container/SALOME_Container_i.hxx
@@ -69,12 +69,10 @@ public:
virtual bool load_component_Library(const char* componentName, CORBA::String_out reason);
virtual Engines::EngineComponent_ptr
- create_component_instance( const char* componentName,
- CORBA::Long studyId); // 0 for multiStudy
+ create_component_instance( const char* componentName);
virtual Engines::EngineComponent_ptr
create_component_instance_env( const char* componentName,
- CORBA::Long studyId, // 0 for multiStudy
const Engines::FieldsDict& env,
CORBA::String_out reason);
@@ -83,8 +81,7 @@ public:
CORBA::String_out reason);
Engines::EngineComponent_ptr
- find_component_instance( const char* registeredName,
- CORBA::Long studyId); // 0 for multiStudy
+ find_component_instance( const char* registeredName);
Engines::EngineComponent_ptr
load_impl(const char* nameToRegister,
@@ -125,9 +122,9 @@ public:
bool load_component_PythonImplementation(const char* componentName,std::string& reason);
bool load_component_ExecutableImplementation(const char* componentName,std::string& reason);
- Engines::EngineComponent_ptr createPythonInstance(std::string CompName, int studyId, std::string& error);
- Engines::EngineComponent_ptr createExecutableInstance(std::string CompName, int studyId, const Engines::FieldsDict& env, std::string& error);
- Engines::EngineComponent_ptr createInstance(std::string genericRegisterName, void *handle, int studyId, std::string& error);
+ Engines::EngineComponent_ptr createPythonInstance(std::string CompName, std::string& error);
+ Engines::EngineComponent_ptr createExecutableInstance(std::string CompName, const Engines::FieldsDict& env, std::string& error);
+ Engines::EngineComponent_ptr createInstance(std::string genericRegisterName, void *handle, std::string& error);
static bool isPythonContainer(const char* ContainerName);
static void decInstanceCnt(std::string genericRegisterName);
diff --git a/src/Container/SALOME_PyNode.py b/src/Container/SALOME_PyNode.py
index 2feb5d4c9..64ba69239 100644
--- a/src/Container/SALOME_PyNode.py
+++ b/src/Container/SALOME_PyNode.py
@@ -24,9 +24,9 @@
# Module : SALOME
# $Header$
#
-import sys,traceback,string
+import sys,traceback
import linecache
-import cPickle
+import pickle
import Engines__POA
import SALOME__POA
import SALOME
@@ -47,7 +47,7 @@ class Generic(SALOME__POA.GenericObj):
self.poa.deactivate_object(oid)
def Destroy(self):
- print "WARNING SALOME::GenericObj::Destroy() function is obsolete! Use UnRegister() instead."
+ print("WARNING SALOME::GenericObj::Destroy() function is obsolete! Use UnRegister() instead.")
self.UnRegister()
class PyNode_i (Engines__POA.PyNode,Generic):
@@ -58,31 +58,31 @@ class PyNode_i (Engines__POA.PyNode,Generic):
self.nodeName=nodeName
self.code=code
self.my_container=my_container._container
- linecache.cache[nodeName]=0,None,string.split(code,'\n'),nodeName
+ linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
ccode=compile(code,nodeName,'exec')
self.context={}
self.context["my_container"] = self.my_container
- exec ccode in self.context
+ exec(ccode, self.context)
def defineNewCustomVar(self,varName,valueOfVar):
- self.context[varName] = cPickle.loads(valueOfVar)
+ self.context[varName] = pickle.loads(valueOfVar)
pass
def executeAnotherPieceOfCode(self,code):
"""Called for initialization of container lodging self."""
try:
ccode=compile(code,self.nodeName,'exec')
- exec ccode in self.context
+ exec(ccode, self.context)
except:
raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
def execute(self,funcName,argsin):
"""Execute the function funcName found in local context with pickled args (argsin)"""
try:
- argsin,kws=cPickle.loads(argsin)
+ argsin,kws=pickle.loads(argsin)
func=self.context[funcName]
argsout=func(*argsin,**kws)
- argsout=cPickle.dumps(argsout,-1)
+ argsout=pickle.dumps(argsout,-1)
return argsout
except:
exc_typ,exc_val,exc_fr=sys.exc_info()
@@ -97,20 +97,20 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic):
self.nodeName=nodeName
self.code=code
self.my_container=my_container._container
- linecache.cache[nodeName]=0,None,string.split(code,'\n'),nodeName
+ linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
self.ccode=compile(code,nodeName,'exec')
self.context={}
self.context["my_container"] = self.my_container
def defineNewCustomVar(self,varName,valueOfVar):
- self.context[varName] = cPickle.loads(valueOfVar)
+ self.context[varName] = pickle.loads(valueOfVar)
pass
def executeAnotherPieceOfCode(self,code):
"""Called for initialization of container lodging self."""
try:
ccode=compile(code,self.nodeName,'exec')
- exec ccode in self.context
+ exec(ccode, self.context)
except:
raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
@@ -124,15 +124,15 @@ class PyScriptNode_i (Engines__POA.PyScriptNode,Generic):
def execute(self,outargsname,argsin):
"""Execute the script stored in attribute ccode with pickled args (argsin)"""
try:
- argsname,kws=cPickle.loads(argsin)
+ argsname,kws=pickle.loads(argsin)
self.context.update(kws)
- exec self.ccode in self.context
+ exec(self.ccode, self.context)
argsout=[]
for arg in outargsname:
- if not self.context.has_key(arg):
+ if arg not in self.context:
raise KeyError("There is no variable %s in context" % arg)
argsout.append(self.context[arg])
- argsout=cPickle.dumps(tuple(argsout),-1)
+ argsout=pickle.dumps(tuple(argsout),-1)
return argsout
except:
exc_typ,exc_val,exc_fr=sys.exc_info()
diff --git a/src/DF/DF_Document.cxx b/src/DF/DF_Document.cxx
index 36a884e2d..d47b7dfc4 100644
--- a/src/DF/DF_Document.cxx
+++ b/src/DF/DF_Document.cxx
@@ -29,7 +29,7 @@ DF_Document::DF_Document(const std::string& theDocumentType)
{
_id = -1;
_type = theDocumentType;
- _modified = true;
+ _modified = false;
}
DF_Document::~DF_Document()
diff --git a/src/DSC/DSC_Python/CMakeLists.txt b/src/DSC/DSC_Python/CMakeLists.txt
index 48a6cb428..697747d88 100755
--- a/src/DSC/DSC_Python/CMakeLists.txt
+++ b/src/DSC/DSC_Python/CMakeLists.txt
@@ -21,6 +21,7 @@ FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(calcium.i PROPERTIES CPLUSPLUS ON)
+SET_SOURCE_FILES_PROPERTIES(calcium.i PROPERTIES SWIG_FLAGS "-py3")
SET(CMAKE_SWIG_FLAGS "-noexcept")
ADD_DEFINITIONS(${OMNIORB_DEFINITIONS} ${BOOST_DEFINITIONS} ${PYTHON_DEFINITIONS} ${NUMPY_DEFINITIONS})
diff --git a/src/DSC/DSC_Python/calcium.i b/src/DSC/DSC_Python/calcium.i
index 424dd6a4a..586cd8def 100644
--- a/src/DSC/DSC_Python/calcium.i
+++ b/src/DSC/DSC_Python/calcium.i
@@ -66,8 +66,8 @@ struct omniORBpyAPI {
%init
%{
+#include
// init section
-
#ifdef WITH_NUMPY
import_array()
#endif
@@ -77,10 +77,10 @@ struct omniORBpyAPI {
{
PyErr_SetString(PyExc_ImportError,
(char*)"Cannot import _omnipy");
- return;
+ return NULL;
}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
- api = (omniORBpyAPI*)PyCObject_AsVoidPtr(pyapi);
+ api = (omniORBpyAPI*)PyCapsule_New(pyapi,NULL,NULL);
Py_DECREF(pyapi);
PyObject* engines = PyImport_ImportModule("Engines");
@@ -142,9 +142,11 @@ const char* pytype_string(PyObject* py_obj) {
if (PyDict_Check( py_obj)) return "dict" ;
if (PyList_Check( py_obj)) return "list" ;
if (PyTuple_Check( py_obj)) return "tuple" ;
- if (PyFile_Check( py_obj)) return "file" ;
if (PyModule_Check( py_obj)) return "module" ;
+#if PY_MAJOR_VERSION < 3
+ if (PyFile_Check( py_obj)) return "file" ;
if (PyInstance_Check(py_obj)) return "instance" ;
+#endif
return "unknown type";
}
diff --git a/src/HDFPersist/HDFfile.cc b/src/HDFPersist/HDFfile.cc
index 3f5e0e1a1..da3eeaa7e 100644
--- a/src/HDFPersist/HDFfile.cc
+++ b/src/HDFPersist/HDFfile.cc
@@ -58,29 +58,36 @@ void HDFfile::CreateOnDisk()
void HDFfile::OpenOnDisk(hdf_access_mode access_mode)
{
- _access_mode = access_mode;
+ _access_mode = access_mode;
+ std::string msgerr;
- switch (_access_mode)
- {
- case HDF_RDWR :
- if (access(_name,F_OK))
+ switch (_access_mode)
{
- if ((_id = HDFfileCreate(_name)) < 0)
- throw HDFexception("Can't open HDF file");
+ case HDF_RDWR:
+ if (access(_name, F_OK))
+ {
+ if ((_id = HDFfileCreate(_name)) < 0) {
+ msgerr = "Can't create HDF in RW mode file" + std::string(_name);
+ throw HDFexception(msgerr.c_str());
+ }
+ }
+ else if ((_id = HDFfileOpen(_name, _access_mode)) < 0) {
+ msgerr = "Can't open HDF in RW mode file " + std::string(_name);
+ throw HDFexception(msgerr.c_str());
+ }
+ break;
+
+ case HDF_RDONLY:
+ if ((_id = HDFfileOpen(_name, _access_mode)) < 0) {
+ msgerr = "Can't open HDF in RO mode file " + std::string(_name);
+ throw HDFexception(msgerr.c_str());
+ }
+ break;
+
+ default:
+ msgerr = "Can't open HDF file " + std::string(_name) + " : bad access option";
+ throw HDFexception(msgerr.c_str());
}
- else
- if ((_id = HDFfileOpen(_name,_access_mode)) < 0)
- throw HDFexception("Can't open HDF file");
- break;
-
- case HDF_RDONLY :
- if ((_id = HDFfileOpen(_name,_access_mode)) < 0)
- throw HDFexception("Can't open HDF file");
- break;
-
- default :
- throw HDFexception("Can't open HDF file : bad access option");
- }
}
void HDFfile::CloseOnDisk()
diff --git a/src/KERNEL_PY/Help.py b/src/KERNEL_PY/Help.py
index 943e1ddc8..23ee4083f 100755
--- a/src/KERNEL_PY/Help.py
+++ b/src/KERNEL_PY/Help.py
@@ -30,7 +30,7 @@ class SalomeDoc:
def __init__(self, aDoc):
self.doc = aDoc
def __repr__(self):
- print self.doc
+ print(self.doc)
return "---"
def salome(self):
doc_salome = '''
@@ -52,9 +52,8 @@ variables:
with a Server name and an Engine name
salome.sg
methods:
- updateObjBrowser(bool):
- getActiveStudyId():
- getActiveStudyName():
+ updateObjBrowser():
+ getStudyName():
SelectedCount(): returns number of selected objects
getSelected(i): returns entry of selected object number i
@@ -71,16 +70,15 @@ variables:
IDToObject(Entry): returns CORBA reference from entry
- salome.myStudyName : active Study Name
- salome.myStudyId : active Study Id
+ salome.myStudyName : the Study Name
salome.myStudy : the active Study itself (CORBA ior)
methods : defined in SALOMEDS.idl
methods:
- salome.DumpStudy(study) : Dump a study, given the ior
+ salome.DumpStudy() : Dump a study, given the ior
---
'''
- print doc_salome
+ print(doc_salome)
def geompy(self):
doc_geompy = '''
@@ -99,7 +97,7 @@ methods:
--- all methods of GEOM_Gen.idl that returns a shape are encapsulated,
with the same interface : shapes are named with their ior
'''
- print doc_geompy
+ print(doc_geompy)
def supervision(self):
doc_supervision = '''
@@ -128,7 +126,7 @@ A new python example avoids references to LifeCycleCORBA
and GraphExample.xml
---
'''
- print doc_supervision
+ print(doc_supervision)
diff --git a/src/KERNEL_PY/PyInterp.py b/src/KERNEL_PY/PyInterp.py
index f10973927..e33625b6a 100755
--- a/src/KERNEL_PY/PyInterp.py
+++ b/src/KERNEL_PY/PyInterp.py
@@ -35,9 +35,10 @@ from SALOME_NamingServicePy import *
#--------------------------------------------------------------------------
-def DumpComponent(Study, SO, offset):
- it = Study.NewChildIterator(SO)
- Builder = Study.NewBuilder()
+def DumpComponent(SO, offset):
+ global myStudy
+ it = myStudy.NewChildIterator(SO)
+ Builder = myStudy.NewBuilder()
while it.More():
CSO = it.Value()
it.Next()
@@ -50,7 +51,7 @@ def DumpComponent(Study, SO, offset):
while ofs <= offset:
a = a + "--"
ofs = ofs +1
- print a + ">" + CSO.GetID() + " " + t_name[1]
+ print(a + ">" + CSO.GetID() + " " + t_name[1])
t_RefSO = CSO.ReferencedObject()
if t_RefSO[0] == 1:
RefSO = t_RefSO[1]
@@ -59,19 +60,20 @@ def DumpComponent(Study, SO, offset):
while ofs <= offset:
a = a + " "
ofs = ofs +1
- print a + ">" + RefSO.GetID()
- DumpComponent(Study, CSO, offset+2)
+ print(a + ">" + RefSO.GetID())
+ DumpComponent(CSO, offset+2)
#--------------------------------------------------------------------------
-def DumpStudy(Study):
- itcomp = Study.NewComponentIterator()
+def DumpStudy():
+ global myStudy
+ itcomp = myStudy.NewComponentIterator()
while itcomp.More():
SC = itcomp.Value()
itcomp.Next()
name = SC.ComponentDataType()
- print "-> ComponentDataType is " + name
- DumpComponent(Study, SC, 1)
+ print("-> ComponentDataType is " + name)
+ DumpComponent(SC, 1)
#--------------------------------------------------------------------------
@@ -88,16 +90,10 @@ sg = SALOMEGUI_Swig()
#create an naming service instance
naming_service = SALOME_NamingServicePy_i(orb)
-# get active study name and id
-myStudyName = sg.getActiveStudyName()
-print myStudyName
+# get active study name
+myStudyName = sg.getStudyName()
+print(myStudyName)
-myStudyId = sg.getActiveStudyId()
-print myStudyId
-
-# get Study Manager reference
-obj = naming_service.Resolve('myStudyManager')
-myStudyManager = obj._narrow(SALOMEDS.StudyManager)
-
-# get active study
-myStudy = myStudyManager.GetStudyByName(myStudyName)
+# get Study reference
+obj = naming_service.Resolve('/Study')
+myStudy = obj._narrow(SALOMEDS.Study)
diff --git a/src/KERNEL_PY/__init__.py b/src/KERNEL_PY/__init__.py
index 47b0b2c43..9c78533a9 100755
--- a/src/KERNEL_PY/__init__.py
+++ b/src/KERNEL_PY/__init__.py
@@ -45,9 +45,7 @@ variables:
- salome.sg : salome object to communicate with the graphical user interface (if any)
- methods:
- - updateObjBrowser(bool):
- - getActiveStudyId():
- - getActiveStudyName():
+ - updateObjBrowser():
- SelectedCount(): returns number of selected objects
- getSelected(i): returns entry of selected object number i
@@ -65,7 +63,6 @@ variables:
- IDToObject(Entry): returns CORBA reference from entry
- salome.myStudyName : active Study Name
- - salome.myStudyId : active Study Id
- salome.myStudy : the active Study itself (CORBA ior)
- methods : defined in SALOMEDS.idl
@@ -78,7 +75,6 @@ variables:
# \param salome.lcc : instance of lifeCycleCORBA class (SALOME_LifeCycleCORBA)
# \param salome.sg : Salome object to communicate with the graphical user interface, if running (see interface in salome_iapp::SalomeOutsideGUI)
# \param salome.myStudyName : active Study Name
-# \param salome.myStudyId : active Study Id
# \param salome.myStudy : the active Study (interface SALOMEDS::Study)
#
@@ -110,13 +106,13 @@ MATCH_ENDING_PATTERN="site-packages" + os.path.sep + "salome"
def extend_path(pname):
for dir in sys.path:
- if not isinstance(dir, basestring) or not os.path.isdir(dir) or not dir.endswith(MATCH_ENDING_PATTERN):
+ if not isinstance(dir, str) or not os.path.isdir(dir) or not dir.endswith(MATCH_ENDING_PATTERN):
continue
subdir = os.path.join(dir, pname)
# XXX This may still add duplicate entries to path on
# case-insensitive filesystems
if os.path.isdir(subdir) and subdir not in __path__:
- if verbose(): print "INFO - The directory %s is appended to sys.path" % subdir
+ if verbose(): print("INFO - The directory %s is appended to sys.path" % subdir)
__path__.append(subdir)
extend_path(ROOT_PYTHONPACKAGE_NAME)
@@ -166,90 +162,58 @@ if not flags:
# pass
orb, lcc, naming_service, cm,sg=None,None,None,None,None
-myStudyManager, myStudyId, myStudy, myStudyName=None,None,None,None
-
-def setCurrentStudy(theStudy):
- """
- Change current study : an existing one given by a study object.
-
- :param theStudy: the study CORBA object to set as current study
- """
- global myStudyId, myStudy, myStudyName
- myStudyId, myStudy, myStudyName =salome_study.setCurrentStudy(theStudy)
-
-def setCurrentStudyId(theStudyId=0):
- """
- Change current study : an existing or new one given by Id.
-
- :param theStudyId: the study Id (optional argument)
- 0 : create a new study (default).
- n (>0) : try connection to study with Id = n, or create a new one
- if study not found.
- """
- global myStudyId, myStudy, myStudyName
- myStudyId, myStudy, myStudyName =salome_study.setCurrentStudyId(theStudyId)
+myStudy, myStudyName=None,None
salome_initial=1
-def salome_init(theStudyId=0,embedded=0):
+def salome_init(embedded=0):
"""
Performs only once SALOME general purpose initialisation for scripts.
- 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.
- If study creation, its Id may be different from theStudyId !
Provides:
orb reference to CORBA
lcc a LifeCycleCorba instance
naming_service a naming service instance
cm reference to the container manager
sg access to SALOME GUI (when linked with IAPP GUI)
- myStudyManager the study manager
- myStudyId active study identifier
myStudy active study itself (CORBA reference)
myStudyName active study name
"""
global salome_initial
global orb, lcc, naming_service, cm
global sg
- global myStudyManager, myStudyId, myStudy, myStudyName
+ global myStudy, myStudyName
try:
if salome_initial:
salome_initial=0
sg = salome_iapp_init(embedded)
orb, lcc, naming_service, cm = salome_kernel_init()
- myStudyManager, myStudyId, myStudy, myStudyName = salome_study_init(theStudyId)
+ myStudy, myStudyName = salome_study_init()
pass
pass
- except RuntimeError, inst:
+ except RuntimeError as inst:
# wait a little to avoid trace mix
import time
time.sleep(0.2)
x = inst
- print "salome.salome_init():", x
- print """
+ print("salome.salome_init():", x)
+ print("""
============================================
May be there is no running SALOME session
salome.salome_init() is intended to be used
within an already running session
============================================
- """
+ """)
raise
def salome_close():
- global salome_initial, myStudy, myStudyId, myStudyName
+ global salome_initial, myStudy, myStudyName
try:
- # study can be closed either from GUI or directly with salome.myStudy.Close()
- myStudy.Close()
+ # study can be clear either from GUI or directly with salome.myStudy.Clear()
+ myStudy.Clear()
except:
pass
salome_initial=1
salome_iapp_close()
- salome_study_close()
- myStudyId, myStudy, myStudyName=None,None,None
pass
diff --git a/src/KERNEL_PY/batchmode_salome.py b/src/KERNEL_PY/batchmode_salome.py
index 7a7ae9e81..59a0bfc85 100755
--- a/src/KERNEL_PY/batchmode_salome.py
+++ b/src/KERNEL_PY/batchmode_salome.py
@@ -35,10 +35,10 @@ from SALOME_NamingServicePy import *
def ImportComponentGUI(ComponentName):
libName = "lib" + ComponentName + "_Swig"
command = "from " + libName + " import *"
- exec ( command )
+ exec (command, globals())
constructor = ComponentName + "GUI_Swig()"
command = "gui = " + constructor
- exec ( command )
+ exec (command, globals())
return gui
#--------------------------------------------------------------------------
@@ -65,12 +65,12 @@ def generateName(prefix = None):
#WITHOUTIHMgetAllSelected = SalomeGUIgetAllSelected
#WITHOUTIHMdef getDesktop(self) :
-# return SalomePyQt.getDesktop()
- #WITHOUTIHMreturn None
+# return SalomePyQt.getDesktop()
+ #WITHOUTIHMreturn None
#WITHOUTIHMdef getSelection(self) :
-# return SalomePyQt.getSelection()
- #WITHOUTIHMreturn None
+# return SalomePyQt.getSelection()
+ #WITHOUTIHMreturn None
#--------------------------------------------------------------------------
@@ -105,7 +105,7 @@ def IDToSObject(id):
#--------------------------------------------------------------------------
-def PersistentPresentation(theStudy, theSO, theWithID):
+def PersistentPresentation(theSO, theWithID):
# put the sobject's content (with subchildren) to the string
aResult = ""
attrs = theSO.GetAllAttributes()
@@ -154,9 +154,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
@@ -178,28 +178,30 @@ def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
while aRoot.GetID() != "0:":
aRoot = aRoot.GetFather()
aTree = GetTree(aRoot)
+ aStudyPersist = PersistentPresentation(aRoot, 1)
+
aStudyPersist = PersistentPresentation(myStudy, aRoot, 1)
- if not myStudyManager.CanCopy(theSO):
- raise RuntimeError, " for "+theInfo+" returns false"
+ if not myStudy.CanCopy(theSO):
+ raise RuntimeError(" for "+theInfo+" returns false")
- if not myStudyManager.Copy(theSO):
- raise RuntimeError, " for "+theInfo+" returns false"
+ if not myStudy.Copy(theSO):
+ raise RuntimeError(" for "+theInfo+" returns false")
- if not myStudyManager.CanPaste(theSO):
- raise RuntimeError, " for "+theInfo+" returns false"
+ if not myStudy.CanPaste(theSO):
+ raise RuntimeError(" 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, " for "+theInfo+" returns None object"
+ if myStudy.Paste(aSObj) == None:
+ raise RuntimeError(" for "+theInfo+" returns None object")
aNewTree = GetTree(aRoot)
aLen = len(aTree)
for a in range(0,aLen):
@@ -209,7 +211,7 @@ 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 FindFileInDataDir(filename):
@@ -246,7 +248,7 @@ while 1:
pass
if orb is None:
- print "Warning: ORB has not been initialized !!!"
+ print("Warning: ORB has not been initialized !!!")
# create an LifeCycleCORBA instance
lcc = LifeCycleCORBA(orb)
@@ -264,42 +266,30 @@ while 1:
pass
if lcc is None:
- print "Warning: LifeCycleCORBA object has not been initialized !!!"
+ print("Warning: LifeCycleCORBA object has not been initialized !!!")
#create a naming service instance
naming_service = SALOME_NamingServicePy_i(orb)
-# get Study Manager reference
+# get Study reference
obj = None
step = 0
sleeping_time = 0.01
sleeping_time_max = 1.0
while 1:
- obj = naming_service.Resolve('myStudyManager')
+ obj = naming_service.Resolve('/Study')
if obj is not None:break
step = step + 1
if step > 100: break
time.sleep(sleeping_time)
sleeping_time = max(sleeping_time_max, 2*sleeping_time)
pass
-
-myStudyManager = obj._narrow(SALOMEDS.StudyManager)
-
-if myStudyManager is None:
- print "Warning: SALOMEDS.StudyManager has not been created !!!"
-
-# create new study
-aListOfOpenStudies = myStudyManager.GetOpenStudies();
-myStudy = None;
-if len(aListOfOpenStudies) == 0 :
- myStudy = myStudyManager.NewStudy("Study1")
-else:
- myStudyName = aListOfOpenStudies[0]
- myStudy = myStudyManager.GetStudyByName(myStudyName)
-myStudyName = myStudy._get_Name()
+myStudy = obj._narrow(SALOMEDS.Study)
-myStudyId = myStudy._get_StudyId()
-#print myStudyId
+if myStudy is None:
+ print("Warning: SALOMEDS.Study has not been created !!!")
+
+myStudyName = myStudy._get_Name()
diff --git a/src/KERNEL_PY/iparameters.py b/src/KERNEL_PY/iparameters.py
index f0b8c06a1..d3ce1c3d8 100755
--- a/src/KERNEL_PY/iparameters.py
+++ b/src/KERNEL_PY/iparameters.py
@@ -84,10 +84,10 @@ class IParameters:
self._ap = attributeParameter
if ( clr ): self.clear()
pass
-
+
def clear(self):
"""Clear parameters"""
- self._ap.Clear()
+ self._ap.Clear()
def append(self, listName, value):
"""Appends a value to the named list"""
diff --git a/src/KERNEL_PY/kernel/__init__.py b/src/KERNEL_PY/kernel/__init__.py
index 1dfd4f750..65dda6ce6 100644
--- a/src/KERNEL_PY/kernel/__init__.py
+++ b/src/KERNEL_PY/kernel/__init__.py
@@ -80,18 +80,18 @@ class Callable:
#
def TEST_serialization():
- from testdata import TestData
+ from .testdata import TestData
ref_name = "my study case"
studyData = TestData()
studyData.setName(ref_name)
- print "serialize data ..."
+ print("serialize data ...")
serialString = serialize(studyData)
- print "unserialize data ..."
+ print("unserialize data ...")
unserialData = unserialize(serialString)
res_name = unserialData.getName()
- print res_name
+ print(res_name)
if ( ref_name != res_name ):
return False
@@ -101,5 +101,5 @@ def TEST_serialization():
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("salome/kernel/__init__","TEST_serialization")
diff --git a/src/KERNEL_PY/kernel/datamodeler.py b/src/KERNEL_PY/kernel/datamodeler.py
index 9251b2a72..b2f12bc5a 100644
--- a/src/KERNEL_PY/kernel/datamodeler.py
+++ b/src/KERNEL_PY/kernel/datamodeler.py
@@ -26,7 +26,7 @@
__author__="gboulant"
__date__ ="$15 avr. 2010 19:44:17$"
-from uiexception import DevelException
+from .uiexception import DevelException
# Most usable class types
TypeString= "".__class__
@@ -105,18 +105,18 @@ class DataModeler:
# Default initialization (if any)
if defaultmap is not None:
self._defaultmap.update(defaultmap)
- for name in self._defaultmap.keys():
+ for name in self._defaultmap:
self.__setattr__(name,self._defaultmap[name])
## %A None argument means that no entry is created in the associated maps.
- def addAttribute(self, name, type=None, range=None, default=None, void=None):
+ def addAttribute(self, name, a_type=None, a_range=None, default=None, void=None):
"""
A None argument means that no entry is created in the associated maps.
"""
- self._typemap[name] = type
+ self._typemap[name] = a_type
- if range is not None:
- self._rangemap[name] = range
+ if a_range is not None:
+ self._rangemap[name] = a_range
if void is not None:
self._voidmap[name] = void
@@ -133,9 +133,9 @@ class DataModeler:
#__GBO_DEBUG_
if name == "_typemap":
- print "WARNING WARNING WARNING : changing value of _typemap by ",val
+ print("WARNING WARNING WARNING : changing value of _typemap by ",val)
- if name not in self._typemap.keys():
+ if name not in self._typemap:
raise DevelException("The class "+str(self.__class__)+" has no attribute "+str(name))
if val is None:
@@ -158,11 +158,11 @@ class DataModeler:
if name in UNCHECKED_ATTRIBUTES:
return self.__dict__[name]
- if name not in self._typemap.keys():
+ if name not in self._typemap:
raise DevelException("The class "+str(self.__class__)+" has no attribute "+str(name))
# The attribute coulb be requested while it has not been created yet (for
# example if we did't call the setter before).
- if not self.__dict__.has_key(name):
+ if name not in self.__dict__:
return None
return self.__dict__[name]
@@ -177,7 +177,7 @@ class DataModeler:
def __isNotValidRange(self, name, val):
isNotValid = (
( self._rangemap is not None) and
- ( self._rangemap.has_key(name) ) and
+ ( name in self._rangemap ) and
( self._rangemap[name] is not None ) and
( val not in self._rangemap[name] ) )
@@ -186,13 +186,13 @@ class DataModeler:
def __isVoidAllowed(self,name):
isVoidAllowed = (
( self._voidmap is not None) and
- ( self._voidmap.has_key(name) ) and
+ ( name in self._voidmap ) and
( self._voidmap[name] is True ) )
return isVoidAllowed
def log(self):
- print "DATAMODELER ["+str(self.__class__)+"]: self._typemap.keys() = "+str(self._typemap.keys())
+ print("DATAMODELER ["+str(self.__class__)+"]: self._typemap.keys() = "+str(list(self._typemap.keys())))
@@ -219,7 +219,7 @@ def TEST_usecase():
data.anydata = "any value"
data.anydata = True
- print data.integerdata
+ print(data.integerdata)
return True
def TEST_addAttribute():
@@ -232,8 +232,8 @@ def TEST_addAttribute():
ref_value = 1.3
data.addAttribute(
name = "myAttr",
- type = TypeDouble,
- range = None,
+ a_type = TypeDouble,
+ a_range = None,
default = ref_value,
void = False)
@@ -242,15 +242,15 @@ def TEST_addAttribute():
return False
data.myAttr = 5.3
#data.myAttr = 5
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
return False
try:
data.myAttr = "bad type value"
return False
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
return True
def TEST_badAttributeName():
@@ -264,8 +264,8 @@ def TEST_badAttributeName():
try:
data.myatt = 3
return False
- except Exception, e:
- print "OK : "+str(e)
+ except Exception as e:
+ print("OK : "+str(e))
return True
def TEST_badAttributeType():
@@ -278,8 +278,8 @@ def TEST_badAttributeType():
try:
data.stringdata = 2
return False
- except Exception, e:
- print "OK : "+str(e)
+ except Exception as e:
+ print("OK : "+str(e))
return True
def TEST_badAttributeRange():
@@ -296,16 +296,16 @@ def TEST_badAttributeRange():
try:
data.integerdata = ref_integervalue
data.stringdata = "anything (no restriction has been defined)"
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
return False
# this should raise an exception
try:
data.integerdata = 9999 # a value not in the range
return False
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
return True
def TEST_voidAttributeAllowed():
@@ -320,17 +320,17 @@ def TEST_voidAttributeAllowed():
try:
# this should not raise an exception
data.stringdata = None
- print data.stringdata
- except Exception, e:
- print e
+ print(data.stringdata)
+ except Exception as e:
+ print(e)
return False
try:
# this should raise an exception
data.integerdata = None
return False
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
return True
def TEST_defaultValues():
@@ -343,14 +343,14 @@ def TEST_defaultValues():
defaultmap["stringdata"] = ref_value
data = DataModeler(typemap=typemap,defaultmap=defaultmap)
- print data.stringdata
+ print(data.stringdata)
if data.stringdata != ref_value:
return False
else:
return True
if __name__ == "__main__":
- from unittester import run
+ from .unittester import run
run("salome/kernel/datamodeler","TEST_usecase")
run("salome/kernel/datamodeler","TEST_addAttribute")
run("salome/kernel/datamodeler","TEST_badAttributeName")
diff --git a/src/KERNEL_PY/kernel/diclookup.py b/src/KERNEL_PY/kernel/diclookup.py
index 1ec0eab17..3420e1fec 100644
--- a/src/KERNEL_PY/kernel/diclookup.py
+++ b/src/KERNEL_PY/kernel/diclookup.py
@@ -38,7 +38,7 @@ __date__ ="$21 mai 2010 18:00:23$"
# \ingroup diclookup
def find_key(dic, val):
"""return the key of dictionary dic given the value"""
- return [k for k, v in dic.iteritems() if v == val][0]
+ return [k for k, v in dic.items() if v == val][0]
## return the value of dictionary dic given the key
# \ingroup diclookup
@@ -55,14 +55,14 @@ class Lookup(dict):
## items can be a list of pair_lists or a dictionary
def __init__(self, items=None):
"""items can be a list of pair_lists or a dictionary"""
- if items is None:
- items = []
+ if items is None:
+ items = []
dict.__init__(self, items)
## find the key(s) as a list given a value
def get_keys(self, value):
"""find the key(s) as a list given a value"""
- return [item[0] for item in self.items() if item[1] == value]
+ return [item[0] for item in list(self.items()) if item[1] == value]
## find the key associated to the given a value. If several keys exist,
# only the first is given. To get the whole list, use get_keys instead.
@@ -100,9 +100,9 @@ def TEST_getTestDictionnary():
def TEST_find_value():
symbol_dic = TEST_getTestDictionnary()
- print find_key(symbol_dic, 'boron') # B
- print find_value(symbol_dic, 'B') # boron
- print find_value(symbol_dic, 'H') # hydrogen
+ print(find_key(symbol_dic, 'boron')) # B
+ print(find_value(symbol_dic, 'B')) # boron
+ print(find_value(symbol_dic, 'H')) # hydrogen
if find_key(symbol_dic, 'nitrogen') != 'N':
return False
return True
@@ -114,24 +114,24 @@ def TEST_lookup():
symbol = 'Li'
# use a dictionary as initialization argument
look = Lookup(symbol_dic)
- print look.get_key(name) # [Li']
+ print(look.get_key(name)) # [Li']
if look.get_key(name) != symbol:
- print "get "+str(look.get_key(name))+" while "+str(symbol)+" was expected"
+ print("get "+str(look.get_key(name))+" while "+str(symbol)+" was expected")
return False
- print look.get_value(symbol) # lithium
+ print(look.get_value(symbol)) # lithium
# use a list of pairs instead of a dictionary as initialization argument
# (will be converted to a dictionary by the class internally)
age_list = [['Fred', 23], ['Larry', 28], ['Ene', 23]]
look2 = Lookup(age_list)
- print look2.get_keys(23) # ['Ene', 'Fred']
+ print(look2.get_keys(23)) # ['Ene', 'Fred']
if look2.get_keys(23)[0] != 'Ene' or look2.get_keys(23)[1] != 'Fred':
- print "get "+str(look2.get_keys(23))+" while ['Ene', 'Fred'] was expected"
+ print("get "+str(look2.get_keys(23))+" while ['Ene', 'Fred'] was expected")
return False
- print look2.get_value('Fred') # 23
+ print(look2.get_value('Fred')) # 23
return True
if __name__ == '__main__':
- import unittester
+ from . import unittester
unittester.run("diclookup", "TEST_find_value")
unittester.run("diclookup", "TEST_lookup")
diff --git a/src/KERNEL_PY/kernel/enumerate.py b/src/KERNEL_PY/kernel/enumerate.py
index 2190b2a01..2ff423aca 100644
--- a/src/KERNEL_PY/kernel/enumerate.py
+++ b/src/KERNEL_PY/kernel/enumerate.py
@@ -53,6 +53,7 @@ class Enumerate(object):
value = offset + number
setattr(self, key, value)
self._dict_keynumbers[key] = value
+ self._dict_numberkeys = {v: k for k, v in self._dict_keynumbers.items()}
## Return true if this enumerate contains the specified key string
# \param key a key string to test
@@ -61,7 +62,7 @@ class Enumerate(object):
Return true if this enumerate contains the specified key string
@key a key string to test
"""
- return (key in self._dict_keynumbers.keys())
+ return key in self._dict_keynumbers
## Returns true if the specified integer value is defined as an identifier
# in this enumerate.
@@ -72,25 +73,21 @@ class Enumerate(object):
in this enumerate.
@value a value to test
"""
- return (value in self._dict_keynumbers.values())
+ return value in self._dict_numberkeys
## Returns the list of keys in this enumerate.
def listkeys(self):
"""
Returns the list of keys in this enumerate.
"""
- list = self._dict_keynumbers.keys()
- list.sort()
- return list
+ return sorted(self._dict_keynumbers)
## Returns the list of values specified to initiate this enumerate.
def listvalues(self):
"""
Returns the list of values specified to initiate this enumerate.
"""
- list = self._dict_keynumbers.values()
- list.sort()
- return list
+ return sorted(self._dict_numberkeys)
## Returns the symbolic key string associated to the specified identifier value.
# \param value an integer value whose associated key string is requested.
@@ -104,7 +101,7 @@ class Enumerate(object):
return None
# _MEM_ We assume here that the keys and associated values are in the
# same order in their list.
- return self._dict_keynumbers.keys()[self._dict_keynumbers.values().index(value)]
+ return self._dict_numberkeys[value]
# If not, weshould use a longer implementation such that:
#for key in self._dict_keynumbers.keys():
@@ -122,7 +119,7 @@ def TEST_simple():
'SEP',
'OTHER'
])
- print TYPES_LIST.listvalues()
+ print(TYPES_LIST.listvalues())
return True
def TEST_createFromList():
@@ -133,8 +130,8 @@ def TEST_createFromList():
'MED',
'SMESH'])
- print codes.KERNEL
- print codes.GEOM
+ print(codes.KERNEL)
+ print(codes.GEOM)
if (codes.KERNEL == 0 and codes.GEOM == 2):
return True
else:
@@ -145,8 +142,8 @@ def TEST_createFromString():
codes = Enumerate(aList.split())
- print codes.KERNEL
- print codes.GEOM
+ print(codes.KERNEL)
+ print(codes.GEOM)
if (codes.KERNEL == 0 and codes.GEOM == 2):
return True
else:
@@ -160,7 +157,7 @@ def TEST_contains():
'MED',
'SMESH'])
- print "VISU in enumerate?", codes.contains("VISU")
+ print("VISU in enumerate?", codes.contains("VISU"))
if (not codes.contains("VISU")):
return True
else:
@@ -187,8 +184,8 @@ def TEST_offset():
'MED',
'SMESH'], offset=20)
- print codes.KERNEL
- print codes.GEOM
+ print(codes.KERNEL)
+ print(codes.GEOM)
if (codes.KERNEL == 20 and codes.GEOM == 22):
return True
else:
@@ -202,7 +199,7 @@ def TEST_listvalues():
'MED',
'SMESH'], offset=20)
- print codes.listvalues()
+ print(codes.listvalues())
if codes.listvalues() != [20, 21, 22, 23, 24]:
return False
return True
@@ -224,7 +221,7 @@ def TEST_keyOf():
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("enumerate", "TEST_simple")
unittester.run("enumerate", "TEST_createFromList")
unittester.run("enumerate", "TEST_createFromString")
diff --git a/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py b/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py
index 0ac0490fc..c779c5158 100644
--- a/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py
+++ b/src/KERNEL_PY/kernel/parametric/study_exchange_vars.py
@@ -53,7 +53,7 @@ class Variable:
def __init__(self, name, dimension = None, minValue = None, maxValue = None,
initialValue = None):
if dimension is None:
- dimension = []
+ dimension = []
self.name = name
# Reserved for future use
@@ -105,9 +105,9 @@ class ExchangeVariables:
def __init__(self, inputVarList = None, outputVarList = None,
refEntry = None):
if inputVarList is None:
- inputVarList = []
- if outputVarList is None:
- outputVarList = []
+ inputVarList = []
+ if outputVarList is None:
+ outputVarList = []
self.inputVarList = inputVarList
self.outputVarList = outputVarList
self.refEntry = refEntry
@@ -182,8 +182,7 @@ def createSObjectForExchangeVariables(fatherSobj, exchangeVariables,
:return: the newly created SObject.
"""
- studyId = fatherSobj.GetStudy()._get_StudyId()
- editor = getStudyEditor(studyId)
+ editor = getStudyEditor()
sobj = editor.createItem(fatherSobj,
name = name,
icon = icon,
@@ -210,8 +209,7 @@ def updateSObjectForExchangeVariables(sobj, exchangeVariables,
other parameters.
"""
- studyId = sobj.GetStudy()._get_StudyId()
- editor = getStudyEditor(studyId)
+ editor = getStudyEditor()
editor.setItem(sobj, name = name, icon = icon, typeId = typeId)
editor.builder.RemoveAttribute(sobj, "AttributeParameter")
_setSObjectForExchangeVariables(editor, sobj, exchangeVariables)
diff --git a/src/KERNEL_PY/kernel/pyunittester.py b/src/KERNEL_PY/kernel/pyunittester.py
index 8c21ec568..fc056f1f8 100644
--- a/src/KERNEL_PY/kernel/pyunittester.py
+++ b/src/KERNEL_PY/kernel/pyunittester.py
@@ -30,16 +30,16 @@ def printfile(filename):
lines = stream.readlines()
stream.close()
for line in lines:
- if not termcolor.canDisplayColor(sys.stdout):
- msg = line.split('\n')[0]
- else:
+ if not termcolor.canDisplayColor(sys.stdout):
+ msg = line.split('\n')[0]
+ else:
msg = termcolor.makeColoredMessage(line.split('\n')[0], termcolor.BLUE)
- print msg
+ print(msg)
import os
import unittest
from unittest import TestCase
-from uiexception import DevelException
+from .uiexception import DevelException
## This class is a simple wrapper of the pyunit framework.
# \ingroup pyunittester
@@ -97,8 +97,8 @@ def execAndConvertExceptionToBoolean(function):
if result is None:
return True
return result
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
return False
# Simple helper function for most cases where there is only one
@@ -121,17 +121,17 @@ def run(testCaseClass):
class MyTestCase(unittest.TestCase):
def test_myTestOk_01(self):
r=True
- print "myTestOk_01: should be OK"
+ print("myTestOk_01: should be OK")
self.assertTrue(r)
def test_myTestOk_02(self):
r=True
- print "myTestOk_02: should be OK"
+ print("myTestOk_02: should be OK")
self.assertTrue(r)
def test_myTestNotOk(self):
r=False
- print "myTestNotOk: should be NOT OK"
+ print("myTestNotOk: should be NOT OK")
self.assertTrue(r)
def functionRaisingAnException():
@@ -144,32 +144,32 @@ def functionReturningTrue():
return True
def functionReturningNothing():
- print "functionReturningNothing"
+ print("functionReturningNothing")
class MyTestCase2(unittest.TestCase):
def test_myTest_01(self):
r=execAndConvertExceptionToBoolean(functionRaisingAnException)
- print "test 01: this test should be NOT OK"
+ print("test 01: this test should be NOT OK")
self.assertTrue(r)
def test_myTest_02(self):
r=execAndConvertExceptionToBoolean(functionReturningFalse)
- print "test 02: this test should be NOT OK"
+ print("test 02: this test should be NOT OK")
self.assertTrue(r)
def test_myTest_03(self):
r=execAndConvertExceptionToBoolean(functionReturningTrue)
- print "test 03: this test should be OK"
+ print("test 03: this test should be OK")
self.assertTrue(r)
def test_myTest_04(self):
r=execAndConvertExceptionToBoolean(functionReturningNothing)
- print "test 04: this test should be OK"
+ print("test 04: this test should be OK")
self.assertTrue(r)
def test_myTest_05(self):
r=True
- print "test 05: this test should be OK"
+ print("test 05: this test should be OK")
self.assertTrue(r)
diff --git a/src/KERNEL_PY/kernel/services.py b/src/KERNEL_PY/kernel/services.py
index 57cdf9b7e..31038407c 100644
--- a/src/KERNEL_PY/kernel/services.py
+++ b/src/KERNEL_PY/kernel/services.py
@@ -38,17 +38,17 @@
# SALOME development).
import salome
-from deprecation import is_called_by_sphinx
+from .deprecation import is_called_by_sphinx
if not is_called_by_sphinx() and salome.lcc is None:
try:
salome.salome_init()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
# Note that the salome module provides you with standard SALOME
# objects: CORBA broker (orb): salome.orb lyfe cycle (lcc) :
-# salome.lcc naming service : salome.naming_service study manager :
-# salome.myStudyManager The default study : salome.myStudy
+# salome.lcc naming service : salome.naming_service
+# The default study : salome.myStudy
#
# Alternatively, you may obtain these objects directly with the
# following instructions:
@@ -96,12 +96,12 @@ def getComponent(componentName = "SalomeTestComponent",
"""
Get a SALOME CORBA component from its name
"""
- print "INF: getting component %s from CORBA module %s ..."%(componentName,corbaModule)
+ print("INF: getting component %s from CORBA module %s ..."%(componentName,corbaModule))
__import__(corbaModule)
component=salome.lcc.FindOrLoadComponent(containerType,componentName)
if component is None:
- print "ERR: the SALOME component "+componentName+" can't be reached"
- print "INF: component %s obtained from CORBA module %s"%(componentName,corbaModule)
+ print("ERR: the SALOME component "+componentName+" can't be reached")
+ print("INF: component %s obtained from CORBA module %s"%(componentName,corbaModule))
return component
# Note that an alternative (and maybe better) method to get a component
@@ -120,30 +120,24 @@ def getComponentList():
obj = salome.naming_service.Resolve('Kernel/ModulCatalog')
catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
if not catalog:
- raise RuntimeError, "Can't access module catalog"
+ raise RuntimeError("Can't access module catalog")
return catalog.GetComponentList()
-## Get a study manager to create and manage %SALOME studies
-# \ingroup service
-def getStudyManager():
- """Get a study manager to create and manage SALOME studies"""
- return salome.myStudyManager
-
import SALOMEDS
-## Get a study manager to create and manage SALOME studies.
-# \warning you should use instead the variable salome.myStudyManager.
+## Get a study to create SALOME study.
+# \warning you should use instead the variable salome.myStudy.
# This function is given for illustration of usage of the naming service
# \ingroup service
-def __getStudyManager_demo():
+def __getStudy_demo():
"""
- Get a study manager to create and manage SALOME studies. WARN: you
- should use instead the variable salome.myStudyManager. This
+ Get a study to create SALOME study. WARN: you
+ should use instead the variable salome.myStudy. This
function is given for illustration of usage of the naming service
"""
naming_service = SALOME_NamingServicePy_i( orb )
- obj = naming_service.Resolve( '/myStudyManager' )
- studyManager = obj._narrow( SALOMEDS.StudyManager)
- return studyManager
+ obj = naming_service.Resolve( '/Study' )
+ study = obj._narrow( SALOMEDS.Study)
+ return study
#
@@ -242,7 +236,7 @@ def TEST_createObject():
"""
import GEOM
from salome.geom import geomBuilder
- geompy = geomBuilder.New(salome.myStudy)
+ geompy = geomBuilder.New()
box = geompy.MakeBoxDXDYDZ(200, 200, 200)
id = geompy.addToStudy( box, 'box' )
@@ -259,14 +253,14 @@ def TEST_objectsManipulation():
myObject = IDToObject(myEntry)
- print myObject
+ print(myObject)
if myObject is None:
return False
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("services","TEST_getComponent")
unittester.run("services","TEST_getComponentList")
unittester.run("services","TEST_objectsManipulation")
diff --git a/src/KERNEL_PY/kernel/studyedit.py b/src/KERNEL_PY/kernel/studyedit.py
index 463b70fb8..c047b046f 100644
--- a/src/KERNEL_PY/kernel/studyedit.py
+++ b/src/KERNEL_PY/kernel/studyedit.py
@@ -31,73 +31,34 @@ This module provides a new class :class:`StudyEditor` to complement
import re
-import salome
-from salome.kernel.logger import Logger
from salome.kernel import termcolor
-logger = Logger("salome.kernel.studyedit", color = termcolor.PURPLE)
+from salome.kernel.logger import Logger
+import salome
+
+
+logger = Logger("salome.kernel.studyedit", color=termcolor.PURPLE)
-_editors = {}
+_editor = None
_DEFAULT_CONTAINER = "FactoryServer"
-# The codec to use for strings that are displayed in Salome study tree is Latin-1
-ENCODING_FOR_SALOME_STUDY = "iso-8859-1"
-## Return the ID of the active study. In GUI mode, this function is equivalent
-# to salome.sg.getActiveStudyId(). Outside GUI, it returns salome.myStudyId
-# variable.
+## Return a \b StudyEditor instance to edit the study.
# \ingroup studyedit
-def getActiveStudyId():
+def getStudyEditor():
"""
- Return the ID of the active study. In GUI mode, this function is equivalent
- to ``salome.sg.getActiveStudyId()``. Outside GUI, it returns
- ``salome.myStudyId`` variable.
+ Return a :class:`StudyEditor` instance to edit the study.
"""
- salome.salome_init()
- # Warning: we don't use salome.getActiveStudy() here because it doesn't
- # work properly when called from Salome modules (multi-study interpreter
- # issue)
- if salome.hasDesktop():
- return salome.sg.getActiveStudyId()
- else:
- return salome.myStudyId
-
-def getActiveStudy():
- return getStudyFromStudyId(getActiveStudyId())
-
-def getStudyFromStudyId(studyId):
- salome.salome_init()
- study = salome.myStudyManager.GetStudyByID(studyId)
- return study
-
-def getStudyIdFromStudy(study):
- studyId = study._get_StudyId()
- return studyId
-
-## Return a \b StudyEditor instance to edit the study with ID studyId.
-# If \b studyId is \b None, return an editor for the current study.
-# \ingroup studyedit
-def getStudyEditor(studyId = None):
- """
- Return a :class:`StudyEditor` instance to edit the study with ID
- `studyId`. If `studyId` is :const:`None`, return an editor for the current
- study.
- """
- if studyId is None:
- studyId = getActiveStudyId()
- if not _editors.has_key(studyId):
- _editors[studyId] = StudyEditor(studyId)
- return _editors[studyId]
+ global _editor
+ if _editor is None:
+ _editor = StudyEditor()
+ return _editor
## This class provides utility methods to complement \b Study and
# \b StudyBuilder classes. Those methods may be moved in those classes
-# in the future. The parameter \b studyId defines the ID of the study to
-# edit. If it is \em None, the edited study will be the current study.
+# in the future.
# The preferred way to get a StudyEditor object is through the method
# \b getStudyEditor which allows to reuse existing instances.
#
-# \param studyId This instance attribute contains the ID of the edited study.
-# This attribute should not be modified.
-#
# \param study This instance attribute contains the underlying \b Study object.
# It can be used to access the study but the attribute itself should not
# be modified.
@@ -110,16 +71,10 @@ class StudyEditor:
"""
This class provides utility methods to complement :class:`Study` and
:class:`StudyBuilder` classes. Those methods may be moved in those classes
- in the future. The parameter `studyId` defines the ID of the study to
- edit. If it is :const:`None`, the edited study will be the current study.
+ in the future.
The preferred way to get a StudyEditor object is through the method
:meth:`getStudyEditor` which allows to reuse existing instances.
- .. attribute:: studyId
-
- This instance attribute contains the ID of the edited study. This
- attribute should not be modified.
-
.. attribute:: study
This instance attribute contains the underlying :class:`Study` object.
@@ -133,15 +88,12 @@ class StudyEditor:
should not be modified.
"""
- def __init__(self, studyId = None):
+ def __init__(self):
salome.salome_init()
- if studyId is None:
- studyId = getActiveStudyId()
- self.studyId = studyId
- self.study = salome.myStudyManager.GetStudyByID(studyId)
+ self.study = salome.myStudy
if self.study is None:
raise Exception("Can't create StudyEditor object: "
- "Study %d doesn't exist" % studyId)
+ "Study doesn't exist")
self.builder = self.study.NewBuilder()
## Find a component corresponding to the Salome module \b moduleName in
@@ -339,19 +291,19 @@ class StudyEditor:
# \return new SObject created in the study.
#
# See \b setItem() for the description of the other parameters.
- def createItem(self, fatherItem, name, fileType = None, fileName = None,
- comment = None, icon = None, IOR = None, typeId = None):
+ def createItem(self, fatherItem, name, fileType=None, fileName=None,
+ comment=None, icon=None, IOR=None, typeId=None):
"""
Create a new object named `name` under `fatherItem` in the study, with
the given attributes. If an object named `name` already exists under
the father object, the new object is created with a new name `name_X`
where X is the first available index.
-
+
:type fatherItem: SObject
:param fatherItem: item under which the new item will be added.
-
+
:return: new SObject created in the study
-
+
See :meth:`setItem` for the description of the other parameters.
"""
aSObject = self.builder.NewObject(fatherItem)
@@ -366,11 +318,10 @@ class StudyEditor:
aSObj = aChildIterator.Value()
aChildIterator.Next()
aName = aSObj.GetName()
- if re.match(aNameRE,aName):
+ if re.match(aNameRE, aName):
aTmp = aName[aLength:]
- if re.match(anIdRE,aTmp):
- import string
- anId = string.atol(aTmp[1:])
+ if re.match(anIdRE, aTmp):
+ anId = int(aTmp[1:])
if aMaxId < anId:
aMaxId = anId
pass
@@ -380,16 +331,16 @@ class StudyEditor:
pass
pass
pass
-
+
aMaxId = aMaxId + 1
aName = name
if aMaxId > 0:
aName = aName + aDelim + str(aMaxId)
pass
-
+
self.setItem(aSObject, aName, fileType, fileName, comment, icon,
IOR, typeId)
-
+
return aSObject
## Modify the attributes of an item in the study. Unspecified attributes
@@ -540,21 +491,19 @@ class StudyEditor:
## Return the name of the object sObject
def getName(self, sObject):
- val = sObject.GetName()
- return unicode(val, ENCODING_FOR_SALOME_STUDY)
+ return sObject.GetName()
## Set the name of the object sObject
def setName(self, sObject, name):
- self.builder.SetName(sObject, name.encode(ENCODING_FOR_SALOME_STUDY))
+ self.builder.SetName(sObject, name)
## Return the comment of the object sObject
def getComment(self, sObject):
- val = sObject.GetComment()
- return unicode(val, ENCODING_FOR_SALOME_STUDY)
+ return sObject.GetComment()
## Set the comment of the object sObject
def setComment(self, sObject, comment):
- self.builder.SetComment(sObject, comment.encode(ENCODING_FOR_SALOME_STUDY))
+ self.builder.SetComment(sObject, comment)
## Return the value of the attribute named \b attributeName on the object
# sObject, or \b default if the attribute doesn't exist.
@@ -604,8 +553,7 @@ class StudyEditor:
Return the value of the attribute "AttributeFileType" of the object
`sObject`, or an empty string if it is not set.
"""
- val = self.getAttributeValue(sObject, "AttributeFileType", "")
- return unicode(val, ENCODING_FOR_SALOME_STUDY)
+ return self.getAttributeValue(sObject, "AttributeFileType", "")
## Set the attribute "AttributeFileType" of the object sObject to the
# value value.
@@ -615,7 +563,7 @@ class StudyEditor:
value `value`.
"""
self.setAttributeValue(sObject, "AttributeFileType",
- value.encode(ENCODING_FOR_SALOME_STUDY))
+ value)
## Return the value of the attribute "AttributeExternalFileDef" of the
# object sObject, or an empty string if it is not set.
@@ -624,8 +572,7 @@ class StudyEditor:
Return the value of the attribute "AttributeExternalFileDef" of the
object `sObject`, or an empty string if it is not set.
"""
- val = self.getAttributeValue(sObject, "AttributeExternalFileDef", "")
- return unicode(val, ENCODING_FOR_SALOME_STUDY)
+ return self.getAttributeValue(sObject, "AttributeExternalFileDef", "")
## Set the attribute "AttributeExternalFileDef" of the object sObject
# to the value value.
@@ -635,7 +582,7 @@ class StudyEditor:
to the value `value`.
"""
self.setAttributeValue(sObject, "AttributeExternalFileDef",
- value.encode(ENCODING_FOR_SALOME_STUDY))
+ value)
## Return the value of the attribute "AttributePixMap" of the object
# sObject, or an empty string if it is not set.
@@ -648,7 +595,7 @@ class StudyEditor:
found, attr = self.builder.FindAttribute(sObject, "AttributePixMap")
if found and attr.HasPixMap():
value = attr.GetPixMap()
- return unicode(value, ENCODING_FOR_SALOME_STUDY)
+ return value
## Set the attribute "AttributePixMap" of the object sObject to the
# value value.
@@ -658,4 +605,4 @@ class StudyEditor:
value `value`.
"""
attr = self.builder.FindOrCreateAttribute(sObject, "AttributePixMap")
- attr.SetPixMap(value.encode(ENCODING_FOR_SALOME_STUDY))
+ attr.SetPixMap(value)
diff --git a/src/KERNEL_PY/kernel/syshelper.py b/src/KERNEL_PY/kernel/syshelper.py
index f3c94600d..abf8b8935 100644
--- a/src/KERNEL_PY/kernel/syshelper.py
+++ b/src/KERNEL_PY/kernel/syshelper.py
@@ -58,7 +58,7 @@ def walktree(rootpath, callback, **kwargs):
pathname = os.path.join(rootpath, f)
try:
mode = os.stat(pathname)[ST_MODE]
- except OSError, e:
+ except OSError as e:
# It probably means that the file is a broken inode
mode = -1
if S_ISDIR(mode):
@@ -69,7 +69,7 @@ def walktree(rootpath, callback, **kwargs):
callback(pathname, **kwargs)
else:
# Unknown file type, print a message
- print 'Skipping %s' % pathname
+ print('Skipping %s' % pathname)
#
@@ -84,26 +84,26 @@ except KeyError:
TESTDOCDIR="/tmp"
def TEST_findFiles():
- print "########## find 1"
+ print("########## find 1")
rootpath=TESTDOCDIR
listfiles=findFiles(rootpath)
for filename in listfiles:
- print filename
+ print(filename)
- print "########## find 2"
+ print("########## find 2")
excludes=[os.path.join(TESTDOCDIR,"doc")]
listfiles=findFiles(rootpath,excludes)
for filename in listfiles:
- print filename
+ print(filename)
return True
# This is the test callback function
def visitfile_withargs(file, rootid):
- print 'visiting file %s (rootid=%s)'%(file,str(rootid))
+ print('visiting file %s (rootid=%s)'%(file,str(rootid)))
def visitfile_withoutargs(file):
- print 'visiting file %s'%(file)
+ print('visiting file %s'%(file))
def TEST_walktree():
#walktree(TESTDOCDIR, visitfile_withargs, rootid=2)
@@ -111,6 +111,6 @@ def TEST_walktree():
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("syshelper", "TEST_findFiles")
unittester.run("syshelper", "TEST_walktree")
diff --git a/src/KERNEL_PY/kernel/termcolor.py b/src/KERNEL_PY/kernel/termcolor.py
index b7d99c778..438d98b67 100644
--- a/src/KERNEL_PY/kernel/termcolor.py
+++ b/src/KERNEL_PY/kernel/termcolor.py
@@ -41,9 +41,9 @@
# import sys
# from salome.kernel import termcolor
# if termcolor.canDisplayColor(sys.stdout):
-# print termcolor.makeColoredMessage("Hello world!", termcolor.BLUE)
+# print(termcolor.makeColoredMessage("Hello world!", termcolor.BLUE))
# else:
-# print "Hello world!"
+# print("Hello world!")
# \endcode
# \}
@@ -65,9 +65,9 @@ Example::
import sys
from salome.kernel import termcolor
if termcolor.canDisplayColor(sys.stdout):
- print termcolor.makeColoredMessage("Hello world!", termcolor.BLUE)
+ print(termcolor.makeColoredMessage("Hello world!", termcolor.BLUE))
else:
- print "Hello world!"
+ print("Hello world!")
"""
@@ -225,13 +225,13 @@ def TEST_termcolor():
"""Test function for termcolor module."""
import sys
if not canDisplayColor(sys.stdout):
- print "Standard output does not support colors."
+ print("Standard output does not support colors.")
return
- print makeColoredMessage("This message must appear in blue.", BLUE)
- print makeColoredMessage("This message must appear in red on green " +
- "background.", RED + GREEN_BG)
- print makeColoredMessage("This message must appear in magenta and " +
- "crossed-out.", PURPLE + ['09'])
+ print(makeColoredMessage("This message must appear in blue.", BLUE))
+ print(makeColoredMessage("This message must appear in red on green " +
+ "background.", RED + GREEN_BG))
+ print(makeColoredMessage("This message must appear in magenta and " +
+ "crossed-out.", PURPLE + ['09']))
# Main function only used to test the module
diff --git a/src/KERNEL_PY/kernel/testdata.py b/src/KERNEL_PY/kernel/testdata.py
index 76485786f..4c671abd8 100644
--- a/src/KERNEL_PY/kernel/testdata.py
+++ b/src/KERNEL_PY/kernel/testdata.py
@@ -24,8 +24,8 @@
__author__="gboulant"
__date__ ="$17 avr. 2010 19:44:36$"
-from enumerate import Enumerate
-from datamodeler import DataModeler, TypeString, TypeInteger
+from .enumerate import Enumerate
+from .datamodeler import DataModeler, TypeString, TypeInteger
from salome.kernel import Callable
class TestData(DataModeler):
@@ -79,7 +79,7 @@ class TestData(DataModeler):
# Basic use cases and unit tests
# ==============================================================================
#
-from uiexception import UiException
+from .uiexception import UiException
def TEST_getName():
testdata = TestData()
@@ -96,8 +96,8 @@ def TEST_useBadKey():
testdata.unknown = "unknown"
# This should not arrive here
return False
- except UiException, err:
- print err
+ except UiException as err:
+ print(err)
return True
def TEST_useBadType():
@@ -106,8 +106,8 @@ def TEST_useBadType():
testdata.TYPE = "unknown"
# This should not arrive here
return False
- except UiException, err:
- print err
+ except UiException as err:
+ print(err)
return True
def TEST_useBadRange():
@@ -117,17 +117,17 @@ def TEST_useBadRange():
testdata.TYPE = TestData.TYPES_LIST.SEP
testdata.setType(TestData.TYPES_LIST.SEP)
# This should arrive here
- except UiException, err:
+ except UiException as err:
# And not here
- print err
+ print(err)
return False
try:
testdata.TYPE = 9999 # a type that does not exist in the range
# This should not arrive here
return False
- except UiException, err:
- print err
+ except UiException as err:
+ print(err)
return True
def TEST_serialize():
@@ -136,7 +136,7 @@ def TEST_serialize():
ref_testdata.setName("The first name")
res_testdata = salome.kernel.unserialize(salome.kernel.serialize(ref_testdata))
- print res_testdata.getName()
+ print(res_testdata.getName())
if res_testdata.getName() != ref_testdata.getName():
return False
@@ -144,14 +144,14 @@ def TEST_serialize():
# Is the unserialized data still functional?
try:
res_testdata.setName("An other name")
- print res_testdata.getName()
+ print(res_testdata.getName())
except:
- print e
+ print(e)
return False
return True
if __name__ == "__main__":
- from unittester import run
+ from .unittester import run
run("salome/kernel/testdata","TEST_getName")
run("salome/kernel/testdata","TEST_useBadKey")
run("salome/kernel/testdata","TEST_useBadType")
diff --git a/src/KERNEL_PY/kernel/threadhelper.py b/src/KERNEL_PY/kernel/threadhelper.py
index c71a9a543..b6d6b0689 100644
--- a/src/KERNEL_PY/kernel/threadhelper.py
+++ b/src/KERNEL_PY/kernel/threadhelper.py
@@ -88,12 +88,12 @@ class Runner(threading.Thread):
Ex�cution de la fonction. Impl�mentation de la m�thode run
d�clench�e par l'appel � Thread.start().
"""
- print "##################### threadhelper.run"
+ print("##################### threadhelper.run")
if self._function is None: return
try:
self._return = self._function(*self._argv)
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
self._exception = e
self._stopevent.set()
self.notifyObserver()
@@ -107,15 +107,15 @@ class Runner(threading.Thread):
return
try:
self._observer.processNotification()
- except AttributeError, att:
+ except AttributeError as att:
if str(att) == "processNotification":
- print "L'observateur n'impl�mente pas la m�thode processNotification()"
+ print("L'observateur n'impl�mente pas la m�thode processNotification()")
else:
- print "La fonction processNotification() a lev� une exception:"
- print att
- except Exception, e:
- print "La fonction processNotification() a lev� une exception:"
- print e
+ print("La fonction processNotification() a lev� une exception:")
+ print(att)
+ except Exception as e:
+ print("La fonction processNotification() a lev� une exception:")
+ print(e)
def callback(self):
if self._callbackFunction is None: return
@@ -232,14 +232,14 @@ class PeriodicTimer( threading.Thread ):
import os
testfilename="/tmp/threadhelperTestFile"
def testIfContinue():
- print "On examine la pr�sence du fichier ", testfilename
+ print("On examine la pr�sence du fichier ", testfilename)
if os.path.exists(testfilename):
return STOP
else:
return CONTINUE
def endedAction():
- print "FINI"
+ print("FINI")
def TEST_PeriodicTimer():
periodicTimer=PeriodicTimer(1,0,testIfContinue, endedAction)
@@ -251,43 +251,43 @@ def function_ok(nbsteps=5):
"""
Fonction qui se termine correctement
"""
- print "D�but"
+ print("D�but")
cnt=0
while ( cnt < nbsteps ):
- print "Etape ", cnt
+ print("Etape ", cnt)
time.sleep(0.6)
cnt+=1
- print "Fin"
+ print("Fin")
def function_with_exception():
"""
Fonction qui aboutie � une lev�e d'exception
"""
- print "D�but"
+ print("D�but")
cnt=0
while ( cnt < 5 ):
- print "Etape ", cnt
+ print("Etape ", cnt)
time.sleep(1)
cnt+=1
raise Exception("erreur d'ex�cution de la fonction")
- print "Fin"
+ print("Fin")
def infinite_function():
"""
fonction de dur�e infinie (tant qu'il y a du courant �l�ctrique) pour
le test du timeout.
"""
- print "D�but"
+ print("D�but")
cnt=0
while ( 1 ):
- print "Etape ", cnt
+ print("Etape ", cnt)
time.sleep(1)
cnt+=1
raise Exception("erreur")
- print "Fin"
+ print("Fin")
def runWithRunner(functionToRun):
@@ -295,21 +295,21 @@ def runWithRunner(functionToRun):
Ex�cute la fonction avec le runner. On illustre ici la modalit�
d'utilisation du Runner.
"""
- print "###########"
+ print("###########")
runner = Runner(functionToRun)
runner.start()
while ( not runner.isEnded() ):
- print "La fonction est en cours"
+ print("La fonction est en cours")
time.sleep(0.2)
e = runner.getException()
if e is not None:
- print "La fonction s'est termin�e en erreur"
- print e
+ print("La fonction s'est termin�e en erreur")
+ print(e)
# On peut en fait la relancer
# raise e
else:
- print "La fonction s'est termin�e correctement"
+ print("La fonction s'est termin�e correctement")
def runWithTimeout(functionToRun, timeout=10):
@@ -317,26 +317,26 @@ def runWithTimeout(functionToRun, timeout=10):
Ex�cute la fonction avec le runner. On illustre ici la modalit�
d'utilisation du Runner.
"""
- print "runWithTimeout : DEBUT"
+ print("runWithTimeout : DEBUT")
runner = Runner(functionToRun)
runner.start()
# On se fixe un temps au del� duquel on consid�re que la fonction
# est en erreur => on tue le thread (timeout)
runner.wait(timeout)
- print "Apr�s runner.timeout(timeout)"
+ print("Apr�s runner.timeout(timeout)")
if not runner.isEnded():
runner.kill()
e = runner.getException()
if e is not None:
- print "La fonction s'est termin�e en erreur"
- print e
+ print("La fonction s'est termin�e en erreur")
+ print(e)
# On peut en fait la relancer
# raise e
else:
- print "La fonction s'est termin�e correctement"
+ print("La fonction s'est termin�e correctement")
- print "runWithTimeout : FIN"
+ print("runWithTimeout : FIN")
import sys
sys.exit(0)
@@ -354,7 +354,7 @@ def TEST_Runner():
def myCallbackFunction():
- print "myCallbackFunction: the job is ended"
+ print("myCallbackFunction: the job is ended")
def TEST_runWithCallback():
@@ -366,17 +366,17 @@ def TEST_runWithCallback():
return False
runnerId = runner.getId()
- print "A runner has been started with id="+str(runnerId)
+ print("A runner has been started with id="+str(runnerId))
cpt = 0
while ( not runner.isEnded() ):
- print "Waiting notification from process "+str(runner.getId())+", step n°"+str(cpt)
+ print("Waiting notification from process "+str(runner.getId())+", step n°"+str(cpt))
time.sleep(0.2)
cpt+=1
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
#TEST_PeriodicTimer()
#TEST_Runner()
#TEST_Timeout()
diff --git a/src/KERNEL_PY/kernel/uiexception.py b/src/KERNEL_PY/kernel/uiexception.py
index b777c4567..a9a215d95 100644
--- a/src/KERNEL_PY/kernel/uiexception.py
+++ b/src/KERNEL_PY/kernel/uiexception.py
@@ -26,7 +26,7 @@
__author__="gboulant"
__date__ ="$31 mars 2010 11:59:33$"
-from enumerate import Enumerate
+from .enumerate import Enumerate
## This exception should be used for functionnal error management, at least in the GUI
# part of the application, for example to set user oriented messages at point
@@ -101,21 +101,21 @@ def TEST_uimessage():
try:
somethingGoesWrong()
return False
- except UiException, err:
- print 'ERROR: %s' % str(err)
+ except UiException as err:
+ print('ERROR: %s' % str(err))
if ( str(err) == "Something goes wrong" ):
return True
else:
return False
def TEST_specificException():
- print DevelException("err")
- print AdminException("err")
- print UserException("err")
+ print(DevelException("err"))
+ print(AdminException("err"))
+ print(UserException("err"))
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("uiexception","TEST_uimessage")
unittester.run("uiexception","TEST_specificException")
diff --git a/src/KERNEL_PY/kernel/unittester.py b/src/KERNEL_PY/kernel/unittester.py
index 1a0001b98..9abb4fa4c 100644
--- a/src/KERNEL_PY/kernel/unittester.py
+++ b/src/KERNEL_PY/kernel/unittester.py
@@ -45,12 +45,12 @@ def run(modulePath, functionName):
module=sys.modules[moduleName]
func = getattr(module,functionName)
tabsize = 70-len(moduleName)-len(functionName)
- print "[TEST] %s.%s %s test in progress" % (moduleName, functionName,"."*tabsize)
+ print("[TEST] %s.%s %s test in progress" % (moduleName, functionName,"."*tabsize))
ok = func()
if ( ok ):
- print "[TEST] %s.%s %s OK" % (moduleName, functionName,"."*tabsize)
+ print("[TEST] %s.%s %s OK" % (moduleName, functionName,"."*tabsize))
else:
- print "[TEST] %s.%s %s NOT OK" % (moduleName, functionName,"."*tabsize)
+ print("[TEST] %s.%s %s NOT OK" % (moduleName, functionName,"."*tabsize))
## This function is for debug only. It executes the specified function with the
# specified arguments in a try/except block so as to display the exception in
@@ -64,11 +64,11 @@ def tryfunction(function,*argv):
the case where an exception is raised (useful to debug server side of a CORBA
process).
"""
- print "[TEST] trying the function %s" % function
+ print("[TEST] trying the function %s" % function)
try:
return function(*argv)
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
raise e
diff --git a/src/KERNEL_PY/omnipatch.py b/src/KERNEL_PY/omnipatch.py
index 963b1e3cb..d39c60469 100644
--- a/src/KERNEL_PY/omnipatch.py
+++ b/src/KERNEL_PY/omnipatch.py
@@ -51,10 +51,10 @@ def openModule(mname, fname=None):
shared_imported[mname]=mod
# Salome modification end
- elif sys.modules.has_key(mname):
+ elif mname in sys.modules:
mod = sys.modules[mname]
- if _partialModules.has_key(mname):
+ if mname in _partialModules:
pmod = _partialModules[mname]
mod.__dict__.update(pmod.__dict__)
del _partialModules[mname]
@@ -62,7 +62,7 @@ def openModule(mname, fname=None):
shared_imported[mname]=mod
# Salome modification end
- elif _partialModules.has_key(mname):
+ elif mname in _partialModules:
mod = _partialModules[mname]
# Salome modification start
@@ -98,10 +98,10 @@ def newModule(mname):
for name in mlist:
current = current + name
- if sys.modules.has_key(current):
+ if current in sys.modules:
mod = sys.modules[current]
- elif _partialModules.has_key(current):
+ elif current in _partialModules:
mod = _partialModules[current]
else:
@@ -120,7 +120,7 @@ def updateModule(mname):
# Be sure to use the right module dictionary
import sys
# Salome modification end
- if _partialModules.has_key(mname):
+ if mname in _partialModules:
pmod = _partialModules[mname]
mod = sys.modules[mname]
mod.__dict__.update(pmod.__dict__)
diff --git a/src/KERNEL_PY/salome_ComponentGUI.py b/src/KERNEL_PY/salome_ComponentGUI.py
index 9baeb7d5d..8bb69f4eb 100644
--- a/src/KERNEL_PY/salome_ComponentGUI.py
+++ b/src/KERNEL_PY/salome_ComponentGUI.py
@@ -41,12 +41,10 @@ def getShapeTypeString(aSubId):
def createAndDisplayGO( *args, **kwargs ):
pass
-
#--------------------------------------------------------------------------
def UpdateViewer():
- pass
-
+ pass
#--------------------------------------------------------------------------
def setDisplayMode(objId, mode):
@@ -83,7 +81,7 @@ def setNameMode(objId, mode):
#--------------------------------------------------------------------------
-def Init(studyId):
+def Init():
return
#--------------------------------------------------------------------------
diff --git a/src/KERNEL_PY/salome_iapp.py b/src/KERNEL_PY/salome_iapp.py
index 0946fe371..30ec34566 100755
--- a/src/KERNEL_PY/salome_iapp.py
+++ b/src/KERNEL_PY/salome_iapp.py
@@ -38,14 +38,14 @@ def ImportComponentGUI(ComponentName):
if IN_SALOME_GUI:
libName = "lib" + ComponentName + "_Swig"
command = "from " + libName + " import *"
- exec ( command )
+ exec (command, globals())
constructor = ComponentName + "_Swig()"
command = "gui = " + constructor
- exec ( command )
- return gui
+ exec (command, globals())
+ return gui # @UndefinedVariable
else:
- print "Warning: ImportComponentGUI(",ComponentName,") outside GUI !"
- print "calls to GUI methods may crash..."
+ print("Warning: ImportComponentGUI(",ComponentName,") outside GUI !")
+ print("calls to GUI methods may crash...")
return salome_ComponentGUI
#--------------------------------------------------------------------------
@@ -71,90 +71,85 @@ class SalomeOutsideGUI(object):
Provides a replacement for class SalomeGUI outside GUI process.
Do almost nothing
"""
- global myStudyId, myStudyName
+ global myStudyName
def hasDesktop(self):
"""Indicate if GUI is running"""
return False
- def updateObjBrowser(self, bid):
+ def updateObjBrowser(self):
"""update the GUI object browser"""
- print "SalomeOutsideGUI: no objectBrowser update outside GUI"
+ print("SalomeOutsideGUI: no objectBrowser update outside GUI")
pass
- def getActiveStudyId(self):
- """Get the active study id"""
- print "SalomeOutsideGUI.getActiveStudyId: avoid use outside GUI"
- return myStudyId
-
- def getActiveStudyName(self):
- """Get the active study name"""
- print "SalomeOutsideGUI.getActiveStudyName: avoid use outside GUI"
+ def getStudyName(self):
+ """Get the study name"""
+ print("SalomeOutsideGUI.getStudyName: avoid use outside GUI")
return myStudyName
def SelectedCount(self):
"""Get the number of active selections"""
- print "SalomeOutsideGUI: no selection mechanism available outside GUI"
+ print("SalomeOutsideGUI: no selection mechanism available outside GUI")
return 0
def getSelected(self, i):
"""Get the selection number i """
- print "SalomeOutsideGUI: no selection mechanism available outside GUI"
+ print("SalomeOutsideGUI: no selection mechanism available outside GUI")
return none
def AddIObject(self, Entry):
"""Add an entry"""
- print "SalomeOutsideGUI.AddIOObject: not available outside GUI"
+ print("SalomeOutsideGUI.AddIOObject: not available outside GUI")
pass
def RemoveIObject(self, Entry):
"""Remove an entry"""
- print "SalomeOutsideGUI.REmoveIOObject: not available outside GUI"
+ print("SalomeOutsideGUI.REmoveIOObject: not available outside GUI")
pass
def ClearIObjects(self):
"""Clear entries"""
- print "SalomeOutsideGUI.ClearIOObject: not available outside GUI"
+ print("SalomeOutsideGUI.ClearIOObject: not available outside GUI")
pass
def Display(self, Entry):
"""Display an entry"""
- print "SalomeOutsideGUI.Display: not available outside GUI"
+ print("SalomeOutsideGUI.Display: not available outside GUI")
pass
def DisplayOnly(self, Entry):
"""Display only an entry"""
- print "SalomeOutsideGUI.DisplayOnly: not available outside GUI"
+ print("SalomeOutsideGUI.DisplayOnly: not available outside GUI")
pass
def Erase(self, Entry):
"""Erase en entry"""
- print "SalomeOutsideGUI.Erase: not available outside GUI"
+ print("SalomeOutsideGUI.Erase: not available outside GUI")
pass
def DisplayAll(self):
"""Display all"""
- print "SalomeOutsideGUI.Erase: not available outside GUI"
+ print("SalomeOutsideGUI.Erase: not available outside GUI")
pass
def EraseAll(self):
"""Erase all"""
- print "SalomeOutsideGUI.EraseAll: not available outside GUI"
+ print("SalomeOutsideGUI.EraseAll: not available outside GUI")
pass
def IsInCurrentView(self, Entry):
"""Indicate if an entry is in current view"""
- print "SalomeOutsideGUI.IsIncurrentView: not available outside GUI"
+ print("SalomeOutsideGUI.IsIncurrentView: not available outside GUI")
return False
def getComponentName(self, ComponentUserName ):
"""Get component name from component user name"""
- print "SalomeOutsideGUI.getComponentName: not available outside GUI"
+ print("SalomeOutsideGUI.getComponentName: not available outside GUI")
return ""
def getComponentUserName( self, ComponentName ):
"""Get component user name from component name"""
- print "SalomeOutsideGUI.getComponentUserName: not available outside GUI"
+ print("SalomeOutsideGUI.getComponentUserName: not available outside GUI")
return ""
#--------------------------------------------------------------------------
diff --git a/src/KERNEL_PY/salome_notebook.py b/src/KERNEL_PY/salome_notebook.py
index 12ac01b82..92857da24 100644
--- a/src/KERNEL_PY/salome_notebook.py
+++ b/src/KERNEL_PY/salome_notebook.py
@@ -36,7 +36,7 @@ class PseudoStudyForNoteBook(object):
pass
def GetVariableNames(self):
- return self.kwargs.keys()
+ return list(self.kwargs.keys())
def IsVariable(self, variableName):
return variableName in self.kwargs
@@ -69,24 +69,27 @@ class PseudoStudyForNoteBook(object):
class NoteBook:
- def __init__(self, Study):
- self.myStudy = Study
+ def __init__(self, theIsEnablePublish = True):
+ if theIsEnablePublish:
+ self.myStudy = salome.myStudy
+ else:
+ self.myStudy = PseudoStudyForNoteBook()
def set(self, variableName, variable):
"""
Create (or modify) variable with name "variableName"
and value equal "theValue".
"""
- if type(variable) == float:
+ if isinstance(variable, float):
self.myStudy.SetReal(variableName, variable)
- elif type(variable) == int:
+ elif isinstance(variable, int):
self.myStudy.SetInteger(variableName, variable)
- elif type(variable) == bool:
+ elif isinstance(variable, bool):
self.myStudy.SetBoolean(variableName, variable)
- elif type(variable) == str:
+ elif isinstance(variable, str):
self.myStudy.SetString(variableName, variable)
def get(self, variableName):
@@ -124,7 +127,7 @@ class NoteBook:
pass
try:
aResult = eval(aResult)
- except Exception, e:
+ except Exception as e:
msg = str(e)
msg += "\n"
msg += "A problem occurs while parsing "
@@ -171,9 +174,8 @@ class NoteBook:
pass
def checkThisNoteBook(**kwargs):
- study = PseudoStudyForNoteBook(**kwargs)
- note_book = NoteBook(study)
+ note_book = NoteBook( False )
note_book.check()
return
-notebook = NoteBook(salome.myStudy)
+notebook = NoteBook()
diff --git a/src/KERNEL_PY/salome_pynode.py b/src/KERNEL_PY/salome_pynode.py
index 124bff168..f1b448754 100644
--- a/src/KERNEL_PY/salome_pynode.py
+++ b/src/KERNEL_PY/salome_pynode.py
@@ -28,7 +28,7 @@
exception
"""
import omniORB
-import cPickle
+import pickle
import SALOME
import Engines
@@ -38,17 +38,17 @@ class SmartPyNode(Engines._objref_PyNode):
def execute(self,functionName,*args,**kws):
try:
- args=cPickle.dumps((args,kws),-1)
+ args=pickle.dumps((args,kws),-1)
results=Engines._objref_PyNode.execute(self,functionName,args)
- x=cPickle.loads(results)
+ x=pickle.loads(results)
return x
- except SALOME.SALOME_Exception, e:
+ except SALOME.SALOME_Exception as e:
raise ValueError(e.details.text)
def __getattr__(self,name):
""" a trick to be able to call directly a remote method by its name : no need to use execute"""
if name[0]== '_':
- raise AttributeError, name
+ raise AttributeError(name)
def afunc(*args,**kws):
return self.execute(name,*args,**kws)
return afunc
@@ -60,11 +60,11 @@ class SmartPyScriptNode(Engines._objref_PyScriptNode):
def execute(self,outargsname,*args,**kws):
#the tuple args are ignored
try:
- args=cPickle.dumps(((),kws),-1)
+ args=pickle.dumps(((),kws),-1)
results=Engines._objref_PyScriptNode.execute(self,outargsname,args)
- x=cPickle.loads(results)
+ x=pickle.loads(results)
return x
- except SALOME.SALOME_Exception, e:
+ except SALOME.SALOME_Exception as e:
raise ValueError(e.details.text)
#Register the new proxy for PyNode
diff --git a/src/KERNEL_PY/salome_study.py b/src/KERNEL_PY/salome_study.py
index c08437325..5626aecdf 100755
--- a/src/KERNEL_PY/salome_study.py
+++ b/src/KERNEL_PY/salome_study.py
@@ -31,15 +31,14 @@ import SALOMEDS
import salome_iapp
from launchConfigureParser import verbose
-myStudyManager = None
-myStudyId = None
myStudy = None
myStudyName = None
#--------------------------------------------------------------------------
-def DumpComponent(Study, SO, Builder,offset):
- it = Study.NewChildIterator(SO)
+def DumpComponent(SO, Builder,offset):
+ global myStudy
+ it = myStudy.NewChildIterator(SO)
while it.More():
CSO = it.Value()
a=offset*"--" + ">" + CSO.GetID()
@@ -52,36 +51,26 @@ def DumpComponent(Study, SO, Builder,offset):
find,RefSO = CSO.ReferencedObject()
if find:
a=a+":"+RefSO.GetID()
- print a
- DumpComponent(Study, CSO, Builder,offset+2)
+ print(a)
+ DumpComponent(CSO, Builder,offset+2)
it.Next()
#--------------------------------------------------------------------------
-def DumpStudy(Study):
+def DumpStudy():
"""
Dump a study, given the ior
"""
- itcomp = Study.NewComponentIterator()
- Builder = Study.NewBuilder()
+ global myStudy
+ itcomp = myStudy.NewComponentIterator()
+ Builder = myStudy.NewBuilder()
while itcomp.More():
SC = itcomp.Value()
name = SC.ComponentDataType()
- print "-> ComponentDataType is " + name
- DumpComponent(Study, SC,Builder, 1)
+ print("-> ComponentDataType is " + name)
+ DumpComponent(SC,Builder, 1)
itcomp.Next()
-def DumpStudies():
- """
- Dump all studies in a StudyManager
- """
- global myStudyManager
- for name in myStudyManager.GetOpenStudies():
- s = myStudyManager.GetStudyByName(name)
- print "study:",name, s._get_StudyId()
- DumpStudy(s)
-
-
#--------------------------------------------------------------------------
def IDToObject(id):
@@ -97,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)
@@ -127,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()
@@ -176,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
@@ -197,34 +188,34 @@ def GetTree(theSO):
#--------------------------------------------------------------------------
def CheckCopyPaste(theSO, theInfo ,theComponentPaste):
- global myStudyManager, myStudy
+ 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, " for "+theInfo+" returns false"
+ if not myStudy.CanCopy(theSO):
+ raise RuntimeError(" for "+theInfo+" returns false")
- if not myStudyManager.Copy(theSO):
- raise RuntimeError, " for "+theInfo+" returns false"
+ if not myStudy.Copy(theSO):
+ raise RuntimeError(" for "+theInfo+" returns false")
- if not myStudyManager.CanPaste(theSO):
- raise RuntimeError, " for "+theInfo+" returns false"
+ if not myStudy.CanPaste(theSO):
+ raise RuntimeError(" 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, " for "+theInfo+" returns None object"
+ if myStudy.Paste(aSObj) == None:
+ raise RuntimeError(" for "+theInfo+" returns None object")
aNewTree = GetTree(aRoot)
aLen = len(aTree)
for a in range(0,aLen):
@@ -234,7 +225,7 @@ 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")
#--------------------------------------------------------------------------
@@ -279,97 +270,12 @@ def FindFileInDataDir(filename):
#--------------------------------------------------------------------------
-salome_study_ID = -1
-
-# *args are used here to support backward compatibility
-# previously it was possible to pass theStudyId parameter to this function
-# which is no more supported.
-def getActiveStudy(*args):
- global myStudyManager
- global salome_study_ID
-
- if not myStudyManager:
- print "No active study"
- return None
- pass
-
- if verbose(): print "getActiveStudy"
- if salome_study_ID == -1:
- listOpenStudies = myStudyManager.GetOpenStudies()
- if len(listOpenStudies) == 0:
- return None
- else:
- s = myStudyManager.GetStudyByName(listOpenStudies[0])
- salome_study_ID = s._get_StudyId()
- if verbose(): print"--- Study Id ", salome_study_ID
- return salome_study_ID
-
- #--------------------------------------------------------------------------
-
-def setCurrentStudy(theStudy):
- """
- Change current study : an existing one given by a study object.
-
- :param theStudy: the study CORBA object to set as current study
-
- Obsolete: only one study can be opened at the moment.
- This function works properly if specified theStudy parameter
- corresponds to the currently opened study.
- Kept for backward compatibility only.
- """
- global myStudyId, myStudy, myStudyName
- global salome_study_ID
- myStudy = theStudy
- myStudyId = theStudy._get_StudyId()
- myStudyName = theStudy._get_Name()
- return myStudyId, myStudy, myStudyName
-
- #--------------------------------------------------------------------------
-
-# *args are used here to support backward compatibility
-# previously it was possible to pass theStudyId parameter to this function
-# which is no more supported.
-def setCurrentStudyId(*args):
- """
- Change current study : an existing or new one.
-
- This function connects to the single opened study if there is any; otherwise
- new empty study is created.
-
- Obsolete: only one study can be opened at the moment.
- Kept for backward compatibility only.
- """
- global myStudyManager, myStudyId, myStudy, myStudyName
- global salome_study_ID
- salome_study_ID = -1
- myStudyId = getActiveStudy()
- if not myStudyId:
- myStudyId = createNewStudy()
- if verbose(): print "myStudyId",myStudyId
- myStudy = myStudyManager.GetStudyByID(myStudyId)
- myStudyName = myStudy._get_Name()
- return myStudyId, myStudy, myStudyName
-
- #--------------------------------------------------------------------------
-
-def createNewStudy():
- global myStudyManager
- print "createNewStudy"
- aStudyName = "extStudy"
- theStudy = myStudyManager.NewStudy(aStudyName)
- theStudyId = theStudy._get_StudyId()
- print aStudyName, theStudyId
- return theStudyId
-
- #--------------------------------------------------------------------------
-
def openStudy(theStudyPath):
- global myStudyManager
- print "openStudy"
- theStudy = myStudyManager.Open(theStudyPath)
- theStudyId = theStudy._get_StudyId()
- print theStudyPath, theStudyId
- return theStudyId
+ print("openStudy")
+ global myStudy, myStudyName
+ myStudy.Open(theStudyPath)
+ myStudyName = myStudy._get_Name()
+ print(theStudyPath, myStudy._get_Name())
#--------------------------------------------------------------------------
@@ -381,40 +287,26 @@ def salome_study_init(theStudyPath=None):
create new empty study if there is active study
(str) : open study with the given file name
"""
- global myStudyManager, myStudyId, myStudy, myStudyName
+ global myStudy, myStudyName
global orb, lcc, naming_service, cm
- if verbose(): print "theStudyPath:", theStudyPath
- if not myStudyManager:
+ if verbose(): print("theStudyPath:", theStudyPath)
+ if not myStudy:
orb, lcc, naming_service, cm = salome_kernel.salome_kernel_init()
- # get Study Manager reference
- if verbose(): print "looking for studyManager ..."
- obj = naming_service.Resolve('myStudyManager')
- myStudyManager = obj._narrow(SALOMEDS.StudyManager)
- if verbose(): print "studyManager found"
+ # 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
- # get active study Id, ref and name
- myStudy = None
- myStudyId = getActiveStudy()
- if myStudyId == None :
- import types
- if theStudyPath and type(theStudyPath) == types.StringType:
- myStudyId = openStudy(theStudyPath)
- else:
- myStudyId = createNewStudy()
- if verbose(): print "myStudyId", myStudyId
-
- if myStudy == None:
- myStudy = myStudyManager.GetStudyByID(myStudyId)
- myStudyName = myStudy._get_Name()
+ import types
+ if theStudyPath and isinstance(theStudyPath, (str, bytes)):
+ if isinstance(theStudyPath, bytes):
+ theStudyPath = str(theStudyPath, 'UTF8')
+ openStudy(theStudyPath)
- return myStudyManager, myStudyId, myStudy, myStudyName
+ myStudyName = myStudy._get_Name()
-def salome_study_close():
- global salome_study_ID
- global myStudyId, myStudy, myStudyName
- salome_study_ID = -1
- myStudyId, myStudy, myStudyName = None, None, None
- pass
+ return myStudy, myStudyName
diff --git a/src/KERNEL_PY/salome_test.py b/src/KERNEL_PY/salome_test.py
index 76dceacd4..4c4c05110 100755
--- a/src/KERNEL_PY/salome_test.py
+++ b/src/KERNEL_PY/salome_test.py
@@ -21,10 +21,10 @@
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-print
-print "Perform quick test of the application by loading of the GEOM, SMESH, MED, PARAVIS"
-print "components and doing some operation within the components."
-print
+print()
+print("Perform quick test of the application by loading of the GEOM, SMESH, MED, PARAVIS")
+print("components and doing some operation within the components.")
+print()
import salome
import SALOME
@@ -35,84 +35,85 @@ import SALOME_ModuleCatalog
step = 1
-print "======================================================================"
-print " %d. Initialize study " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print(" %d. Initialize study " % step); step+=1
+print("======================================================================")
# initialize study
salome.salome_init()
# get study builder
builder = salome.myStudy.NewBuilder()
-print "OK"
+print("OK")
-print
+print()
-print "======================================================================"
-print " %d. Retrieve module catalog " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print(" %d. Retrieve module catalog " % step); step+=1
+print("======================================================================")
obj = salome.naming_service.Resolve('Kernel/ModulCatalog')
catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
if not catalog:
- raise RuntimeError, "Can't access module catalog"
-print "OK"
-print
+ raise RuntimeError("Can't access module catalog")
+print("OK")
-print "======================================================================"
-print " %d. Check modules availability in the module catalog " % step; step+=1
-print "======================================================================"
+print()
+
+print("======================================================================")
+print(" %d. Check modules availability in the module catalog " % step); step+=1
+print("======================================================================")
for module in [ "GEOM", "SMESH", "MEDFactory", "PVSERVER"]:
- print
- print "--- Check %s ..." % module
+ print()
+ print("--- Check %s ..." % module)
comp = catalog.GetComponent(module)
if not comp:
- raise RuntimeError, "Component %s is not found in Module Catalog." % module
- print "OK"
+ raise RuntimeError("Component %s is not found in Module Catalog." % module)
+ print("OK")
pass
-print
+print()
-print "======================================================================"
-print " %d. Test Data Server " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print(" %d. Test Data Server " % step); step+=1
+print("======================================================================")
-print
-print "--- Create new component ..."
+print()
+print("--- Create new component ...")
comp = builder.NewComponent("TEST")
if not comp:
- raise RuntimeError, "Can't create new component"
-print "OK"
+ raise RuntimeError("Can't create new component")
+print("OK")
-print
-print "--- Create AttributeName ..."
+print()
+print("--- Create AttributeName ...")
A = builder.FindOrCreateAttribute(comp, "AttributeName")
if not A:
- raise RuntimeError, "Can't create AttributeName attribute"
+ raise RuntimeError("Can't create AttributeName attribute")
A.SetValue("TEST")
if A.Value() != "TEST":
- raise RuntimeError, "Error : wrong value of AttributeName"
-print "OK"
+ raise RuntimeError("Error : wrong value of AttributeName")
+print("OK")
-print
-print "--- Create AttributeReal ..."
+print()
+print("--- Create AttributeReal ...")
A = builder.FindOrCreateAttribute(comp, "AttributeReal")
if not A:
- raise RuntimeError, "Can't create AttributeReal attribute"
+ raise RuntimeError("Can't create AttributeReal attribute")
A.SetValue(0.0001)
if A.Value() != 0.0001:
- raise RuntimeError, "Error : wrong value of AttributeReal"
-print "OK"
+ raise RuntimeError("Error : wrong value of AttributeReal")
+print("OK")
-print
+print()
-print "======================================================================"
-print " %d. Test Geometry " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print(" %d. Test Geometry " % step); step+=1
+print("======================================================================")
from salome.geom import geomBuilder
-geompy = geomBuilder.New(salome.myStudy)
+geompy = geomBuilder.New()
ShapeTypeCompSolid = 1
ShapeTypeSolid = 2
@@ -122,54 +123,54 @@ ShapeTypeWire = 5
ShapeTypeEdge = 6
ShapeTypeVertex = 7
-print
-print "--- Create a box ..."
+print()
+print("--- Create a box ...")
box = geompy.MakeBox(0., 0., 0., 100., 200., 300.)
idbox = geompy.addToStudy(box, "box")
box_obj = salome.myStudy.FindObjectByPath("/Geometry/box")
if not box_obj:
- raise RuntimeError, "Error : wrong value of AttributeReal"
-print "OK"
+ raise RuntimeError("Error : wrong value of AttributeReal")
+print("OK")
# ---- add shell from box in study
-print
-print "--- Extract shell ..."
+print()
+print("--- Extract shell ...")
subShellList = geompy.SubShapeAll(box, ShapeTypeShell)
shell = subShellList[0]
name = geompy.SubShapeName(shell, box)
idshell = geompy.addToStudyInFather(box, shell, name)
-print name
-print "OK"
+print(name)
+print("OK")
# ---- add first face of box in study
-print
-print "--- Extract face ..."
+print()
+print("--- Extract face ...")
subShapeList = geompy.SubShapeAll(box, ShapeTypeFace)
face = subShapeList[0]
name = geompy.SubShapeName(face, box)
idface = geompy.addToStudyInFather(box, face, name)
-print name
-print "OK"
+print(name)
+print("OK")
# ---- add first edge of face in study
-print
-print "--- Extract edge ..."
+print()
+print("--- Extract edge ...")
edgeList = geompy.SubShapeAll(face, ShapeTypeEdge)
edge = edgeList[0];
name = geompy.SubShapeName(edge, face)
idedge = geompy.addToStudyInFather(face, edge, name)
-print name
-print "OK"
+print(name)
+print("OK")
# ---- update object browser
if salome.hasDesktop():
- salome.sg.updateObjBrowser(True);
+ salome.sg.updateObjBrowser();
-print
+print()
-print "======================================================================"
-print " %d. Test Mesh " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print(" %d. Test Mesh " % step); step+=1
+print("======================================================================")
from salome.StdMeshers import StdMeshersBuilder
import SMESH
@@ -178,94 +179,94 @@ from salome.smesh import smeshBuilder
smesh = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH")
if salome.hasDesktop():
smeshgui = salome.ImportComponentGUI("SMESH")
- smeshgui.Init(salome.myStudyId);
+ smeshgui.Init();
else:
- smesh = smeshBuilder.New(salome.myStudy)
+ smesh = smeshBuilder.New()
# ---- create hypotheses
stdMeshersEngine = "StdMeshersEngine"
-print
-print "--- Create hypotheses ..."
+print()
+print("--- Create hypotheses ...")
-print
-print "------ LocalLength ..."
+print()
+print("------ LocalLength ...")
hypLen1 = smesh.CreateHypothesis( "LocalLength", stdMeshersEngine )
hypLen1.SetLength(100)
-print hypLen1.GetName()
-print hypLen1.GetId()
-print hypLen1.GetLength()
+print(hypLen1.GetName())
+print(hypLen1.GetId())
+print(hypLen1.GetLength())
if salome.hasDesktop():
smeshgui.SetName(salome.ObjectToID(hypLen1), "Local_Length_100")
-print "OK"
+print("OK")
-print
-print "------ NumberOfSegments ..."
+print()
+print("------ NumberOfSegments ...")
hypNbSeg1= smesh.CreateHypothesis( "NumberOfSegments", stdMeshersEngine )
hypNbSeg1.SetNumberOfSegments(7)
-print hypNbSeg1.GetName()
-print hypNbSeg1.GetId()
-print hypNbSeg1.GetNumberOfSegments()
+print(hypNbSeg1.GetName())
+print(hypNbSeg1.GetId())
+print(hypNbSeg1.GetNumberOfSegments())
if salome.hasDesktop():
smeshgui.SetName(salome.ObjectToID(hypNbSeg1), "NumberOfSegments_7")
-print "OK"
+print("OK")
-print
-print "------ MaxElementArea [1] ..."
+print()
+print("------ MaxElementArea [1] ...")
hypArea1 = smesh.CreateHypothesis( "MaxElementArea", stdMeshersEngine )
hypArea1.SetMaxElementArea(2500)
-print hypArea1.GetName()
-print hypArea1.GetId()
-print hypArea1.GetMaxElementArea()
+print(hypArea1.GetName())
+print(hypArea1.GetId())
+print(hypArea1.GetMaxElementArea())
if salome.hasDesktop():
smeshgui.SetName(salome.ObjectToID(hypArea1), "MaxElementArea_2500")
-print "OK"
+print("OK")
-print
-print "------ MaxElementArea [2] ..."
+print()
+print("------ MaxElementArea [2] ...")
hypArea2 = smesh.CreateHypothesis( "MaxElementArea", stdMeshersEngine )
hypArea2.SetMaxElementArea(500)
-print hypArea2.GetName()
-print hypArea2.GetId()
-print hypArea2.GetMaxElementArea()
+print(hypArea2.GetName())
+print(hypArea2.GetId())
+print(hypArea2.GetMaxElementArea())
if salome.hasDesktop():
smeshgui.SetName(salome.ObjectToID(hypArea2), "MaxElementArea_500")
-print "OK"
+print("OK")
# ---- create algorithms
-print
-print "--- Create algorithms ..."
+print()
+print("--- Create algorithms ...")
-print
-print "------ Regular_1D ..."
+print()
+print("------ Regular_1D ...")
algoReg = smesh.CreateHypothesis( "Regular_1D", stdMeshersEngine )
listHyp = algoReg.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
-print algoReg.GetName()
-print algoReg.GetId()
+ print(hyp)
+print(algoReg.GetName())
+print(algoReg.GetId())
if salome.hasDesktop():
smeshgui.SetName(salome.ObjectToID(algoReg), "Regular_1D" )
-print "OK"
+print("OK")
-print
-print "------ MEFISTO_2D ..."
+print()
+print("------ MEFISTO_2D ...")
algoMef = smesh.CreateHypothesis( "MEFISTO_2D", stdMeshersEngine )
listHyp=algoMef.GetCompatibleHypothesis()
for hyp in listHyp:
- print hyp
-print algoMef.GetName()
-print algoMef.GetId()
+ print(hyp)
+print(algoMef.GetName())
+print(algoMef.GetId())
if salome.hasDesktop():
smeshgui.SetName(salome.ObjectToID(algoMef), "MEFISTO_2D" )
-print "OK"
+print("OK")
# ---- create mesh on the box, apply hypotheses / algorithms
-print
-print "--- Create mesh on the box ..."
+print()
+print("--- Create mesh on the box ...")
mesh = smesh.CreateMesh(box)
if salome.hasDesktop():
smeshgui.SetName( salome.ObjectToID(mesh), "MeshBox" );
@@ -273,40 +274,40 @@ ret = mesh.AddHypothesis(box, algoReg)
ret = mesh.AddHypothesis(box, algoMef)
ret = mesh.AddHypothesis(box, hypNbSeg1)
ret = mesh.AddHypothesis(box, hypArea1)
-print "OK"
+print("OK")
# ---- create submesh on the edge, add hypothesis
-print
-print "--- Add 1D sub-mesh on the edge ..."
+print()
+print("--- Add 1D sub-mesh on the edge ...")
submesh = mesh.GetSubMesh(edge, "SubMeshEdge")
ret = mesh.AddHypothesis(edge, algoReg)
ret = mesh.AddHypothesis(edge, hypLen1)
-print "OK"
+print("OK")
# ---- create submesh on the edge, add hypothesis
-print
-print "--- Add 2D sub-mesh on the face ..."
+print()
+print("--- Add 2D sub-mesh on the face ...")
submesh = mesh.GetSubMesh(face, "SubMeshFace")
ret = mesh.AddHypothesis(face, hypArea2)
-print "OK"
+print("OK")
# ---- compute mesh
-print
-print "--- Compute mesh ..."
+print()
+print("--- Compute mesh ...")
smesh.Compute(mesh, box)
-print "OK"
+print("OK")
# ---- update object browser
if salome.hasDesktop():
- salome.sg.updateObjBrowser(True);
+ salome.sg.updateObjBrowser();
-print
+print()
-print "======================================================================"
-print " %d. Test Med " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print(" %d. Test Med " % step); step+=1
+print("======================================================================")
import medcalc
#from medcalc import properties
@@ -315,7 +316,7 @@ from medcalc.fieldproxy import FieldProxy
medcalc.medconsole.setConsoleGlobals(globals())
try:
med_root=os.environ["MED_ROOT_DIR"]
-except KeyError, e:
+except KeyError as e:
raise RuntimeError("MED_ROOT_DIR should be defined to load the test data")
filepath = os.path.join(med_root,"share","salome","resources","med","medcalc_testfiles","smallmesh_varfield.med")
@@ -323,71 +324,71 @@ medcalc.medio.LoadDataSource(filepath)
fieldHandlerList = medcalc.medevents.dataManager.getFieldHandlerList()
fieldHandler0 = fieldHandlerList[0]
-print "---Field Handler 0:\n%s" % fieldHandler0
+print("---Field Handler 0:\n%s" % fieldHandler0)
fieldHandler1 = fieldHandlerList[1]
-print "---Field Handler 1:\n%s" % fieldHandler1
+print("---Field Handler 1:\n%s" % fieldHandler1)
-print "--- The addition of two fields can be done using field handler directly."
+print("--- The addition of two fields can be done using field handler directly.")
addFieldHandler = medcalc.fieldproxy.calculator.add(fieldHandler0,fieldHandler1)
-print "--- Result handler:\n%s" % addFieldHandler
+print("--- Result handler:\n%s" % addFieldHandler)
-print "--- Or with a field proxy that easy the writing of operations."
+print("--- Or with a field proxy that easy the writing of operations.")
fieldProxy0 = FieldProxy(fieldHandler0)
fieldProxy1 = FieldProxy(fieldHandler1)
resHandler = fieldProxy0 + fieldProxy1
if resHandler is None:
- print "Error: result handler is None!"
+ print("Error: result handler is None!")
else:
- print "--- Result handler:\n%s" % resHandler
- print "OK"
+ print("--- Result handler:\n%s" % resHandler)
+ print("OK")
-print
+print()
-print "======================================================================"
-print " %d. Test Paravis " % step; step+=1
-print "======================================================================"
+print("======================================================================")
+print(" %d. Test Paravis " % step); step+=1
+print("======================================================================")
if salome.hasDesktop(): # in gui mode
- print "**** Importing pvserver... It can take some time."
+ print("**** Importing pvserver... It can take some time.")
import pvserver
import pvsimple
#====================Stage1: Importing MED file====================
- print "**** Stage1: Importing MED file"
+ print("**** Stage1: Importing MED file")
- print 'Import "ResOK_0000.med"...............',
+ print('Import "ResOK_0000.med"...............', end=' ')
medFileName = "ResOK_0000.med"
medFile = os.path.join(os.getenv('DATA_DIR'), 'MedFiles', medFileName)
pvsimple.MEDReader( FileName=medFile )
med_reader = pvsimple.GetActiveSource()
if med_reader is None:
- print "FAILED"
+ print("FAILED")
else:
- print "OK"
+ print("OK")
#====================Stage2: Displaying presentation===============
- print "**** Stage2: Displaying presentation"
+ print("**** Stage2: Displaying presentation")
- print 'Get view...................',
+ print('Get view...................', end=' ')
view = pvsimple.GetRenderView()
if view is None:
- print "FAILED"
+ print("FAILED")
else:
- print "OK"
+ print ("OK")
- print "Creating presentation.......",
+ print("Creating presentation.......",end='')
prs = pvsimple.GetRepresentation(med_reader)
if prs is None:
- print "FAILED"
+ print("FAILED")
else:
- rep_list = view.Representations
- for rep in rep_list:
+ rep_list = view.Representations
+ for rep in rep_list:
if hasattr(rep, 'Visibility'):
rep.Visibility = (rep == prs)
pvsimple.Render(view=view)
@@ -396,16 +397,16 @@ if salome.hasDesktop(): # in gui mode
prs.SetRepresentationType('Surface')
view.ResetCamera()
- print "OK"
+ print ("OK")
else: # not in gui mode, Paravis can not be tested
- print
- print "PARAVIS module requires SALOME to be running in GUI mode."
- print
- print "Skipping test for PARAVIS..."
+ print()
+ print("PARAVIS module requires SALOME to be running in GUI mode.")
+ print()
+ print("Skipping test for PARAVIS...")
pass
# ---- update object browser
if salome.hasDesktop():
- salome.sg.updateObjBrowser(True);
+ salome.sg.updateObjBrowser();
diff --git a/src/KERNEL_PY/salome_version.py b/src/KERNEL_PY/salome_version.py
index a17424a15..1642ed9a7 100644
--- a/src/KERNEL_PY/salome_version.py
+++ b/src/KERNEL_PY/salome_version.py
@@ -49,7 +49,7 @@ def getVersion( mod = "KERNEL", full = False ):
global _salome_versions
mod = mod.upper()
dev_flag = { True : "dev", False : "" }
- if not _salome_versions.has_key( mod ):
+ if mod not in _salome_versions:
_salome_versions[ mod ] = [ None, "" ]
import os
root_dir = os.getenv( "%s_ROOT_DIR" % mod )
diff --git a/src/KernelHelpers/KernelHelpersUseCases.cxx b/src/KernelHelpers/KernelHelpersUseCases.cxx
index 7feaf8a2d..02341d11e 100644
--- a/src/KernelHelpers/KernelHelpersUseCases.cxx
+++ b/src/KernelHelpers/KernelHelpersUseCases.cxx
@@ -60,8 +60,8 @@ bool TEST_getLifeCycleCORBA() {
return true;
}
-bool TEST_getStudyManager() {
- SALOMEDS::Study_ptr myTestStudy = KERNEL::getStudyManager()->NewStudy("kerneltest");
+bool TEST_getStudy() {
+ SALOMEDS::Study_ptr myTestStudy = KERNEL::getStudyServant();
if ( CORBA::is_nil(myTestStudy) ) {
return false;
}
@@ -70,9 +70,8 @@ bool TEST_getStudyManager() {
myTestStudy->SetString("material","wood");
myTestStudy->SetReal("volume",3.23);
- // The study is characterized by an ID
- int myTestStudyId = myTestStudy->StudyId();
- LOG("TestComponentImpl::testkernel: study id = "<Resolve("/myStudyManager");
- aStudyManager = SALOMEDS::StudyManager::_narrow(anObject);
+ CORBA::Object_ptr anObject = aNamingService->Resolve("/Study");
+ aStudy = SALOMEDS::Study::_narrow(anObject);
}
- return aStudyManager;
+ return aStudy;
}
/**
@@ -117,27 +116,6 @@ namespace KERNEL {
return resourcesManager;
}
- /**
- * This returns the study with the specified id if it's defined in
- * the SALOME study manager. Returns null otherwise.
- * Please not that it is just a shortcut, and you may prefer use
- * directly the study manager:
- * KERNEL::getStudyManager()->GetStudyByID(aStudyId)
- */
- SALOMEDS::Study_ptr getStudyById(int aStudyId) {
- if ( aStudyId < 0 ) {
- INFOS("ERR: trying to get a study with ID<0");
- return SALOMEDS::Study::_nil();
- }
- return getStudyManager()->GetStudyByID(aStudyId);
- }
-
- int getStudyId(SALOMEDS::Study_ptr study) {
- if( CORBA::is_nil(study) ) return -1;
- return study->StudyId();
- }
-
-
/**
* This function retrieve the CORBA object reference from the study
* object wrapping it.
diff --git a/src/KernelHelpers/SALOME_KernelServices.hxx b/src/KernelHelpers/SALOME_KernelServices.hxx
index 5c0f39edc..4353d44f1 100644
--- a/src/KernelHelpers/SALOME_KernelServices.hxx
+++ b/src/KernelHelpers/SALOME_KernelServices.hxx
@@ -41,7 +41,7 @@ namespace KERNEL {
KERNELHELPERS_EXPORT SALOME_NamingService * getNamingService();
KERNELHELPERS_EXPORT SALOME_LifeCycleCORBA * getLifeCycleCORBA();
KERNELHELPERS_EXPORT SALOME::Session_ptr getSalomeSession();
- KERNELHELPERS_EXPORT SALOMEDS::StudyManager_ptr getStudyManager();
+ KERNELHELPERS_EXPORT SALOMEDS::Study_ptr getStudyServant();
KERNELHELPERS_EXPORT Engines::SalomeLauncher_ptr getSalomeLauncher();
KERNELHELPERS_EXPORT Engines::ResourcesManager_ptr getResourcesManager();
@@ -49,8 +49,6 @@ namespace KERNEL {
// SALOME KERNEL services to deal with a SALOME study, SObject and
// SComponent.
//
- KERNELHELPERS_EXPORT SALOMEDS::Study_ptr getStudyById(int aStudyId);
- KERNELHELPERS_EXPORT int getStudyId(SALOMEDS::Study_ptr study);
KERNELHELPERS_EXPORT CORBA::Object_ptr IORToObject(char * IOR);
KERNELHELPERS_EXPORT CORBA::Object_ptr SObjectToObject(SALOMEDS::SObject_ptr);
diff --git a/src/KernelHelpers/SALOME_StudyEditor.cxx b/src/KernelHelpers/SALOME_StudyEditor.cxx
index 6eabba0e0..16391639c 100644
--- a/src/KernelHelpers/SALOME_StudyEditor.cxx
+++ b/src/KernelHelpers/SALOME_StudyEditor.cxx
@@ -23,27 +23,7 @@
/** Canonic constructor. The object can't be used without a setStudy() */
SALOME_StudyEditor::SALOME_StudyEditor() {
-}
-
-void SALOME_StudyEditor::setStudy(SALOMEDS::Study_ptr study) {
- _study = study;
- _sbuilder = _study->NewBuilder();
-}
-
-void SALOME_StudyEditor::setStudyById(int studyId) {
- this->setStudy(KERNEL::getStudyManager()->GetStudyByID(studyId));
-}
-
-int SALOME_StudyEditor::getStudyId() {
- if ( _study->_is_nil() ) return UNDEFINED;
- return _study->StudyId();
-}
-
-SALOME_StudyEditor::SALOME_StudyEditor(int studyId) {
- this->setStudyById(studyId);
-}
-SALOME_StudyEditor::SALOME_StudyEditor(SALOMEDS::Study_ptr study) {
- this->setStudy(study);
+ _sbuilder = KERNEL::getStudyServant()->NewBuilder();
}
SALOMEDS::SObject_ptr SALOME_StudyEditor::newObject(SALOMEDS::SObject_ptr parent) {
@@ -51,7 +31,7 @@ SALOMEDS::SObject_ptr SALOME_StudyEditor::newObject(SALOMEDS::SObject_ptr parent
}
SALOMEDS::SObject_ptr SALOME_StudyEditor::findObject(const char * entry) {
- SALOMEDS::SObject_var sobject = _study->FindObjectID(entry);
+ SALOMEDS::SObject_var sobject = KERNEL::getStudyServant()->FindObjectID(entry);
return sobject._retn();
}
@@ -78,7 +58,7 @@ bool SALOME_StudyEditor::bindEngine(SALOMEDS::SComponent_var studyRoot,
}
SALOMEDS::SComponent_ptr SALOME_StudyEditor::findRoot(const char * moduleName) {
- return _study->FindComponent(moduleName);
+ return KERNEL::getStudyServant()->FindComponent(moduleName);
}
void SALOME_StudyEditor::setName(SALOMEDS::SObject_var sobject, const char * value) {
diff --git a/src/KernelHelpers/SALOME_StudyEditor.hxx b/src/KernelHelpers/SALOME_StudyEditor.hxx
index 23329461d..334f953b9 100644
--- a/src/KernelHelpers/SALOME_StudyEditor.hxx
+++ b/src/KernelHelpers/SALOME_StudyEditor.hxx
@@ -32,8 +32,7 @@
class KERNELHELPERS_EXPORT SALOME_StudyEditor {
public:
- SALOME_StudyEditor(int studyId);
- SALOME_StudyEditor(SALOMEDS::Study_ptr study);
+ SALOME_StudyEditor();
typedef std::vector SObjectList;
@@ -55,14 +54,6 @@ public:
static const int UNDEFINED = -1;
-protected:
- SALOME_StudyEditor();
- void setStudy(SALOMEDS::Study_ptr study);
- void setStudyById(int studyId);
- int getStudyId();
-
- SALOMEDS::Study_var _study;
-
private:
SALOMEDS::StudyBuilder_var _sbuilder;
};
diff --git a/src/KernelHelpers/Test/KernelHelpersUnitTests.cxx b/src/KernelHelpers/Test/KernelHelpersUnitTests.cxx
index a3aa4cbb7..7aa3bc436 100644
--- a/src/KernelHelpers/Test/KernelHelpersUnitTests.cxx
+++ b/src/KernelHelpers/Test/KernelHelpersUnitTests.cxx
@@ -77,30 +77,16 @@ void KernelHelpersUnitTests::TEST_getLifeCycleCORBA() {
CPPUNIT_ASSERT( strcmp(coucou_res, coucou_ref) == 0 );
}
-void KernelHelpersUnitTests::TEST_getStudyManager() {
- SALOMEDS::StudyManager_var studyManager = KERNEL::getStudyManager();
-
- #ifndef ALLOW_MULTI_STUDIES
- SALOMEDS::ListOfOpenStudies_var _list_open_studies = studyManager->GetOpenStudies();
- for (unsigned int ind = 0; ind < _list_open_studies->length();ind++)
- {
- LOG("Close study : " << _list_open_studies[ind]);
- SALOMEDS::Study_var study = studyManager->GetStudyByName(_list_open_studies[0]);
- if(study)
- studyManager->Close(study);
- }
- #endif
-
- SALOMEDS::Study_ptr myTestStudy = studyManager->NewStudy("kerneltest");
+void KernelHelpersUnitTests::TEST_getStudy() {
+ SALOMEDS::Study_ptr myTestStudy = KERNEL::getStudyServant();
CPPUNIT_ASSERT(!CORBA::is_nil(myTestStudy));
// One can use the study to store some general properties
myTestStudy->SetString("material","wood");
myTestStudy->SetReal("volume",3.23);
- // The study is characterized by an ID
- int myTestStudyId = myTestStudy->StudyId();
- LOG("TestComponentImpl::testkernel: study id = "<
-
@@ -316,7 +315,7 @@ f.close()
resManager= salome.lcc.getResourcesManager()
for resource in self.ressources:
- print "Testing yacs job on ", resource
+ print("Testing yacs job on ", resource)
job_params.result_directory = local_result_dir + resource
job_params.job_name = "YacsJob_" + resource
job_params.resource_required.name = resource
@@ -332,14 +331,14 @@ f.close()
jobState = launcher.getJobState(job_id)
yacs_dump_success = False
- print "Job %d state: %s" % (job_id,jobState)
+ print("Job %d state: %s" % (job_id,jobState))
while jobState != "FINISHED" and jobState != "FAILED" :
time.sleep(5)
jobState = launcher.getJobState(job_id)
# yacs_dump_success = launcher.getJobWorkFile(job_id, "dumpState_mySchema.xml",
yacs_dump_success = launcher.getJobDumpState(job_id,
job_params.result_directory)
- print "Job %d state: %s - dump: %s" % (job_id,jobState, yacs_dump_success)
+ print("Job %d state: %s - dump: %s" % (job_id,jobState, yacs_dump_success))
pass
self.assertEqual(jobState, "FINISHED")
@@ -380,7 +379,6 @@ f.close()
# job script
script_text = """
-
@@ -428,7 +426,7 @@ f.close()
resManager= salome.lcc.getResourcesManager()
for resource in self.ressources:
- print "Testing yacs job with options on ", resource
+ print("Testing yacs job with options on ", resource)
job_params.result_directory = local_result_dir + resource
job_params.job_name = "YacsJobOpt_" + resource
job_params.resource_required.name = resource
@@ -444,11 +442,11 @@ f.close()
jobState = launcher.getJobState(job_id)
yacs_dump_success = False
- print "Job %d state: %s" % (job_id,jobState)
+ print("Job %d state: %s" % (job_id,jobState))
while jobState != "FINISHED" and jobState != "FAILED" :
time.sleep(5)
jobState = launcher.getJobState(job_id)
- print "Job %d state: %s " % (job_id,jobState)
+ print("Job %d state: %s " % (job_id,jobState))
pass
self.assertEqual(jobState, "FINISHED")
diff --git a/src/LifeCycleCORBA/SALOME_LifeCycleCORBA.cxx b/src/LifeCycleCORBA/SALOME_LifeCycleCORBA.cxx
index cf181f04e..0bbed6c92 100644
--- a/src/LifeCycleCORBA/SALOME_LifeCycleCORBA.cxx
+++ b/src/LifeCycleCORBA/SALOME_LifeCycleCORBA.cxx
@@ -132,14 +132,12 @@ SALOME_LifeCycleCORBA::~SALOME_LifeCycleCORBA()
*
* \param params container parameters like type or name...
* \param componentName the name of component class
- * \param studyId default = 0 : multistudy instance
* \return a CORBA reference of the component instance, or _nil if not found
*/
//=============================================================================
Engines::EngineComponent_ptr
SALOME_LifeCycleCORBA::FindComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId)
+ const char *componentName)
{
if (! isKnownComponentClass(componentName))
return Engines::EngineComponent::_nil();
@@ -160,7 +158,6 @@ SALOME_LifeCycleCORBA::FindComponent(const Engines::ContainerParameters& params,
Engines::EngineComponent_var compo = _FindComponent(new_params,
componentName,
- studyId,
listOfResources);
return compo._retn();
@@ -171,15 +168,13 @@ SALOME_LifeCycleCORBA::FindComponent(const Engines::ContainerParameters& params,
*
* \param params container parameters like type or name...
* \param componentName the name of component class
- * \param studyId default = 0 : multistudy instance
* \return a CORBA reference of the component instance, or _nil if problem
*/
//=============================================================================
Engines::EngineComponent_ptr
SALOME_LifeCycleCORBA::LoadComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId)
+ const char *componentName)
{
// --- Check if Component Name is known in ModuleCatalog
@@ -203,8 +198,7 @@ SALOME_LifeCycleCORBA::LoadComponent(const Engines::ContainerParameters& params,
new_params.resource_params.resList = listOfResources;
Engines::EngineComponent_var compo = _LoadComponent(new_params,
- componentName,
- studyId);
+ componentName);
return compo._retn();
}
@@ -215,7 +209,6 @@ SALOME_LifeCycleCORBA::LoadComponent(const Engines::ContainerParameters& params,
*
* \param params container parameters like type or name...
* \param componentName the name of component class
- * \param studyId default = 0 : multistudy instance
* \return a CORBA reference of the component instance, or _nil if problem
*/
//=============================================================================
@@ -223,8 +216,7 @@ SALOME_LifeCycleCORBA::LoadComponent(const Engines::ContainerParameters& params,
Engines::EngineComponent_ptr
SALOME_LifeCycleCORBA::
FindOrLoad_Component(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId)
+ const char *componentName)
{
// --- Check if Component Name is known in ModuleCatalog
@@ -247,16 +239,14 @@ FindOrLoad_Component(const Engines::ContainerParameters& params,
}
Engines::EngineComponent_var compo = _FindComponent(new_params,
- componentName,
- studyId,
- listOfResources);
+ componentName,
+ listOfResources);
if(CORBA::is_nil(compo))
{
new_params.resource_params.resList = listOfResources;
compo = _LoadComponent(new_params,
- componentName,
- studyId);
+ componentName);
}
return compo._retn();
@@ -475,10 +465,10 @@ void SALOME_LifeCycleCORBA::shutdownServers()
// 2) SALOMEDS
try
{
- CORBA::Object_var objSDS = _NS->Resolve("/myStudyManager");
- SALOMEDS::StudyManager_var studyManager = SALOMEDS::StudyManager::_narrow(objSDS) ;
- if ( !CORBA::is_nil(studyManager) && ( pid != studyManager->getPID() ) )
- studyManager->Shutdown();
+ CORBA::Object_var objSDS = _NS->Resolve("/Study");
+ SALOMEDS::Study_var study = SALOMEDS::Study::_narrow(objSDS) ;
+ if ( !CORBA::is_nil(study) && ( pid != study->getPID() ) )
+ study->Shutdown();
}
catch(const CORBA::Exception& e)
{
@@ -599,7 +589,7 @@ void SALOME_LifeCycleCORBA::killOmniNames()
std::string portNumber (::getenv ("NSPORT") );
std::string python_exe;
- python_exe = std::string("python");
+ python_exe = std::string("python3");
if ( !portNumber.empty() )
{
@@ -639,7 +629,6 @@ void SALOME_LifeCycleCORBA::killOmniNames()
*
* \param params machine parameters like type or name...
* \param componentName the name of component class
- * \param studyId default = 0 : multistudy instance
* \param listOfMachines list of machine address
* \return a CORBA reference of the component instance, or _nil if not found
*/
@@ -649,7 +638,6 @@ Engines::EngineComponent_ptr
SALOME_LifeCycleCORBA::
_FindComponent(const Engines::ContainerParameters& params,
const char *componentName,
- int studyId,
const Engines::ResourceList& listOfResources)
{
// --- build the list of machines on which the component is already running
@@ -700,7 +688,6 @@ _FindComponent(const Engines::ContainerParameters& params,
*
* \param params machine parameters like type or name...
* \param componentName the name of component class
- * \param studyId default = 0 : multistudy instance
* \return a CORBA reference of the component instance, or _nil if problem
*/
//=============================================================================
@@ -708,8 +695,7 @@ _FindComponent(const Engines::ContainerParameters& params,
Engines::EngineComponent_ptr
SALOME_LifeCycleCORBA::
_LoadComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId)
+ const char *componentName)
{
MESSAGE("_LoadComponent, required " << params.container_name <<
" " << componentName << " " << NbProc(params));
@@ -730,7 +716,7 @@ _LoadComponent(const Engines::ContainerParameters& params,
CORBA::string_free(reason);
Engines::EngineComponent_var myInstance =
- cont->create_component_instance(componentName, studyId);
+ cont->create_component_instance(componentName);
return myInstance._retn();
}
@@ -739,14 +725,12 @@ _LoadComponent(const Engines::ContainerParameters& params,
*
* \param params machine parameters like type or name...
* \param componentName the name of component class
- * \param studyId default = 0 : multistudy instance
* \return a CORBA reference of the parallel component instance, or _nil if problem
*/
//=============================================================================
Engines::EngineComponent_ptr
SALOME_LifeCycleCORBA::Load_ParallelComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId)
+ const char *componentName)
{
MESSAGE("Entering LoadParallelComponent");
@@ -782,7 +766,7 @@ SALOME_LifeCycleCORBA::Load_ParallelComponent(const Engines::ContainerParameters
// @PARALLEL@ permits to identify that the component requested
// is a parallel component.
std::string name = std::string(componentName);
- Engines::EngineComponent_var myInstance = cont->create_component_instance(name.c_str(), studyId);
+ Engines::EngineComponent_var myInstance = cont->create_component_instance(name.c_str());
if (CORBA::is_nil(myInstance))
INFOS("create_component_instance returns a NULL component !");
return myInstance._retn();
diff --git a/src/LifeCycleCORBA/SALOME_LifeCycleCORBA.hxx b/src/LifeCycleCORBA/SALOME_LifeCycleCORBA.hxx
index 8713d5705..4da31b0d9 100644
--- a/src/LifeCycleCORBA/SALOME_LifeCycleCORBA.hxx
+++ b/src/LifeCycleCORBA/SALOME_LifeCycleCORBA.hxx
@@ -66,18 +66,15 @@ public:
Engines::EngineComponent_ptr
FindComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId=0);
+ const char *componentName);
Engines::EngineComponent_ptr
LoadComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId=0);
+ const char *componentName);
Engines::EngineComponent_ptr
FindOrLoad_Component(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId =0);
+ const char *componentName);
Engines::EngineComponent_ptr
FindOrLoad_Component(const char *containerName,
@@ -86,8 +83,7 @@ public:
// Parallel extension
Engines::EngineComponent_ptr
Load_ParallelComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId);
+ const char *componentName);
bool isKnownComponentClass(const char *componentName);
@@ -115,13 +111,11 @@ protected:
Engines::EngineComponent_ptr
_FindComponent(const Engines::ContainerParameters& params,
const char *componentName,
- int studyId,
const Engines::ResourceList& listOfResources);
Engines::EngineComponent_ptr
_LoadComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId);
+ const char *componentName);
SALOME_NamingService *_NS;
SALOME_NamingService *_NSnew;
diff --git a/src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py b/src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py
index 68d582703..6d52cebce 100644
--- a/src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py
+++ b/src/LifeCycleCORBA/Test/TestLifeCycleCORBA.py
@@ -21,7 +21,7 @@
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
import subprocess
import runSalome
import setenv
diff --git a/src/LifeCycleCORBA_SWIG/CMakeLists.txt b/src/LifeCycleCORBA_SWIG/CMakeLists.txt
index 38e526dfa..4a8decb55 100755
--- a/src/LifeCycleCORBA_SWIG/CMakeLists.txt
+++ b/src/LifeCycleCORBA_SWIG/CMakeLists.txt
@@ -20,13 +20,14 @@
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(libSALOME_LifeCycleCORBA.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(libSALOME_LifeCycleCORBA.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(libSALOME_LifeCycleCORBA.i PROPERTIES SWIG_FLAGS "-py3")
ADD_DEFINITIONS(${OMNIORB_DEFINITIONS})
INCLUDE_DIRECTORIES(
${PYTHON_INCLUDE_DIRS}
${PTHREAD_INCLUDE_DIR}
${OMNIORB_INCLUDE_DIR}
+ ${OMNIORBPY_INCLUDE_DIR}
${PROJECT_BINARY_DIR}/salome_adm
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
diff --git a/src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py b/src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py
index 6690b5193..303d2cc1b 100644
--- a/src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py
+++ b/src/LifeCycleCORBA_SWIG/Test/LifeCycleCORBA_SWIGTest.py
@@ -177,7 +177,7 @@ class LifeCycleCORBA_SWIGTest(unittest.TestCase):
containerName += "/swTheContainer"
try:
cp1=self.lcc.FindOrLoad_Component(containerName,"SalomeTestComponent")
- except RuntimeError,ex :
+ except RuntimeError as ex :
self.assertEqual(ex.args[0],'unknown host')
pass
diff --git a/src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py b/src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py
index 36f2a570c..073af7047 100644
--- a/src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py
+++ b/src/LifeCycleCORBA_SWIG/Test/TestLifeCycleCORBA_SWIG.py
@@ -26,7 +26,7 @@
# Module : SALOME
# $Header$
#
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
import subprocess
import runSalome
import setenv
diff --git a/src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py b/src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py
index b0800d53d..e4ad07863 100644
--- a/src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py
+++ b/src/LifeCycleCORBA_SWIG/TestLifeCycleCORBA.py
@@ -44,7 +44,7 @@ try :
engine=lcc.FindComponent(param,'SalomeTestComponent')
engine.Coucou(1)
except :
- print 'lcc.FindOrLoad_Component("FactoryServer","SalomeTestComponent") failed'
+ print('lcc.FindOrLoad_Component("FactoryServer","SalomeTestComponent") failed')
import sys
from omniORB import CORBA
@@ -71,7 +71,7 @@ try :
engineCPP=lcc.FindComponent(myContainerparamsCPP,'SalomeTestComponent')
engineCPP.Coucou(1)
except :
- print 'ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) C++ failed'
+ print('ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) C++ failed')
try :
myContainerparamsPy = LifeCycleCORBA.ContainerParameters()
@@ -85,5 +85,5 @@ try :
enginePy=lcc.FindComponent(myContainerparamsPy,'SALOME_TestComponentPy')
enginePy.Coucou(1)
except :
- print 'ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) Python failed'
+ print('ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) Python failed')
diff --git a/src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i b/src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i
index 2f80c10c1..0cce5c6ee 100644
--- a/src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i
+++ b/src/LifeCycleCORBA_SWIG/libSALOME_LifeCycleCORBA.i
@@ -45,27 +45,9 @@ typedef int Py_ssize_t;
#define PY_SSIZE_T_MIN INT_MIN
#endif
-//--- from omniORBpy.h (not present on Debian Sarge packages)
-
-struct omniORBpyAPI {
-
- PyObject* (*cxxObjRefToPyObjRef)(const CORBA::Object_ptr cxx_obj,
- CORBA::Boolean hold_lock);
- // Convert a C++ object reference to a Python object reference.
- // If is true, caller holds the Python interpreter lock.
-
- CORBA::Object_ptr (*pyObjRefToCxxObjRef)(PyObject* py_obj,
- CORBA::Boolean hold_lock);
- // Convert a Python object reference to a C++ object reference.
- // Raises BAD_PARAM if the Python object is not an object reference.
- // If is true, caller holds the Python interpreter lock.
-
-
- omniORBpyAPI();
- // Constructor for the singleton. Sets up the function pointers.
-};
-
-omniORBpyAPI* api;
+#include
+#include
+omniORBpyAPI* api=0;
%}
@@ -81,10 +63,10 @@ omniORBpyAPI* api;
if (!omnipy)
{
PyErr_SetString(PyExc_ImportError, (char*)"Cannot import _omnipy");
- return;
+ return NULL;
}
PyObject* pyapi = PyObject_GetAttrString(omnipy, (char*)"API");
- api = (omniORBpyAPI*)PyCObject_AsVoidPtr(pyapi);
+ api = (omniORBpyAPI*)PyCapsule_GetPointer(pyapi,"_omnipy.API");
Py_DECREF(pyapi);
%}
diff --git a/src/Logger/SALOME_Trace.py b/src/Logger/SALOME_Trace.py
index f2cc791a3..faf4c3421 100644
--- a/src/Logger/SALOME_Trace.py
+++ b/src/Logger/SALOME_Trace.py
@@ -33,7 +33,7 @@ import time
import os
trace="local"
-if (os.environ.has_key("SALOME_trace")):
+if ("SALOME_trace" in os.environ):
if (os.environ["SALOME_trace"] == "with_logger"):
trace="logger"
@@ -57,22 +57,22 @@ class SALOME_Trace :
if not self.m_pInterfaceLogger is None:
ok = 1
- except CosNaming.NamingContext.NotFound, e :
- if steps == 1: print "Caught exception: Naming Service can't found Logger"
+ except CosNaming.NamingContext.NotFound as e :
+ if steps == 1: print("Caught exception: Naming Service can't found Logger")
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
- if steps == 1: print "Caught CORBA::SystemException CommFailure"
- except CORBA.SystemException, e:
- if steps == 1: print "Caught CORBA::SystemException."
- except CORBA.Exception, e:
- if steps == 1: print "Caught CORBA::Exception."
- except Exception, e:
- if steps == 1: print "Caught unknown exception."
+ if steps == 1: print("Caught CORBA::SystemException CommFailure")
+ except CORBA.SystemException as e:
+ if steps == 1: print("Caught CORBA::SystemException.")
+ except CORBA.Exception as e:
+ if steps == 1: print("Caught CORBA::Exception.")
+ except Exception as e:
+ if steps == 1: print("Caught unknown exception.")
time.sleep(0.25)
steps = steps - 1
def putMessage ( self, LogMsg ) :
if (CORBA.is_nil(self.m_pInterfaceLogger)):
- print LogMsg;
+ print(LogMsg);
else:
self.m_pInterfaceLogger.putMessage (LogMsg)
diff --git a/src/Logger/Test/TestKiller.py b/src/Logger/Test/TestKiller.py
index a05bfd39a..d84ad9db6 100644
--- a/src/Logger/Test/TestKiller.py
+++ b/src/Logger/Test/TestKiller.py
@@ -21,13 +21,13 @@
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import sys, os,signal,string,commands
+import sys, os,signal,subprocess
def getCurrentPort():
fic=os.environ['OMNIORB_CONFIG']
with open(fic,'r') as f:
line=f.readline()
- port=string.split(line,':')[-1][0:4]
+ port=line.split(':')[-1][0:4]
return port
@@ -35,7 +35,7 @@ def closeSalome():
port = getCurrentPort()
try:
from PortManager import releasePort
- print "### release current port:", port
+ print("### release current port:", port)
releasePort(port)
except:
pass
@@ -50,12 +50,12 @@ def killNamingService():
"""
port = getCurrentPort()
command='ps -eo pid,command | grep "omniNames -start '+str(port)+'" | grep --invert-match grep'
- output_com = commands.getoutput(command)
+ output_com = subprocess.getoutput(command)
try:
- pid=string.split(output_com)[0]
+ pid=output_com.split()[0]
os.kill(int(pid),signal.SIGKILL)
except:
- print "killNamingService failed."
+ print("killNamingService failed.")
def killProcess(process_id):
@@ -64,12 +64,12 @@ def killProcess(process_id):
generated by runSalome.Server() class and derived, (method run).
kills also local Naming server.
"""
- for pid, cmd in process_id.items():
- print "stop process %s : %s"% (pid, cmd[0])
+ for pid, cmd in list(process_id.items()):
+ print("stop process %s : %s"% (pid, cmd[0]))
try:
os.kill(int(pid),signal.SIGKILL)
except:
- print " ---- process %s : %s inexistant"% (pid, cmd[0])
+ print(" ---- process %s : %s inexistant"% (pid, cmd[0]))
pass
del process_id[pid]
pass
diff --git a/src/MPIContainer/MPIContainer_i.cxx b/src/MPIContainer/MPIContainer_i.cxx
index 2dc859857..e2fd703e4 100644
--- a/src/MPIContainer/MPIContainer_i.cxx
+++ b/src/MPIContainer/MPIContainer_i.cxx
@@ -202,7 +202,7 @@ bool Engines_MPIContainer_i::Lload_component_Library(const char* componentName)
PyObject *result = PyObject_CallMethod(pyCont,
(char*)"import_component",
(char*)"s",componentName);
- std::string ret= PyString_AsString(result);
+ std::string ret= PyUnicode_AsUTF8(result);
SCRUTE(ret);
Py_RELEASE_NEW_THREAD;
@@ -219,7 +219,6 @@ bool Engines_MPIContainer_i::Lload_component_Library(const char* componentName)
// Create an instance of component
Engines::EngineComponent_ptr
Engines_MPIContainer_i::create_component_instance_env( const char* componentName,
- CORBA::Long studyId,
const Engines::FieldsDict& env,
CORBA::String_out reason)
{
@@ -233,12 +232,11 @@ Engines_MPIContainer_i::create_component_instance_env( const char* componentName
st->ip = ip;
st->tior = _tior;
st->compoName = componentName;
- st->studyId = studyId;
pthread_create(&(th[ip]),NULL,th_createcomponentinstance,(void*)st);
}
}
- Engines::EngineComponent_ptr cptr = Lcreate_component_instance(componentName,studyId);
+ Engines::EngineComponent_ptr cptr = Lcreate_component_instance(componentName);
if(_numproc == 0){
for(int ip=1;ip<_nbproc;ip++)
@@ -250,13 +248,8 @@ Engines_MPIContainer_i::create_component_instance_env( const char* componentName
}
Engines::EngineComponent_ptr
-Engines_MPIContainer_i::Lcreate_component_instance( const char* genericRegisterName, CORBA::Long studyId)
+Engines_MPIContainer_i::Lcreate_component_instance( const char* genericRegisterName )
{
- if (studyId < 0) {
- INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
- return Engines::EngineComponent::_nil() ;
- }
-
Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
Engines::MPIObject_var pobj;
@@ -283,10 +276,9 @@ Engines_MPIContainer_i::Lcreate_component_instance( const char* genericRegisterN
PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
PyObject *result = PyObject_CallMethod(pyCont,
(char*)"create_component_instance",
- (char*)"ssl",
+ (char*)"ss",
aCompName.c_str(),
- instanceName.c_str(),
- studyId);
+ instanceName.c_str());
const char *ior;
const char *error;
PyArg_ParseTuple(result,"ss", &ior, &error);
@@ -316,8 +308,7 @@ Engines_MPIContainer_i::Lcreate_component_instance( const char* genericRegisterN
{
void* handle = _library_map[impl_name];
iobject = createMPIInstance(genericRegisterName,
- handle,
- studyId);
+ handle);
return iobject._retn();
}
@@ -326,8 +317,7 @@ Engines_MPIContainer_i::Lcreate_component_instance( const char* genericRegisterN
Engines::EngineComponent_ptr
Engines_MPIContainer_i::createMPIInstance(std::string genericRegisterName,
- void *handle,
- int studyId)
+ void *handle)
{
Engines::EngineComponent_var iobject;
Engines::MPIObject_var pobj;
@@ -377,27 +367,14 @@ Engines_MPIContainer_i::createMPIInstance(std::string genericRegisterName,
PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
id = (MPIComponent_factory) ( _orb, _poa, _id, instanceName.c_str(), aGenRegisterName.c_str() ) ;
- // --- get reference & servant from id
+ // --- get reference from id
CORBA::Object_var obj = _poa->id_to_reference(*id);
iobject = Engines::EngineComponent::_narrow( obj ) ;
pobj = Engines::MPIObject::_narrow(obj) ;
- Engines_Component_i *servant =
- dynamic_cast(_poa->reference_to_servant(iobject));
- ASSERT(servant);
- //SCRUTE(servant->pd_refCount);
- servant->_remove_ref(); // compensate previous id_to_reference
- //SCRUTE(servant->pd_refCount);
_listInstances_map[instanceName] = iobject;
_cntInstances_map[aGenRegisterName] += 1;
- //SCRUTE(servant->pd_refCount);
-#ifndef _DEBUG_
- servant->setStudyId(studyId);
-#else
- bool ret_studyId = servant->setStudyId(studyId);
- ASSERT(ret_studyId);
-#endif
// --- register the engine under the name
// containerName(.dir)/instanceName(.object)
@@ -616,7 +593,7 @@ void *th_loadcomponentlibrary(void *s)
void *th_createcomponentinstance(void *s)
{
thread_st *st = (thread_st*)s;
- (Engines::MPIContainer::_narrow((*(st->tior))[st->ip]))->create_component_instance(st->compoName.c_str(),st->studyId);
+ (Engines::MPIContainer::_narrow((*(st->tior))[st->ip]))->create_component_instance(st->compoName.c_str());
return NULL;
}
diff --git a/src/MPIContainer/MPIContainer_i.hxx b/src/MPIContainer/MPIContainer_i.hxx
index c53cdefd5..3a8ed1deb 100644
--- a/src/MPIContainer/MPIContainer_i.hxx
+++ b/src/MPIContainer/MPIContainer_i.hxx
@@ -41,7 +41,6 @@ typedef struct {
Engines::IORTab* tior;
std::string compoName;
std::string nameToRegister;
- long studyId;
Engines::EngineComponent_ptr cptr;
} thread_st;
@@ -71,7 +70,6 @@ class Engines_MPIContainer_i : public POA_Engines::MPIContainer,
// synchronous version for process 0
virtual Engines::EngineComponent_ptr
create_component_instance_env( const char* componentName,
- CORBA::Long studyId, // 0 for multiStudy
const Engines::FieldsDict& env,
CORBA::String_out reason);
@@ -90,15 +88,13 @@ class Engines_MPIContainer_i : public POA_Engines::MPIContainer,
private:
bool Lload_component_Library(const char* componentName);
Engines::EngineComponent_ptr
- Lcreate_component_instance( const char* componentName,
- CORBA::Long studyId); // 0 for multiStudy
+ Lcreate_component_instance(const char* componentName);
Engines::EngineComponent_ptr Lload_impl(const char* nameToRegister,
const char* componentName);
Engines::EngineComponent_ptr
createMPIInstance(std::string genericRegisterName,
- void *handle,
- int studyId);
+ void *handle);
};
#endif
diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_Acomponent_impl.cxx b/src/ModuleCatalog/SALOME_ModuleCatalog_Acomponent_impl.cxx
index 5ee49c0be..9e574d274 100644
--- a/src/ModuleCatalog/SALOME_ModuleCatalog_Acomponent_impl.cxx
+++ b/src/ModuleCatalog/SALOME_ModuleCatalog_Acomponent_impl.cxx
@@ -42,8 +42,7 @@ static int MYDEBUG = 0;
//----------------------------------------------------------------------
// Function : SALOME_ModuleCatalog_AcomponentImpl
// Purpose : Constructor
-// Affect the component name, type, icon, and bool to define
-// if it's multi-study or not.
+// Affect the component name, type,icon
// Affect too the constraint and the interfaces of the component
// and the path prefixes for all computers
//----------------------------------------------------------------------
@@ -399,16 +398,6 @@ char* SALOME_ModuleCatalog_AcomponentImpl::componentusername()
return CORBA::string_dup(_Component.username);
}
-//----------------------------------------------------------------------
-// Function : multistudy
-// Purpose : define if a component can be multistudy or not
-//----------------------------------------------------------------------
-CORBA::Boolean SALOME_ModuleCatalog_AcomponentImpl::multistudy()
-{
- return _Component.multistudy ;
-}
-
-
//----------------------------------------------------------------------
// Function : implementation type
// Purpose : return the implementation type : C++ (dyn lib), Python (module) or executable
diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_Acomponent_impl.hxx b/src/ModuleCatalog/SALOME_ModuleCatalog_Acomponent_impl.hxx
index 5078c95f4..d84bd08da 100644
--- a/src/ModuleCatalog/SALOME_ModuleCatalog_Acomponent_impl.hxx
+++ b/src/ModuleCatalog/SALOME_ModuleCatalog_Acomponent_impl.hxx
@@ -121,12 +121,6 @@ public:
*/
virtual char* componentusername();
- //! method to define if a component can be multistudy or not
- /*!
- \return true if the component supports multistudy
- */
- virtual CORBA::Boolean multistudy();
-
//! method to define the type of the component
/*!
\return the component type
diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_Client.cxx b/src/ModuleCatalog/SALOME_ModuleCatalog_Client.cxx
index 8ed79652e..858cc45a7 100644
--- a/src/ModuleCatalog/SALOME_ModuleCatalog_Client.cxx
+++ b/src/ModuleCatalog/SALOME_ModuleCatalog_Client.cxx
@@ -152,7 +152,6 @@ int main(int argc,char **argv)
void PrintComponent(SALOME_ModuleCatalog::Acomponent_ptr C)
{
MESSAGE("Name : " << C->componentname());
- MESSAGE("Type : " << C->component_type() << " multistudy : " << C->multistudy());
MESSAGE("Constraint : " << C->constraint());
MESSAGE("Icon : " << C->component_icone());
diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_Handler.cxx b/src/ModuleCatalog/SALOME_ModuleCatalog_Handler.cxx
index 693ec8b43..b12bec2b1 100644
--- a/src/ModuleCatalog/SALOME_ModuleCatalog_Handler.cxx
+++ b/src/ModuleCatalog/SALOME_ModuleCatalog_Handler.cxx
@@ -64,7 +64,6 @@ SALOME_ModuleCatalog_Handler::SALOME_ModuleCatalog_Handler(ParserPathPrefixes& p
test_component_name = "component-name";
test_component_username = "component-username";
test_component_type = "component-type" ;
- test_component_multistudy = "component-multistudy";
test_component_icon = "component-icone" ;
test_component_impltype = "component-impltype";
test_component_implname = "component-implname";
@@ -477,10 +476,6 @@ void SALOME_ModuleCatalog_Handler::ProcessXmlDocument(xmlDocPtr theDoc)
_aModule.type = OTHER ;
}
- // Tag test_component_multistudy
- if ( !xmlStrcmp(aComponentSubNode->name, (const xmlChar*)test_component_multistudy) )
- _aModule.multistudy = atoi( aContent.c_str() ) != 0;
-
// Tag test_component_impltype
if ( !xmlStrcmp(aComponentSubNode->name, (const xmlChar*)test_component_impltype) )
_aModule.implementationType = aContent;
diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_Handler.hxx b/src/ModuleCatalog/SALOME_ModuleCatalog_Handler.hxx
index f75ca4ae2..1ad92fab9 100644
--- a/src/ModuleCatalog/SALOME_ModuleCatalog_Handler.hxx
+++ b/src/ModuleCatalog/SALOME_ModuleCatalog_Handler.hxx
@@ -65,7 +65,6 @@ private:
const char *test_component_name;
const char *test_component_username;
const char *test_component_type ;
- const char *test_component_multistudy ;
const char *test_component_icon ;
const char *test_component_impltype;
const char *test_component_implname;
diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_Parser.hxx b/src/ModuleCatalog/SALOME_ModuleCatalog_Parser.hxx
index 622af9b9e..9f1e4a6cd 100644
--- a/src/ModuleCatalog/SALOME_ModuleCatalog_Parser.hxx
+++ b/src/ModuleCatalog/SALOME_ModuleCatalog_Parser.hxx
@@ -91,7 +91,6 @@ struct ParserComponent
std::string name;
std::string username;
ParserComponentType type;
- bool multistudy;
std::string icon;
std::string constraint;
ParserInterfaces interfaces;
diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_Parser_IO.cxx b/src/ModuleCatalog/SALOME_ModuleCatalog_Parser_IO.cxx
index 29a9f25c2..26f7c7838 100644
--- a/src/ModuleCatalog/SALOME_ModuleCatalog_Parser_IO.cxx
+++ b/src/ModuleCatalog/SALOME_ModuleCatalog_Parser_IO.cxx
@@ -124,8 +124,6 @@ std::ostream & operator<< (std::ostream & f,
<< " name : " << C.name << std::endl;
f << " user name : " << C.username << std::endl;
f << " type : " << C.type << std::endl;
- f << " multistudy : " << (C.multistudy ? "yes" : "no")
- << std::endl;
f << " icon : " << C.icon << std::endl;
f << " constraint : " << C.constraint << std::endl;
diff --git a/src/ModuleCatalog/SALOME_ModuleCatalog_impl.cxx b/src/ModuleCatalog/SALOME_ModuleCatalog_impl.cxx
index 56580e4c8..9924f6687 100644
--- a/src/ModuleCatalog/SALOME_ModuleCatalog_impl.cxx
+++ b/src/ModuleCatalog/SALOME_ModuleCatalog_impl.cxx
@@ -897,7 +897,6 @@ void SALOME_ModuleCatalogImpl::Private::duplicate
{
C_corba.name = CORBA::string_dup(C_parser.name.c_str());
C_corba.username = CORBA::string_dup(C_parser.username.c_str());
- C_corba.multistudy = C_parser.multistudy;
C_corba.icon = CORBA::string_dup(C_parser.icon.c_str());
C_corba.type = ComponentTypeConvert[C_parser.type];
if(C_parser.implementationType == "EXE")
diff --git a/src/ModuleCatalog/TestModuleCatalog.py b/src/ModuleCatalog/TestModuleCatalog.py
index 9e89c6a6d..de3c69a6a 100755
--- a/src/ModuleCatalog/TestModuleCatalog.py
+++ b/src/ModuleCatalog/TestModuleCatalog.py
@@ -24,63 +24,63 @@
import batchmode_salome
import SALOME_ModuleCatalog
-print
-print "======================================================================"
-print " XML Catalog file generation from idl file"
-print "======================================================================"
+print()
+print("======================================================================")
+print(" XML Catalog file generation from idl file")
+print("======================================================================")
import os
os.system('runIDLparser -Wbcatalog=x \
${KERNEL_ROOT_DIR}/idl/salome/SALOME_TestModuleCatalog.idl')
-print "======================================================================"
-print " Get Catalog "
-print "======================================================================"
+print("======================================================================")
+print(" Get Catalog ")
+print("======================================================================")
obj = batchmode_salome.naming_service.Resolve('Kernel/ModulCatalog')
catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
catalog.GetComponentList()
-print
-print "======================================================================"
-print " Import xml file "
-print "======================================================================"
+print()
+print("======================================================================")
+print(" Import xml file ")
+print("======================================================================")
catalog.ImportXmlCatalogFile("x.xml")
name = "AddComponent"
-print
-print "======================================================================"
-print " Dump component <", name, "> "
-print "======================================================================"
+print()
+print("======================================================================")
+print(" Dump component <", name, "> ")
+print("======================================================================")
C = catalog.GetComponent(name)
-print "name : ", C._get_componentname()
-print "username : ", C._get_componentusername()
-print "type : ", C._get_component_type()
-print "constraint : ", C._get_constraint()
-print "icon : ", C._get_component_icone()
+print("name : ", C._get_componentname())
+print("username : ", C._get_componentusername())
+print("type : ", C._get_component_type())
+print("constraint : ", C._get_constraint())
+print("icon : ", C._get_component_icone())
for iL in C.GetInterfaceList():
I = C.GetInterface(iL)
- print "interface : ", I.interfacename
+ print("interface : ", I.interfacename)
for S in I.interfaceservicelist:
- print " service : ", S.ServiceName
- print " ", len(S.ServiceinParameter), "in params : "
+ print(" service : ", S.ServiceName)
+ print(" ", len(S.ServiceinParameter), "in params : ")
for iP in S.ServiceinParameter:
- print ' ' + iP.Parametername + '(' + iP.Parametertype + ')'
+ print(' ' + iP.Parametername + '(' + iP.Parametertype + ')')
pass
- print " ", len(S.ServiceoutParameter), "out params : "
+ print(" ", len(S.ServiceoutParameter), "out params : ")
for iP in S.ServiceoutParameter:
- print ' ' + iP.Parametername + '(' + iP.Parametertype + ')'
+ print(' ' + iP.Parametername + '(' + iP.Parametertype + ')')
pass
- print " ", len(S.ServiceinDataStreamParameter), "in datastream params : "
+ print(" ", len(S.ServiceinDataStreamParameter), "in datastream params : ")
for iP in S.ServiceinDataStreamParameter:
- print ' ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \
- str(iP.Parameterdependency) + ')'
+ print(' ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \
+ str(iP.Parameterdependency) + ')')
pass
- print " ", len(S.ServiceoutDataStreamParameter), "out datastream params : "
+ print(" ", len(S.ServiceoutDataStreamParameter), "out datastream params : ")
for iP in S.ServiceoutDataStreamParameter:
- print ' ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \
- str(iP.Parameterdependency) + ')'
+ print(' ' + iP.Parametername + '(' + str(iP.Parametertype) + ', ' + \
+ str(iP.Parameterdependency) + ')')
pass
pass
pass
diff --git a/src/ModuleGenerator/IDLparser.py b/src/ModuleGenerator/IDLparser.py
index 0f2ab825d..b2107353a 100644
--- a/src/ModuleGenerator/IDLparser.py
+++ b/src/ModuleGenerator/IDLparser.py
@@ -39,7 +39,6 @@ common_data={"AUTHOR" : "",
"COMP_TYPE" : "",
"COMP_NAME" : "",
"COMP_UNAME" : "",
- "COMP_MULT" : "",
"COMP_IMPL" : ""
}
@@ -68,7 +67,7 @@ def getParamValue( param_name, default_value, args ):
# print error message
#--------------------------------------------------
def error (message):
- print "ERROR : ", message
+ print("ERROR : ", message)
#--------------------------------------------------
@@ -119,7 +118,7 @@ class Tree:
if self.name != '':
s = string.ljust('', 4*depth)
s += '<' + self.name
- for k,v in self.attrs.items():
+ for k,v in list(self.attrs.items()):
s += ' ' + k + '="' + v + '"'
s += '>'
if self.content != '':
@@ -145,7 +144,7 @@ class Tree:
if levels == 0: return
s = string.ljust('', 4*depth)
- print s, self, self.content
+ print(s, self, self.content)
for i in self.childs:
i.Dump(levels-1, depth+1)
@@ -296,8 +295,7 @@ def parseComment(comment):
## the remaining part of input string
m = re.match(pattern, sPorts)
if m is None:
- raise LookupError, \
- 'format error in DataStreamPort definition : '+sPorts
+ raise LookupError('format error in DataStreamPort definition : '+sPorts)
sPorts = sPorts[m.end():]
result.append(m.groups())
@@ -402,9 +400,8 @@ class Interface(Tree):
if type == 'DataStreamPorts':
Service = self.findService(key)
if Service is None:
- raise LookupError, \
- 'service ' + key + \
- ' not found in interface : ' + self.key
+ raise LookupError('service ' + key + \
+ ' not found in interface : ' + self.key)
for p in result:
## process next DataStreamPort
Service.createDataStreamParameter(p)
@@ -437,7 +434,6 @@ class Component(Tree):
self.addNamedChild('component-author', common_data["AUTHOR"])
self.addNamedChild('component-version', common_data["VERSION"])
self.addNamedChild('component-comment', 'unknown')
- self.addNamedChild('component-multistudy', common_data["COMP_MULT"])
self.addNamedChild('component-impltype', common_data["COMP_IMPL"])
self.addNamedChild('component-icone', common_data["ICON"])
self.addNamedChild('constraint')
@@ -456,7 +452,7 @@ class Component(Tree):
for i in ['component-username', 'component-author',
'component-type', 'component-icone', 'component-version',
- 'component-multistudy', 'component-impltype', 'constraint']:
+ 'component-impltype', 'constraint']:
ext = C.getChild(i)
int = self.getChild(i)
if int is None:
@@ -503,14 +499,14 @@ class Catalog(ContentHandler, Tree):
complist = self.getNode('component-list')
idx = 0
if complist is None:
- print "Catalog.removeComponent() : 'component-list' is not found"
+ print("Catalog.removeComponent() : 'component-list' is not found")
return
for comp in complist.childs:
cname = comp.getChild('component-name')
if cname is not None:
if cname.content == name:
complist.childs.pop(idx)
- print "Component " + name + " is removed"
+ print("Component " + name + " is removed")
idx += 1
def startDocument(self):
@@ -571,10 +567,10 @@ class Catalog(ContentHandler, Tree):
break;
if present == 0:
- print ' add component', i_ext.getChild('component-name').content
+ print(' add component', i_ext.getChild('component-name').content)
L_int.addChild(i_ext)
else:
- print ' replace component', i_ext.getChild('component-name').content
+ print(' replace component', i_ext.getChild('component-name').content)
i_int.merge(i_ext)
def mergeType(self, type):
@@ -833,23 +829,22 @@ def run(tree, args):
common_data["COMP_NAME"] = getParamValue("name", "", args)
common_data["COMP_UNAME"] = getParamValue("username", "", args)
common_data["COMP_TYPE"] = getParamValue("type", "OTHER", args)
- common_data["COMP_MULT"] = getParamValue("multistudy", "1", args)
common_data["COMP_IMPL"] = getParamValue("impltype", "1", args)
- print common_data
+ print(common_data)
remove_comp = getParamValue("remove", "", args)
#==================================================
if (os.path.exists(CatalogFileName)):
- print "Importing", CatalogFileName
+ print("Importing", CatalogFileName)
C = Catalog(CatalogFileName)
else:
- print "Creating ",CatalogFileName
+ print("Creating ",CatalogFileName)
C = Catalog()
- print "Reading idl file"
+ print("Reading idl file")
visitor = ModuleCatalogVisitor(C)
tree.accept(visitor)
@@ -860,12 +855,12 @@ def run(tree, args):
C.removeComponent(remove_comp)
if (os.path.exists(CatalogFileName)):
- print "Updating", CatalogFileName
+ print("Updating", CatalogFileName)
CatalogFileName_old = CatalogFileName + '_old'
os.rename(CatalogFileName, CatalogFileName_old)
else:
CatalogFileName_old = ""
- print "Writing", CatalogFileName
+ print("Writing", CatalogFileName)
CatalogFileName_new = CatalogFileName + '_new'
f=open(CatalogFileName_new, 'w')
@@ -877,10 +872,10 @@ def run(tree, args):
if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
os.unlink(CatalogFileName_old)
- print
+ print()
if __name__ == "__main__":
- print
- print "Usage : omniidl -bIDLparser [-I]* -Wbcatalog=[,icon=][,version=][,author=][,name=][,username=][,multistudy=][,impltype=] "
- print
+ print()
+ print("Usage : omniidl -bIDLparser [-I]* -Wbcatalog=[,icon=][,version=][,author=][,name=][,username=][,impltype=] ")
+ print()
diff --git a/src/NOTIFICATION_SWIG/CMakeLists.txt b/src/NOTIFICATION_SWIG/CMakeLists.txt
index bdc345db9..d041a89a6 100755
--- a/src/NOTIFICATION_SWIG/CMakeLists.txt
+++ b/src/NOTIFICATION_SWIG/CMakeLists.txt
@@ -20,7 +20,7 @@
INCLUDE(${SWIG_USE_FILE})
SET_SOURCE_FILES_PROPERTIES(NOTIFICATION.i PROPERTIES CPLUSPLUS ON)
-SET_SOURCE_FILES_PROPERTIES(NOTIFICATION.i PROPERTIES SWIG_DEFINITIONS "-shadow")
+SET_SOURCE_FILES_PROPERTIES(NOTIFICATION.i PROPERTIES SWIG_FLAGS "-py3")
SET_SOURCE_FILES_PROPERTIES(NOTIFICATIONPYTHON_wrap.cxx PROPERTIES COMPILE_FLAGS "${OMNIORB_DEFINITIONS} -DHAVE_CONFIG_H")
INCLUDE_DIRECTORIES(
diff --git a/src/NamingService/SALOME_NamingServicePy.py b/src/NamingService/SALOME_NamingServicePy.py
index 4233797e6..7ca7f90fd 100644
--- a/src/NamingService/SALOME_NamingServicePy.py
+++ b/src/NamingService/SALOME_NamingServicePy.py
@@ -101,7 +101,7 @@ class SALOME_NamingServicePy_i(object):
#delete first '/' before split
Path=Path[1:]
- result_resolve_path = string.split(Path,'/')
+ result_resolve_path = Path.split('/')
if len(result_resolve_path)>1:
# A directory is treated (not only an object name)
# We had to test if the directory where ObjRef should be recorded
@@ -114,11 +114,11 @@ class SALOME_NamingServicePy_i(object):
try:
obj = self._current_context.resolve(_context_name)
self._current_context = obj._narrow(CosNaming.NamingContext)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
_not_exist = 1
- except CosNaming.NamingContext.InvalidName, ex:
+ except CosNaming.NamingContext.InvalidName as ex:
MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" )
- except CosNaming.NamingContext.CannotProceed, ex:
+ except CosNaming.NamingContext.CannotProceed as ex:
MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" )
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
MESSAGE ( "Register : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
@@ -133,7 +133,7 @@ class SALOME_NamingServicePy_i(object):
try:
obj = self._current_context.resolve(_context_name)
self._current_context = obj._narrow(CosNaming.NamingContext)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
#This context is not created. It will be done
self._current_context = self._current_context.bind_new_context(_context_name)
@@ -143,13 +143,13 @@ class SALOME_NamingServicePy_i(object):
_context_name = [CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object")]
try:
self._current_context.bind(_context_name,ObjRef)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
MESSAGE ( "Register : CosNaming.NamingContext.NotFound" )
- except CosNaming.NamingContext.InvalidName, ex:
+ except CosNaming.NamingContext.InvalidName as ex:
MESSAGE ( "Register : CosNaming.NamingContext.InvalidName" )
- except CosNaming.NamingContext.CannotProceed, ex:
+ except CosNaming.NamingContext.CannotProceed as ex:
MESSAGE ( "Register : CosNaming.NamingContext.CannotProceed" )
- except CosNaming.NamingContext.AlreadyBound, ex:
+ except CosNaming.NamingContext.AlreadyBound as ex:
MESSAGE ( "Register : CosNaming.NamingContext.AlreadyBound, object will be rebind" )
self._current_context.rebind(_context_name,ObjRef)
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
@@ -169,20 +169,20 @@ class SALOME_NamingServicePy_i(object):
#delete first '/' before split
Path=Path[1:]
- result_resolve_path = string.split(Path,'/')
+ result_resolve_path = Path.split('/')
_context_name=[]
for i in range(len(result_resolve_path)-1):
_context_name.append(CosNaming.NameComponent(result_resolve_path[i],"dir"))
_context_name.append(CosNaming.NameComponent(result_resolve_path[len(result_resolve_path)-1],"object"))
try:
self._obj = self._current_context.resolve(_context_name)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
MESSAGE ( "Resolve : CosNaming.NamingContext.NotFound" )
self._obj = None
- except CosNaming.NamingContext.InvalidName, ex:
+ except CosNaming.NamingContext.InvalidName as ex:
MESSAGE ( "Resolve : CosNaming.NamingContext.InvalidName" )
self._obj = None
- except CosNaming.NamingContext.CannotProceed, ex:
+ except CosNaming.NamingContext.CannotProceed as ex:
MESSAGE ( "Resolve : CosNaming.NamingContext.CannotProceed" )
self._obj = None
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
@@ -206,18 +206,18 @@ class SALOME_NamingServicePy_i(object):
#delete first '/' before split
Path=Path[1:]
- result_resolve_path = string.split(Path,'/')
+ result_resolve_path = Path.split('/')
_context_name = []
for i in range(len(result_resolve_path)):
_context_name[CosNaming.NameComponent(result_resolve_path[i],"dir")]
try:
obj = self._current_context.resolve(_context_name)
self._current_context = obj._narrow(CosNaming.NamingContext)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
self._current_context = self._current_context.bind_new_context(_context_name)
- except CosNaming.NamingContext.InvalidName, ex:
+ except CosNaming.NamingContext.InvalidName as ex:
MESSAGE ( "Create_Directory : CosNaming.NamingContext.InvalidName" )
- except CosNaming.NamingContext.CannotProceed, ex:
+ except CosNaming.NamingContext.CannotProceed as ex:
MESSAGE ( "Create_Directory : CosNaming.NamingContext.CannotProceed" )
except (CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE):
MESSAGE ( "Create_Directory : CORBA.TRANSIENT,CORBA.OBJECT_NOT_EXIST,CORBA.COMM_FAILURE" )
@@ -227,7 +227,7 @@ class SALOME_NamingServicePy_i(object):
remove a name in naming service
"""
- resolve_path=string.split(Path,'/')
+ resolve_path=Path.split('/')
if resolve_path[0] == '': del resolve_path[0]
dir_path=resolve_path[:-1]
context_name=[]
@@ -237,9 +237,9 @@ class SALOME_NamingServicePy_i(object):
try:
self._root_context.unbind(context_name)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
return
- except CORBA.Exception,ex:
+ except CORBA.Exception as ex:
return
def Destroy_FullDirectory(self,Path):
@@ -248,15 +248,15 @@ class SALOME_NamingServicePy_i(object):
remove recursively a directory
"""
context_name=[]
- for e in string.split(Path,'/'):
+ for e in Path.split('/'):
if e == '':continue
context_name.append(CosNaming.NameComponent(e,"dir"))
try:
context=self._root_context.resolve(context_name)
- except CosNaming.NamingContext.NotFound, ex:
+ except CosNaming.NamingContext.NotFound as ex:
return
- except CORBA.Exception,ex:
+ except CORBA.Exception as ex:
return
bl,bi=context.list(0)
diff --git a/src/NamingService/Test/TestNamingService.py b/src/NamingService/Test/TestNamingService.py
index 51fe25b2d..e8c2a8203 100644
--- a/src/NamingService/Test/TestNamingService.py
+++ b/src/NamingService/Test/TestNamingService.py
@@ -21,7 +21,7 @@
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
import subprocess
import runSalome
import setenv
diff --git a/src/ParallelContainer/SALOME_ParallelComponent_i.cxx b/src/ParallelContainer/SALOME_ParallelComponent_i.cxx
index f5fb351fc..ddbdb04bd 100644
--- a/src/ParallelContainer/SALOME_ParallelComponent_i.cxx
+++ b/src/ParallelContainer/SALOME_ParallelComponent_i.cxx
@@ -22,7 +22,7 @@
// SALOME_ParallelComponent : implementation of container and engine for Parallel Kernel
// File : SALOME_ParallelComponent_i.cxx
-// Author : André RIBES, EDF
+// Author : Andr� RIBES, EDF
// Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
//
#include "SALOME_ParallelComponent_i.hxx"
@@ -53,7 +53,6 @@ int SIGUSR11 = 1000;
extern bool _Sleeping ;
static Engines_Parallel_Component_i * theEngines_Component ;
-bool Engines_Parallel_Component_i::_isMultiStudy = true;
bool Engines_Parallel_Component_i::_isMultiInstance = false;
//=============================================================================
@@ -90,7 +89,6 @@ Engines_Parallel_Component_i::Engines_Parallel_Component_i(CORBA::ORB_ptr orb, c
_Executed(false) ,
_graphName("") ,
_nodeName(""),
- _studyId(-1),
_destroyed(false),
_CanceledThread(false)
{
@@ -160,20 +158,6 @@ char* Engines_Parallel_Component_i::interfaceName()
return CORBA::string_dup(_interfaceName.c_str()) ;
}
-//=============================================================================
-/*!
- * CORBA method: Get study Id
- * \return -1: not initialised (Internal Error)
- * 0: multistudy component instance
- * >0: study id associated to this instance
- */
-//=============================================================================
-
-CORBA::Long Engines_Parallel_Component_i::getStudyId()
-{
- return _studyId;
-}
-
//=============================================================================
/*!
* CORBA method: Test if instance is alive and responds
@@ -517,31 +501,6 @@ Engines_Parallel_Container_i *Engines_Parallel_Component_i::GetContainerPtr()
return dynamic_cast(_poa->id_to_servant(*_contId)) ;
}
-//=============================================================================
-/*!
- * C++ method: set study Id
- * \param studyId 0 if instance is not associated to a study,
- * >0 otherwise (== study id)
- * \return true if the set of study Id is OK
- * must be set once by Container, at instance creation,
- * and cannot be changed after.
- */
-//=============================================================================
-
-CORBA::Boolean Engines_Parallel_Component_i::setStudyId(CORBA::Long studyId)
-{
- ASSERT( studyId >= 0);
- CORBA::Boolean ret = false;
- if (_studyId < 0) // --- not yet initialized
- {
- _studyId = studyId;
- ret = true;
- }
- else
- if ( _studyId == studyId) ret = true;
- return ret;
-}
-
//=============================================================================
/*!
* C++ method: return CORBA instance id, the id is set in derived class
@@ -846,12 +805,11 @@ std::string Engines_Parallel_Component_i::GetDynLibraryName(const char *componen
*/
//=============================================================================
-Engines::TMPFile* Engines_Parallel_Component_i::DumpPython(CORBA::Object_ptr theStudy,
- CORBA::Boolean isPublished,
+Engines::TMPFile* Engines_Parallel_Component_i::DumpPython(CORBA::Boolean isPublished,
CORBA::Boolean isMultiFile,
CORBA::Boolean& isValidScript)
{
- const char* aScript = isMultiFile ? "def RebuildData(theStudy): pass" : "";
+ const char* aScript = isMultiFile ? "def RebuildData(): pass" : "";
char* aBuffer = new char[strlen(aScript)+1];
strcpy(aBuffer, aScript);
CORBA::Octet* anOctetBuf = (CORBA::Octet*)aBuffer;
diff --git a/src/ParallelContainer/SALOME_ParallelComponent_i.hxx b/src/ParallelContainer/SALOME_ParallelComponent_i.hxx
index a5d41f270..9ab9b5cb5 100644
--- a/src/ParallelContainer/SALOME_ParallelComponent_i.hxx
+++ b/src/ParallelContainer/SALOME_ParallelComponent_i.hxx
@@ -22,7 +22,7 @@
// SALOME_ParallelComponent : implementation of container and engine for Parallel Kernel
// File : SALOME_ParallelComponent_i.hxx
-// Author : André RIBES, EDF
+// Author : Andr� RIBES, EDF
// Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
//
#ifndef _SALOME_PARALLEL_COMPONENT_I_HXX_
@@ -80,7 +80,6 @@ public:
void ping();
void destroy();
- CORBA::Long getStudyId();
Engines::Container_ptr GetContainerRef();
void setProperties(const Engines::FieldsDict& dico);
@@ -93,8 +92,7 @@ public:
bool Resume_impl();
CORBA::Long CpuUsed_impl() ;
- virtual Engines::TMPFile* DumpPython(CORBA::Object_ptr theStudy,
- CORBA::Boolean isPublished,
+ virtual Engines::TMPFile* DumpPython(CORBA::Boolean isPublished,
CORBA::Boolean isMultiFile,
CORBA::Boolean& isValidScript);
@@ -116,15 +114,13 @@ public:
// Object information
virtual bool hasObjectInfo() { return false; }
- virtual char* getObjectInfo(CORBA::Long studyId, const char* entry) { return ""; }
+ virtual char* getObjectInfo(const char* entry) { return ""; }
// --- local C++ methods
PortableServer::ObjectId * getId();
Engines_Parallel_Container_i *GetContainerPtr();
- bool setStudyId(CORBA::Long studyId);
- static bool isMultiStudy();
static bool isMultiInstance();
static std::string GetDynLibraryName(const char *componentName);
@@ -146,8 +142,6 @@ public:
Engines::Parallel_Salome_file_proxy_impl * file);
protected:
- int _studyId; // -1: not initialised; 0: multiStudy; >0: study
- static bool _isMultiStudy;
static bool _isMultiInstance;
std::string _instanceName ;
diff --git a/src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx b/src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx
index c3ef5afcf..3e4445d72 100644
--- a/src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx
+++ b/src/ParallelContainer/SALOME_ParallelContainerProxy_i.cxx
@@ -216,7 +216,7 @@ Container_proxy_impl_final::load_component_Library(const char* componentName, CO
PyObject *result = PyObject_CallMethod(pyCont,
(char*)"import_component",
(char*)"s",componentName);
- std::string ret_p= PyString_AsString(result);
+ std::string ret_p= PyUnicode_AsUTF8(result);
Py_XDECREF(result);
Py_RELEASE_NEW_THREAD;
@@ -275,11 +275,11 @@ Container_proxy_impl_final::load_component_Library(const char* componentName, CO
}
Engines::EngineComponent_ptr
-Container_proxy_impl_final::create_component_instance(const char* componentName, ::CORBA::Long studyId)
+Container_proxy_impl_final::create_component_instance(const char* componentName)
{
Engines::FieldsDict_var env = new Engines::FieldsDict;
char* reason;
- Engines::EngineComponent_ptr compo = create_component_instance_env(componentName, studyId, env, reason);
+ Engines::EngineComponent_ptr compo = create_component_instance_env(componentName, env, reason);
CORBA::string_free(reason);
return compo;
}
@@ -289,7 +289,7 @@ Container_proxy_impl_final::create_component_instance(const char* componentName,
// Composant parallèle -> création du proxy ici puis appel de la création de chaque objet participant
// au composant parallèle
Engines::EngineComponent_ptr
-Container_proxy_impl_final::create_component_instance_env(const char* componentName, ::CORBA::Long studyId,
+Container_proxy_impl_final::create_component_instance_env(const char* componentName,
const Engines::FieldsDict& env, CORBA::String_out reason)
{
reason=CORBA::string_dup("");
@@ -309,7 +309,7 @@ Container_proxy_impl_final::create_component_instance_env(const char* componentN
_numInstance++;
_numInstanceMutex.unlock();
Engines::PACO_Container_proxy_impl::updateInstanceNumber();
- return Engines::Container_proxy_impl::create_component_instance(componentName, studyId);
+ return Engines::Container_proxy_impl::create_component_instance(componentName);
}
// Parallel Component !
@@ -361,7 +361,7 @@ Container_proxy_impl_final::create_component_instance_env(const char* componentN
instanceName.c_str(),
_parallel_object_topology.total);
- // --- get reference & servant from id
+ // --- get reference from id
CORBA::Object_var obj = _poa->id_to_reference(*(proxy->proxy_id));
component_proxy = Engines::EngineComponent::_narrow(obj);
proxy->proxy_corba_ref = component_proxy;
@@ -400,7 +400,7 @@ Container_proxy_impl_final::create_component_instance_env(const char* componentN
{
try
{
- node->create_paco_component_node_instance(componentName, _containerName.c_str(), studyId);
+ node->create_paco_component_node_instance(componentName, _containerName.c_str());
MESSAGE("Call create_paco_component_node_instance done on node : " << i);
}
catch (SALOME::SALOME_Exception & ex)
diff --git a/src/ParallelContainer/SALOME_ParallelContainerProxy_i.hxx b/src/ParallelContainer/SALOME_ParallelContainerProxy_i.hxx
index 3949f0f82..d825dec45 100644
--- a/src/ParallelContainer/SALOME_ParallelContainerProxy_i.hxx
+++ b/src/ParallelContainer/SALOME_ParallelContainerProxy_i.hxx
@@ -54,10 +54,8 @@ class Container_proxy_impl_final :
virtual void Shutdown();
virtual ::CORBA::Boolean load_component_Library(const char* componentName,CORBA::String_out reason);
- virtual Engines::EngineComponent_ptr create_component_instance (const char* componentName,
- ::CORBA::Long studyId);
+ virtual Engines::EngineComponent_ptr create_component_instance (const char* componentName);
virtual Engines::EngineComponent_ptr create_component_instance_env (const char* componentName,
- CORBA::Long studyId, // 0 for multiStudy
const Engines::FieldsDict& env,
CORBA::String_out reason);
diff --git a/src/ParallelContainer/SALOME_ParallelContainer_i.cxx b/src/ParallelContainer/SALOME_ParallelContainer_i.cxx
index e4f1c1254..d0a58336e 100644
--- a/src/ParallelContainer/SALOME_ParallelContainer_i.cxx
+++ b/src/ParallelContainer/SALOME_ParallelContainer_i.cxx
@@ -353,7 +353,7 @@ Engines_Parallel_Container_i::load_component_Library(const char* componentName,
PyObject *result = PyObject_CallMethod(pyCont,
(char*)"import_component",
(char*)"s",componentName);
- std::string ret_p= PyString_AsString(result);
+ std::string ret_p= PyUnicode_AsUTF8(result);
Py_XDECREF(result);
Py_RELEASE_NEW_THREAD;
@@ -380,18 +380,15 @@ Engines_Parallel_Container_i::load_component_Library(const char* componentName,
* The servant registers itself to naming service and Registry.
* \param genericRegisterName Name of the component instance to register
* in Registry & Name Service (without _inst_n suffix)
- * \param studyId 0 for multiStudy instance,
- * study Id (>0) otherwise
* \return a loaded component
*/
//=============================================================================
Engines::EngineComponent_ptr
-Engines_Parallel_Container_i::create_component_instance(const char*genericRegisterName,
- CORBA::Long studyId)
+Engines_Parallel_Container_i::create_component_instance(const char*genericRegisterName)
{
Engines::FieldsDict_var env = new Engines::FieldsDict;
char* reason;
- Engines::EngineComponent_ptr compo = create_component_instance_env(genericRegisterName,studyId,env, reason);
+ Engines::EngineComponent_ptr compo = create_component_instance_env(genericRegisterName,env, reason);
CORBA::string_free(reason);
return compo;
}
@@ -403,8 +400,6 @@ Engines_Parallel_Container_i::create_component_instance(const char*genericRegist
* The servant registers itself to naming service and Registry.
* \param genericRegisterName Name of the component instance to register
* in Registry & Name Service (without _inst_n suffix)
- * \param studyId 0 for multiStudy instance,
- * study Id (>0) otherwise
* \param env dict of environment variables
* \return a loaded component
*/
@@ -412,19 +407,12 @@ Engines_Parallel_Container_i::create_component_instance(const char*genericRegist
Engines::EngineComponent_ptr
Engines_Parallel_Container_i::create_component_instance_env(const char*genericRegisterName,
- CORBA::Long studyId,
const Engines::FieldsDict& env,
CORBA::String_out reason)
{
MESSAGE("Begin of create_component_instance in node : " << getMyRank());
reason=CORBA::string_dup("");
- if (studyId < 0)
- {
- INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
- return Engines::EngineComponent::_nil() ;
- }
-
std::string aCompName = genericRegisterName;
#ifndef WIN32
#ifdef __APPLE__
@@ -456,9 +444,9 @@ Engines_Parallel_Container_i::create_component_instance_env(const char*genericRe
Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil();
if (type_of_lib == "cpp")
- iobject = createCPPInstance(aCompName, handle, studyId);
+ iobject = createCPPInstance(aCompName, handle);
else
- iobject = createPythonInstance(aCompName, studyId);
+ iobject = createPythonInstance(aCompName);
_numInstanceMutex.unlock();
return iobject._retn();
@@ -470,14 +458,11 @@ Engines_Parallel_Container_i::create_component_instance_env(const char*genericRe
* CORBA method: Finds a servant instance of a component
* \param registeredName Name of the component in Registry or Name Service,
* without instance suffix number
- * \param studyId 0 if instance is not associated to a study,
- * >0 otherwise (== study id)
- * \return the first instance found with same studyId
+ * \return the first found instance
*/
//=============================================================================
-Engines::EngineComponent_ptr Engines_Parallel_Container_i::find_component_instance( const char* registeredName,
- CORBA::Long studyId)
+Engines::EngineComponent_ptr Engines_Parallel_Container_i::find_component_instance(const char* registeredName)
{
Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
std::map::iterator itm =_listInstances_map.begin();
@@ -488,10 +473,7 @@ Engines::EngineComponent_ptr Engines_Parallel_Container_i::find_component_instan
if (instance.find(registeredName) == 0)
{
anEngine = (*itm).second;
- if (studyId == anEngine->getStudyId())
- {
- return anEngine._retn();
- }
+ return anEngine._retn();
}
itm++;
}
@@ -737,22 +719,11 @@ Engines_Parallel_Container_i::find_or_create_instance(std::string genericRegiste
CORBA::Object_var obj = _NS->ResolveFirst(component_registerBase.c_str());
if (CORBA::is_nil( obj ))
{
- iobject = create_component_instance(genericRegisterName.c_str(),
- 0); // force multiStudy instance here !
+ iobject = create_component_instance(genericRegisterName.c_str());
}
else
{
iobject = Engines::EngineComponent::_narrow(obj) ;
- Engines_Component_i *servant = dynamic_cast(_poa->reference_to_servant(iobject));
- ASSERT(servant)
- int studyId = servant->getStudyId();
- ASSERT (studyId >= 0);
- if (studyId != 0) // monoStudy instance: NOK
- {
- iobject = Engines::EngineComponent::_nil();
- INFOS("load_impl & find_component_instance methods "
- << "NOT SUITABLE for mono study components");
- }
}
}
catch (...)
@@ -770,8 +741,6 @@ Engines_Parallel_Container_i::find_or_create_instance(std::string genericRegiste
* in Registry & Name Service,
* (without _inst_n suffix, like "COMPONENT")
* \param handle loaded library handle
- * \param studyId 0 for multiStudy instance,
- * study Id (>0) otherwise
* \return a loaded component
*
* example with names:
@@ -784,7 +753,7 @@ Engines_Parallel_Container_i::find_or_create_instance(std::string genericRegiste
*/
//=============================================================================
Engines::EngineComponent_ptr
-Engines_Parallel_Container_i::createPythonInstance(std::string genericRegisterName, int studyId)
+Engines_Parallel_Container_i::createPythonInstance(std::string genericRegisterName)
{
Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil();
@@ -801,10 +770,9 @@ Engines_Parallel_Container_i::createPythonInstance(std::string genericRegisterNa
PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
PyObject *result = PyObject_CallMethod(pyCont,
(char*)"create_component_instance",
- (char*)"ssl",
+ (char*)"ss",
genericRegisterName.c_str(),
- instanceName.c_str(),
- studyId);
+ instanceName.c_str());
const char *ior;
const char *error;
PyArg_ParseTuple(result,"ss", &ior, &error);
@@ -832,8 +800,6 @@ Engines_Parallel_Container_i::createPythonInstance(std::string genericRegisterNa
* in Registry & Name Service,
* (without _inst_n suffix, like "COMPONENT")
* \param handle loaded library handle
- * \param studyId 0 for multiStudy instance,
- * study Id (>0) otherwise
* \return a loaded component
*
* example with names:
@@ -847,8 +813,7 @@ Engines_Parallel_Container_i::createPythonInstance(std::string genericRegisterNa
//=============================================================================
Engines::EngineComponent_ptr
Engines_Parallel_Container_i::createCPPInstance(std::string genericRegisterName,
- void *handle,
- int studyId)
+ void *handle)
{
MESSAGE("Entering Engines_Parallel_Container_i::createCPPInstance");
@@ -902,22 +867,12 @@ Engines_Parallel_Container_i::createCPPInstance(std::string genericRegisterName,
return iobject._retn();
}
- // --- get reference & servant from id
+ // --- get reference from id
CORBA::Object_var obj = _poa->id_to_reference(*id);
iobject = Engines::EngineComponent::_narrow(obj);
- Engines_Component_i *servant =
- dynamic_cast(_poa->reference_to_servant(iobject));
- ASSERT(servant);
- servant->_remove_ref(); // compensate previous id_to_reference
_listInstances_map[instanceName] = iobject;
_cntInstances_map[aGenRegisterName] += 1;
-#if defined(_DEBUG_) || defined(_DEBUG)
- bool ret_studyId = servant->setStudyId(studyId);
- ASSERT(ret_studyId);
-#else
- servant->setStudyId(studyId);
-#endif
// --- register the engine under the name
// containerName(.dir)/instanceName(.object)
@@ -933,8 +888,7 @@ Engines_Parallel_Container_i::createCPPInstance(std::string genericRegisterName,
void
Engines_Parallel_Container_i::create_paco_component_node_instance(const char* componentName,
- const char* proxy_containerName,
- CORBA::Long studyId)
+ const char* proxy_containerName)
{
// Init de la méthode
char * proxy_ior;
@@ -1003,7 +957,7 @@ Engines_Parallel_Container_i::create_paco_component_node_instance(const char* co
id = (Component_factory) (_orb, proxy_ior, getMyRank(), _poa, _id, instanceName.c_str(), componentName);
CORBA::string_free(proxy_ior);
- // --- get reference & servant from id
+ // --- get reference from id
CORBA::Object_var obj = _poa->id_to_reference(*id);
work_node = Engines::EngineComponent_PaCO::_narrow(obj) ;
if (CORBA::is_nil(work_node))
diff --git a/src/ParallelContainer/SALOME_ParallelContainer_i.hxx b/src/ParallelContainer/SALOME_ParallelContainer_i.hxx
index b99f8f782..52d232dce 100644
--- a/src/ParallelContainer/SALOME_ParallelContainer_i.hxx
+++ b/src/ParallelContainer/SALOME_ParallelContainer_i.hxx
@@ -20,7 +20,7 @@
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// File : SALOME_ParallelContainer_i.hxx
-// Author : André RIBES, EDF
+// Author : Andr� RIBES, EDF
#ifndef _SALOME_PARALLEL_CONTAINER_I_HXX_
#define _SALOME_PARALLEL_CONTAINER_I_HXX_
@@ -73,12 +73,10 @@ public:
virtual bool load_component_Library(const char* componentName, CORBA::String_out reason);
virtual Engines::EngineComponent_ptr
- create_component_instance( const char* componentName,
- CORBA::Long studyId); // 0 for multiStudy
+ create_component_instance( const char* componentName);
virtual Engines::EngineComponent_ptr
create_component_instance_env( const char* componentName,
- CORBA::Long studyId, // 0 for multiStudy
const Engines::FieldsDict& env,
CORBA::String_out reason);
@@ -87,8 +85,7 @@ public:
CORBA::String_out reason);
Engines::EngineComponent_ptr
- find_component_instance( const char* registeredName,
- CORBA::Long studyId); // 0 for multiStudy
+ find_component_instance( const char* registeredName);
Engines::EngineComponent_ptr
load_impl(const char* nameToRegister,
@@ -96,8 +93,7 @@ public:
void
create_paco_component_node_instance(const char* componentName,
- const char* proxy_containerName,
- CORBA::Long studyId); // 0 for multiStudy
+ const char* proxy_containerName);
void updateInstanceNumber();
@@ -123,12 +119,10 @@ public:
Engines::EngineComponent_ptr
createCPPInstance(std::string genericRegisterName,
- void *handle,
- int studyId);
+ void *handle);
Engines::EngineComponent_ptr
- createPythonInstance(std::string genericRegisterName,
- int studyId);
+ createPythonInstance(std::string genericRegisterName);
static bool isPythonContainer(const char* ContainerName);
static void decInstanceCnt(std::string genericRegisterName);
@@ -167,8 +161,8 @@ protected:
_fileRef_map_t _fileRef_map;
_Salome_file_map_t _Salome_file_map;
- // Cette map contient les references vers les différentes
- // instances d'objets parallèles.
+ // Cette map contient les references vers les diff�rentes
+ // instances d'objets parall�les.
std::map _par_obj_inst_map;
typedef PortableServer::ObjectId * (*FACTORY_FUNCTION) (CORBA::ORB_ptr, char *, int,
diff --git a/src/SALOMEDS/CMakeLists.txt b/src/SALOMEDS/CMakeLists.txt
index 894e6f744..14ae84208 100755
--- a/src/SALOMEDS/CMakeLists.txt
+++ b/src/SALOMEDS/CMakeLists.txt
@@ -57,13 +57,13 @@ SET(COMMON_LIBS
SalomeGenericObj
SalomeLifeCycleCORBA
SalomeIDLKernel
+ SalomeDSClient
${HDF5_C_LIBRARIES}
)
SET(SalomeDS_SOURCES
SALOMEDS.cxx
SALOMEDS_Driver_i.cxx
- SALOMEDS_StudyManager_i.cxx
SALOMEDS_UseCaseBuilder_i.cxx
SALOMEDS_UseCaseIterator_i.cxx
SALOMEDS_ChildIterator_i.cxx
@@ -112,7 +112,6 @@ SET(SalomeDS_SOURCES
SALOMEDS_UseCaseBuilder.cxx
SALOMEDS_StudyBuilder.cxx
SALOMEDS_Study.cxx
- SALOMEDS_StudyManager.cxx
SALOMEDS_AttributeStudyProperties.cxx
SALOMEDS_AttributeComment.cxx
SALOMEDS_AttributeDrawable.cxx
@@ -166,9 +165,7 @@ INSTALL(TARGETS SALOMEDS_Server SALOMEDS_Client
SALOME_INSTALL_SCRIPTS(SALOME_DriverPy.py ${SALOME_INSTALL_SCRIPT_PYTHON})
SET(COMMON_HEADERS_HXX
- SALOMEDS_StudyManager_i.hxx
SALOMEDS_Driver_i.hxx
- SALOMEDS_StudyManager.hxx
SALOMEDS_Study_i.hxx
SALOMEDS_Study.hxx
SALOMEDS_SObject_i.hxx
diff --git a/src/SALOMEDS/SALOMEDS.cxx b/src/SALOMEDS/SALOMEDS.cxx
index e6313314b..b6fdf918b 100644
--- a/src/SALOMEDS/SALOMEDS.cxx
+++ b/src/SALOMEDS/SALOMEDS.cxx
@@ -27,19 +27,19 @@
// $Header$
//
#include "SALOMEDS.hxx"
-#include "SALOMEDS_StudyManager.hxx"
#include "SALOMEDS_Study.hxx"
+#include "SALOMEDS_Study_i.hxx"
#include "SALOMEDS_StudyBuilder.hxx"
#include "SALOMEDS_SObject.hxx"
#include "SALOMEDS_SComponent.hxx"
#include "SALOMEDSClient.hxx"
#include "SALOMEDSClient_IParameters.hxx"
#include "SALOMEDS_IParameters.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
-#include "utilities.h"
#include "SALOMEDS_Defines.hxx"
+#include
+
// IDL headers
#include
#include CORBA_SERVER_HEADER(SALOMEDS)
@@ -63,12 +63,10 @@ void SALOMEDS::lock()
void SALOMEDS::unlock()
{
- SALOMEDS::Locker::MutexDS.unlock();
+ SALOMEDS::Locker::MutexDS.unlock();
}
-
-
-// srn: Added new library methods that create basic SALOMEDS objects (StudyManager, Study, SComponent, SObject)
+// srn: Added new library methods that create basic SALOMEDS objects (Study, SComponent, SObject)
//=============================================================================
/*!
@@ -79,99 +77,86 @@ void SALOMEDS::unlock()
extern "C"
{
-SALOMEDS_EXPORT
- SALOMEDSClient_StudyManager* StudyManagerFactory()
-{
- return new SALOMEDS_StudyManager();
-}
-SALOMEDS_EXPORT
+ SALOMEDS_EXPORT
SALOMEDSClient_Study* StudyFactory(SALOMEDS::Study_ptr theStudy)
-{
- if(CORBA::is_nil(theStudy)) return NULL;
- return new SALOMEDS_Study(theStudy);
-}
+ {
+ if(CORBA::is_nil(theStudy)) return NULL;
+ return new SALOMEDS_Study(theStudy);
+ }
-SALOMEDS_EXPORT
+ SALOMEDS_EXPORT
SALOMEDSClient_SObject* SObjectFactory(SALOMEDS::SObject_ptr theSObject)
-{
- if(CORBA::is_nil(theSObject)) return NULL;
- return new SALOMEDS_SObject(theSObject);
-}
+ {
+ if(CORBA::is_nil(theSObject)) return NULL;
+ return new SALOMEDS_SObject(theSObject);
+ }
-SALOMEDS_EXPORT
+ SALOMEDS_EXPORT
SALOMEDSClient_SComponent* SComponentFactory(SALOMEDS::SComponent_ptr theSComponent)
-{
- if(CORBA::is_nil(theSComponent)) return NULL;
- return new SALOMEDS_SComponent(theSComponent);
-}
+ {
+ if(CORBA::is_nil(theSComponent)) return NULL;
+ return new SALOMEDS_SComponent(theSComponent);
+ }
-SALOMEDS_EXPORT
+ SALOMEDS_EXPORT
SALOMEDSClient_StudyBuilder* BuilderFactory(SALOMEDS::StudyBuilder_ptr theBuilder)
-{
- if(CORBA::is_nil(theBuilder)) return NULL;
- return new SALOMEDS_StudyBuilder(theBuilder);
-}
+ {
+ if(CORBA::is_nil(theBuilder)) return NULL;
+ return new SALOMEDS_StudyBuilder(theBuilder);
+ }
-SALOMEDS_EXPORT
- SALOMEDSClient_StudyManager* CreateStudyManager(CORBA::ORB_ptr orb, PortableServer::POA_ptr root_poa)
-{
- SALOME_NamingService namingService(orb);
- CORBA::Object_var obj = namingService.Resolve( "/myStudyManager" );
- SALOMEDS::StudyManager_var theManager = SALOMEDS::StudyManager::_narrow( obj );
- if( CORBA::is_nil(theManager) )
+ SALOMEDS_EXPORT
+ void CreateStudy(CORBA::ORB_ptr orb, PortableServer::POA_ptr root_poa)
{
- PortableServer::POAManager_var pman = root_poa->the_POAManager();
- CORBA::PolicyList policies;
- policies.length(2);
- //PortableServer::ThreadPolicy_var threadPol(root_poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL));
- PortableServer::ThreadPolicy_var threadPol(root_poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL));
- PortableServer::ImplicitActivationPolicy_var implicitPol(root_poa->create_implicit_activation_policy(PortableServer::IMPLICIT_ACTIVATION));
- policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
- policies[1] = PortableServer::ImplicitActivationPolicy::_duplicate(implicitPol);
- PortableServer::POA_var poa = root_poa->create_POA("KERNELStudySingleThreadPOA",pman,policies);
- MESSAGE("CreateStudyManager: KERNELStudySingleThreadPOA: "<< poa);
- threadPol->destroy();
-
- SALOMEDS_StudyManager_i * aStudyManager_i = new SALOMEDS_StudyManager_i(orb, poa);
- // Activate the objects. This tells the POA that the objects are ready to accept requests.
- PortableServer::ObjectId_var aStudyManager_iid = poa->activate_object(aStudyManager_i);
- //give ownership to the poa : the object will be deleted by the poa
- aStudyManager_i->_remove_ref();
- aStudyManager_i->register_name((char*)"/myStudyManager");
+ SALOME_NamingService namingService(orb);
+ CORBA::Object_var obj = namingService.Resolve( "/Study" );
+ SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( obj );
+ if( CORBA::is_nil(aStudy) ) {
+ PortableServer::POAManager_var pman = root_poa->the_POAManager();
+ CORBA::PolicyList policies;
+ policies.length(2);
+ //PortableServer::ThreadPolicy_var threadPol(root_poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL));
+ PortableServer::ThreadPolicy_var threadPol(root_poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL));
+ PortableServer::ImplicitActivationPolicy_var implicitPol(root_poa->create_implicit_activation_policy(PortableServer::IMPLICIT_ACTIVATION));
+ policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
+ policies[1] = PortableServer::ImplicitActivationPolicy::_duplicate(implicitPol);
+ PortableServer::POA_var poa = root_poa->create_POA("KERNELStudySingleThreadPOA",pman,policies);
+ MESSAGE("CreateStudy: KERNELStudySingleThreadPOA: "<< poa);
+ threadPol->destroy();
+
+ SALOMEDS_Study_i::SetThePOA(poa);
+ SALOMEDS_Study_i* aStudy_i = new SALOMEDS_Study_i(orb);
+
+ // Activate the objects. This tells the POA that the objects are ready to accept requests.
+ PortableServer::ObjectId_var aStudy_iid = root_poa->activate_object(aStudy_i);
+ aStudy = aStudy_i->_this();
+ namingService.Register(aStudy, "/Study");
+ aStudy_i->GetImpl()->GetDocument()->SetModified(false);
+ aStudy_i->_remove_ref();
+ }
}
- return new SALOMEDS_StudyManager();
-}
-SALOMEDS_EXPORT
+ SALOMEDS_EXPORT
SALOMEDSClient_IParameters* GetIParameters(const _PTR(AttributeParameter)& ap)
-{
- return new SALOMEDS_IParameters(ap);
-}
+ {
+ return new SALOMEDS_IParameters(ap);
+ }
-SALOMEDS_EXPORT
+ SALOMEDS_EXPORT
SALOMEDS::SObject_ptr ConvertSObject(const _PTR(SObject)& theSObject)
-{
-
- SALOMEDS_SObject* so = _CAST(SObject, theSObject);
- if(!theSObject || !so) return SALOMEDS::SObject::_nil();
- return so->GetSObject();
-}
-
-SALOMEDS_EXPORT
- SALOMEDS::Study_ptr ConvertStudy(const _PTR(Study)& theStudy)
-{
- SALOMEDS_Study* study = _CAST(Study, theStudy);
- if(!theStudy || !study) return SALOMEDS::Study::_nil();
- return study->GetStudy();
-}
+ {
+ SALOMEDS_SObject* so = _CAST(SObject, theSObject);
+ if ( !theSObject || !so )
+ return SALOMEDS::SObject::_nil();
+ return so->GetSObject();
+ }
-SALOMEDS_EXPORT
+ SALOMEDS_EXPORT
SALOMEDS::StudyBuilder_ptr ConvertBuilder(const _PTR(StudyBuilder)& theBuilder)
-{
- SALOMEDS_StudyBuilder* builder = _CAST(StudyBuilder, theBuilder);
- if(!theBuilder || !builder) return SALOMEDS::StudyBuilder::_nil();
- return builder->GetBuilder();
-}
-
-
+ {
+ SALOMEDS_StudyBuilder* builder = _CAST(StudyBuilder, theBuilder);
+ if ( !theBuilder || !builder )
+ return SALOMEDS::StudyBuilder::_nil();
+ return builder->GetBuilder();
+ }
}
diff --git a/src/SALOMEDS/SALOMEDS_ChildIterator_i.cxx b/src/SALOMEDS/SALOMEDS_ChildIterator_i.cxx
index 3a17656b0..574cf45b0 100644
--- a/src/SALOMEDS/SALOMEDS_ChildIterator_i.cxx
+++ b/src/SALOMEDS/SALOMEDS_ChildIterator_i.cxx
@@ -25,7 +25,7 @@
// Module : SALOME
//
#include "SALOMEDS_ChildIterator_i.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
+#include "SALOMEDS_Study_i.hxx"
#include "SALOMEDS_SObject_i.hxx"
#include "SALOMEDS.hxx"
#include "SALOMEDSImpl_SObject.hxx"
@@ -39,7 +39,7 @@
//============================================================================
SALOMEDS_ChildIterator_i::SALOMEDS_ChildIterator_i(const SALOMEDSImpl_ChildIterator& theImpl,
CORBA::ORB_ptr orb) :
- GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA()),
+ GenericObj_i(SALOMEDS_Study_i::GetThePOA()),
_it(theImpl.GetPersistentCopy())
{
SALOMEDS::Locker lock;
@@ -68,7 +68,7 @@ SALOMEDS_ChildIterator_i::~SALOMEDS_ChildIterator_i()
//============================================================================
PortableServer::POA_ptr SALOMEDS_ChildIterator_i::_default_POA()
{
- myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
+ myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
//MESSAGE("SALOMEDS_ChildIterator_i::_default_POA: " << myPOA);
return PortableServer::POA::_duplicate(myPOA);
}
diff --git a/src/SALOMEDS/SALOMEDS_Client.cxx b/src/SALOMEDS/SALOMEDS_Client.cxx
index 2650e1d0a..db0f0e245 100644
--- a/src/SALOMEDS/SALOMEDS_Client.cxx
+++ b/src/SALOMEDS/SALOMEDS_Client.cxx
@@ -28,8 +28,9 @@
//
#include
#include CORBA_SERVER_HEADER(SALOMEDS)
-#include "SALOMEDS_StudyManager_i.hxx"
#include "SALOMEDS_AttributeName_i.hxx"
+#include "SALOME_KernelServices.hxx"
+#include "Basics_Utils.hxx"
#include "utilities.h"
#include "HDFOI.hxx"
@@ -38,9 +39,9 @@
* Purpose :
*/
//============================================================================
-static void DumpComponent(SALOMEDS::Study_ptr Study,SALOMEDS::SObject_ptr SO, int offset) {
+static void DumpComponent(SALOMEDS::SObject_ptr SO, int offset) {
SALOMEDS::SObject_var RefSO;
- SALOMEDS::ChildIterator_var it = Study->NewChildIterator(SO);
+ SALOMEDS::ChildIterator_var it = KERNEL::getStudyServant()->NewChildIterator(SO);
for (; it->More();it->Next()){
SALOMEDS::SObject_var CSO= it->Value();
SALOMEDS::GenericAttribute_var anAttr;
@@ -57,7 +58,7 @@ static void DumpComponent(SALOMEDS::Study_ptr Study,SALOMEDS::SObject_ptr SO, in
MESSAGE(" ");
MESSAGE("*Reference"<GetID());
}
- DumpComponent(Study,CSO,offset+2);
+ DumpComponent(CSO,offset+2);
}
}
@@ -66,17 +67,17 @@ static void DumpComponent(SALOMEDS::Study_ptr Study,SALOMEDS::SObject_ptr SO, in
* Purpose :
*/
//============================================================================
-static void DumpStudy (SALOMEDS::Study_ptr Study) {
+static void DumpStudy() {
MESSAGE("Explore Study and Write name of each object if it exists");
char* name;
- SALOMEDS::SComponentIterator_var itcomp = Study->NewComponentIterator();
+ SALOMEDS::SComponentIterator_var itcomp = KERNEL::getStudyServant()->NewComponentIterator();
int offset = 1;
for (; itcomp->More(); itcomp->Next()) {
SALOMEDS::SComponent_var SC = itcomp->Value();
name = SC->ComponentDataType();
MESSAGE("-> ComponentDataType is "<NewStudy("Study1");
-
+
+ SALOMEDS::Study_var myStudy = KERNEL::getStudyServant();
+
MESSAGE("Create Builder ");
SALOMEDS::StudyBuilder_var StudyBuild = myStudy->NewBuilder();
-
// Create new components
SALOMEDS::GenericAttribute_var anAttr;
SALOMEDS::AttributeName_var Name;
@@ -186,62 +186,35 @@ static void Test(SALOMEDS::StudyManager_ptr myStudyMgr )
Name->SetValue("mesh_cylinder_0");
StudyBuild->CommitCommand();
- MESSAGE("Test GetStudy");
- SALOMEDS::Study_var stu = mesh_cylinder->GetStudy();
- MESSAGE ("-> Study Name is "<Name());
-
- DumpStudy(myStudy);
+ DumpStudy();
StudyBuild->Undo();
// Study should have no trace of object mesh_cylinder
- DumpStudy(myStudy);
-
-
- //myStudyMgr->Open ((char*)name);
- //MESSAGE("Name " << name);
-
- // GetOpenStudies
- MESSAGE("GetOpenStudies list");
- SALOMEDS::ListOfOpenStudies_var _list_open_studies = myStudyMgr->GetOpenStudies();
-
- for (unsigned int ind = 0; ind < _list_open_studies->length();ind++)
- {
- MESSAGE("Open studies list : " << _list_open_studies[ind]);
- }
-
-
- // GetStudyByName
- SALOMEDS::Study_var myStudy1 =myStudyMgr->GetStudyByName(_list_open_studies[0]);
- MESSAGE("GetStudyByName done");
+ DumpStudy();
// Save as
- myStudyMgr->SaveAs("/home/edeville/Study1.hdf",myStudy1, false);
+ myStudy->SaveAs(Kernel_Utils::decode("/home/edeville/Study1.hdf"), false, false);
// Get Persistent Reference of the study test
- name = myStudy1->GetPersistentReference();
+ name = myStudy->GetPersistentReference();
MESSAGE("Persitent Reference of the study " << name);
- // Get Transient Reference of the study test
- name = myStudy1->GetTransientReference();
- MESSAGE("Transient Reference of the study " << name);
-
// FindComponent Test
- SALOMEDS::SComponent_var compo = myStudy1->FindComponent("GEOM");
+ SALOMEDS::SComponent_var compo = myStudy->FindComponent("GEOM");
// Get ComponentDataType test
MESSAGE("Find ComponentDataType of compo");
name = compo->ComponentDataType();
- MESSAGE("-> ComponentDataType is "< ComponentDataType is "<FindComponentID("0:1:2");
+ SALOMEDS::SComponent_var compo1 = myStudy->FindComponentID("0:1:2");
// Get ComponentDataType test
MESSAGE("Find ComponentDataType of compo1");
name = compo1->ComponentDataType();
- MESSAGE("-> ComponentDataType is "< ComponentDataType is "<FindObject("cylinder_0");
+ SALOMEDS::SObject_var objn = myStudy->FindObject("cylinder_0");
// Test FindAttribute function : get AttributeName attribute
MESSAGE("Find Name in object objn");
if (objn->FindAttribute(anAttr, "AttributeName")) {
@@ -254,7 +227,7 @@ static void Test(SALOMEDS::StudyManager_ptr myStudyMgr )
}
// FindObjectID Test
- SALOMEDS::SObject_var obj = myStudy1->FindObjectID("0:1:2:1:1");
+ SALOMEDS::SObject_var obj = myStudy->FindObjectID("0:1:2:1:1");
// Test FindAttribute function : get AttributeName attribute
MESSAGE("Find Name in object obj");
if (obj->FindAttribute(anAttr, "AttributeName")) {
@@ -265,7 +238,7 @@ static void Test(SALOMEDS::StudyManager_ptr myStudyMgr )
else {
MESSAGE("-> Name is not found");
}
- //DumpStudy(myStudy1);
+ //DumpStudy();
}
catch(HDFexception)
{
@@ -289,19 +262,13 @@ int main(int argc, char** argv)
CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);
- SALOME_NamingService * salomens = new SALOME_NamingService(orb);
-
- MESSAGE("Find StudyManager ");
- CORBA::Object_ptr obj2 = salomens->Resolve("myStudyManager");
- SALOMEDS::StudyManager_var myStudyMgr = SALOMEDS::StudyManager::_narrow(obj2);
-
// Obtain a POAManager, and tell the POA to start accepting
// requests on its objects.
PortableServer::POAManager_var pman = poa->the_POAManager();
pman->activate();
// Test basic services
- Test(myStudyMgr);
+ Test();
orb->run();
orb->destroy();
diff --git a/src/SALOMEDS/SALOMEDS_Driver_i.cxx b/src/SALOMEDS/SALOMEDS_Driver_i.cxx
index c0f78849f..3c6116ad4 100644
--- a/src/SALOMEDS/SALOMEDS_Driver_i.cxx
+++ b/src/SALOMEDS/SALOMEDS_Driver_i.cxx
@@ -28,6 +28,7 @@
#include "SALOMEDS_Study_i.hxx"
#include "SALOMEDS.hxx"
#include
+#include
#include
#include CORBA_CLIENT_HEADER(SALOME_Session)
@@ -321,22 +322,18 @@ std::string SALOMEDS_Driver_i::PasteInto(const unsigned char* theStream,
return entry;
}
-SALOMEDSImpl_TMPFile* SALOMEDS_Driver_i::DumpPython(SALOMEDSImpl_Study* theStudy,
- bool isPublished,
+SALOMEDSImpl_TMPFile* SALOMEDS_Driver_i::DumpPython(bool isPublished,
bool isMultiFile,
bool& isValidScript,
long& theStreamLength)
{
- SALOMEDS_Study_i * st_servant = SALOMEDS_Study_i::GetStudyServant(theStudy, _orb);//new SALOMEDS_Study_i (theStudy, _orb);
- SALOMEDS::Study_var st = SALOMEDS::Study::_narrow(st_servant->_this());
-
SALOMEDS::unlock();
Engines::TMPFile_var aStream;
CORBA::Boolean aValidScript = true; // VSR: maybe should be false by default ???
if ( !CORBA::is_nil( _engine ) )
- aStream = _engine->DumpPython(st.in(), isPublished, isMultiFile, aValidScript);
+ aStream = _engine->DumpPython(isPublished, isMultiFile, aValidScript);
SALOMEDSImpl_TMPFile* aTMPFile = new Engines_TMPFile_i(aStream._retn());
theStreamLength = aTMPFile->Size();
diff --git a/src/SALOMEDS/SALOMEDS_Driver_i.hxx b/src/SALOMEDS/SALOMEDS_Driver_i.hxx
index c07c30eb4..1b1809b30 100644
--- a/src/SALOMEDS/SALOMEDS_Driver_i.hxx
+++ b/src/SALOMEDS/SALOMEDS_Driver_i.hxx
@@ -98,8 +98,7 @@ public:
int theObjectID,
const SALOMEDSImpl_SObject& theObject);
- virtual SALOMEDSImpl_TMPFile* DumpPython(SALOMEDSImpl_Study* theStudy,
- bool isPublished,
+ virtual SALOMEDSImpl_TMPFile* DumpPython(bool isPublished,
bool isMultiFile,
bool& isValidScript,
long& theStreamLength);
diff --git a/src/SALOMEDS/SALOMEDS_GenericAttribute_i.cxx b/src/SALOMEDS/SALOMEDS_GenericAttribute_i.cxx
index 114c0a228..7014f54c8 100644
--- a/src/SALOMEDS/SALOMEDS_GenericAttribute_i.cxx
+++ b/src/SALOMEDS/SALOMEDS_GenericAttribute_i.cxx
@@ -26,7 +26,7 @@
//
#include "utilities.h"
#include "SALOMEDS_GenericAttribute_i.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
+#include "SALOMEDS_Study_i.hxx"
#include "SALOMEDS_Attributes.hxx"
#include "SALOMEDS.hxx"
#include "SALOMEDSImpl_SObject.hxx"
@@ -45,7 +45,7 @@
UNEXPECT_CATCH(GALockProtection, SALOMEDS::GenericAttribute::LockProtection);
SALOMEDS_GenericAttribute_i::SALOMEDS_GenericAttribute_i(DF_Attribute* theImpl, CORBA::ORB_ptr theOrb) :
- GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA())
+ GenericObj_i(SALOMEDS_Study_i::GetThePOA())
{
_orb = CORBA::ORB::_duplicate(theOrb);
_impl = theImpl;
@@ -67,7 +67,7 @@ SALOMEDS_GenericAttribute_i::~SALOMEDS_GenericAttribute_i()
//============================================================================
PortableServer::POA_ptr SALOMEDS_GenericAttribute_i::_default_POA()
{
- myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
+ myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
//MESSAGE("SALOMEDS_GenericAttribute_i::_default_POA: " << myPOA);
return PortableServer::POA::_duplicate(myPOA);
}
diff --git a/src/SALOMEDS/SALOMEDS_IParameters.cxx b/src/SALOMEDS/SALOMEDS_IParameters.cxx
index 8329a78ef..a7104f459 100644
--- a/src/SALOMEDS/SALOMEDS_IParameters.cxx
+++ b/src/SALOMEDS/SALOMEDS_IParameters.cxx
@@ -21,6 +21,8 @@
//
#include "SALOMEDS_IParameters.hxx"
+#include
+#include
#include
#define PT_INTEGER 0
@@ -46,8 +48,6 @@ SALOMEDS_IParameters::SALOMEDS_IParameters(const _PTR(AttributeParameter)& ap)
{
if(!ap) return;
_ap = ap;
- _PTR(SObject) so = _ap->GetSObject();
- _study = so->GetStudy();
}
SALOMEDS_IParameters::~SALOMEDS_IParameters()
@@ -258,14 +258,13 @@ std::string SALOMEDS_IParameters::encodeEntry(const std::string& entry, const st
std::string SALOMEDS_IParameters::decodeEntry(const std::string& entry)
{
- if(!_study) return entry;
int pos = entry.rfind("_");
if(pos < 0 || pos >= entry.length()) return entry;
std::string compName(entry, 0, pos), compID, tail(entry, pos+1, entry.length()-1);
if(_compNames.find(compName) == _compNames.end()) {
- _PTR(SObject) so = _study->FindComponent(compName);
+ _PTR(SObject) so = ClientFactory::Study(KERNEL::getStudyServant())->FindComponent(compName);
if(!so) return entry;
compID = so->GetID();
_compNames[compName] = compID;
@@ -278,23 +277,23 @@ std::string SALOMEDS_IParameters::decodeEntry(const std::string& entry)
return newEntry;
}
-void SALOMEDS_IParameters::setDumpPython(_PTR(Study) study, const std::string& theID)
+void SALOMEDS_IParameters::setDumpPython(const std::string& theID)
{
std::string anID;
if(theID == "") anID = getDefaultVisualComponent();
else anID = theID;
- _PTR(AttributeParameter) ap = study->GetCommonParameters(anID, 0);
- ap->SetBool(_AP_DUMP_PYTHON_, !isDumpPython(study, theID));
+ _PTR(AttributeParameter) ap = ClientFactory::Study(KERNEL::getStudyServant())->GetCommonParameters(anID, 0);
+ ap->SetBool(_AP_DUMP_PYTHON_, !isDumpPython(theID));
}
-bool SALOMEDS_IParameters::isDumpPython(_PTR(Study) study, const std::string& theID)
+bool SALOMEDS_IParameters::isDumpPython(const std::string& theID)
{
std::string anID;
if(theID == "") anID = getDefaultVisualComponent();
else anID = theID;
- _PTR(AttributeParameter) ap = study->GetCommonParameters(anID, 0);
+ _PTR(AttributeParameter) ap = ClientFactory::Study(KERNEL::getStudyServant())->GetCommonParameters(anID, 0);
if(!ap) return false;
if(!ap->IsSet(_AP_DUMP_PYTHON_, PT_BOOLEAN)) return false;
return (bool)ap->GetBool(_AP_DUMP_PYTHON_);
diff --git a/src/SALOMEDS/SALOMEDS_IParameters.hxx b/src/SALOMEDS/SALOMEDS_IParameters.hxx
index 24468d011..197eace7d 100644
--- a/src/SALOMEDS/SALOMEDS_IParameters.hxx
+++ b/src/SALOMEDS/SALOMEDS_IParameters.hxx
@@ -142,12 +142,12 @@ public:
/*!
Enables/Disables the dumping visual parameters
*/
- virtual void setDumpPython(_PTR(Study) study, const std::string& theID = "");
+ virtual void setDumpPython(const std::string& theID = "");
/*!
Returns whether there is the dumping visual parameters
*/
- virtual bool isDumpPython(_PTR(Study) study, const std::string& theID = "");
+ virtual bool isDumpPython(const std::string& theID = "");
/*!
Returns a default name of the component where the visula parameters are stored.
@@ -156,7 +156,6 @@ public:
private:
_PTR(AttributeParameter) _ap;
- _PTR(Study) _study;
std::map _compNames;
};
diff --git a/src/SALOMEDS/SALOMEDS_SComponentIterator_i.cxx b/src/SALOMEDS/SALOMEDS_SComponentIterator_i.cxx
index 07b24a93c..35b3b34fb 100644
--- a/src/SALOMEDS/SALOMEDS_SComponentIterator_i.cxx
+++ b/src/SALOMEDS/SALOMEDS_SComponentIterator_i.cxx
@@ -27,7 +27,7 @@
#include "SALOMEDS_SComponentIterator_i.hxx"
#include "SALOMEDS.hxx"
#include "SALOMEDSImpl_SComponent.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
+#include "SALOMEDS_Study_i.hxx"
#include "utilities.h"
//============================================================================
@@ -38,7 +38,7 @@
SALOMEDS_SComponentIterator_i::SALOMEDS_SComponentIterator_i(const SALOMEDSImpl_SComponentIterator& theImpl,
CORBA::ORB_ptr orb) :
- GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA())
+ GenericObj_i(SALOMEDS_Study_i::GetThePOA())
{
_orb = CORBA::ORB::_duplicate(orb);
_impl = theImpl.GetPersistentCopy();
@@ -66,7 +66,7 @@ SALOMEDS_SComponentIterator_i::~SALOMEDS_SComponentIterator_i()
//============================================================================
PortableServer::POA_ptr SALOMEDS_SComponentIterator_i::_default_POA()
{
- myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
+ myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
MESSAGE("SALOMEDS_SComponentIterator_i::_default_POA: " << myPOA);
return PortableServer::POA::_duplicate(myPOA);
}
diff --git a/src/SALOMEDS/SALOMEDS_SObject.cxx b/src/SALOMEDS/SALOMEDS_SObject.cxx
index 88aa17af3..db9ab6fd9 100644
--- a/src/SALOMEDS/SALOMEDS_SObject.cxx
+++ b/src/SALOMEDS/SALOMEDS_SObject.cxx
@@ -196,16 +196,6 @@ bool SALOMEDS_SObject::FindSubObject(int theTag, _PTR(SObject)& theObject)
return ret;
}
-_PTR(Study) SALOMEDS_SObject::GetStudy()
-{
- if (_isLocal) {
- SALOMEDS::Locker lock;
- return _PTR(Study)(new SALOMEDS_Study(_local_impl->GetStudy()));
- }
- SALOMEDS::Study_var study=_corba_impl->GetStudy();
- return _PTR(Study)(new SALOMEDS_Study(study));
-}
-
std::string SALOMEDS_SObject::Name()
{
std::string aName;
diff --git a/src/SALOMEDS/SALOMEDS_SObject.hxx b/src/SALOMEDS/SALOMEDS_SObject.hxx
index 6b77e485c..51c363818 100644
--- a/src/SALOMEDS/SALOMEDS_SObject.hxx
+++ b/src/SALOMEDS/SALOMEDS_SObject.hxx
@@ -60,7 +60,6 @@ public:
virtual bool FindAttribute(_PTR(GenericAttribute)& anAttribute, const std::string& aTypeOfAttribute);
virtual bool ReferencedObject(_PTR(SObject)& theObject);
virtual bool FindSubObject(int theTag, _PTR(SObject)& theObject);
- virtual _PTR(Study) GetStudy();
virtual std::string Name();
virtual void Name(const std::string& theName);
virtual std::vector<_PTR(GenericAttribute)> GetAllAttributes();
diff --git a/src/SALOMEDS/SALOMEDS_SObject_i.cxx b/src/SALOMEDS/SALOMEDS_SObject_i.cxx
index bfff08d5e..36e8cbb4c 100644
--- a/src/SALOMEDS/SALOMEDS_SObject_i.cxx
+++ b/src/SALOMEDS/SALOMEDS_SObject_i.cxx
@@ -26,9 +26,9 @@
//
#include "utilities.h"
#include "SALOMEDS_SObject_i.hxx"
+#include "SALOMEDS_Study_i.hxx"
#include "SALOMEDS_SComponent_i.hxx"
#include "SALOMEDS_GenericAttribute_i.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
#include "SALOMEDS.hxx"
#include "SALOMEDSImpl_GenericAttribute.hxx"
#include "SALOMEDSImpl_SComponent.hxx"
@@ -59,7 +59,7 @@ SALOMEDS::SObject_ptr SALOMEDS_SObject_i::New(const SALOMEDSImpl_SObject& theImp
*/
//============================================================================
SALOMEDS_SObject_i::SALOMEDS_SObject_i(const SALOMEDSImpl_SObject& impl, CORBA::ORB_ptr orb) :
- GenericObj_i(SALOMEDS_StudyManager_i::GetThePOA())
+ GenericObj_i(SALOMEDS_Study_i::GetThePOA())
{
_impl = 0;
if(!impl.IsNull()) {
@@ -72,7 +72,6 @@ SALOMEDS_SObject_i::SALOMEDS_SObject_i(const SALOMEDSImpl_SObject& impl, CORBA::
}
}
_orb = CORBA::ORB::_duplicate(orb);
- //SALOME::GenericObj_i::myPOA = SALOMEDS_StudyManager_i::GetPOA(GetStudy());
}
@@ -98,7 +97,7 @@ SALOMEDS_SObject_i::~SALOMEDS_SObject_i()
//============================================================================
PortableServer::POA_ptr SALOMEDS_SObject_i::_default_POA()
{
- myPOA = PortableServer::POA::_duplicate(SALOMEDS_StudyManager_i::GetThePOA());
+ myPOA = PortableServer::POA::_duplicate(SALOMEDS_Study_i::GetThePOA());
//MESSAGE("SALOMEDS_SObject_i::_default_POA: " << myPOA);
return PortableServer::POA::_duplicate(myPOA);
}
@@ -150,27 +149,6 @@ SALOMEDS::SObject_ptr SALOMEDS_SObject_i::GetFather()
return so._retn();
}
-//============================================================================
-/*! Function :
- * Purpose :
- */
-//============================================================================
-SALOMEDS::Study_ptr SALOMEDS_SObject_i::GetStudy()
-{
- SALOMEDS::Locker lock;
- SALOMEDSImpl_Study* aStudy = _impl->GetStudy();
- if(!aStudy) {
- MESSAGE("Problem GetStudy");
- return SALOMEDS::Study::_nil();
- }
-
- std::string IOR = aStudy->GetTransientReference();
- CORBA::Object_var obj = _orb->string_to_object(IOR.c_str());
- SALOMEDS::Study_var Study = SALOMEDS::Study::_narrow(obj) ;
- ASSERT(!CORBA::is_nil(Study));
- return SALOMEDS::Study::_duplicate(Study);
-}
-
//============================================================================
/*! Function : FindAttribute
* Purpose : Find attribute of given type on this SObject
diff --git a/src/SALOMEDS/SALOMEDS_SObject_i.hxx b/src/SALOMEDS/SALOMEDS_SObject_i.hxx
index 5c0bdc652..a4c68741c 100644
--- a/src/SALOMEDS/SALOMEDS_SObject_i.hxx
+++ b/src/SALOMEDS/SALOMEDS_SObject_i.hxx
@@ -64,7 +64,6 @@ public:
virtual CORBA::Boolean ReferencedObject(SALOMEDS::SObject_out obj) ;
virtual CORBA::Boolean FindSubObject(CORBA::Long atag, SALOMEDS::SObject_out obj );
- virtual SALOMEDS::Study_ptr GetStudy() ;
virtual char* Name();
virtual void Name(const char*);
virtual SALOMEDS::ListOfAttributes* GetAllAttributes();
diff --git a/src/SALOMEDS/SALOMEDS_Server.cxx b/src/SALOMEDS/SALOMEDS_Server.cxx
index 26cce9bb7..7de665e28 100644
--- a/src/SALOMEDS/SALOMEDS_Server.cxx
+++ b/src/SALOMEDS/SALOMEDS_Server.cxx
@@ -30,7 +30,7 @@
#include "Utils_SINGLETON.hxx"
#include "SALOME_NamingService.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
+#include "SALOMEDS_Study_i.hxx"
#include
#include CORBA_SERVER_HEADER(SALOMEDS)
@@ -58,7 +58,8 @@ int main(int argc, char** argv)
CORBA::ORB_var orb = CORBA::ORB_init( argc, argv, "omniORB4" ) ;
#else
CORBA::ORB_var orb = CORBA::ORB_init( argc, argv, "omniORB3" );
-#endif
+#endif
+ SALOME_NamingService* NS = 0;
// Obtain a reference to the root POA.
long TIMESleep = 500000000;
int NumberOfTries = 40;
@@ -121,8 +122,8 @@ int main(int argc, char** argv)
if(EnvL==1)
{
CORBA::ORB_var orb1 = CORBA::ORB_init(argc,argv) ;
- SALOME_NamingService &NS = *SINGLETON_::Instance() ;
- NS.init_orb( orb1 ) ;
+ NS = SINGLETON_::Instance() ;
+ NS->init_orb( orb1 ) ;
for(int j=1; j<=NumberOfTries; j++)
{
if (j!=1)
@@ -167,13 +168,19 @@ int main(int argc, char** argv)
// We allocate the objects on the heap. Since these are reference
// counted objects, they will be deleted by the POA when they are no
// longer needed.
- SALOMEDS_StudyManager_i * myStudyManager_i = new SALOMEDS_StudyManager_i(orb,poa);
+ SALOMEDS_Study_i * myStudy_i = new SALOMEDS_Study_i(orb);
// Activate the objects. This tells the POA that the objects are
// ready to accept requests.
- PortableServer::ObjectId_var myStudyManager_iid = poa->activate_object(myStudyManager_i);
- myStudyManager_i->register_name("/myStudyManager");
- myStudyManager_i->_remove_ref();
+ PortableServer::ObjectId_var myStudy_iid = poa->activate_object(myStudy_i);
+ SALOMEDS::Study_var Study = myStudy_i->_this();
+ if (!NS)
+ {
+ NS = SINGLETON_::Instance();
+ NS->init_orb( orb );
+ }
+ NS->Register(Study, "/Study");
+ myStudy_i->_remove_ref();
// Obtain a POAManager, and tell the POA to start accepting
// requests on its objects.
diff --git a/src/SALOMEDS/SALOMEDS_Study.cxx b/src/SALOMEDS/SALOMEDS_Study.cxx
index 50d658b7d..f7ea3dc15 100644
--- a/src/SALOMEDS/SALOMEDS_Study.cxx
+++ b/src/SALOMEDS/SALOMEDS_Study.cxx
@@ -48,6 +48,8 @@
#include "SALOMEDSImpl_GenericVariable.hxx"
#include "SALOMEDSImpl_UseCaseBuilder.hxx"
+#include
+
#include "SALOMEDS_Driver_i.hxx"
#include "SALOMEDS_Study_i.hxx"
@@ -71,7 +73,7 @@ SALOMEDS_Study::SALOMEDS_Study(SALOMEDSImpl_Study* theStudy)
pthread_mutex_init( &SALOMEDS_StudyBuilder::_remoteBuilderMutex, 0 );
- init_orb();
+ InitORB();
}
SALOMEDS_Study::SALOMEDS_Study(SALOMEDS::Study_ptr theStudy)
@@ -94,32 +96,171 @@ SALOMEDS_Study::SALOMEDS_Study(SALOMEDS::Study_ptr theStudy)
_corba_impl = SALOMEDS::Study::_duplicate(theStudy);
}
- init_orb();
+ InitORB();
}
SALOMEDS_Study::~SALOMEDS_Study()
{
}
-std::string SALOMEDS_Study::GetPersistentReference()
+void SALOMEDS_Study::InitORB()
{
- std::string aRef;
+ ORB_INIT &init = *SINGLETON_::Instance();
+ ASSERT(SINGLETON_::IsAlreadyExisting());
+ _orb = init(0 , 0 ) ;
+}
+
+void SALOMEDS_Study::Init()
+{
+ if(CORBA::is_nil(_corba_impl))
+ return;
+
+ _corba_impl->Init();
+}
+
+void SALOMEDS_Study::Clear()
+{
+ if(CORBA::is_nil(_corba_impl))
+ return;
+
+ _corba_impl->Clear();
+}
+
+bool SALOMEDS_Study::Open(const std::string& theStudyUrl)
+{
+ if(CORBA::is_nil(_corba_impl))
+ return false;
+ std::wstring wtheStudyUrl = std::wstring(theStudyUrl.begin(), theStudyUrl.end());
+
+ if (!_corba_impl->Open( (wchar_t*)wtheStudyUrl.c_str() ) )
+ return false;
+
+ return true;
+}
+
+bool SALOMEDS_Study::Save(bool theMultiFile, bool theASCII)
+{
+ if(CORBA::is_nil(_corba_impl))
+ return false;
+
+ return _corba_impl->Save(theMultiFile, theASCII);
+}
+
+bool SALOMEDS_Study::SaveAs(const std::string& theUrl, bool theMultiFile, bool theASCII)
+{
+ if(CORBA::is_nil(_corba_impl))
+ return false;
+
+ return _corba_impl->SaveAs(Kernel_Utils::decode_s(theUrl), theMultiFile, theASCII);
+}
+
+SALOMEDS_Driver_i* GetDriver(const SALOMEDSImpl_SObject& theObject, CORBA::ORB_ptr orb)
+{
+ SALOMEDS_Driver_i* driver = NULL;
+
+ SALOMEDSImpl_SComponent aSCO = theObject.GetFatherComponent();
+ if(!aSCO.IsNull()) {
+ std::string IOREngine = aSCO.GetIOR();
+ if(!IOREngine.empty()) {
+ CORBA::Object_var obj = orb->string_to_object(IOREngine.c_str());
+ Engines::EngineComponent_var Engine = Engines::EngineComponent::_narrow(obj) ;
+ driver = new SALOMEDS_Driver_i(Engine, orb);
+ }
+ }
+
+ return driver;
+}
+
+bool SALOMEDS_Study::CanCopy(const _PTR(SObject)& theSO)
+{
+ SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
+ bool ret;
+
if (_isLocal) {
SALOMEDS::Locker lock;
- aRef = _local_impl->GetPersistentReference();
+
+ SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
+ SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
+ ret = _local_impl->CanCopy(aSO_impl, aDriver);
+ delete aDriver;
}
- else aRef = (CORBA::String_var)_corba_impl->GetPersistentReference();
- return aRef;
+ else {
+ ret = _corba_impl->CanCopy(aSO->GetCORBAImpl());
+ }
+
+ return ret;
+}
+
+bool SALOMEDS_Study::Copy(const _PTR(SObject)& theSO)
+{
+ SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
+ bool ret;
+ if (_isLocal) {
+ SALOMEDS::Locker lock;
+
+ SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
+ SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
+ ret = _local_impl->Copy(aSO_impl, aDriver);
+ delete aDriver;
+ }
+ else {
+ ret = _corba_impl->Copy(aSO->GetCORBAImpl());
+ }
+ return ret;
+}
+
+bool SALOMEDS_Study::CanPaste(const _PTR(SObject)& theSO)
+{
+ SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
+ bool ret;
+
+ if (_isLocal) {
+ SALOMEDS::Locker lock;
+
+ SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
+ SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
+ ret = _local_impl->CanPaste(aSO_impl, aDriver);
+ delete aDriver;
+ }
+ else {
+ ret = _corba_impl->CanPaste(aSO->GetCORBAImpl());
+ }
+
+ return ret;
+}
+
+_PTR(SObject) SALOMEDS_Study::Paste(const _PTR(SObject)& theSO)
+{
+ SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
+ SALOMEDSClient_SObject* aResult = NULL;
+
+ if (_isLocal) {
+ SALOMEDS::Locker lock;
+
+ SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
+ SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
+ SALOMEDSImpl_SObject aNewSO = _local_impl->Paste(aSO_impl, aDriver);
+ delete aDriver;
+ if(aNewSO.IsNull()) return _PTR(SObject)(aResult);
+ aResult = new SALOMEDS_SObject(aNewSO);
+ }
+ else {
+ SALOMEDS::SObject_ptr aNewSO = _corba_impl->Paste(aSO->GetCORBAImpl());
+ if(CORBA::is_nil(aNewSO)) return _PTR(SObject)(aResult);
+ aResult = new SALOMEDS_SObject(aNewSO);
+ }
+
+ return _PTR(SObject)(aResult);
}
-std::string SALOMEDS_Study::GetTransientReference()
+std::string SALOMEDS_Study::GetPersistentReference()
{
std::string aRef;
if (_isLocal) {
SALOMEDS::Locker lock;
- aRef = _local_impl->GetTransientReference();
+ aRef = _local_impl->GetPersistentReference();
}
- else aRef = _corba_impl->GetTransientReference();
+ else aRef = (CORBA::String_var)_corba_impl->GetPersistentReference();
return aRef;
}
@@ -304,91 +445,6 @@ std::string SALOMEDS_Study::GetObjectPath(const _PTR(SObject)& theSO)
return aPath;
}
-void SALOMEDS_Study::SetContext(const std::string& thePath)
-{
- if (_isLocal) {
- SALOMEDS::Locker lock;
- _local_impl->SetContext(thePath);
- }
- else _corba_impl->SetContext((char*)thePath.c_str());
-}
-
-std::string SALOMEDS_Study::GetContext()
-{
- std::string aPath;
- if (_isLocal) {
- SALOMEDS::Locker lock;
- aPath = _local_impl->GetContext();
- }
- else aPath = _corba_impl->GetContext();
- return aPath;
-}
-
-std::vector SALOMEDS_Study::GetObjectNames(const std::string& theContext)
-{
- std::vector aVector;
- int aLength, i;
- if (_isLocal) {
- SALOMEDS::Locker lock;
- aVector = _local_impl->GetObjectNames(theContext);
- }
- else {
- SALOMEDS::ListOfStrings_var aSeq = _corba_impl->GetObjectNames((char*)theContext.c_str());
- aLength = aSeq->length();
- for (i = 0; i < aLength; i++) aVector.push_back(std::string((std::string)aSeq[i].in()));
- }
- return aVector;
-}
-
-std::vector SALOMEDS_Study::GetDirectoryNames(const std::string& theContext)
-{
- std::vector aVector;
- int aLength, i;
- if (_isLocal) {
- SALOMEDS::Locker lock;
- aVector = _local_impl->GetDirectoryNames(theContext);
- }
- else {
- SALOMEDS::ListOfStrings_var aSeq = _corba_impl->GetDirectoryNames((char*)theContext.c_str());
- aLength = aSeq->length();
- for (i = 0; i < aLength; i++) aVector.push_back((char*)aSeq[i].in());
- }
- return aVector;
-}
-
-std::vector SALOMEDS_Study::GetFileNames(const std::string& theContext)
-{
- std::vector aVector;
- int aLength, i;
- if (_isLocal) {
- SALOMEDS::Locker lock;
- aVector = _local_impl->GetFileNames(theContext);
- }
- else {
- SALOMEDS::ListOfStrings_var aSeq = _corba_impl->GetFileNames((char*)theContext.c_str());
- aLength = aSeq->length();
-
- for (i = 0; i < aLength; i++) aVector.push_back((char*)aSeq[i].in());
- }
- return aVector;
-}
-
-std::vector SALOMEDS_Study::GetComponentNames(const std::string& theContext)
-{
- std::vector aVector;
- int aLength, i;
- if (_isLocal) {
- SALOMEDS::Locker lock;
- aVector = _local_impl->GetComponentNames(theContext);
- }
- else {
- SALOMEDS::ListOfStrings_var aSeq = _corba_impl->GetComponentNames((char*)theContext.c_str());
- aLength = aSeq->length();
- for (i = 0; i < aLength; i++) aVector.push_back((char*)aSeq[i].in());
- }
- return aVector;
-}
-
_PTR(ChildIterator) SALOMEDS_Study::NewChildIterator(const _PTR(SObject)& theSO)
{
SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
@@ -447,7 +503,7 @@ std::string SALOMEDS_Study::Name()
SALOMEDS::Locker lock;
aName = _local_impl->Name();
}
- else aName = _corba_impl->Name();
+ else aName = Kernel_Utils::encode_s(_corba_impl->Name());
return aName;
}
@@ -457,7 +513,7 @@ void SALOMEDS_Study::Name(const std::string& theName)
SALOMEDS::Locker lock;
_local_impl->Name(theName);
}
- else _corba_impl->Name((char*)theName.c_str());
+ else _corba_impl->Name(Kernel_Utils::decode_s(theName));
}
bool SALOMEDS_Study::IsSaved()
@@ -508,7 +564,8 @@ std::string SALOMEDS_Study::URL()
SALOMEDS::Locker lock;
aURL = _local_impl->URL();
}
- else aURL = _corba_impl->URL();
+ else
+ aURL = Kernel_Utils::encode_s(_corba_impl->URL());
return aURL;
}
@@ -518,27 +575,7 @@ void SALOMEDS_Study::URL(const std::string& url)
SALOMEDS::Locker lock;
_local_impl->URL(url);
}
- else _corba_impl->URL((char*)url.c_str());
-}
-
-int SALOMEDS_Study::StudyId()
-{
- int anID;
- if (_isLocal) {
- SALOMEDS::Locker lock;
- anID = _local_impl->StudyId();
- }
- else anID = _corba_impl->StudyId();
- return anID;
-}
-
-void SALOMEDS_Study::StudyId(int id)
-{
- if (_isLocal) {
- SALOMEDS::Locker lock;
- _local_impl->StudyId(id);
- }
- else _corba_impl->StudyId(id);
+ else _corba_impl->URL(Kernel_Utils::decode_s(url));
}
std::vector<_PTR(SObject)> SALOMEDS_Study::FindDependances(const _PTR(SObject)& theSO)
@@ -619,15 +656,6 @@ _PTR(UseCaseBuilder) SALOMEDS_Study::GetUseCaseBuilder()
return _PTR(UseCaseBuilder)(aUB);
}
-void SALOMEDS_Study::Close()
-{
- if (_isLocal) {
- SALOMEDS::Locker lock;
- _local_impl->Close();
- }
- else _corba_impl->Close();
-}
-
void SALOMEDS_Study::EnableUseCaseAutoFilling(bool isEnabled)
{
if(_isLocal) _local_impl->EnableUseCaseAutoFilling(isEnabled);
@@ -639,10 +667,10 @@ bool SALOMEDS_Study::DumpStudy(const std::string& thePath,
bool isPublished,
bool isMultiFile)
{
- //SRN: Pure CORBA DumpStudy as it does more cleaning than the local one
- if(CORBA::is_nil(_corba_impl)) GetStudy(); //If CORBA implementation is null then retrieve it
- bool ret = _corba_impl->DumpStudy(thePath.c_str(), theBaseName.c_str(), isPublished, isMultiFile);
- return ret;
+ if(CORBA::is_nil(_corba_impl))
+ return false;
+
+ return _corba_impl->DumpStudy(thePath.c_str(), theBaseName.c_str(), isPublished, isMultiFile);
}
void SALOMEDS_Study::SetStudyLock(const std::string& theLockerID)
@@ -943,40 +971,6 @@ CORBA::Object_ptr SALOMEDS_Study::ConvertIORToObject(const std::string& theIOR)
return _orb->string_to_object(theIOR.c_str());
}
-void SALOMEDS_Study::init_orb()
-{
- ORB_INIT &init = *SINGLETON_::Instance() ;
- ASSERT(SINGLETON_::IsAlreadyExisting());
- _orb = init(0 , 0 ) ;
-}
-
-SALOMEDS::Study_ptr SALOMEDS_Study::GetStudy()
-{
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- if (!CORBA::is_nil(_corba_impl)) return SALOMEDS::Study::_duplicate(_corba_impl);
- std::string anIOR = _local_impl->GetTransientReference();
- SALOMEDS::Study_var aStudy;
- if (!_local_impl->IsError() && anIOR != "") {
- aStudy = SALOMEDS::Study::_narrow(_orb->string_to_object(anIOR.c_str()));
- }
- else {
- SALOMEDS_Study_i *aStudy_servant = new SALOMEDS_Study_i(_local_impl, _orb);
- aStudy = aStudy_servant->_this();
- _local_impl->SetTransientReference(_orb->object_to_string(aStudy));
- }
- _corba_impl = SALOMEDS::Study::_duplicate(aStudy);
- return aStudy._retn();
- }
- else {
- return SALOMEDS::Study::_duplicate(_corba_impl);
- }
-
- return SALOMEDS::Study::_nil();
-}
-
-
_PTR(AttributeParameter) SALOMEDS_Study::GetCommonParameters(const std::string& theID, int theSavePoint)
{
SALOMEDSClient_AttributeParameter* AP = NULL;
@@ -1010,12 +1004,16 @@ _PTR(AttributeParameter) SALOMEDS_Study::GetModuleParameters(const std::string&
void SALOMEDS_Study::attach(SALOMEDS::Observer_ptr theObserver,bool modify)
{
- if(CORBA::is_nil(_corba_impl)) GetStudy(); //If CORBA implementation is null then retrieve it
+ if(CORBA::is_nil(_corba_impl))
+ return;
+
_corba_impl->attach(theObserver,modify);
}
void SALOMEDS_Study::detach(SALOMEDS::Observer_ptr theObserver)
{
- if(CORBA::is_nil(_corba_impl)) GetStudy(); //If CORBA implementation is null then retrieve it
+ if(CORBA::is_nil(_corba_impl))
+ return;
+
_corba_impl->detach(theObserver);
}
diff --git a/src/SALOMEDS/SALOMEDS_Study.hxx b/src/SALOMEDS/SALOMEDS_Study.hxx
index af663d633..affbad4fc 100644
--- a/src/SALOMEDS/SALOMEDS_Study.hxx
+++ b/src/SALOMEDS/SALOMEDS_Study.hxx
@@ -52,8 +52,20 @@ public:
SALOMEDS_Study(SALOMEDS::Study_ptr theStudy);
~SALOMEDS_Study();
+ virtual void Clear();
+ virtual void Init();
+
+ virtual bool Open(const std::string& theStudyUrl);
+
+ virtual bool Save(bool theMultiFile, bool theASCII);
+ virtual bool SaveAs(const std::string& theUrl, bool theMultiFile, bool theASCII);
+
+ virtual bool CanCopy(const _PTR(SObject)& theSO);
+ virtual bool Copy(const _PTR(SObject)& theSO);
+ virtual bool CanPaste(const _PTR(SObject)& theSO);
+ virtual _PTR(SObject) Paste(const _PTR(SObject)& theSO);
+
virtual std::string GetPersistentReference();
- virtual std::string GetTransientReference();
virtual bool IsEmpty();
virtual _PTR(SComponent) FindComponent (const std::string& aComponentName);
virtual _PTR(SComponent) FindComponentID(const std::string& aComponentID);
@@ -64,12 +76,6 @@ public:
virtual _PTR(SObject) FindObjectIOR(const std::string& anObjectIOR);
virtual _PTR(SObject) FindObjectByPath(const std::string& thePath);
virtual std::string GetObjectPath(const _PTR(SObject)& theSO);
- virtual void SetContext(const std::string& thePath);
- virtual std::string GetContext();
- virtual std::vector GetObjectNames(const std::string& theContext);
- virtual std::vector GetDirectoryNames(const std::string& theContext);
- virtual std::vector GetFileNames(const std::string& theContext);
- virtual std::vector GetComponentNames(const std::string& theContext);
virtual _PTR(ChildIterator) NewChildIterator(const _PTR(SObject)& theSO);
virtual _PTR(SComponentIterator) NewComponentIterator();
virtual _PTR(StudyBuilder) NewBuilder();
@@ -81,14 +87,11 @@ public:
virtual void Modified();
virtual std::string URL();
virtual void URL(const std::string& url);
- virtual int StudyId();
- virtual void StudyId(int id);
virtual std::vector<_PTR(SObject)> FindDependances(const _PTR(SObject)& theSO);
virtual _PTR(AttributeStudyProperties) GetProperties();
virtual std::string GetLastModificationDate();
virtual std::vector GetModificationsDate();
virtual _PTR(UseCaseBuilder) GetUseCaseBuilder();
- virtual void Close();
virtual void EnableUseCaseAutoFilling(bool isEnabled);
virtual bool DumpStudy(const std::string& thePath,const std::string& theBaseName,bool isPublished,bool isMultiFile);
virtual _PTR(AttributeParameter) GetCommonParameters(const std::string& theID, int theSavePoint);
@@ -127,13 +130,11 @@ public:
std::string ConvertObjectToIOR(CORBA::Object_ptr theObject);
CORBA::Object_ptr ConvertIORToObject(const std::string& theIOR);
-
- SALOMEDS::Study_ptr GetStudy();
SALOMEDSImpl_Study* GetLocalImpl() { return _local_impl; }
-
+
private:
- void init_orb();
+ void InitORB();
};
#endif
diff --git a/src/SALOMEDS/SALOMEDS_StudyBuilder.cxx b/src/SALOMEDS/SALOMEDS_StudyBuilder.cxx
index 8aeed232c..80477af72 100644
--- a/src/SALOMEDS/SALOMEDS_StudyBuilder.cxx
+++ b/src/SALOMEDS/SALOMEDS_StudyBuilder.cxx
@@ -32,7 +32,6 @@
#include "SALOMEDS_SObject.hxx"
#include "SALOMEDS_SComponent.hxx"
#include "SALOMEDS_GenericAttribute.hxx"
-#include "SALOMEDS_StudyManager.hxx"
#include "SALOMEDS_StudyBuilder_i.hxx"
#include "SALOMEDS_Driver_i.hxx"
@@ -175,23 +174,6 @@ _PTR(SObject) SALOMEDS_StudyBuilder::NewObjectToTag(const _PTR(SObject)& theFath
return _PTR(SObject)(aSO);
}
-void SALOMEDS_StudyBuilder::AddDirectory(const std::string& thePath)
-{
- if (_isLocal) {
- CheckLocked();
- SALOMEDS::Locker lock;
-
- _local_impl->AddDirectory((char*)thePath.c_str());
- if (_local_impl->IsError()) {
- std::string anErrorCode = _local_impl->GetErrorCode();
- if (anErrorCode == "StudyNameAlreadyUsed") throw SALOMEDS::Study::StudyNameAlreadyUsed();
- if (anErrorCode == "StudyInvalidDirectory") throw SALOMEDS::Study::StudyInvalidDirectory();
- if (anErrorCode == "StudyInvalidComponent") throw SALOMEDS::Study::StudyInvalidComponent();
- }
- }
- else _corba_impl->AddDirectory((char*)thePath.c_str());
-}
-
void SALOMEDS_StudyBuilder::LoadWith(const _PTR(SComponent)& theSCO, const std::string& theIOR)
{
if(!theSCO) return;
diff --git a/src/SALOMEDS/SALOMEDS_StudyBuilder.hxx b/src/SALOMEDS/SALOMEDS_StudyBuilder.hxx
index 37336327f..ebb138633 100644
--- a/src/SALOMEDS/SALOMEDS_StudyBuilder.hxx
+++ b/src/SALOMEDS/SALOMEDS_StudyBuilder.hxx
@@ -58,7 +58,6 @@ public:
virtual void RemoveComponent(const _PTR(SComponent)& theSCO);
virtual _PTR(SObject) NewObject(const _PTR(SObject)& theFatherObject);
virtual _PTR(SObject) NewObjectToTag(const _PTR(SObject)& theFatherObject, int theTag);
- virtual void AddDirectory(const std::string& thePath);
virtual void LoadWith(const _PTR(SComponent)& theSCO, const std::string& theIOR);
virtual void Load(const _PTR(SObject)& theSCO);
virtual void RemoveObject(const _PTR(SObject)& theSO);
diff --git a/src/SALOMEDS/SALOMEDS_StudyBuilder_i.cxx b/src/SALOMEDS/SALOMEDS_StudyBuilder_i.cxx
index e3013e714..f9ecf67a2 100644
--- a/src/SALOMEDS/SALOMEDS_StudyBuilder_i.cxx
+++ b/src/SALOMEDS/SALOMEDS_StudyBuilder_i.cxx
@@ -26,7 +26,6 @@
//
#include "utilities.h"
#include "SALOMEDS_StudyBuilder_i.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
#include "SALOMEDS_Study_i.hxx"
#include "SALOMEDS_SObject_i.hxx"
#include "SALOMEDS_SComponent_i.hxx"
@@ -80,7 +79,7 @@ SALOMEDS_StudyBuilder_i::~SALOMEDS_StudyBuilder_i()
//============================================================================
PortableServer::POA_ptr SALOMEDS_StudyBuilder_i::_default_POA()
{
- PortableServer::POA_ptr poa = SALOMEDS_StudyManager_i::GetThePOA();
+ PortableServer::POA_ptr poa = SALOMEDS_Study_i::GetThePOA();
MESSAGE("SALOMEDS_StudyBuilder_i::_default_POA: " << poa);
return PortableServer::POA::_duplicate(poa);
}
@@ -338,26 +337,6 @@ void SALOMEDS_StudyBuilder_i::RemoveReference(SALOMEDS::SObject_ptr me)
_impl->RemoveReference(aSO);
}
-
-//============================================================================
-/*! Function : AddDirectory
- * Purpose : adds a new directory with a path = thePath
- */
-//============================================================================
-void SALOMEDS_StudyBuilder_i::AddDirectory(const char* thePath)
-{
- SALOMEDS::Locker lock;
- CheckLocked();
- if(thePath == NULL || strlen(thePath) == 0) throw SALOMEDS::Study::StudyInvalidDirectory();
- if(!_impl->AddDirectory(std::string(thePath))) {
- std::string anErrorCode = _impl->GetErrorCode();
- if(anErrorCode == "StudyNameAlreadyUsed") throw SALOMEDS::Study::StudyNameAlreadyUsed();
- if(anErrorCode == "StudyInvalidDirectory") throw SALOMEDS::Study::StudyInvalidDirectory();
- if(anErrorCode == "StudyInvalidComponent") throw SALOMEDS::Study::StudyInvalidComponent();
- }
-}
-
-
//============================================================================
/*! Function : SetGUID
* Purpose :
diff --git a/src/SALOMEDS/SALOMEDS_StudyBuilder_i.hxx b/src/SALOMEDS/SALOMEDS_StudyBuilder_i.hxx
index 99b44a92c..cfaee100e 100644
--- a/src/SALOMEDS/SALOMEDS_StudyBuilder_i.hxx
+++ b/src/SALOMEDS/SALOMEDS_StudyBuilder_i.hxx
@@ -90,11 +90,6 @@ public:
*/
virtual SALOMEDS::SObject_ptr NewObjectToTag(SALOMEDS::SObject_ptr theFatherObject, CORBA::Long atag);
- /*!
- The methods adds a new subdirectory, the path can be absolute or relative (then the current context is used)
- */
- virtual void AddDirectory(const char* thePath);
-
virtual void LoadWith(SALOMEDS::SComponent_ptr sco, SALOMEDS::Driver_ptr Engine)
throw(SALOME::SALOME_Exception);
virtual void Load(SALOMEDS::SObject_ptr sco);
diff --git a/src/SALOMEDS/SALOMEDS_StudyManager.cxx b/src/SALOMEDS/SALOMEDS_StudyManager.cxx
deleted file mode 100644
index ba0a8f206..000000000
--- a/src/SALOMEDS/SALOMEDS_StudyManager.cxx
+++ /dev/null
@@ -1,326 +0,0 @@
-// Copyright (C) 2007-2016 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 : SALOMEDSClient_StudyManager.cxx
-// Author : Sergey RUIN
-// Module : SALOME
-//
-#include "SALOMEDS_StudyManager.hxx"
-
-#include "SALOMEDS.hxx"
-#include "SALOMEDS_Study.hxx"
-#include "SALOMEDS_SObject.hxx"
-#include "SALOMEDS_Driver_i.hxx"
-
-#include "SALOMEDSImpl_Study.hxx"
-
-#include "Utils_ORB_INIT.hxx"
-#include "Utils_SINGLETON.hxx"
-#include "utilities.h"
-
-#include "Basics_Utils.hxx"
-
-#ifdef WIN32
-#include
-#else
-#include
-#include
-#endif
-
-SALOMEDS_Driver_i* GetDriver(const SALOMEDSImpl_SObject& theObject, CORBA::ORB_ptr orb);
-
-SALOMEDS_StudyManager::SALOMEDS_StudyManager(SALOMEDS::StudyManager_ptr theManager)
-{
-
-#ifdef WIN32
- long pid = (long)_getpid();
-#else
- long pid = (long)getpid();
-#endif
-
- CORBA::LongLong addr = theManager->GetLocalImpl(Kernel_Utils::GetHostname().c_str(), pid, _isLocal);
- if(_isLocal) {
- _local_impl = reinterpret_cast(addr);
- _corba_impl = SALOMEDS::StudyManager::_duplicate(theManager);
- }
- else {
- _local_impl = NULL;
- _corba_impl = SALOMEDS::StudyManager::_duplicate(theManager);
- }
-
- init_orb();
-}
-
-SALOMEDS_StudyManager::SALOMEDS_StudyManager()
-{
- init_orb();
-
- SALOME_NamingService namingService(_orb);
- CORBA::Object_var obj = namingService.Resolve( "/myStudyManager" );
- SALOMEDS::StudyManager_var theManager = SALOMEDS::StudyManager::_narrow( obj );
- ASSERT( !CORBA::is_nil(theManager) );
-
-#ifdef WIN32
- long pid = (long)_getpid();
-#else
- long pid = (long)getpid();
-#endif
-
- CORBA::LongLong addr = theManager->GetLocalImpl(Kernel_Utils::GetHostname().c_str(), pid, _isLocal);
- if(_isLocal) {
- _local_impl = reinterpret_cast(addr);
- _corba_impl = SALOMEDS::StudyManager::_duplicate(theManager);
- }
- else {
- _local_impl = NULL;
- _corba_impl = SALOMEDS::StudyManager::_duplicate(theManager);
- }
-}
-
-SALOMEDS_StudyManager::~SALOMEDS_StudyManager()
-{
-}
-
-_PTR(Study) SALOMEDS_StudyManager::NewStudy(const std::string& study_name)
-{
- //SRN: Pure CORBA NewStudy as it does more initialization than the local one
- SALOMEDSClient_Study* aStudy = NULL;
-
- SALOMEDS::Study_var aStudy_impl = _corba_impl->NewStudy((char*)study_name.c_str());
- if(CORBA::is_nil(aStudy_impl)) return _PTR(Study)(aStudy);
- aStudy = new SALOMEDS_Study(aStudy_impl);
-
- return _PTR(Study)(aStudy);
-}
-
-_PTR(Study) SALOMEDS_StudyManager::Open(const std::string& theStudyUrl)
-{
- //SRN: Pure CORBA Open as it does more initialization than the local one
- SALOMEDSClient_Study* aStudy = NULL;
-
- SALOMEDS::Study_var aStudy_impl = _corba_impl->Open((char*)theStudyUrl.c_str());
- if(CORBA::is_nil(aStudy_impl)) return _PTR(Study)(aStudy);
-
- aStudy = new SALOMEDS_Study(aStudy_impl.in());
-
- return _PTR(Study)(aStudy);
-}
-
-void SALOMEDS_StudyManager::Close(const _PTR(Study)& theStudy)
-{
- //SRN: Pure CORBA close as it does more cleaning than the local one
- SALOMEDS::Study_var aStudy = _corba_impl->GetStudyByID(theStudy->StudyId());
- _corba_impl->Close(aStudy);
-}
-
-bool SALOMEDS_StudyManager::Save(const _PTR(Study)& theStudy, bool theMultiFile)
-{
- //SRN: Pure CORBA save as the save operation require CORBA in any case
- SALOMEDS::Study_var aStudy = _corba_impl->GetStudyByID(theStudy->StudyId());
- return _corba_impl->Save(aStudy, theMultiFile);
-}
-
-bool SALOMEDS_StudyManager::SaveASCII(const _PTR(Study)& theStudy, bool theMultiFile)
-{
- //SRN: Pure CORBA save as the save operation require CORBA in any case
- SALOMEDS::Study_var aStudy = _corba_impl->GetStudyByID(theStudy->StudyId());
- return _corba_impl->SaveASCII(aStudy, theMultiFile);
-}
-
-bool SALOMEDS_StudyManager::SaveAs(const std::string& theUrl, const _PTR(Study)& theStudy, bool theMultiFile)
-{
- //SRN: Pure CORBA save as the save operation require CORBA in any case
- SALOMEDS::Study_var aStudy = _corba_impl->GetStudyByID(theStudy->StudyId());
- return _corba_impl->SaveAs((char*)theUrl.c_str(), aStudy, theMultiFile);
-}
-
-bool SALOMEDS_StudyManager::SaveAsASCII(const std::string& theUrl, const _PTR(Study)& theStudy, bool theMultiFile)
-{
- //SRN: Pure CORBA save as the save operation require CORBA in any case
- SALOMEDS::Study_var aStudy = _corba_impl->GetStudyByID(theStudy->StudyId());
- return _corba_impl->SaveAsASCII((char*)theUrl.c_str(), aStudy, theMultiFile);
-}
-
-std::vector SALOMEDS_StudyManager::GetOpenStudies()
-{
- std::vector aVector;
- int aLength, i;
-
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- std::vector aSeq = _local_impl->GetOpenStudies();
- aLength = aSeq.size();
- for(i = 0; i < aLength; i++)
- aVector.push_back(aSeq[i]->Name());
- }
- else {
- SALOMEDS::ListOfOpenStudies_var aSeq = _corba_impl->GetOpenStudies();
- aLength = aSeq->length();
- for(i = 0; i < aLength; i++)
- aVector.push_back(aSeq[i].in());
- }
- return aVector;
-}
-
-_PTR(Study) SALOMEDS_StudyManager::GetStudyByName(const std::string& theStudyName)
-{
- SALOMEDSClient_Study* aStudy = NULL;
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_Study* aStudy_impl = _local_impl->GetStudyByName(theStudyName);
- if(!aStudy_impl) return _PTR(Study)(aStudy);
- aStudy = new SALOMEDS_Study(aStudy_impl);
- }
- else {
- SALOMEDS::Study_var aStudy_impl = _corba_impl->GetStudyByName((char*)theStudyName.c_str());
- if(CORBA::is_nil(aStudy_impl)) return _PTR(Study)(aStudy);
- aStudy = new SALOMEDS_Study(aStudy_impl);
- }
- return _PTR(Study)(aStudy);
-}
-
-_PTR(Study) SALOMEDS_StudyManager::GetStudyByID(int theStudyID)
-{
- SALOMEDSClient_Study* aStudy = NULL;
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_Study* aStudy_impl = _local_impl->GetStudyByID(theStudyID);
- if(!aStudy_impl) return _PTR(Study)(aStudy);
- aStudy = new SALOMEDS_Study(aStudy_impl);
- }
- else {
- SALOMEDS::Study_var aStudy_impl = _corba_impl->GetStudyByID(theStudyID);
- if(CORBA::is_nil(aStudy_impl)) return _PTR(Study)(aStudy);
- aStudy = new SALOMEDS_Study(aStudy_impl);
- }
- return _PTR(Study)(aStudy);
-}
-
-bool SALOMEDS_StudyManager::CanCopy(const _PTR(SObject)& theSO)
-{
- SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
- bool ret;
-
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
- SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
- ret = _local_impl->CanCopy(aSO_impl, aDriver);
- delete aDriver;
- }
- else {
- ret = _corba_impl->CanCopy(aSO->GetCORBAImpl());
- }
-
- return ret;
-}
-
-bool SALOMEDS_StudyManager::Copy(const _PTR(SObject)& theSO)
-{
- SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
- bool ret;
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
- SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
- ret = _local_impl->Copy(aSO_impl, aDriver);
- delete aDriver;
- }
- else {
- ret = _corba_impl->Copy(aSO->GetCORBAImpl());
- }
- return ret;
-}
-
-bool SALOMEDS_StudyManager::CanPaste(const _PTR(SObject)& theSO)
-{
- SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
- bool ret;
-
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
- SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
- ret = _local_impl->CanPaste(aSO_impl, aDriver);
- delete aDriver;
- }
- else {
- ret = _corba_impl->CanPaste(aSO->GetCORBAImpl());
- }
-
- return ret;
-}
-
-_PTR(SObject) SALOMEDS_StudyManager::Paste(const _PTR(SObject)& theSO)
-{
- SALOMEDS_SObject* aSO = dynamic_cast(theSO.get());
- SALOMEDSClient_SObject* aResult = NULL;
-
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_SObject aSO_impl = *(aSO->GetLocalImpl());
- SALOMEDS_Driver_i* aDriver = GetDriver(aSO_impl, _orb);
- SALOMEDSImpl_SObject aNewSO = _local_impl->Paste(aSO_impl, aDriver);
- delete aDriver;
- if(aNewSO.IsNull()) return _PTR(SObject)(aResult);
- aResult = new SALOMEDS_SObject(aNewSO);
- }
- else {
- SALOMEDS::SObject_ptr aNewSO = _corba_impl->Paste(aSO->GetCORBAImpl());
- if(CORBA::is_nil(aNewSO)) return _PTR(SObject)(aResult);
- aResult = new SALOMEDS_SObject(aNewSO);
- }
-
- return _PTR(SObject)(aResult);
-}
-
-
-void SALOMEDS_StudyManager::init_orb()
-{
- ORB_INIT &init = *SINGLETON_::Instance();
- ASSERT(SINGLETON_::IsAlreadyExisting());
- _orb = init(0 , 0 );
-}
-
-SALOMEDS_Driver_i* GetDriver(const SALOMEDSImpl_SObject& theObject, CORBA::ORB_ptr orb)
-{
- SALOMEDS_Driver_i* driver = NULL;
-
- SALOMEDSImpl_SComponent aSCO = theObject.GetFatherComponent();
- if(!aSCO.IsNull()) {
- std::string IOREngine = aSCO.GetIOR();
- if(!IOREngine.empty()) {
- CORBA::Object_var obj = orb->string_to_object(IOREngine.c_str());
- Engines::EngineComponent_var Engine = Engines::EngineComponent::_narrow(obj) ;
- driver = new SALOMEDS_Driver_i(Engine, orb);
- }
- }
-
- return driver;
-}
diff --git a/src/SALOMEDS/SALOMEDS_StudyManager.hxx b/src/SALOMEDS/SALOMEDS_StudyManager.hxx
deleted file mode 100644
index 600676199..000000000
--- a/src/SALOMEDS/SALOMEDS_StudyManager.hxx
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright (C) 2007-2016 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 : SALOMEDS_StudyManager.hxx
-// Author : Sergey RUIN
-// Module : SALOME
-//
-#ifndef __SALOMEDS_STUDYMANAGER_H__
-#define __SALOMEDS_STUDYMANAGER_H__
-
-#include
-#include
-
-#include "SALOMEDSClient.hxx"
-#include "SALOMEDSImpl_StudyManager.hxx"
-
-// IDL headers
-
-#include
-#include CORBA_SERVER_HEADER(SALOMEDS)
-
-class Standard_EXPORT SALOMEDS_StudyManager: public SALOMEDSClient_StudyManager
-{
-private:
- bool _isLocal;
- SALOMEDSImpl_StudyManager* _local_impl;
- SALOMEDS::StudyManager_var _corba_impl;
- CORBA::ORB_var _orb;
-
-public:
-
- SALOMEDS_StudyManager(SALOMEDS::StudyManager_ptr theManager);
- SALOMEDS_StudyManager();
- ~SALOMEDS_StudyManager();
-
- virtual _PTR(Study) NewStudy(const std::string& study_name);
- virtual _PTR(Study) Open(const std::string& theStudyUrl);
- virtual void Close(const _PTR(Study)& theStudy);
- virtual bool Save(const _PTR(Study)& theStudy, bool theMultiFile);
- virtual bool SaveASCII(const _PTR(Study)& theStudy, bool theMultiFile);
- virtual bool SaveAs(const std::string& theUrl, const _PTR(Study)& theStudy, bool theMultiFile);
- virtual bool SaveAsASCII(const std::string& theUrl, const _PTR(Study)& theStudy, bool theMultiFile);
- virtual std::vector GetOpenStudies();
- virtual _PTR(Study) GetStudyByName(const std::string& theStudyName) ;
- virtual _PTR(Study) GetStudyByID(int theStudyID) ;
- virtual bool CanCopy(const _PTR(SObject)& theSO);
- virtual bool Copy(const _PTR(SObject)& theSO);
- virtual bool CanPaste(const _PTR(SObject)& theSO);
- virtual _PTR(SObject) Paste(const _PTR(SObject)& theSO);
-
-private:
- void init_orb();
-};
-
-#endif
diff --git a/src/SALOMEDS/SALOMEDS_StudyManager_i.cxx b/src/SALOMEDS/SALOMEDS_StudyManager_i.cxx
deleted file mode 100644
index 0db23404c..000000000
--- a/src/SALOMEDS/SALOMEDS_StudyManager_i.cxx
+++ /dev/null
@@ -1,569 +0,0 @@
-// Copyright (C) 2007-2016 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 : SALOMEDS_StudyManager_i.cxx
-// Author : Sergey RUIN
-// Module : SALOME
-//
-#include "utilities.h"
-#include "SALOME_LifeCycleCORBA.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
-#include "SALOMEDS_Study_i.hxx"
-#include "SALOMEDS_SComponent_i.hxx"
-#include "SALOMEDS_Driver_i.hxx"
-#include "SALOMEDS.hxx"
-
-#include "SALOMEDSImpl_Study.hxx"
-#include "SALOMEDSImpl_SObject.hxx"
-#include "SALOMEDSImpl_SComponent.hxx"
-#include "SALOMEDSImpl_AttributeIOR.hxx"
-
-#include "Utils_CorbaException.hxx"
-#include "Utils_ExceptHandlers.hxx"
-#include "Basics_Utils.hxx"
-#include "SALOME_GenericObj_i.hh"
-
-#include
-#include
-#include